!function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../lib/codemirror"),require("../addon/search/searchcursor"),require("../addon/dialog/dialog"),require("../addon/edit/matchbrackets.js")):"function"==typeof define&&define.amd?define(["../lib/codemirror","../addon/search/searchcursor","../addon/dialog/dialog","../addon/edit/matchbrackets"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function initVim$1(CodeMirror){var Pos=CodeMirror.Pos;function transformCursor(cm,range){var vim=cm.state.vim;if(!vim||vim.insertMode)return range.head;var head=vim.sel.head;return head?vim.visualBlock&&range.head.line!=head.line?void 0:range.from()!=range.anchor||range.empty()||range.head.line!=head.line||range.head.ch==head.ch?range.head:new Pos(range.head.line,range.head.ch-1):range.head}var defaultKeymap=[{keys:"",type:"keyToKey",toKeys:"h"},{keys:"",type:"keyToKey",toKeys:"l"},{keys:"",type:"keyToKey",toKeys:"k"},{keys:"",type:"keyToKey",toKeys:"j"},{keys:"g",type:"keyToKey",toKeys:"gk"},{keys:"g",type:"keyToKey",toKeys:"gj"},{keys:"",type:"keyToKey",toKeys:"l"},{keys:"",type:"keyToKey",toKeys:"h",context:"normal"},{keys:"",type:"keyToKey",toKeys:"x",context:"normal"},{keys:"",type:"keyToKey",toKeys:"W"},{keys:"",type:"keyToKey",toKeys:"B",context:"normal"},{keys:"",type:"keyToKey",toKeys:"w"},{keys:"",type:"keyToKey",toKeys:"b",context:"normal"},{keys:"",type:"keyToKey",toKeys:"j"},{keys:"",type:"keyToKey",toKeys:"k"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"s",type:"keyToKey",toKeys:"cl",context:"normal"},{keys:"s",type:"keyToKey",toKeys:"c",context:"visual"},{keys:"S",type:"keyToKey",toKeys:"cc",context:"normal"},{keys:"S",type:"keyToKey",toKeys:"VdO",context:"visual"},{keys:"",type:"keyToKey",toKeys:"0"},{keys:"",type:"keyToKey",toKeys:"$"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"j^",context:"normal"},{keys:"",type:"keyToKey",toKeys:"i",context:"normal"},{keys:"",type:"action",action:"toggleOverwrite",context:"insert"},{keys:"H",type:"motion",motion:"moveToTopLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"M",type:"motion",motion:"moveToMiddleLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"L",type:"motion",motion:"moveToBottomLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"h",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!1}},{keys:"l",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!0}},{keys:"j",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,linewise:!0}},{keys:"k",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,linewise:!0}},{keys:"gj",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!0}},{keys:"gk",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!1}},{keys:"w",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1}},{keys:"W",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1,bigWord:!0}},{keys:"e",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,inclusive:!0}},{keys:"E",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"b",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1}},{keys:"B",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1,bigWord:!0}},{keys:"ge",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,inclusive:!0}},{keys:"gE",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"{",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!1,toJumplist:!0}},{keys:"}",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!0,toJumplist:!0}},{keys:"(",type:"motion",motion:"moveBySentence",motionArgs:{forward:!1}},{keys:")",type:"motion",motion:"moveBySentence",motionArgs:{forward:!0}},{keys:"",type:"motion",motion:"moveByPage",motionArgs:{forward:!0}},{keys:"",type:"motion",motion:"moveByPage",motionArgs:{forward:!1}},{keys:"",type:"motion",motion:"moveByScroll",motionArgs:{forward:!0,explicitRepeat:!0}},{keys:"",type:"motion",motion:"moveByScroll",motionArgs:{forward:!1,explicitRepeat:!0}},{keys:"gg",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"G",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!0,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"g$",type:"motion",motion:"moveToEndOfDisplayLine"},{keys:"g^",type:"motion",motion:"moveToStartOfDisplayLine"},{keys:"g0",type:"motion",motion:"moveToStartOfDisplayLine"},{keys:"0",type:"motion",motion:"moveToStartOfLine"},{keys:"^",type:"motion",motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"+",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0}},{keys:"-",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,toFirstChar:!0}},{keys:"_",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0,repeatOffset:-1}},{keys:"$",type:"motion",motion:"moveToEol",motionArgs:{inclusive:!0}},{keys:"%",type:"motion",motion:"moveToMatchedSymbol",motionArgs:{inclusive:!0,toJumplist:!0}},{keys:"f",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"F",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!1}},{keys:"t",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"T",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!1}},{keys:";",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!0}},{keys:",",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!1}},{keys:"'",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0,linewise:!0}},{keys:"`",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0}},{keys:"]`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0}},{keys:"[`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1}},{keys:"]'",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0,linewise:!0}},{keys:"['",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1,linewise:!0}},{keys:"]p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0,matchIndent:!0}},{keys:"[p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0,matchIndent:!0}},{keys:"]",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!0,toJumplist:!0}},{keys:"[",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!1,toJumplist:!0}},{keys:"|",type:"motion",motion:"moveToColumn"},{keys:"o",type:"motion",motion:"moveToOtherHighlightedEnd",context:"visual"},{keys:"O",type:"motion",motion:"moveToOtherHighlightedEnd",motionArgs:{sameLine:!0},context:"visual"},{keys:"d",type:"operator",operator:"delete"},{keys:"y",type:"operator",operator:"yank"},{keys:"c",type:"operator",operator:"change"},{keys:"=",type:"operator",operator:"indentAuto"},{keys:">",type:"operator",operator:"indent",operatorArgs:{indentRight:!0}},{keys:"<",type:"operator",operator:"indent",operatorArgs:{indentRight:!1}},{keys:"g~",type:"operator",operator:"changeCase"},{keys:"gu",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},isEdit:!0},{keys:"gU",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},isEdit:!0},{keys:"n",type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:!0}},{keys:"N",type:"motion",motion:"findNext",motionArgs:{forward:!1,toJumplist:!0}},{keys:"gn",type:"motion",motion:"findAndSelectNextInclusive",motionArgs:{forward:!0}},{keys:"gN",type:"motion",motion:"findAndSelectNextInclusive",motionArgs:{forward:!1}},{keys:"x",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!0},operatorMotionArgs:{visualLine:!1}},{keys:"X",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!1},operatorMotionArgs:{visualLine:!0}},{keys:"D",type:"operatorMotion",operator:"delete",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"D",type:"operator",operator:"delete",operatorArgs:{linewise:!0},context:"visual"},{keys:"Y",type:"operatorMotion",operator:"yank",motion:"expandToLine",motionArgs:{linewise:!0},context:"normal"},{keys:"Y",type:"operator",operator:"yank",operatorArgs:{linewise:!0},context:"visual"},{keys:"C",type:"operatorMotion",operator:"change",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"C",type:"operator",operator:"change",operatorArgs:{linewise:!0},context:"visual"},{keys:"~",type:"operatorMotion",operator:"changeCase",motion:"moveByCharacters",motionArgs:{forward:!0},operatorArgs:{shouldMoveCursor:!0},context:"normal"},{keys:"~",type:"operator",operator:"changeCase",context:"visual"},{keys:"",type:"operatorMotion",operator:"delete",motion:"moveToStartOfLine",context:"insert"},{keys:"",type:"operatorMotion",operator:"delete",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1},context:"insert"},{keys:"",type:"idle",context:"normal"},{keys:"",type:"action",action:"jumpListWalk",actionArgs:{forward:!0}},{keys:"",type:"action",action:"jumpListWalk",actionArgs:{forward:!1}},{keys:"",type:"action",action:"scroll",actionArgs:{forward:!0,linewise:!0}},{keys:"",type:"action",action:"scroll",actionArgs:{forward:!1,linewise:!0}},{keys:"a",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"charAfter"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"eol"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"endOfSelectedArea"},context:"visual"},{keys:"i",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"inplace"},context:"normal"},{keys:"gi",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"lastEdit"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"firstNonBlank"},context:"normal"},{keys:"gI",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"bol"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"startOfSelectedArea"},context:"visual"},{keys:"o",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!0},context:"normal"},{keys:"O",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!1},context:"normal"},{keys:"v",type:"action",action:"toggleVisualMode"},{keys:"V",type:"action",action:"toggleVisualMode",actionArgs:{linewise:!0}},{keys:"",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"gv",type:"action",action:"reselectLastSelection"},{keys:"J",type:"action",action:"joinLines",isEdit:!0},{keys:"gJ",type:"action",action:"joinLines",actionArgs:{keepSpaces:!0},isEdit:!0},{keys:"p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0}},{keys:"P",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0}},{keys:"r",type:"action",action:"replace",isEdit:!0},{keys:"@",type:"action",action:"replayMacro"},{keys:"q",type:"action",action:"enterMacroRecordMode"},{keys:"R",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{replace:!0},context:"normal"},{keys:"R",type:"operator",operator:"change",operatorArgs:{linewise:!0,fullLine:!0},context:"visual",exitVisualBlock:!0},{keys:"u",type:"action",action:"undo",context:"normal"},{keys:"u",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},context:"visual",isEdit:!0},{keys:"U",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},context:"visual",isEdit:!0},{keys:"",type:"action",action:"redo"},{keys:"m",type:"action",action:"setMark"},{keys:'"',type:"action",action:"setRegister"},{keys:"zz",type:"action",action:"scrollToCursor",actionArgs:{position:"center"}},{keys:"z.",type:"action",action:"scrollToCursor",actionArgs:{position:"center"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"zt",type:"action",action:"scrollToCursor",actionArgs:{position:"top"}},{keys:"z",type:"action",action:"scrollToCursor",actionArgs:{position:"top"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"zb",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"}},{keys:"z-",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:".",type:"action",action:"repeatLastEdit"},{keys:"",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!0,backtrack:!1}},{keys:"",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!1,backtrack:!1}},{keys:"",type:"action",action:"indent",actionArgs:{indentRight:!0},context:"insert"},{keys:"",type:"action",action:"indent",actionArgs:{indentRight:!1},context:"insert"},{keys:"a",type:"motion",motion:"textObjectManipulation"},{keys:"i",type:"motion",motion:"textObjectManipulation",motionArgs:{textObjectInner:!0}},{keys:"/",type:"search",searchArgs:{forward:!0,querySrc:"prompt",toJumplist:!0}},{keys:"?",type:"search",searchArgs:{forward:!1,querySrc:"prompt",toJumplist:!0}},{keys:"*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"g*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:"g#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:":",type:"ex"}],defaultKeymapLength=defaultKeymap.length,defaultExCommandMap=[{name:"colorscheme",shortName:"colo"},{name:"map"},{name:"imap",shortName:"im"},{name:"nmap",shortName:"nm"},{name:"vmap",shortName:"vm"},{name:"unmap"},{name:"write",shortName:"w"},{name:"undo",shortName:"u"},{name:"redo",shortName:"red"},{name:"set",shortName:"se"},{name:"setlocal",shortName:"setl"},{name:"setglobal",shortName:"setg"},{name:"sort",shortName:"sor"},{name:"substitute",shortName:"s",possiblyAsync:!0},{name:"nohlsearch",shortName:"noh"},{name:"yank",shortName:"y"},{name:"delmarks",shortName:"delm"},{name:"registers",shortName:"reg",excludeFromCommandHistory:!0},{name:"vglobal",shortName:"v"},{name:"global",shortName:"g"}];function enterVimMode(cm){cm.setOption("disableInput",!0),cm.setOption("showCursorWhenSelecting",!1),CodeMirror.signal(cm,"vim-mode-change",{mode:"normal"}),cm.on("cursorActivity",onCursorActivity),maybeInitVimState(cm),CodeMirror.on(cm.getInputField(),"paste",getOnPasteFn(cm))}function leaveVimMode(cm){cm.setOption("disableInput",!1),cm.off("cursorActivity",onCursorActivity),CodeMirror.off(cm.getInputField(),"paste",getOnPasteFn(cm)),cm.state.vim=null,highlightTimeout&&clearTimeout(highlightTimeout)}function detachVimMap(cm,next){this==CodeMirror.keyMap.vim&&(cm.options.$customCursor=null,CodeMirror.rmClass(cm.getWrapperElement(),"cm-fat-cursor")),next&&next.attach==attachVimMap||leaveVimMode(cm)}function attachVimMap(cm,prev){this==CodeMirror.keyMap.vim&&(cm.curOp&&(cm.curOp.selectionChanged=!0),cm.options.$customCursor=transformCursor,CodeMirror.addClass(cm.getWrapperElement(),"cm-fat-cursor")),prev&&prev.attach==attachVimMap||enterVimMode(cm)}function cmKey(key,cm){if(cm){if(this[key])return this[key];var vimKey=cmKeyToVimKey(key);if(!vimKey)return!1;var cmd=vimApi.findKey(cm,vimKey);return"function"==typeof cmd&&CodeMirror.signal(cm,"vim-keypress",vimKey),cmd}}CodeMirror.defineOption("vimMode",!1,function(cm,val,prev){val&&"vim"!=cm.getOption("keyMap")?cm.setOption("keyMap","vim"):!val&&prev!=CodeMirror.Init&&/^vim/.test(cm.getOption("keyMap"))&&cm.setOption("keyMap","default")});var modifiers={Shift:"S",Ctrl:"C",Alt:"A",Cmd:"D",Mod:"A",CapsLock:""},specialKeys={Enter:"CR",Backspace:"BS",Delete:"Del",Insert:"Ins"};function cmKeyToVimKey(key){if("'"==key.charAt(0))return key.charAt(1);var pieces=key.split(/-(?!$)/),lastPiece=pieces[pieces.length-1];if(1==pieces.length&&1==pieces[0].length)return!1;if(2==pieces.length&&"Shift"==pieces[0]&&1==lastPiece.length)return!1;for(var hasCharacter=!1,i=0;i")}function getOnPasteFn(cm){var vim=cm.state.vim;return vim.onPasteFn||(vim.onPasteFn=function(){vim.insertMode||(cm.setCursor(offsetCursor(cm.getCursor(),0,1)),actions.enterInsertMode(cm,{},vim))}),vim.onPasteFn}var numberRegex=/[\d]/,wordCharTest=[CodeMirror.isWordChar,function(ch){return ch&&!CodeMirror.isWordChar(ch)&&!/\s/.test(ch)}],bigWordCharTest=[function(ch){return/\S/.test(ch)}];function makeKeyRange(start,size){for(var keys=[],i=start;i"]),validRegisters=[].concat(upperCaseAlphabet,lowerCaseAlphabet,numbers,["-",'"',".",":","_","/"]),upperCaseChars;try{upperCaseChars=new RegExp("^[\\p{Lu}]$","u")}catch(_){upperCaseChars=/^[A-Z]$/}function isLine(cm,line){return line>=cm.firstLine()&&line<=cm.lastLine()}function isLowerCase(k){return/^[a-z]$/.test(k)}function isMatchableSymbol(k){return-1!="()[]{}".indexOf(k)}function isNumber(k){return numberRegex.test(k)}function isUpperCase(k){return upperCaseChars.test(k)}function isWhiteSpaceString(k){return/^\s*$/.test(k)}function isEndOfSentenceSymbol(k){return-1!=".?!".indexOf(k)}function inArray(val,arr){for(var i=0;ihead?pointer=head:pointer0?1:-1,newCur,oldCur=cm.getCursor();do{if((mark=buffer[(size+(pointer+=inc))%size])&&(newCur=mark.find())&&!cursorEqual(oldCur,newCur))break}while(pointertail)}return mark}function find(cm,offset){var oldPointer=pointer,mark=move(cm,offset);return pointer=oldPointer,mark&&mark.find()}return{cachedCursor:void 0,add:add,find:find,move:move}},createInsertModeChanges=function(c){return c?{changes:c.changes,expectCursorActivityForChange:c.expectCursorActivityForChange}:{changes:[],expectCursorActivityForChange:!1}},vimGlobalState,lastInsertModeKeyTimer;function MacroModeState(){this.latestRegister=void 0,this.isPlaying=!1,this.isRecording=!1,this.replaySearchQueries=[],this.onRecordingDone=void 0,this.lastInsertModeChanges=createInsertModeChanges()}function maybeInitVimState(cm){return cm.state.vim||(cm.state.vim={inputState:new InputState,lastEditInputState:void 0,lastEditActionCommand:void 0,lastHPos:-1,lastHSPos:-1,lastMotion:null,marks:{},insertMode:!1,insertModeRepeat:void 0,visualMode:!1,visualLine:!1,visualBlock:!1,lastSelection:null,lastPastedText:null,sel:{},options:{}}),cm.state.vim}function resetVimGlobalState(){for(var optionName in vimGlobalState={searchQuery:null,searchIsReversed:!1,lastSubstituteReplacePart:void 0,jumpList:createCircularJumpList(),macroModeState:new MacroModeState,lastCharacterSearch:{increment:0,forward:!0,selectedCharacter:""},registerController:new RegisterController({}),searchHistoryController:new HistoryController,exCommandHistoryController:new HistoryController},options){var option=options[optionName];option.value=option.defaultValue}}MacroModeState.prototype={exitMacroRecordMode:function(){var macroModeState=vimGlobalState.macroModeState;macroModeState.onRecordingDone&¯oModeState.onRecordingDone(),macroModeState.onRecordingDone=void 0,macroModeState.isRecording=!1},enterMacroRecordMode:function(cm,registerName){var register=vimGlobalState.registerController.getRegister(registerName);if(register){if(register.clear(),this.latestRegister=registerName,cm.openDialog){var template=dom("span",{class:"cm-vim-message"},"recording @"+registerName);this.onRecordingDone=cm.openDialog(template,null,{bottom:!0})}this.isRecording=!0}}};var vimApi={enterVimMode:enterVimMode,buildKeyMap:function(){},getRegisterController:function(){return vimGlobalState.registerController},resetVimGlobalState_:resetVimGlobalState,getVimGlobalState_:function(){return vimGlobalState},maybeInitVimState_:maybeInitVimState,suppressErrorLogging:!1,InsertModeKey:InsertModeKey,map:function(lhs,rhs,ctx){exCommandDispatcher.map(lhs,rhs,ctx)},unmap:function(lhs,ctx){return exCommandDispatcher.unmap(lhs,ctx)},noremap:function(lhs,rhs,ctx){function toCtxArray(ctx){return ctx?[ctx]:["normal","insert","visual"]}for(var ctxsToMap=toCtxArray(ctx),actualLength=defaultKeymap.length,origLength,i=actualLength-defaultKeymapLength;i=0;i--){var mapping=userKeymap[i];if(ctx!==mapping.context)if(mapping.context)this._mapCommand(mapping);else{var contexts=["normal","insert","visual"];for(var j in contexts)if(contexts[j]!==ctx){var newMapping={};for(var key in mapping)newMapping[key]=mapping[key];newMapping.context=contexts[j],this._mapCommand(newMapping)}}}},setOption:setOption,getOption:getOption,defineOption:defineOption,defineEx:function(name,prefix,func){if(prefix){if(0!==name.indexOf(prefix))throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered')}else prefix=name;exCommands[name]=func,exCommandDispatcher.commandMap_[prefix]={name:name,shortName:prefix,type:"api"}},handleKey:function(cm,key,origin){var command=this.findKey(cm,key,origin);if("function"==typeof command)return command()},multiSelectHandleKey:multiSelectHandleKey,findKey:function(cm,key,origin){var vim=maybeInitVimState(cm),command;function handleMacroRecording(){var macroModeState=vimGlobalState.macroModeState;if(macroModeState.isRecording){if("q"==key)return macroModeState.exitMacroRecordMode(),clearInputState(cm),!0;"mapping"!=origin&&logKey(macroModeState,key)}}function handleEsc(){if(""==key){if(vim.visualMode)exitVisualMode(cm);else{if(!vim.insertMode)return;exitInsertMode(cm)}return clearInputState(cm),!0}}function doKeyToKey(keys){for(var match;keys;)match=/<\w+-.+?>|<\w+>|./.exec(keys),key=match[0],keys=keys.substring(match.index+key.length),vimApi.handleKey(cm,key,"mapping")}function handleKeyInsertMode(){if(handleEsc())return!0;for(var keys=vim.inputState.keyBuffer=vim.inputState.keyBuffer+key,keysAreChars=1==key.length,match=commandDispatcher.matchCommand(keys,defaultKeymap,vim.inputState,"insert");keys.length>1&&"full"!=match.type;){var keys=vim.inputState.keyBuffer=keys.slice(1),thisMatch=commandDispatcher.matchCommand(keys,defaultKeymap,vim.inputState,"insert");"none"!=thisMatch.type&&(match=thisMatch)}if("none"==match.type)return clearInputState(cm),!1;if("partial"==match.type)return lastInsertModeKeyTimer&&window.clearTimeout(lastInsertModeKeyTimer),lastInsertModeKeyTimer=window.setTimeout(function(){vim.insertMode&&vim.inputState.keyBuffer&&clearInputState(cm)},getOption("insertModeEscKeysTimeout")),!keysAreChars;if(lastInsertModeKeyTimer&&window.clearTimeout(lastInsertModeKeyTimer),keysAreChars){for(var selections=cm.listSelections(),i=0;i0||this.motionRepeat.length>0)&&(repeat=1,this.prefixRepeat.length>0&&(repeat*=parseInt(this.prefixRepeat.join(""),10)),this.motionRepeat.length>0&&(repeat*=parseInt(this.motionRepeat.join(""),10))),repeat},Register.prototype={setText:function(text,linewise,blockwise){this.keyBuffer=[text||""],this.linewise=!!linewise,this.blockwise=!!blockwise},pushText:function(text,linewise){linewise&&(this.linewise||this.keyBuffer.push("\n"),this.linewise=!0),this.keyBuffer.push(text)},pushInsertModeChanges:function(changes){this.insertModeChanges.push(createInsertModeChanges(changes))},pushSearchQuery:function(query){this.searchQueries.push(query)},clear:function(){this.keyBuffer=[],this.insertModeChanges=[],this.searchQueries=[],this.linewise=!1},toString:function(){return this.keyBuffer.join("")}},RegisterController.prototype={pushText:function(registerName,operator,text,linewise,blockwise){if("_"!==registerName){linewise&&"\n"!==text.charAt(text.length-1)&&(text+="\n");var register=this.isValidRegister(registerName)?this.getRegister(registerName):null;if(register){var append;isUpperCase(registerName)?register.pushText(text,linewise):register.setText(text,linewise,blockwise),this.unnamedRegister.setText(register.toString(),linewise)}else{switch(operator){case"yank":this.registers[0]=new Register(text,linewise,blockwise);break;case"delete":case"change":-1==text.indexOf("\n")?this.registers["-"]=new Register(text,linewise):(this.shiftNumericRegisters_(),this.registers[1]=new Register(text,linewise))}this.unnamedRegister.setText(text,linewise,blockwise)}}},getRegister:function(name){return this.isValidRegister(name)?(name=name.toLowerCase(),this.registers[name]||(this.registers[name]=new Register),this.registers[name]):this.unnamedRegister},isValidRegister:function(name){return name&&inArray(name,validRegisters)},shiftNumericRegisters_:function(){for(var i=9;i>=2;i--)this.registers[i]=this.getRegister(""+(i-1))}},HistoryController.prototype={nextMatch:function(input,up){var historyBuffer=this.historyBuffer,dir=up?-1:1;null===this.initialPrefix&&(this.initialPrefix=input);for(var i=this.iterator+dir;up?i>=0:i=historyBuffer.length?(this.iterator=historyBuffer.length,this.initialPrefix):i<0?input:void 0},pushInput:function(input){var index=this.historyBuffer.indexOf(input);index>-1&&this.historyBuffer.splice(index,1),input.length&&this.historyBuffer.push(input)},reset:function(){this.initialPrefix=null,this.iterator=this.historyBuffer.length}};var commandDispatcher={matchCommand:function(keys,keyMap,inputState,context){var matches=commandMatches(keys,keyMap,context,inputState),bestMatch;if(!matches.full&&!matches.partial)return{type:"none"};if(!matches.full&&matches.partial)return{type:"partial"};for(var i=0;i"==bestMatch.keys.slice(-11)){var character=lastChar(keys);if(!character||character.length>1)return{type:"clear"};inputState.selectedCharacter=character}return{type:"full",command:bestMatch}},processCommand:function(cm,vim,command){switch(vim.inputState.repeatOverride=command.repeatOverride,command.type){case"motion":this.processMotion(cm,vim,command);break;case"operator":this.processOperator(cm,vim,command);break;case"operatorMotion":this.processOperatorMotion(cm,vim,command);break;case"action":this.processAction(cm,vim,command);break;case"search":this.processSearch(cm,vim,command);break;case"ex":case"keyToEx":this.processEx(cm,vim,command)}},processMotion:function(cm,vim,command){vim.inputState.motion=command.motion,vim.inputState.motionArgs=copyArgs(command.motionArgs),this.evalInput(cm,vim)},processOperator:function(cm,vim,command){var inputState=vim.inputState;if(inputState.operator){if(inputState.operator==command.operator)return inputState.motion="expandToLine",inputState.motionArgs={linewise:!0},void this.evalInput(cm,vim);clearInputState(cm)}inputState.operator=command.operator,inputState.operatorArgs=copyArgs(command.operatorArgs),command.keys.length>1&&(inputState.operatorShortcut=command.keys),command.exitVisualBlock&&(vim.visualBlock=!1,updateCmSelection(cm)),vim.visualMode&&this.evalInput(cm,vim)},processOperatorMotion:function(cm,vim,command){var visualMode=vim.visualMode,operatorMotionArgs=copyArgs(command.operatorMotionArgs);operatorMotionArgs&&visualMode&&operatorMotionArgs.visualLine&&(vim.visualLine=!0),this.processOperator(cm,vim,command),visualMode||this.processMotion(cm,vim,command)},processAction:function(cm,vim,command){var inputState=vim.inputState,repeat=inputState.getRepeat(),repeatIsExplicit=!!repeat,actionArgs=copyArgs(command.actionArgs)||{};inputState.selectedCharacter&&(actionArgs.selectedCharacter=inputState.selectedCharacter),command.operator&&this.processOperator(cm,vim,command),command.motion&&this.processMotion(cm,vim,command),(command.motion||command.operator)&&this.evalInput(cm,vim),actionArgs.repeat=repeat||1,actionArgs.repeatIsExplicit=repeatIsExplicit,actionArgs.registerName=inputState.registerName,clearInputState(cm),vim.lastMotion=null,command.isEdit&&this.recordLastEdit(vim,inputState,command),actions[command.action](cm,actionArgs,vim)},processSearch:function(cm,vim,command){if(cm.getSearchCursor){var forward=command.searchArgs.forward,wholeWordOnly=command.searchArgs.wholeWordOnly;getSearchState(cm).setReversed(!forward);var promptPrefix=forward?"/":"?",originalQuery=getSearchState(cm).getQuery(),originalScrollPos=cm.getScrollInfo();switch(command.searchArgs.querySrc){case"prompt":var macroModeState=vimGlobalState.macroModeState,query;if(macroModeState.isPlaying)handleQuery(query=macroModeState.replaySearchQueries.shift(),!0,!1);else showPrompt(cm,{onClose:onPromptClose,prefix:promptPrefix,desc:"(JavaScript regexp)",onKeyUp:onPromptKeyUp,onKeyDown:onPromptKeyDown});break;case"wordUnderCursor":var word=expandWordUnderCursor(cm,!1,!0,!1,!0),isKeyword=!0;if(word||(word=expandWordUnderCursor(cm,!1,!0,!1,!1),isKeyword=!1),!word)return;var query=cm.getLine(word.start.line).substring(word.start.ch,word.end.ch);query=isKeyword&&wholeWordOnly?"\\b"+query+"\\b":escapeRegex(query),vimGlobalState.jumpList.cachedCursor=cm.getCursor(),cm.setCursor(word.start),handleQuery(query,!0,!1)}}function handleQuery(query,ignoreCase,smartCase){vimGlobalState.searchHistoryController.pushInput(query),vimGlobalState.searchHistoryController.reset();try{updateSearchQuery(cm,query,ignoreCase,smartCase)}catch(e){return showConfirm(cm,"Invalid regex: "+query),void clearInputState(cm)}commandDispatcher.processMotion(cm,vim,{type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:command.searchArgs.toJumplist}})}function onPromptClose(query){cm.scrollTo(originalScrollPos.left,originalScrollPos.top),handleQuery(query,!0,!0);var macroModeState=vimGlobalState.macroModeState;macroModeState.isRecording&&logSearchQuery(macroModeState,query)}function onPromptKeyUp(e,query,close){var keyName=CodeMirror.keyName(e),up,offset,parsedQuery;"Up"==keyName||"Down"==keyName?(up="Up"==keyName,offset=e.target?e.target.selectionEnd:0,close(query=vimGlobalState.searchHistoryController.nextMatch(query,up)||""),offset&&e.target&&(e.target.selectionEnd=e.target.selectionStart=Math.min(offset,e.target.value.length))):"Left"!=keyName&&"Right"!=keyName&&"Ctrl"!=keyName&&"Alt"!=keyName&&"Shift"!=keyName&&vimGlobalState.searchHistoryController.reset();try{parsedQuery=updateSearchQuery(cm,query,!0,!0)}catch(e){}parsedQuery?cm.scrollIntoView(findNext(cm,!forward,parsedQuery),30):(clearSearchHighlight(cm),cm.scrollTo(originalScrollPos.left,originalScrollPos.top))}function onPromptKeyDown(e,query,close){var keyName=CodeMirror.keyName(e);"Esc"==keyName||"Ctrl-C"==keyName||"Ctrl-["==keyName||"Backspace"==keyName&&""==query?(vimGlobalState.searchHistoryController.pushInput(query),vimGlobalState.searchHistoryController.reset(),updateSearchQuery(cm,originalQuery),clearSearchHighlight(cm),cm.scrollTo(originalScrollPos.left,originalScrollPos.top),CodeMirror.e_stop(e),clearInputState(cm),close(),cm.focus()):"Up"==keyName||"Down"==keyName?CodeMirror.e_stop(e):"Ctrl-U"==keyName&&(CodeMirror.e_stop(e),close(""))}},processEx:function(cm,vim,command){function onPromptClose(input){vimGlobalState.exCommandHistoryController.pushInput(input),vimGlobalState.exCommandHistoryController.reset(),exCommandDispatcher.processCommand(cm,input),clearInputState(cm)}function onPromptKeyDown(e,input,close){var keyName=CodeMirror.keyName(e),up,offset;("Esc"==keyName||"Ctrl-C"==keyName||"Ctrl-["==keyName||"Backspace"==keyName&&""==input)&&(vimGlobalState.exCommandHistoryController.pushInput(input),vimGlobalState.exCommandHistoryController.reset(),CodeMirror.e_stop(e),clearInputState(cm),close(),cm.focus()),"Up"==keyName||"Down"==keyName?(CodeMirror.e_stop(e),up="Up"==keyName,offset=e.target?e.target.selectionEnd:0,close(input=vimGlobalState.exCommandHistoryController.nextMatch(input,up)||""),offset&&e.target&&(e.target.selectionEnd=e.target.selectionStart=Math.min(offset,e.target.value.length))):"Ctrl-U"==keyName?(CodeMirror.e_stop(e),close("")):"Left"!=keyName&&"Right"!=keyName&&"Ctrl"!=keyName&&"Alt"!=keyName&&"Shift"!=keyName&&vimGlobalState.exCommandHistoryController.reset()}"keyToEx"==command.type?exCommandDispatcher.processCommand(cm,command.exArgs.input):vim.visualMode?showPrompt(cm,{onClose:onPromptClose,prefix:":",value:"'<,'>",onKeyDown:onPromptKeyDown,selectValueOnOpen:!1}):showPrompt(cm,{onClose:onPromptClose,prefix:":",onKeyDown:onPromptKeyDown})},evalInput:function(cm,vim){var inputState=vim.inputState,motion=inputState.motion,motionArgs=inputState.motionArgs||{},operator=inputState.operator,operatorArgs=inputState.operatorArgs||{},registerName=inputState.registerName,sel=vim.sel,origHead=copyCursor(vim.visualMode?clipCursorToContent(cm,sel.head):cm.getCursor("head")),origAnchor=copyCursor(vim.visualMode?clipCursorToContent(cm,sel.anchor):cm.getCursor("anchor")),oldHead=copyCursor(origHead),oldAnchor=copyCursor(origAnchor),newHead,newAnchor,repeat;if(operator&&this.recordLastEdit(vim,inputState),(repeat=void 0!==inputState.repeatOverride?inputState.repeatOverride:inputState.getRepeat())>0&&motionArgs.explicitRepeat?motionArgs.repeatIsExplicit=!0:(motionArgs.noRepeat||!motionArgs.explicitRepeat&&0===repeat)&&(repeat=1,motionArgs.repeatIsExplicit=!1),inputState.selectedCharacter&&(motionArgs.selectedCharacter=operatorArgs.selectedCharacter=inputState.selectedCharacter),motionArgs.repeat=repeat,clearInputState(cm),motion){var motionResult=motions[motion](cm,origHead,motionArgs,vim,inputState);if(vim.lastMotion=motions[motion],!motionResult)return;if(motionArgs.toJumplist){var jumpList=vimGlobalState.jumpList,cachedCursor=jumpList.cachedCursor;cachedCursor?(recordJumpPosition(cm,cachedCursor,motionResult),delete jumpList.cachedCursor):recordJumpPosition(cm,origHead,motionResult)}motionResult instanceof Array?(newAnchor=motionResult[0],newHead=motionResult[1]):newHead=motionResult,newHead||(newHead=copyCursor(origHead)),vim.visualMode?(vim.visualBlock&&newHead.ch===1/0||(newHead=clipCursorToContent(cm,newHead)),newAnchor&&(newAnchor=clipCursorToContent(cm,newAnchor)),newAnchor=newAnchor||oldAnchor,sel.anchor=newAnchor,sel.head=newHead,updateCmSelection(cm),updateMark(cm,vim,"<",cursorIsBefore(newAnchor,newHead)?newAnchor:newHead),updateMark(cm,vim,">",cursorIsBefore(newAnchor,newHead)?newHead:newAnchor)):operator||(newHead=clipCursorToContent(cm,newHead),cm.setCursor(newHead.line,newHead.ch))}if(operator){if(operatorArgs.lastSel){newAnchor=oldAnchor;var lastSel=operatorArgs.lastSel,lineOffset=Math.abs(lastSel.head.line-lastSel.anchor.line),chOffset=Math.abs(lastSel.head.ch-lastSel.anchor.ch);newHead=lastSel.visualLine?new Pos(oldAnchor.line+lineOffset,oldAnchor.ch):lastSel.visualBlock?new Pos(oldAnchor.line+lineOffset,oldAnchor.ch+chOffset):lastSel.head.line==lastSel.anchor.line?new Pos(oldAnchor.line,oldAnchor.ch+chOffset):new Pos(oldAnchor.line+lineOffset,oldAnchor.ch),vim.visualMode=!0,vim.visualLine=lastSel.visualLine,vim.visualBlock=lastSel.visualBlock,sel=vim.sel={anchor:newAnchor,head:newHead},updateCmSelection(cm)}else vim.visualMode&&(operatorArgs.lastSel={anchor:copyCursor(sel.anchor),head:copyCursor(sel.head),visualBlock:vim.visualBlock,visualLine:vim.visualLine});var curStart,curEnd,linewise,mode,cmSel;if(vim.visualMode){if(curStart=cursorMin(sel.head,sel.anchor),curEnd=cursorMax(sel.head,sel.anchor),linewise=vim.visualLine||operatorArgs.linewise,cmSel=makeCmSelection(cm,{anchor:curStart,head:curEnd},mode=vim.visualBlock?"block":linewise?"line":"char"),linewise){var ranges=cmSel.ranges;if("block"==mode)for(var i=0;iline:posV.linelast&&cur.line==last?moveToEol(cm,head,motionArgs,vim,!0):(motionArgs.toFirstChar&&(endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line)),vim.lastHPos=endCh),vim.lastHSPos=cm.charCoords(new Pos(line,endCh),"div").left,new Pos(line,endCh))},moveByDisplayLines:function(cm,head,motionArgs,vim){var cur=head;switch(vim.lastMotion){case this.moveByDisplayLines:case this.moveByScroll:case this.moveByLines:case this.moveToColumn:case this.moveToEol:break;default:vim.lastHSPos=cm.charCoords(cur,"div").left}var repeat=motionArgs.repeat,res;if((res=cm.findPosV(cur,motionArgs.forward?repeat:-repeat,"line",vim.lastHSPos)).hitSide)if(motionArgs.forward)var lastCharCoords,goalCoords={top:cm.charCoords(res,"div").top+8,left:vim.lastHSPos},res=cm.coordsChar(goalCoords,"div");else{var resCoords=cm.charCoords(new Pos(cm.firstLine(),0),"div");resCoords.left=vim.lastHSPos,res=cm.coordsChar(resCoords,"div")}return vim.lastHPos=res.ch,res},moveByPage:function(cm,head,motionArgs){var curStart=head,repeat=motionArgs.repeat;return cm.findPosV(curStart,motionArgs.forward?repeat:-repeat,"page")},moveByParagraph:function(cm,head,motionArgs){var dir=motionArgs.forward?1:-1;return findParagraph(cm,head,motionArgs.repeat,dir)},moveBySentence:function(cm,head,motionArgs){var dir=motionArgs.forward?1:-1;return findSentence(cm,head,motionArgs.repeat,dir)},moveByScroll:function(cm,head,motionArgs,vim){var scrollbox=cm.getScrollInfo(),curEnd=null,repeat=motionArgs.repeat;repeat||(repeat=scrollbox.clientHeight/(2*cm.defaultTextHeight()));var orig=cm.charCoords(head,"local");if(motionArgs.repeat=repeat,!(curEnd=motions.moveByDisplayLines(cm,head,motionArgs,vim)))return null;var dest=cm.charCoords(curEnd,"local");return cm.scrollTo(null,scrollbox.top+dest.top-orig.top),curEnd},moveByWords:function(cm,head,motionArgs){return moveToWord(cm,head,motionArgs.repeat,!!motionArgs.forward,!!motionArgs.wordEnd,!!motionArgs.bigWord)},moveTillCharacter:function(cm,_head,motionArgs){var repeat,curEnd=moveToCharacter(cm,motionArgs.repeat,motionArgs.forward,motionArgs.selectedCharacter),increment=motionArgs.forward?-1:1;return recordLastCharacterSearch(increment,motionArgs),curEnd?(curEnd.ch+=increment,curEnd):null},moveToCharacter:function(cm,head,motionArgs){var repeat=motionArgs.repeat;return recordLastCharacterSearch(0,motionArgs),moveToCharacter(cm,repeat,motionArgs.forward,motionArgs.selectedCharacter)||head},moveToSymbol:function(cm,head,motionArgs){var repeat;return findSymbol(cm,motionArgs.repeat,motionArgs.forward,motionArgs.selectedCharacter)||head},moveToColumn:function(cm,head,motionArgs,vim){var repeat=motionArgs.repeat;return vim.lastHPos=repeat-1,vim.lastHSPos=cm.charCoords(head,"div").left,moveToColumn(cm,repeat)},moveToEol:function(cm,head,motionArgs,vim){return moveToEol(cm,head,motionArgs,vim,!1)},moveToFirstNonWhiteSpaceCharacter:function(cm,head){var cursor=head;return new Pos(cursor.line,findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)))},moveToMatchedSymbol:function(cm,head){for(var cursor=head,line=cursor.line,ch=cursor.ch,lineText=cm.getLine(line),symbol;ch"===ch?/[(){}[\]<>]/:/[(){}[\]]/,matched;return cm.findMatchingBracket(new Pos(line,ch),{bracketRegex:re}).to}return cursor},moveToStartOfLine:function(_cm,head){return new Pos(head.line,0)},moveToLineOrEdgeOfDocument:function(cm,_head,motionArgs){var lineNum=motionArgs.forward?cm.lastLine():cm.firstLine();return motionArgs.repeatIsExplicit&&(lineNum=motionArgs.repeat-cm.getOption("firstLineNumber")),new Pos(lineNum,findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)))},moveToStartOfDisplayLine:function(cm){return cm.execCommand("goLineLeft"),cm.getCursor()},moveToEndOfDisplayLine:function(cm){cm.execCommand("goLineRight");var head=cm.getCursor();return"before"==head.sticky&&head.ch--,head},textObjectManipulation:function(cm,head,motionArgs,vim){var mirroredPairs={"(":")",")":"(","{":"}","}":"{","[":"]","]":"[","<":">",">":"<"},selfPaired={"'":!0,'"':!0,"`":!0},character=motionArgs.selectedCharacter;"b"==character?character="(":"B"==character&&(character="{");var inclusive=!motionArgs.textObjectInner,tmp;if(mirroredPairs[character])tmp=selectCompanionObject(cm,head,character,inclusive);else if(selfPaired[character])tmp=findBeginningAndEnd(cm,head,character,inclusive);else if("W"===character)tmp=expandWordUnderCursor(cm,inclusive,!0,!0);else if("w"===character)tmp=expandWordUnderCursor(cm,inclusive,!0,!1);else if("p"===character)if(tmp=findParagraph(cm,head,motionArgs.repeat,0,inclusive),motionArgs.linewise=!0,vim.visualMode)vim.visualLine||(vim.visualLine=!0);else{var operatorArgs=vim.inputState.operatorArgs;operatorArgs&&(operatorArgs.linewise=!0),tmp.end.line--}else if("t"===character)tmp=expandTagUnderCursor(cm,head,inclusive);else{if("s"!==character)return null;var content=cm.getLine(head.line);head.ch>0&&isEndOfSentenceSymbol(content[head.ch])&&(head.ch-=1);var end=getSentence(cm,head,motionArgs.repeat,1,inclusive),start=getSentence(cm,head,motionArgs.repeat,-1,inclusive);isWhiteSpaceString(cm.getLine(start.line)[start.ch])&&isWhiteSpaceString(cm.getLine(end.line)[end.ch-1])&&(start={line:start.line,ch:start.ch+1}),tmp={start:start,end:end}}return cm.state.vim.visualMode?expandSelection(cm,tmp.start,tmp.end):[tmp.start,tmp.end]},repeatLastCharacterSearch:function(cm,head,motionArgs){var lastSearch=vimGlobalState.lastCharacterSearch,repeat=motionArgs.repeat,forward=motionArgs.forward===lastSearch.forward,increment=(lastSearch.increment?1:0)*(forward?-1:1);cm.moveH(-increment,"char"),motionArgs.inclusive=!!forward;var curEnd=moveToCharacter(cm,repeat,forward,lastSearch.selectedCharacter);return curEnd?(curEnd.ch+=increment,curEnd):(cm.moveH(increment,"char"),head)}};function defineMotion(name,fn){motions[name]=fn}function fillArray(val,times){for(var arr=[],i=0;icm.lastLine()&&args.linewise&&!wasLastLine?cm.replaceRange("",prevLineEnd,head):cm.replaceRange("",anchor,head),args.linewise&&(wasLastLine||(cm.setCursor(prevLineEnd),CodeMirror.commands.newlineAndIndent(cm)),anchor.ch=Number.MAX_VALUE),finalHead=anchor}vimGlobalState.registerController.pushText(args.registerName,"change",text,args.linewise,ranges.length>1),actions.enterInsertMode(cm,{head:finalHead},cm.state.vim)},delete:function(cm,args,ranges){var finalHead,text,vim=cm.state.vim;if(vim.visualBlock){text=cm.getSelection();var replacement=fillArray("",ranges.length);cm.replaceSelections(replacement),finalHead=cursorMin(ranges[0].head,ranges[0].anchor)}else{var anchor=ranges[0].anchor,head=ranges[0].head;args.linewise&&head.line!=cm.firstLine()&&anchor.line==cm.lastLine()&&anchor.line==head.line-1&&(anchor.line==cm.firstLine()?anchor.ch=0:anchor=new Pos(anchor.line-1,lineLength(cm,anchor.line-1))),text=cm.getRange(anchor,head),cm.replaceRange("",anchor,head),finalHead=anchor,args.linewise&&(finalHead=motions.moveToFirstNonWhiteSpaceCharacter(cm,anchor))}return vimGlobalState.registerController.pushText(args.registerName,"delete",text,args.linewise,vim.visualBlock),clipCursorToContent(cm,finalHead)},indent:function(cm,args,ranges){var vim=cm.state.vim;if(cm.indentMore)for(var repeat=vim.visualMode?args.repeat:1,j=0;jcursorCoords.top?(cursor.line+=(newPos-cursorCoords.top)/lineHeight,cursor.line=Math.ceil(cursor.line),cm.setCursor(cursor),cursorCoords=cm.charCoords(cursor,"local"),cm.scrollTo(null,cursorCoords.top)):cm.scrollTo(null,newPos);else{var newBottom=newPos+cm.getScrollInfo().clientHeight;newBottom=sel.anchor.line?offsetCursor(sel.head,0,1):new Pos(sel.anchor.line,0)}else if("inplace"==insertAt){if(vim.visualMode)return}else"lastEdit"==insertAt&&(head=getLastEditPos(cm)||head);cm.setOption("disableInput",!1),actionArgs&&actionArgs.replace?(cm.toggleOverwrite(!0),cm.setOption("keyMap","vim-replace"),CodeMirror.signal(cm,"vim-mode-change",{mode:"replace"})):(cm.toggleOverwrite(!1),cm.setOption("keyMap","vim-insert"),CodeMirror.signal(cm,"vim-mode-change",{mode:"insert"})),vimGlobalState.macroModeState.isPlaying||(cm.on("change",onChange),CodeMirror.on(cm.getInputField(),"keydown",onKeyEventTargetKeyDown)),vim.visualMode&&exitVisualMode(cm),selectForInsert(cm,head,height)}},toggleVisualMode:function(cm,actionArgs,vim){var repeat=actionArgs.repeat,anchor=cm.getCursor(),head;vim.visualMode?vim.visualLine^actionArgs.linewise||vim.visualBlock^actionArgs.blockwise?(vim.visualLine=!!actionArgs.linewise,vim.visualBlock=!!actionArgs.blockwise,CodeMirror.signal(cm,"vim-mode-change",{mode:"visual",subMode:vim.visualLine?"linewise":vim.visualBlock?"blockwise":""}),updateCmSelection(cm)):exitVisualMode(cm):(vim.visualMode=!0,vim.visualLine=!!actionArgs.linewise,vim.visualBlock=!!actionArgs.blockwise,head=clipCursorToContent(cm,new Pos(anchor.line,anchor.ch+repeat-1)),vim.sel={anchor:anchor,head:head},CodeMirror.signal(cm,"vim-mode-change",{mode:"visual",subMode:vim.visualLine?"linewise":vim.visualBlock?"blockwise":""}),updateCmSelection(cm),updateMark(cm,vim,"<",cursorMin(anchor,head)),updateMark(cm,vim,">",cursorMax(anchor,head)))},reselectLastSelection:function(cm,_actionArgs,vim){var lastSelection=vim.lastSelection;if(vim.visualMode&&updateLastSelection(cm,vim),lastSelection){var anchor=lastSelection.anchorMark.find(),head=lastSelection.headMark.find();if(!anchor||!head)return;vim.sel={anchor:anchor,head:head},vim.visualMode=!0,vim.visualLine=lastSelection.visualLine,vim.visualBlock=lastSelection.visualBlock,updateCmSelection(cm),updateMark(cm,vim,"<",cursorMin(anchor,head)),updateMark(cm,vim,">",cursorMax(anchor,head)),CodeMirror.signal(cm,"vim-mode-change",{mode:"visual",subMode:vim.visualLine?"linewise":vim.visualBlock?"blockwise":""})}},joinLines:function(cm,actionArgs,vim){var curStart,curEnd;if(vim.visualMode){if(curStart=cm.getCursor("anchor"),cursorIsBefore(curEnd=cm.getCursor("head"),curStart)){var tmp=curEnd;curEnd=curStart,curStart=tmp}curEnd.ch=lineLength(cm,curEnd.line)-1}else{var repeat=Math.max(actionArgs.repeat,2);curStart=cm.getCursor(),curEnd=clipCursorToContent(cm,new Pos(curStart.line+repeat-1,1/0))}for(var finalCh=0,i=curStart.line;i1)var text=Array(actionArgs.repeat+1).join(text);var linewise=register.linewise,blockwise=register.blockwise,curPosFinal,idx;if(blockwise){text=text.split("\n"),linewise&&text.pop();for(var i=0;icm.lastLine()&&cm.replaceRange("\n",new Pos(line,0)),lineLength(cm,line)line.length&&(replaceTo=line.length),curEnd=new Pos(curStart.line,replaceTo)}if("\n"==replaceWith)vim.visualMode||cm.replaceRange("",curStart,curEnd),(CodeMirror.commands.newlineAndIndentContinueComment||CodeMirror.commands.newlineAndIndent)(cm);else{var replaceWithStr=cm.getRange(curStart,curEnd);if(replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith),vim.visualBlock){var spaces=new Array(cm.getOption("tabSize")+1).join(" ");replaceWithStr=(replaceWithStr=cm.getSelection()).replace(/\t/g,spaces).replace(/[^\n]/g,replaceWith).split("\n"),cm.replaceSelections(replaceWithStr)}else cm.replaceRange(replaceWithStr,curStart,curEnd);vim.visualMode?(curStart=cursorIsBefore(selections[0].anchor,selections[0].head)?selections[0].anchor:selections[0].head,cm.setCursor(curStart),exitVisualMode(cm,!1)):cm.setCursor(offsetCursor(curEnd,0,-1))}},incrementNumberToken:function(cm,actionArgs){for(var cur=cm.getCursor(),lineStr=cm.getLine(cur.line),re=/(-?)(?:(0x)([\da-f]+)|(0b|0|)(\d+))/gi,match,start,end,numberStr;null!==(match=re.exec(lineStr))&&(end=(start=match.index)+match[0].length,!(cur.ch"==mapped.slice(-11)){var prefixLen=mapped.length-11,pressedPrefix=pressed.slice(0,prefixLen),mappedPrefix=mapped.slice(0,prefixLen);return pressedPrefix==mappedPrefix&&pressed.length>prefixLen?"full":0==mappedPrefix.indexOf(pressedPrefix)&&"partial"}return pressed==mapped?"full":0==mapped.indexOf(pressed)&&"partial"}function lastChar(keys){var match=/^.*(<[^>]+>)$/.exec(keys),selectedCharacter=match?match[1]:keys.slice(-1);if(selectedCharacter.length>1)switch(selectedCharacter){case"":selectedCharacter="\n";break;case"":selectedCharacter=" ";break;default:selectedCharacter=""}return selectedCharacter}function repeatFn(cm,fn,repeat){return function(){for(var i=0;i2&&(cur2=cursorMin.apply(void 0,Array.prototype.slice.call(arguments,1))),cursorIsBefore(cur1,cur2)?cur1:cur2}function cursorMax(cur1,cur2){return arguments.length>2&&(cur2=cursorMax.apply(void 0,Array.prototype.slice.call(arguments,1))),cursorIsBefore(cur1,cur2)?cur2:cur1}function cursorIsBetween(cur1,cur2,cur3){var cur1before2=cursorIsBefore(cur1,cur2),cur2before3=cursorIsBefore(cur2,cur3);return cur1before2&&cur2before3}function lineLength(cm,lineNum){return cm.getLine(lineNum).length}function trim(s){return s.trim?s.trim():s.replace(/^\s+|\s+$/g,"")}function escapeRegex(s){return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g,"\\$1")}function extendLineToColumn(cm,lineNum,column){var endCh=lineLength(cm,lineNum),spaces=new Array(column-endCh+1).join(" ");cm.setCursor(new Pos(lineNum,endCh)),cm.replaceRange(spaces,cm.getCursor())}function selectBlock(cm,selectionEnd){var selections=[],ranges=cm.listSelections(),head=copyCursor(cm.clipPos(selectionEnd)),isClipped=!cursorEqual(selectionEnd,head),curHead,primIndex=getIndex(ranges,cm.getCursor("head")),wasClipped=cursorEqual(ranges[primIndex].head,ranges[primIndex].anchor),max=ranges.length-1,index=max-primIndex>primIndex?max:0,base=ranges[index].anchor,firstLine=Math.min(base.line,head.line),lastLine=Math.max(base.line,head.line),baseCh=base.ch,headCh=head.ch,dir=ranges[index].head.ch-baseCh,newDir=headCh-baseCh;dir>0&&newDir<=0?(baseCh++,isClipped||headCh--):dir<0&&newDir>=0?(baseCh--,wasClipped||headCh++):dir<0&&-1==newDir&&(baseCh--,headCh++);for(var line=firstLine;line<=lastLine;line++){var range={anchor:new Pos(line,baseCh),head:new Pos(line,headCh)};selections.push(range)}return cm.setSelections(selections),selectionEnd.ch=headCh,base.ch=baseCh,base}function selectForInsert(cm,head,height){for(var sel=[],i=0;ilastLine&&(head.line=lastLine),head.ch=lineLength(cm,head.line)}return{ranges:[{anchor:anchor,head:head}],primary:0}}if("block"==mode){var top=Math.min(anchor.line,head.line),fromCh=anchor.ch,bottom=Math.max(anchor.line,head.line),toCh=head.ch;fromCh0&&line&&isWhiteSpaceString(line);line=lines.pop())curEnd.line--,curEnd.ch=0;line?(curEnd.line--,curEnd.ch=lineLength(cm,curEnd.line)):curEnd.ch=0}}function expandSelectionToLine(_cm,curStart,curEnd){curStart.ch=0,curEnd.ch=0,curEnd.line++}function findFirstNonWhiteSpaceCharacter(text){if(!text)return 0;var firstNonWS=text.search(/\S/);return-1==firstNonWS?text.length:firstNonWS}function expandWordUnderCursor(cm,inclusive,_forward,bigWord,noSymbol){for(var cur=getHead(cm),line=cm.getLine(cur.line),idx=cur.ch,test=noSymbol?wordCharTest[0]:bigWordCharTest[0];!test(line.charAt(idx));)if(++idx>=line.length)return null;bigWord?test=bigWordCharTest[0]:(test=wordCharTest[0])(line.charAt(idx))||(test=wordCharTest[1]);for(var end=idx,start=idx;test(line.charAt(end))&&end=0;)start--;if(start++,inclusive){for(var wordEnd=end;/\s/.test(line.charAt(end))&&end0;)start--;start||(start=wordStart)}}return{start:new Pos(cur.line,start),end:new Pos(cur.line,end)}}function expandTagUnderCursor(cm,head,inclusive){var cur=head;if(!CodeMirror.findMatchingTag||!CodeMirror.findEnclosingTag)return{start:cur,end:cur};var tags=CodeMirror.findMatchingTag(cm,head)||CodeMirror.findEnclosingTag(cm,head);return tags&&tags.open&&tags.close?inclusive?{start:tags.open.from,end:tags.close.to}:{start:tags.open.to,end:tags.close.from}:{start:cur,end:cur}}function recordJumpPosition(cm,oldCur,newCur){cursorEqual(oldCur,newCur)||vimGlobalState.jumpList.add(cm,oldCur,newCur)}function recordLastCharacterSearch(increment,args){vimGlobalState.lastCharacterSearch.increment=increment,vimGlobalState.lastCharacterSearch.forward=args.forward,vimGlobalState.lastCharacterSearch.selectedCharacter=args.selectedCharacter}var symbolToMode={"(":"bracket",")":"bracket","{":"bracket","}":"bracket","[":"section","]":"section","*":"comment","/":"comment",m:"method",M:"method","#":"preprocess"},findSymbolModes={bracket:{isComplete:function(state){if(state.nextCh===state.symb){if(state.depth++,state.depth>=1)return!0}else state.nextCh===state.reverseSymb&&state.depth--;return!1}},section:{init:function(state){state.curMoveThrough=!0,state.symb=(state.forward?"]":"[")===state.symb?"{":"}"},isComplete:function(state){return 0===state.index&&state.nextCh===state.symb}},comment:{isComplete:function(state){var found="*"===state.lastCh&&"/"===state.nextCh;return state.lastCh=state.nextCh,found}},method:{init:function(state){state.symb="m"===state.symb?"{":"}",state.reverseSymb="{"===state.symb?"}":"{"},isComplete:function(state){return state.nextCh===state.symb}},preprocess:{init:function(state){state.index=0},isComplete:function(state){if("#"===state.nextCh){var token=state.lineText.match(/^#(\w+)/)[1];if("endif"===token){if(state.forward&&0===state.depth)return!0;state.depth++}else if("if"===token){if(!state.forward&&0===state.depth)return!0;state.depth--}if("else"===token&&0===state.depth)return!0}return!1}}};function findSymbol(cm,repeat,forward,symb){var cur=copyCursor(cm.getCursor()),increment=forward?1:-1,endLine=forward?cm.lineCount():-1,curCh=cur.ch,line=cur.line,lineText=cm.getLine(line),state={lineText:lineText,nextCh:lineText.charAt(curCh),lastCh:null,index:curCh,symb:symb,reverseSymb:(forward?{")":"(","}":"{"}:{"(":")","{":"}"})[symb],forward:forward,depth:0,curMoveThrough:!1},mode=symbolToMode[symb];if(!mode)return cur;var init=findSymbolModes[mode].init,isComplete=findSymbolModes[mode].isComplete;for(init&&init(state);line!==endLine&&repeat;){if(state.index+=increment,state.nextCh=state.lineText.charAt(state.index),!state.nextCh){if(line+=increment,state.lineText=cm.getLine(line)||"",increment>0)state.index=0;else{var lineLen=state.lineText.length;state.index=lineLen>0?lineLen-1:0}state.nextCh=state.lineText.charAt(state.index)}isComplete(state)&&(cur.line=line,cur.ch=state.index,repeat--)}return state.nextCh||state.curMoveThrough?new Pos(line,state.index):cur}function findWord(cm,cur,forward,bigWord,emptyLineIsWord){var lineNum=cur.line,pos=cur.ch,line=cm.getLine(lineNum),dir=forward?1:-1,charTests=bigWord?bigWordCharTest:wordCharTest;if(emptyLineIsWord&&""==line){if(lineNum+=dir,line=cm.getLine(lineNum),!isLine(cm,lineNum))return null;pos=forward?0:line.length}for(;;){if(emptyLineIsWord&&""==line)return{from:0,to:0,line:lineNum};for(var stop=dir>0?line.length:-1,wordStart=stop,wordEnd=stop;pos!=stop;){for(var foundWord=!1,i=0;i0?0:line.length}}function moveToWord(cm,cur,repeat,forward,wordEnd,bigWord){var curStart=copyCursor(cur),words=[];(forward&&!wordEnd||!forward&&wordEnd)&&repeat++;for(var emptyLineIsWord=!(forward&&wordEnd),i=0;i0;)isBoundary(i,dir)&&repeat--,i+=dir;return new Pos(i,0)}var vim=cm.state.vim;if(vim.visualLine&&isBoundary(line,1,!0)){var anchor=vim.sel.anchor;isBoundary(anchor.line,-1,!0)&&(inclusive&&anchor.line==line||(line+=1))}var startState=isEmpty(line);for(i=line;i<=max&&repeat;i++)isBoundary(i,1,!0)&&(inclusive&&isEmpty(i)==startState||repeat--);for(end=new Pos(i,0),i>max&&!startState?startState=!0:inclusive=!1,i=line;i>min&&(inclusive&&isEmpty(i)!=startState&&i!=line||!isBoundary(i,-1,!0));i--);return{start:start=new Pos(i,0),end:end}}function getSentence(cm,cur,repeat,dir,inclusive){function nextChar(curr){curr.pos+curr.dir<0||curr.pos+curr.dir>=curr.line.length?curr.line=null:curr.pos+=curr.dir}function forward(cm,ln,pos,dir){var line,curr={line:cm.getLine(ln),ln:ln,pos:pos,dir:dir};if(""===curr.line)return{ln:curr.ln,pos:curr.pos};var lastSentencePos=curr.pos;for(nextChar(curr);null!==curr.line;){if(lastSentencePos=curr.pos,isEndOfSentenceSymbol(curr.line[curr.pos])){if(inclusive){for(nextChar(curr);null!==curr.line&&isWhiteSpaceString(curr.line[curr.pos]);)lastSentencePos=curr.pos,nextChar(curr);return{ln:curr.ln,pos:lastSentencePos+1}}return{ln:curr.ln,pos:curr.pos+1}}nextChar(curr)}return{ln:curr.ln,pos:lastSentencePos+1}}function reverse(cm,ln,pos,dir){var line=cm.getLine(ln),curr={line:line,ln:ln,pos:pos,dir:dir};if(""===curr.line)return{ln:curr.ln,pos:curr.pos};var lastSentencePos=curr.pos;for(nextChar(curr);null!==curr.line;){if(isWhiteSpaceString(curr.line[curr.pos])||isEndOfSentenceSymbol(curr.line[curr.pos])){if(isEndOfSentenceSymbol(curr.line[curr.pos]))return inclusive&&isWhiteSpaceString(curr.line[curr.pos+1])?{ln:curr.ln,pos:curr.pos+1}:{ln:curr.ln,pos:lastSentencePos}}else lastSentencePos=curr.pos;nextChar(curr)}return curr.line=line,inclusive&&isWhiteSpaceString(curr.line[curr.pos])?{ln:curr.ln,pos:curr.pos}:{ln:curr.ln,pos:lastSentencePos}}for(var curr_index={ln:cur.line,pos:cur.ch};repeat>0;)curr_index=dir<0?reverse(cm,curr_index.ln,curr_index.pos,dir):forward(cm,curr_index.ln,curr_index.pos,dir),repeat--;return new Pos(curr_index.ln,curr_index.pos)}function findSentence(cm,cur,repeat,dir){function nextChar(cm,idx){if(idx.pos+idx.dir<0||idx.pos+idx.dir>=idx.line.length){if(idx.ln+=idx.dir,!isLine(cm,idx.ln))return idx.line=null,idx.ln=null,void(idx.pos=null);idx.line=cm.getLine(idx.ln),idx.pos=idx.dir>0?0:idx.line.length-1}else idx.pos+=idx.dir}function forward(cm,ln,pos,dir){var line,stop=""===(line=cm.getLine(ln)),curr={line:line,ln:ln,pos:pos,dir:dir},last_valid={ln:curr.ln,pos:curr.pos},skip_empty_lines=""===curr.line;for(nextChar(cm,curr);null!==curr.line;){if(last_valid.ln=curr.ln,last_valid.pos=curr.pos,""===curr.line&&!skip_empty_lines)return{ln:curr.ln,pos:curr.pos};if(stop&&""!==curr.line&&!isWhiteSpaceString(curr.line[curr.pos]))return{ln:curr.ln,pos:curr.pos};!isEndOfSentenceSymbol(curr.line[curr.pos])||stop||curr.pos!==curr.line.length-1&&!isWhiteSpaceString(curr.line[curr.pos+1])||(stop=!0),nextChar(cm,curr)}var line=cm.getLine(last_valid.ln);last_valid.pos=0;for(var i=line.length-1;i>=0;--i)if(!isWhiteSpaceString(line[i])){last_valid.pos=i;break}return last_valid}function reverse(cm,ln,pos,dir){var line,curr={line:line=cm.getLine(ln),ln:ln,pos:pos,dir:dir},last_valid={ln:curr.ln,pos:null},skip_empty_lines=""===curr.line;for(nextChar(cm,curr);null!==curr.line;){if(""===curr.line&&!skip_empty_lines)return null!==last_valid.pos?last_valid:{ln:curr.ln,pos:curr.pos};if(isEndOfSentenceSymbol(curr.line[curr.pos])&&null!==last_valid.pos&&(curr.ln!==last_valid.ln||curr.pos+1!==last_valid.pos))return last_valid;""===curr.line||isWhiteSpaceString(curr.line[curr.pos])||(skip_empty_lines=!1,last_valid={ln:curr.ln,pos:curr.pos}),nextChar(cm,curr)}var line=cm.getLine(last_valid.ln);last_valid.pos=0;for(var i=0;i0;)curr_index=dir<0?reverse(cm,curr_index.ln,curr_index.pos,dir):forward(cm,curr_index.ln,curr_index.pos,dir),repeat--;return new Pos(curr_index.ln,curr_index.pos)}function selectCompanionObject(cm,head,symb,inclusive){var cur=head,start,end,bracketRegexp={"(":/[()]/,")":/[()]/,"[":/[[\]]/,"]":/[[\]]/,"{":/[{}]/,"}":/[{}]/,"<":/[<>]/,">":/[<>]/}[symb],openSym={"(":"(",")":"(","[":"[","]":"[","{":"{","}":"{","<":"<",">":"<"}[symb],curChar,offset=cm.getLine(cur.line).charAt(cur.ch)===openSym?1:0;if(start=cm.scanForBracket(new Pos(cur.line,cur.ch+offset),-1,void 0,{bracketRegex:bracketRegexp}),end=cm.scanForBracket(new Pos(cur.line,cur.ch+offset),1,void 0,{bracketRegex:bracketRegexp}),!start||!end)return{start:cur,end:cur};if(start=start.pos,end=end.pos,start.line==end.line&&start.ch>end.ch||start.line>end.line){var tmp=start;start=end,end=tmp}return inclusive?end.ch+=1:start.ch+=1,{start:start,end:end}}function findBeginningAndEnd(cm,head,symb,inclusive){var cur=copyCursor(head),line,chars=cm.getLine(cur.line).split(""),start,end,i,len,firstIndex=chars.indexOf(symb);if(cur.ch-1&&!start;i--)chars[i]==symb&&(start=i+1);else start=cur.ch+1;if(start&&!end)for(i=start,len=chars.length;i=start&&pos<=end:pos==start}function getUserVisibleLines(cm){var scrollInfo=cm.getScrollInfo(),occludeToleranceTop=6,occludeToleranceBottom=10,from=cm.coordsChar({left:0,top:6+scrollInfo.top},"local"),bottomY=scrollInfo.clientHeight-10+scrollInfo.top,to=cm.coordsChar({left:0,top:bottomY},"local");return{top:from.line,bottom:to.line}}function getMarkPos(cm,vim,markName){if("'"==markName||"`"==markName)return vimGlobalState.jumpList.find(cm,-1)||new Pos(0,0);if("."==markName)return getLastEditPos(cm);var mark=vim.marks[markName];return mark&&mark.find()}function getLastEditPos(cm){for(var done=cm.doc.history.done,i=done.length;i--;)if(done[i].changes)return copyCursor(done[i].changes[0].to)}var ExCommandDispatcher=function(){this.buildCommandMap_()};ExCommandDispatcher.prototype={processCommand:function(cm,input,opt_params){var that=this;cm.operation(function(){cm.curOp.isVimOp=!0,that._processCommand(cm,input,opt_params)})},_processCommand:function(cm,input,opt_params){var vim=cm.state.vim,commandHistoryRegister=vimGlobalState.registerController.getRegister(":"),previousCommand=commandHistoryRegister.toString();vim.visualMode&&exitVisualMode(cm);var inputStream=new CodeMirror.StringStream(input);commandHistoryRegister.setText(input);var params=opt_params||{},command,commandName;params.input=input;try{this.parseInput_(cm,inputStream,params)}catch(e){throw showConfirm(cm,e.toString()),e}if(params.commandName){if(command=this.matchCommand_(params.commandName)){if(commandName=command.name,command.excludeFromCommandHistory&&commandHistoryRegister.setText(previousCommand),this.parseCommandArgs_(inputStream,params,command),"exToKey"==command.type){for(var i=0;i@~])/);return result.commandName=commandMatch?commandMatch[1]:inputStream.match(/.*/)[0],result},parseLineSpec_:function(cm,inputStream){var numberMatch=inputStream.match(/^(\d+)/);if(numberMatch)return parseInt(numberMatch[1],10)-1;switch(inputStream.next()){case".":return this.parseLineSpecOffset_(inputStream,cm.getCursor().line);case"$":return this.parseLineSpecOffset_(inputStream,cm.lastLine());case"'":var markName=inputStream.next(),markPos=getMarkPos(cm,cm.state.vim,markName);if(!markPos)throw new Error("Mark not set");return this.parseLineSpecOffset_(inputStream,markPos.line);case"-":case"+":return inputStream.backUp(1),this.parseLineSpecOffset_(inputStream,cm.getCursor().line);default:return void inputStream.backUp(1)}},parseLineSpecOffset_:function(inputStream,line){var offsetMatch=inputStream.match(/^([+-])?(\d+)/);if(offsetMatch){var offset=parseInt(offsetMatch[2],10);"-"==offsetMatch[1]?line-=offset:line+=offset}return line},parseCommandArgs_:function(inputStream,params,command){if(!inputStream.eol()){params.argString=inputStream.match(/.*/)[0];var delim=command.argDelimiter||/\s+/,args=trim(params.argString).split(delim);args.length&&args[0]&&(params.args=args)}},matchCommand_:function(commandName){for(var i=commandName.length;i>0;i--){var prefix=commandName.substring(0,i);if(this.commandMap_[prefix]){var command=this.commandMap_[prefix];if(0===command.name.indexOf(commandName))return command}}return null},buildCommandMap_:function(){this.commandMap_={};for(var i=0;i1)return"Invalid arguments";number=(decimal?"decimal":hex&&"hex")||octal&&"octal"}opts[2]&&(pattern=new RegExp(opts[2].substr(1,opts[2].length-2),ignoreCase?"i":""))}}var err=parseArgs();if(err)showConfirm(cm,err+": "+params.argString);else{var lineStart=params.line||cm.firstLine(),lineEnd=params.lineEnd||params.line||cm.lastLine();if(lineStart!=lineEnd){var curStart=new Pos(lineStart,0),curEnd=new Pos(lineEnd,lineLength(cm,lineEnd)),text=cm.getRange(curStart,curEnd).split("\n"),numberRegex=pattern||("decimal"==number?/(-?)([\d]+)/:"hex"==number?/(-?)(?:0x)?([0-9a-f]+)/i:"octal"==number?/([0-7]+)/:null),radix="decimal"==number?10:"hex"==number?16:"octal"==number?8:null,numPart=[],textPart=[];if(number||pattern)for(var i=0;i=finish)return void showConfirm(cm,"Invalid argument: "+params.argString.substring(count));for(var j=0;j<=finish-start;j++){var mark=String.fromCharCode(start+j);delete state.marks[mark]}}else delete state.marks[sym]}else showConfirm(cm,"Argument required")}},exCommandDispatcher=new ExCommandDispatcher;function doReplace(cm,confirm,global,lineStart,lineEnd,searchCursor,query,replaceWith,callback){cm.state.vim.exMode=!0;var done=!1,lastPos,modifiedLineNumber,joined;function replaceAll(){cm.operation(function(){for(;!done;)replace(),next();stop()})}function replace(){var text,newText=cm.getRange(searchCursor.from(),searchCursor.to()).replace(query,replaceWith),unmodifiedLineNumber=searchCursor.to().line;searchCursor.replace(newText),modifiedLineNumber=searchCursor.to().line,lineEnd+=modifiedLineNumber-unmodifiedLineNumber,joined=modifiedLineNumber1&&(repeatLastEdit(cm,vim,vim.insertModeRepeat-1,!0),vim.lastEditInputState.repeatOverride=vim.insertModeRepeat),delete vim.insertModeRepeat,vim.insertMode=!1,cm.setCursor(cm.getCursor().line,cm.getCursor().ch-1),cm.setOption("keyMap","vim"),cm.setOption("disableInput",!0),cm.toggleOverwrite(!1),insertModeChangeRegister.setText(lastChange.changes.join("")),CodeMirror.signal(cm,"vim-mode-change",{mode:"normal"}),macroModeState.isRecording&&logInsertModeChange(macroModeState)}function _mapCommand(command){defaultKeymap.unshift(command)}function mapCommand(keys,type,name,args,extra){var command={keys:keys,type:type};for(var key in command[type]=name,command[type+"Args"]=args,extra)command[key]=extra[key];_mapCommand(command)}function executeMacroRegister(cm,vim,macroModeState,registerName){var register=vimGlobalState.registerController.getRegister(registerName);if(":"==registerName)return register.keyBuffer[0]&&exCommandDispatcher.processCommand(cm,register.keyBuffer[0]),void(macroModeState.isPlaying=!1);var keyBuffer=register.keyBuffer,imc=0;macroModeState.isPlaying=!0,macroModeState.replaySearchQueries=register.searchQueries.slice(0);for(var i=0;i|<\w+>|./.exec(text))[0],text=text.substring(match.index+key.length),vimApi.handleKey(cm,key,"macro"),vim.insertMode){var changes=register.insertModeChanges[imc++].changes;vimGlobalState.macroModeState.lastInsertModeChanges.changes=changes,repeatInsertModeChanges(cm,changes,1),exitInsertMode(cm)}macroModeState.isPlaying=!1}function logKey(macroModeState,key){if(!macroModeState.isPlaying){var registerName=macroModeState.latestRegister,register=vimGlobalState.registerController.getRegister(registerName);register&®ister.pushText(key)}}function logInsertModeChange(macroModeState){if(!macroModeState.isPlaying){var registerName=macroModeState.latestRegister,register=vimGlobalState.registerController.getRegister(registerName);register&®ister.pushInsertModeChanges&®ister.pushInsertModeChanges(macroModeState.lastInsertModeChanges)}}function logSearchQuery(macroModeState,query){if(!macroModeState.isPlaying){var registerName=macroModeState.latestRegister,register=vimGlobalState.registerController.getRegister(registerName);register&®ister.pushSearchQuery&®ister.pushSearchQuery(query)}}function onChange(cm,changeObj){var macroModeState=vimGlobalState.macroModeState,lastChange=macroModeState.lastInsertModeChanges;if(!macroModeState.isPlaying)for(;changeObj;){if(lastChange.expectCursorActivityForChange=!0,lastChange.ignoreCount>1)lastChange.ignoreCount--;else if("+input"==changeObj.origin||"paste"==changeObj.origin||void 0===changeObj.origin){var selectionCount=cm.listSelections().length;selectionCount>1&&(lastChange.ignoreCount=selectionCount);var text=changeObj.text.join("\n");lastChange.maybeReset&&(lastChange.changes=[],lastChange.maybeReset=!1),text&&(cm.state.overwrite&&!/\n/.test(text)?lastChange.changes.push([text]):lastChange.changes.push(text))}changeObj=changeObj.next}}function onCursorActivity(cm){var vim=cm.state.vim;if(vim.insertMode){var macroModeState=vimGlobalState.macroModeState;if(macroModeState.isPlaying)return;var lastChange=macroModeState.lastInsertModeChanges;lastChange.expectCursorActivityForChange?lastChange.expectCursorActivityForChange=!1:lastChange.maybeReset=!0}else cm.curOp.isVimOp||handleExternalSelection(cm,vim)}function handleExternalSelection(cm,vim){var anchor=cm.getCursor("anchor"),head=cm.getCursor("head");if(vim.visualMode&&!cm.somethingSelected()?exitVisualMode(cm,!1):vim.visualMode||vim.insertMode||!cm.somethingSelected()||(vim.visualMode=!0,vim.visualLine=!1,CodeMirror.signal(cm,"vim-mode-change",{mode:"visual"})),vim.visualMode){var headOffset=cursorIsBefore(head,anchor)?0:-1,anchorOffset=cursorIsBefore(head,anchor)?-1:0;head=offsetCursor(head,0,headOffset),anchor=offsetCursor(anchor,0,anchorOffset),vim.sel={anchor:anchor,head:head},updateMark(cm,vim,"<",cursorMin(head,anchor)),updateMark(cm,vim,">",cursorMax(head,anchor))}else vim.insertMode||(vim.lastHPos=cm.getCursor().ch)}function InsertModeKey(keyName){this.keyName=keyName}function onKeyEventTargetKeyDown(e){var macroModeState,lastChange=vimGlobalState.macroModeState.lastInsertModeChanges,keyName=CodeMirror.keyName(e);function onKeyFound(){return lastChange.maybeReset&&(lastChange.changes=[],lastChange.maybeReset=!1),lastChange.changes.push(new InsertModeKey(keyName)),!0}keyName&&(-1==keyName.indexOf("Delete")&&-1==keyName.indexOf("Backspace")||CodeMirror.lookupKey(keyName,"vim-insert",onKeyFound))}function repeatLastEdit(cm,vim,repeat,repeatForInsert){var macroModeState=vimGlobalState.macroModeState;macroModeState.isPlaying=!0;var isAction=!!vim.lastEditActionCommand,cachedInputState=vim.inputState;function repeatCommand(){isAction?commandDispatcher.processAction(cm,vim,vim.lastEditActionCommand):commandDispatcher.evalInput(cm,vim)}function repeatInsert(repeat){if(macroModeState.lastInsertModeChanges.changes.length>0){repeat=vim.lastEditActionCommand?repeat:1;var changeObject=macroModeState.lastInsertModeChanges;repeatInsertModeChanges(cm,changeObject.changes,repeat)}}if(vim.inputState=vim.lastEditInputState,isAction&&vim.lastEditActionCommand.interlaceInsertRepeat)for(var i=0;i"!=key||vim.insertMode||vim.visualMode||!wasMultiselect||""!=vim.status)if(visualBlock||!wasMultiselect||cm.inVirtualSelectionMode)isHandled=vimApi.handleKey(cm,key,origin);else{var old=cloneVimState(vim);cm.operation(function(){cm.curOp.isVimOp=!0,cm.forEachSelection(function(){var head=cm.getCursor("head"),anchor=cm.getCursor("anchor"),headOffset=cursorIsBefore(head,anchor)?0:-1,anchorOffset=cursorIsBefore(head,anchor)?-1:0;head=offsetCursor(head,0,headOffset),anchor=offsetCursor(anchor,0,anchorOffset),cm.state.vim.sel.head=head,cm.state.vim.sel.anchor=anchor,isHandled=vimApi.handleKey(cm,key,origin),cm.virtualSelection&&(cm.state.vim=cloneVimState(old))}),cm.curOp.cursorActivity&&!isHandled&&(cm.curOp.cursorActivity=!1),cm.state.vim=vim},!0)}else clearInputState(cm);return!isHandled||vim.visualMode||vim.insert||vim.visualMode==cm.somethingSelected()||handleExternalSelection(cm,vim),isHandled}return CodeMirror.keyMap.vim={attach:attachVimMap,detach:detachVimMap,call:cmKey},defineOption("insertModeEscKeysTimeout",200,"number"),CodeMirror.keyMap["vim-insert"]={fallthrough:["default"],attach:attachVimMap,detach:detachVimMap,call:cmKey},CodeMirror.keyMap["vim-replace"]={Backspace:"goCharLeft",fallthrough:["vim-insert"],attach:attachVimMap,detach:detachVimMap,call:cmKey},resetVimGlobalState(),vimApi}function initVim(CodeMirror5){return CodeMirror5.Vim=initVim$1(CodeMirror5),CodeMirror5.Vim}CodeMirror.Vim=initVim(CodeMirror)});