gump 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (359) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +24 -0
  3. data/Gemfile +4 -0
  4. data/LICENSE.txt +22 -0
  5. data/README.md +71 -0
  6. data/Rakefile +2 -0
  7. data/bin/gump +37 -0
  8. data/gump.gemspec +17 -0
  9. data/lib/gump.rb +50 -0
  10. data/lib/version.rb +3 -0
  11. data/server/assets/css/style.css +6949 -0
  12. data/server/assets/images/arrow.png +0 -0
  13. data/server/assets/images/logo.png +0 -0
  14. data/server/assets/js/bootstrap/dist/css/bootstrap-theme.css +347 -0
  15. data/server/assets/js/bootstrap/dist/css/bootstrap-theme.css.map +1 -0
  16. data/server/assets/js/bootstrap/dist/css/bootstrap-theme.min.css +7 -0
  17. data/server/assets/js/bootstrap/dist/css/bootstrap.css +5785 -0
  18. data/server/assets/js/bootstrap/dist/css/bootstrap.css.map +1 -0
  19. data/server/assets/js/bootstrap/dist/css/bootstrap.min.css +7 -0
  20. data/server/assets/js/bootstrap/dist/fonts/glyphicons-halflings-regular.eot +0 -0
  21. data/server/assets/js/bootstrap/dist/fonts/glyphicons-halflings-regular.svg +229 -0
  22. data/server/assets/js/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf +0 -0
  23. data/server/assets/js/bootstrap/dist/fonts/glyphicons-halflings-regular.woff +0 -0
  24. data/server/assets/js/bootstrap/dist/js/bootstrap.js +1951 -0
  25. data/server/assets/js/bootstrap/dist/js/bootstrap.min.js +6 -0
  26. data/server/assets/js/jquery.codemirror/.gitattributes +8 -0
  27. data/server/assets/js/jquery.codemirror/.gitignore +6 -0
  28. data/server/assets/js/jquery.codemirror/.travis.yml +3 -0
  29. data/server/assets/js/jquery.codemirror/AUTHORS +255 -0
  30. data/server/assets/js/jquery.codemirror/CONTRIBUTING.md +72 -0
  31. data/server/assets/js/jquery.codemirror/LICENSE +19 -0
  32. data/server/assets/js/jquery.codemirror/README.md +11 -0
  33. data/server/assets/js/jquery.codemirror/addon/comment/comment.js +145 -0
  34. data/server/assets/js/jquery.codemirror/addon/comment/continuecomment.js +54 -0
  35. data/server/assets/js/jquery.codemirror/addon/dialog/dialog.css +32 -0
  36. data/server/assets/js/jquery.codemirror/addon/dialog/dialog.js +121 -0
  37. data/server/assets/js/jquery.codemirror/addon/display/fullscreen.css +6 -0
  38. data/server/assets/js/jquery.codemirror/addon/display/fullscreen.js +31 -0
  39. data/server/assets/js/jquery.codemirror/addon/display/placeholder.js +48 -0
  40. data/server/assets/js/jquery.codemirror/addon/edit/closebrackets.js +82 -0
  41. data/server/assets/js/jquery.codemirror/addon/edit/closetag.js +89 -0
  42. data/server/assets/js/jquery.codemirror/addon/edit/continuelist.js +25 -0
  43. data/server/assets/js/jquery.codemirror/addon/edit/matchbrackets.js +87 -0
  44. data/server/assets/js/jquery.codemirror/addon/edit/matchtags.js +56 -0
  45. data/server/assets/js/jquery.codemirror/addon/edit/trailingspace.js +15 -0
  46. data/server/assets/js/jquery.codemirror/addon/fold/brace-fold.js +93 -0
  47. data/server/assets/js/jquery.codemirror/addon/fold/comment-fold.js +40 -0
  48. data/server/assets/js/jquery.codemirror/addon/fold/foldcode.js +75 -0
  49. data/server/assets/js/jquery.codemirror/addon/fold/foldgutter.css +21 -0
  50. data/server/assets/js/jquery.codemirror/addon/fold/foldgutter.js +124 -0
  51. data/server/assets/js/jquery.codemirror/addon/fold/indent-fold.js +30 -0
  52. data/server/assets/js/jquery.codemirror/addon/fold/xml-fold.js +167 -0
  53. data/server/assets/js/jquery.codemirror/addon/hint/anyword-hint.js +34 -0
  54. data/server/assets/js/jquery.codemirror/addon/hint/css-hint.js +50 -0
  55. data/server/assets/js/jquery.codemirror/addon/hint/html-hint.js +337 -0
  56. data/server/assets/js/jquery.codemirror/addon/hint/javascript-hint.js +131 -0
  57. data/server/assets/js/jquery.codemirror/addon/hint/pig-hint.js +121 -0
  58. data/server/assets/js/jquery.codemirror/addon/hint/python-hint.js +95 -0
  59. data/server/assets/js/jquery.codemirror/addon/hint/show-hint.css +38 -0
  60. data/server/assets/js/jquery.codemirror/addon/hint/show-hint.js +286 -0
  61. data/server/assets/js/jquery.codemirror/addon/hint/sql-hint.js +105 -0
  62. data/server/assets/js/jquery.codemirror/addon/hint/xml-hint.js +69 -0
  63. data/server/assets/js/jquery.codemirror/addon/lint/coffeescript-lint.js +27 -0
  64. data/server/assets/js/jquery.codemirror/addon/lint/css-lint.js +19 -0
  65. data/server/assets/js/jquery.codemirror/addon/lint/javascript-lint.js +126 -0
  66. data/server/assets/js/jquery.codemirror/addon/lint/json-lint.js +17 -0
  67. data/server/assets/js/jquery.codemirror/addon/lint/lint.css +73 -0
  68. data/server/assets/js/jquery.codemirror/addon/lint/lint.js +203 -0
  69. data/server/assets/js/jquery.codemirror/addon/merge/dep/diff_match_patch.js +50 -0
  70. data/server/assets/js/jquery.codemirror/addon/merge/merge.css +92 -0
  71. data/server/assets/js/jquery.codemirror/addon/merge/merge.js +474 -0
  72. data/server/assets/js/jquery.codemirror/addon/mode/loadmode.js +51 -0
  73. data/server/assets/js/jquery.codemirror/addon/mode/multiplex.js +101 -0
  74. data/server/assets/js/jquery.codemirror/addon/mode/multiplex_test.js +30 -0
  75. data/server/assets/js/jquery.codemirror/addon/mode/overlay.js +59 -0
  76. data/server/assets/js/jquery.codemirror/addon/runmode/colorize.js +29 -0
  77. data/server/assets/js/jquery.codemirror/addon/runmode/runmode-standalone.js +136 -0
  78. data/server/assets/js/jquery.codemirror/addon/runmode/runmode.js +56 -0
  79. data/server/assets/js/jquery.codemirror/addon/runmode/runmode.node.js +103 -0
  80. data/server/assets/js/jquery.codemirror/addon/scroll/scrollpastend.js +34 -0
  81. data/server/assets/js/jquery.codemirror/addon/search/match-highlighter.js +91 -0
  82. data/server/assets/js/jquery.codemirror/addon/search/search.js +133 -0
  83. data/server/assets/js/jquery.codemirror/addon/search/searchcursor.js +143 -0
  84. data/server/assets/js/jquery.codemirror/addon/selection/active-line.js +39 -0
  85. data/server/assets/js/jquery.codemirror/addon/selection/mark-selection.js +108 -0
  86. data/server/assets/js/jquery.codemirror/addon/tern/tern.css +85 -0
  87. data/server/assets/js/jquery.codemirror/addon/tern/tern.js +632 -0
  88. data/server/assets/js/jquery.codemirror/addon/tern/worker.js +41 -0
  89. data/server/assets/js/jquery.codemirror/addon/wrap/hardwrap.js +99 -0
  90. data/server/assets/js/jquery.codemirror/bin/authors.sh +6 -0
  91. data/server/assets/js/jquery.codemirror/bin/compress +92 -0
  92. data/server/assets/js/jquery.codemirror/bin/lint +16 -0
  93. data/server/assets/js/jquery.codemirror/bin/source-highlight +61 -0
  94. data/server/assets/js/jquery.codemirror/bower.json +15 -0
  95. data/server/assets/js/jquery.codemirror/demo/activeline.html +78 -0
  96. data/server/assets/js/jquery.codemirror/demo/anywordhint.html +79 -0
  97. data/server/assets/js/jquery.codemirror/demo/bidi.html +74 -0
  98. data/server/assets/js/jquery.codemirror/demo/btree.html +86 -0
  99. data/server/assets/js/jquery.codemirror/demo/buffers.html +109 -0
  100. data/server/assets/js/jquery.codemirror/demo/changemode.html +59 -0
  101. data/server/assets/js/jquery.codemirror/demo/closebrackets.html +63 -0
  102. data/server/assets/js/jquery.codemirror/demo/closetag.html +40 -0
  103. data/server/assets/js/jquery.codemirror/demo/complete.html +80 -0
  104. data/server/assets/js/jquery.codemirror/demo/emacs.html +75 -0
  105. data/server/assets/js/jquery.codemirror/demo/folding.html +75 -0
  106. data/server/assets/js/jquery.codemirror/demo/fullscreen.html +130 -0
  107. data/server/assets/js/jquery.codemirror/demo/hardwrap.html +69 -0
  108. data/server/assets/js/jquery.codemirror/demo/html5complete.html +54 -0
  109. data/server/assets/js/jquery.codemirror/demo/indentwrap.html +58 -0
  110. data/server/assets/js/jquery.codemirror/demo/lint.html +171 -0
  111. data/server/assets/js/jquery.codemirror/demo/loadmode.html +49 -0
  112. data/server/assets/js/jquery.codemirror/demo/marker.html +52 -0
  113. data/server/assets/js/jquery.codemirror/demo/markselection.html +45 -0
  114. data/server/assets/js/jquery.codemirror/demo/matchhighlighter.html +47 -0
  115. data/server/assets/js/jquery.codemirror/demo/matchtags.html +49 -0
  116. data/server/assets/js/jquery.codemirror/demo/merge.html +82 -0
  117. data/server/assets/js/jquery.codemirror/demo/multiplex.html +75 -0
  118. data/server/assets/js/jquery.codemirror/demo/mustache.html +68 -0
  119. data/server/assets/js/jquery.codemirror/demo/placeholder.html +45 -0
  120. data/server/assets/js/jquery.codemirror/demo/preview.html +88 -0
  121. data/server/assets/js/jquery.codemirror/demo/resize.html +58 -0
  122. data/server/assets/js/jquery.codemirror/demo/runmode.html +62 -0
  123. data/server/assets/js/jquery.codemirror/demo/search.html +94 -0
  124. data/server/assets/js/jquery.codemirror/demo/spanaffectswrapping_shim.html +85 -0
  125. data/server/assets/js/jquery.codemirror/demo/tern.html +129 -0
  126. data/server/assets/js/jquery.codemirror/demo/theme.html +121 -0
  127. data/server/assets/js/jquery.codemirror/demo/trailingspace.html +48 -0
  128. data/server/assets/js/jquery.codemirror/demo/variableheight.html +67 -0
  129. data/server/assets/js/jquery.codemirror/demo/vim.html +74 -0
  130. data/server/assets/js/jquery.codemirror/demo/visibletabs.html +62 -0
  131. data/server/assets/js/jquery.codemirror/demo/widget.html +85 -0
  132. data/server/assets/js/jquery.codemirror/demo/xmlcomplete.html +116 -0
  133. data/server/assets/js/jquery.codemirror/index.html +192 -0
  134. data/server/assets/js/jquery.codemirror/keymap/emacs.js +387 -0
  135. data/server/assets/js/jquery.codemirror/keymap/extra.js +43 -0
  136. data/server/assets/js/jquery.codemirror/keymap/vim.js +3703 -0
  137. data/server/assets/js/jquery.codemirror/lib/codemirror.css +263 -0
  138. data/server/assets/js/jquery.codemirror/lib/codemirror.js +5944 -0
  139. data/server/assets/js/jquery.codemirror/mode/apl/apl.js +160 -0
  140. data/server/assets/js/jquery.codemirror/mode/apl/index.html +72 -0
  141. data/server/assets/js/jquery.codemirror/mode/asterisk/asterisk.js +183 -0
  142. data/server/assets/js/jquery.codemirror/mode/asterisk/index.html +154 -0
  143. data/server/assets/js/jquery.codemirror/mode/clike/clike.js +362 -0
  144. data/server/assets/js/jquery.codemirror/mode/clike/index.html +195 -0
  145. data/server/assets/js/jquery.codemirror/mode/clike/scala.html +767 -0
  146. data/server/assets/js/jquery.codemirror/mode/clojure/clojure.js +224 -0
  147. data/server/assets/js/jquery.codemirror/mode/clojure/index.html +88 -0
  148. data/server/assets/js/jquery.codemirror/mode/cobol/cobol.js +240 -0
  149. data/server/assets/js/jquery.codemirror/mode/cobol/index.html +210 -0
  150. data/server/assets/js/jquery.codemirror/mode/coffeescript/coffeescript.js +354 -0
  151. data/server/assets/js/jquery.codemirror/mode/coffeescript/index.html +740 -0
  152. data/server/assets/js/jquery.codemirror/mode/commonlisp/commonlisp.js +105 -0
  153. data/server/assets/js/jquery.codemirror/mode/commonlisp/index.html +177 -0
  154. data/server/assets/js/jquery.codemirror/mode/css/css.js +639 -0
  155. data/server/assets/js/jquery.codemirror/mode/css/index.html +70 -0
  156. data/server/assets/js/jquery.codemirror/mode/css/scss.html +157 -0
  157. data/server/assets/js/jquery.codemirror/mode/css/scss_test.js +93 -0
  158. data/server/assets/js/jquery.codemirror/mode/css/test.js +142 -0
  159. data/server/assets/js/jquery.codemirror/mode/d/d.js +205 -0
  160. data/server/assets/js/jquery.codemirror/mode/d/index.html +273 -0
  161. data/server/assets/js/jquery.codemirror/mode/diff/diff.js +32 -0
  162. data/server/assets/js/jquery.codemirror/mode/diff/index.html +117 -0
  163. data/server/assets/js/jquery.codemirror/mode/dtd/dtd.js +127 -0
  164. data/server/assets/js/jquery.codemirror/mode/dtd/index.html +89 -0
  165. data/server/assets/js/jquery.codemirror/mode/ecl/ecl.js +192 -0
  166. data/server/assets/js/jquery.codemirror/mode/ecl/index.html +52 -0
  167. data/server/assets/js/jquery.codemirror/mode/eiffel/eiffel.js +147 -0
  168. data/server/assets/js/jquery.codemirror/mode/eiffel/index.html +430 -0
  169. data/server/assets/js/jquery.codemirror/mode/erlang/erlang.js +484 -0
  170. data/server/assets/js/jquery.codemirror/mode/erlang/index.html +75 -0
  171. data/server/assets/js/jquery.codemirror/mode/fortran/fortran.js +173 -0
  172. data/server/assets/js/jquery.codemirror/mode/fortran/index.html +81 -0
  173. data/server/assets/js/jquery.codemirror/mode/gas/gas.js +330 -0
  174. data/server/assets/js/jquery.codemirror/mode/gas/index.html +68 -0
  175. data/server/assets/js/jquery.codemirror/mode/gfm/gfm.js +97 -0
  176. data/server/assets/js/jquery.codemirror/mode/gfm/index.html +82 -0
  177. data/server/assets/js/jquery.codemirror/mode/gfm/test.js +112 -0
  178. data/server/assets/js/jquery.codemirror/mode/gherkin/gherkin.js +168 -0
  179. data/server/assets/js/jquery.codemirror/mode/gherkin/index.html +48 -0
  180. data/server/assets/js/jquery.codemirror/mode/go/go.js +168 -0
  181. data/server/assets/js/jquery.codemirror/mode/go/index.html +85 -0
  182. data/server/assets/js/jquery.codemirror/mode/groovy/groovy.js +211 -0
  183. data/server/assets/js/jquery.codemirror/mode/groovy/index.html +84 -0
  184. data/server/assets/js/jquery.codemirror/mode/haml/haml.js +153 -0
  185. data/server/assets/js/jquery.codemirror/mode/haml/index.html +79 -0
  186. data/server/assets/js/jquery.codemirror/mode/haml/test.js +94 -0
  187. data/server/assets/js/jquery.codemirror/mode/haskell/haskell.js +250 -0
  188. data/server/assets/js/jquery.codemirror/mode/haskell/index.html +73 -0
  189. data/server/assets/js/jquery.codemirror/mode/haxe/haxe.js +429 -0
  190. data/server/assets/js/jquery.codemirror/mode/haxe/index.html +103 -0
  191. data/server/assets/js/jquery.codemirror/mode/htmlembedded/htmlembedded.js +73 -0
  192. data/server/assets/js/jquery.codemirror/mode/htmlembedded/index.html +60 -0
  193. data/server/assets/js/jquery.codemirror/mode/htmlmixed/htmlmixed.js +104 -0
  194. data/server/assets/js/jquery.codemirror/mode/htmlmixed/index.html +85 -0
  195. data/server/assets/js/jquery.codemirror/mode/http/http.js +98 -0
  196. data/server/assets/js/jquery.codemirror/mode/http/index.html +45 -0
  197. data/server/assets/js/jquery.codemirror/mode/index.html +114 -0
  198. data/server/assets/js/jquery.codemirror/mode/jade/index.html +66 -0
  199. data/server/assets/js/jquery.codemirror/mode/jade/jade.js +90 -0
  200. data/server/assets/js/jquery.codemirror/mode/javascript/index.html +107 -0
  201. data/server/assets/js/jquery.codemirror/mode/javascript/javascript.js +617 -0
  202. data/server/assets/js/jquery.codemirror/mode/javascript/test.js +72 -0
  203. data/server/assets/js/jquery.codemirror/mode/javascript/typescript.html +61 -0
  204. data/server/assets/js/jquery.codemirror/mode/jinja2/index.html +50 -0
  205. data/server/assets/js/jquery.codemirror/mode/jinja2/jinja2.js +42 -0
  206. data/server/assets/js/jquery.codemirror/mode/julia/index.html +187 -0
  207. data/server/assets/js/jquery.codemirror/mode/julia/julia.js +262 -0
  208. data/server/assets/js/jquery.codemirror/mode/less/index.html +753 -0
  209. data/server/assets/js/jquery.codemirror/mode/less/less.js +346 -0
  210. data/server/assets/js/jquery.codemirror/mode/livescript/index.html +459 -0
  211. data/server/assets/js/jquery.codemirror/mode/livescript/livescript.js +267 -0
  212. data/server/assets/js/jquery.codemirror/mode/livescript/livescript.ls +266 -0
  213. data/server/assets/js/jquery.codemirror/mode/lua/index.html +86 -0
  214. data/server/assets/js/jquery.codemirror/mode/lua/lua.js +144 -0
  215. data/server/assets/js/jquery.codemirror/mode/markdown/index.html +359 -0
  216. data/server/assets/js/jquery.codemirror/mode/markdown/markdown.js +560 -0
  217. data/server/assets/js/jquery.codemirror/mode/markdown/test.js +664 -0
  218. data/server/assets/js/jquery.codemirror/mode/meta.js +91 -0
  219. data/server/assets/js/jquery.codemirror/mode/mirc/index.html +161 -0
  220. data/server/assets/js/jquery.codemirror/mode/mirc/mirc.js +177 -0
  221. data/server/assets/js/jquery.codemirror/mode/nginx/index.html +181 -0
  222. data/server/assets/js/jquery.codemirror/mode/nginx/nginx.js +163 -0
  223. data/server/assets/js/jquery.codemirror/mode/ntriples/index.html +45 -0
  224. data/server/assets/js/jquery.codemirror/mode/ntriples/ntriples.js +170 -0
  225. data/server/assets/js/jquery.codemirror/mode/ocaml/index.html +146 -0
  226. data/server/assets/js/jquery.codemirror/mode/ocaml/ocaml.js +116 -0
  227. data/server/assets/js/jquery.codemirror/mode/octave/index.html +95 -0
  228. data/server/assets/js/jquery.codemirror/mode/octave/octave.js +118 -0
  229. data/server/assets/js/jquery.codemirror/mode/pascal/index.html +61 -0
  230. data/server/assets/js/jquery.codemirror/mode/pascal/pascal.js +94 -0
  231. data/server/assets/js/jquery.codemirror/mode/pegjs/index.html +66 -0
  232. data/server/assets/js/jquery.codemirror/mode/pegjs/pegjs.js +103 -0
  233. data/server/assets/js/jquery.codemirror/mode/perl/index.html +75 -0
  234. data/server/assets/js/jquery.codemirror/mode/perl/perl.js +816 -0
  235. data/server/assets/js/jquery.codemirror/mode/php/index.html +62 -0
  236. data/server/assets/js/jquery.codemirror/mode/php/php.js +132 -0
  237. data/server/assets/js/jquery.codemirror/mode/pig/index.html +55 -0
  238. data/server/assets/js/jquery.codemirror/mode/pig/pig.js +171 -0
  239. data/server/assets/js/jquery.codemirror/mode/properties/index.html +53 -0
  240. data/server/assets/js/jquery.codemirror/mode/properties/properties.js +63 -0
  241. data/server/assets/js/jquery.codemirror/mode/python/index.html +187 -0
  242. data/server/assets/js/jquery.codemirror/mode/python/python.js +368 -0
  243. data/server/assets/js/jquery.codemirror/mode/q/index.html +144 -0
  244. data/server/assets/js/jquery.codemirror/mode/q/q.js +124 -0
  245. data/server/assets/js/jquery.codemirror/mode/r/index.html +86 -0
  246. data/server/assets/js/jquery.codemirror/mode/r/r.js +141 -0
  247. data/server/assets/js/jquery.codemirror/mode/rpm/changes/changes.js +19 -0
  248. data/server/assets/js/jquery.codemirror/mode/rpm/changes/index.html +67 -0
  249. data/server/assets/js/jquery.codemirror/mode/rpm/spec/index.html +114 -0
  250. data/server/assets/js/jquery.codemirror/mode/rpm/spec/spec.css +5 -0
  251. data/server/assets/js/jquery.codemirror/mode/rpm/spec/spec.js +66 -0
  252. data/server/assets/js/jquery.codemirror/mode/rst/index.html +534 -0
  253. data/server/assets/js/jquery.codemirror/mode/rst/rst.js +560 -0
  254. data/server/assets/js/jquery.codemirror/mode/ruby/index.html +185 -0
  255. data/server/assets/js/jquery.codemirror/mode/ruby/ruby.js +247 -0
  256. data/server/assets/js/jquery.codemirror/mode/rust/index.html +61 -0
  257. data/server/assets/js/jquery.codemirror/mode/rust/rust.js +436 -0
  258. data/server/assets/js/jquery.codemirror/mode/sass/index.html +66 -0
  259. data/server/assets/js/jquery.codemirror/mode/sass/sass.js +330 -0
  260. data/server/assets/js/jquery.codemirror/mode/scheme/index.html +77 -0
  261. data/server/assets/js/jquery.codemirror/mode/scheme/scheme.js +232 -0
  262. data/server/assets/js/jquery.codemirror/mode/shell/index.html +66 -0
  263. data/server/assets/js/jquery.codemirror/mode/shell/shell.js +118 -0
  264. data/server/assets/js/jquery.codemirror/mode/sieve/index.html +93 -0
  265. data/server/assets/js/jquery.codemirror/mode/sieve/sieve.js +183 -0
  266. data/server/assets/js/jquery.codemirror/mode/smalltalk/index.html +68 -0
  267. data/server/assets/js/jquery.codemirror/mode/smalltalk/smalltalk.js +151 -0
  268. data/server/assets/js/jquery.codemirror/mode/smarty/index.html +136 -0
  269. data/server/assets/js/jquery.codemirror/mode/smarty/smarty.js +205 -0
  270. data/server/assets/js/jquery.codemirror/mode/smartymixed/index.html +114 -0
  271. data/server/assets/js/jquery.codemirror/mode/smartymixed/smartymixed.js +175 -0
  272. data/server/assets/js/jquery.codemirror/mode/sparql/index.html +54 -0
  273. data/server/assets/js/jquery.codemirror/mode/sparql/sparql.js +145 -0
  274. data/server/assets/js/jquery.codemirror/mode/sql/index.html +75 -0
  275. data/server/assets/js/jquery.codemirror/mode/sql/sql.js +365 -0
  276. data/server/assets/js/jquery.codemirror/mode/stex/index.html +110 -0
  277. data/server/assets/js/jquery.codemirror/mode/stex/stex.js +246 -0
  278. data/server/assets/js/jquery.codemirror/mode/stex/test.js +120 -0
  279. data/server/assets/js/jquery.codemirror/mode/tcl/index.html +143 -0
  280. data/server/assets/js/jquery.codemirror/mode/tcl/tcl.js +131 -0
  281. data/server/assets/js/jquery.codemirror/mode/tiddlywiki/index.html +155 -0
  282. data/server/assets/js/jquery.codemirror/mode/tiddlywiki/tiddlywiki.css +14 -0
  283. data/server/assets/js/jquery.codemirror/mode/tiddlywiki/tiddlywiki.js +353 -0
  284. data/server/assets/js/jquery.codemirror/mode/tiki/index.html +95 -0
  285. data/server/assets/js/jquery.codemirror/mode/tiki/tiki.css +26 -0
  286. data/server/assets/js/jquery.codemirror/mode/tiki/tiki.js +308 -0
  287. data/server/assets/js/jquery.codemirror/mode/toml/index.html +73 -0
  288. data/server/assets/js/jquery.codemirror/mode/toml/toml.js +71 -0
  289. data/server/assets/js/jquery.codemirror/mode/turtle/index.html +51 -0
  290. data/server/assets/js/jquery.codemirror/mode/turtle/turtle.js +145 -0
  291. data/server/assets/js/jquery.codemirror/mode/vb/index.html +103 -0
  292. data/server/assets/js/jquery.codemirror/mode/vb/vb.js +259 -0
  293. data/server/assets/js/jquery.codemirror/mode/vbscript/index.html +55 -0
  294. data/server/assets/js/jquery.codemirror/mode/vbscript/vbscript.js +334 -0
  295. data/server/assets/js/jquery.codemirror/mode/velocity/index.html +119 -0
  296. data/server/assets/js/jquery.codemirror/mode/velocity/velocity.js +186 -0
  297. data/server/assets/js/jquery.codemirror/mode/verilog/index.html +132 -0
  298. data/server/assets/js/jquery.codemirror/mode/verilog/verilog.js +182 -0
  299. data/server/assets/js/jquery.codemirror/mode/xml/index.html +57 -0
  300. data/server/assets/js/jquery.codemirror/mode/xml/xml.js +345 -0
  301. data/server/assets/js/jquery.codemirror/mode/xquery/index.html +210 -0
  302. data/server/assets/js/jquery.codemirror/mode/xquery/test.js +64 -0
  303. data/server/assets/js/jquery.codemirror/mode/xquery/xquery.js +432 -0
  304. data/server/assets/js/jquery.codemirror/mode/yaml/index.html +80 -0
  305. data/server/assets/js/jquery.codemirror/mode/yaml/yaml.js +97 -0
  306. data/server/assets/js/jquery.codemirror/mode/z80/index.html +52 -0
  307. data/server/assets/js/jquery.codemirror/mode/z80/z80.js +85 -0
  308. data/server/assets/js/jquery.codemirror/package.json +19 -0
  309. data/server/assets/js/jquery.codemirror/test/comment_test.js +51 -0
  310. data/server/assets/js/jquery.codemirror/test/doc_test.js +329 -0
  311. data/server/assets/js/jquery.codemirror/test/driver.js +139 -0
  312. data/server/assets/js/jquery.codemirror/test/emacs_test.js +135 -0
  313. data/server/assets/js/jquery.codemirror/test/index.html +209 -0
  314. data/server/assets/js/jquery.codemirror/test/lint/acorn.js +1593 -0
  315. data/server/assets/js/jquery.codemirror/test/lint/lint.js +139 -0
  316. data/server/assets/js/jquery.codemirror/test/lint/walk.js +216 -0
  317. data/server/assets/js/jquery.codemirror/test/mode_test.css +10 -0
  318. data/server/assets/js/jquery.codemirror/test/mode_test.js +200 -0
  319. data/server/assets/js/jquery.codemirror/test/phantom_driver.js +31 -0
  320. data/server/assets/js/jquery.codemirror/test/run.js +34 -0
  321. data/server/assets/js/jquery.codemirror/test/test.js +1562 -0
  322. data/server/assets/js/jquery.codemirror/test/vim_test.js +2391 -0
  323. data/server/assets/js/jquery.codemirror/theme/3024-day.css +34 -0
  324. data/server/assets/js/jquery.codemirror/theme/3024-night.css +34 -0
  325. data/server/assets/js/jquery.codemirror/theme/ambiance-mobile.css +5 -0
  326. data/server/assets/js/jquery.codemirror/theme/ambiance.css +70 -0
  327. data/server/assets/js/jquery.codemirror/theme/base16-dark.css +34 -0
  328. data/server/assets/js/jquery.codemirror/theme/base16-light.css +34 -0
  329. data/server/assets/js/jquery.codemirror/theme/blackboard.css +28 -0
  330. data/server/assets/js/jquery.codemirror/theme/cobalt.css +21 -0
  331. data/server/assets/js/jquery.codemirror/theme/eclipse.css +23 -0
  332. data/server/assets/js/jquery.codemirror/theme/elegant.css +13 -0
  333. data/server/assets/js/jquery.codemirror/theme/erlang-dark.css +30 -0
  334. data/server/assets/js/jquery.codemirror/theme/lesser-dark.css +47 -0
  335. data/server/assets/js/jquery.codemirror/theme/mbo.css +37 -0
  336. data/server/assets/js/jquery.codemirror/theme/midnight.css +43 -0
  337. data/server/assets/js/jquery.codemirror/theme/monokai.css +29 -0
  338. data/server/assets/js/jquery.codemirror/theme/neat.css +12 -0
  339. data/server/assets/js/jquery.codemirror/theme/night.css +24 -0
  340. data/server/assets/js/jquery.codemirror/theme/paraiso-dark.css +34 -0
  341. data/server/assets/js/jquery.codemirror/theme/paraiso-light.css +34 -0
  342. data/server/assets/js/jquery.codemirror/theme/rubyblue.css +23 -0
  343. data/server/assets/js/jquery.codemirror/theme/solarized.css +180 -0
  344. data/server/assets/js/jquery.codemirror/theme/the-matrix.css +26 -0
  345. data/server/assets/js/jquery.codemirror/theme/tomorrow-night-eighties.css +34 -0
  346. data/server/assets/js/jquery.codemirror/theme/twilight.css +28 -0
  347. data/server/assets/js/jquery.codemirror/theme/vibrant-ink.css +30 -0
  348. data/server/assets/js/jquery.codemirror/theme/xq-dark.css +49 -0
  349. data/server/assets/js/jquery.codemirror/theme/xq-light.css +43 -0
  350. data/server/assets/js/jquery.js +4 -0
  351. data/server/assets/js/jquery.nanoscroller/jquery.nanoscroller.js +2 -0
  352. data/server/assets/js/jquery.nanoscroller/nanoscroller.css +49 -0
  353. data/server/assets/js/tester.js +161 -0
  354. data/server/config.ru +2 -0
  355. data/server/server.rb +41 -0
  356. data/server/views/_content.erb +65 -0
  357. data/server/views/_sidebar.erb +32 -0
  358. data/server/views/index.erb +40 -0
  359. metadata +402 -0
@@ -0,0 +1,387 @@
1
+ (function() {
2
+ "use strict";
3
+
4
+ var Pos = CodeMirror.Pos;
5
+ function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
6
+
7
+ // Kill 'ring'
8
+
9
+ var killRing = [];
10
+ function addToRing(str) {
11
+ killRing.push(str);
12
+ if (killRing.length > 50) killRing.shift();
13
+ }
14
+ function growRingTop(str) {
15
+ if (!killRing.length) return addToRing(str);
16
+ killRing[killRing.length - 1] += str;
17
+ }
18
+ function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || ""; }
19
+ function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }
20
+
21
+ var lastKill = null;
22
+
23
+ function kill(cm, from, to, mayGrow, text) {
24
+ if (text == null) text = cm.getRange(from, to);
25
+
26
+ if (mayGrow && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen))
27
+ growRingTop(text);
28
+ else
29
+ addToRing(text);
30
+ cm.replaceRange("", from, to, "+delete");
31
+
32
+ if (mayGrow) lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()};
33
+ else lastKill = null;
34
+ }
35
+
36
+ // Boundaries of various units
37
+
38
+ function byChar(cm, pos, dir) {
39
+ return cm.findPosH(pos, dir, "char", true);
40
+ }
41
+
42
+ function byWord(cm, pos, dir) {
43
+ return cm.findPosH(pos, dir, "word", true);
44
+ }
45
+
46
+ function byLine(cm, pos, dir) {
47
+ return cm.findPosV(pos, dir, "line", cm.doc.sel.goalColumn);
48
+ }
49
+
50
+ function byPage(cm, pos, dir) {
51
+ return cm.findPosV(pos, dir, "page", cm.doc.sel.goalColumn);
52
+ }
53
+
54
+ function byParagraph(cm, pos, dir) {
55
+ var no = pos.line, line = cm.getLine(no);
56
+ var sawText = /\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch));
57
+ var fst = cm.firstLine(), lst = cm.lastLine();
58
+ for (;;) {
59
+ no += dir;
60
+ if (no < fst || no > lst)
61
+ return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null));
62
+ line = cm.getLine(no);
63
+ var hasText = /\S/.test(line);
64
+ if (hasText) sawText = true;
65
+ else if (sawText) return Pos(no, 0);
66
+ }
67
+ }
68
+
69
+ function bySentence(cm, pos, dir) {
70
+ var line = pos.line, ch = pos.ch;
71
+ var text = cm.getLine(pos.line), sawWord = false;
72
+ for (;;) {
73
+ var next = text.charAt(ch + (dir < 0 ? -1 : 0));
74
+ if (!next) { // End/beginning of line reached
75
+ if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
76
+ text = cm.getLine(line + dir);
77
+ if (!/\S/.test(text)) return Pos(line, ch);
78
+ line += dir;
79
+ ch = dir < 0 ? text.length : 0;
80
+ continue;
81
+ }
82
+ if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0));
83
+ if (!sawWord) sawWord = /\w/.test(next);
84
+ ch += dir;
85
+ }
86
+ }
87
+
88
+ function byExpr(cm, pos, dir) {
89
+ var wrap;
90
+ if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, true))
91
+ && wrap.match && (wrap.forward ? 1 : -1) == dir)
92
+ return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to;
93
+
94
+ for (var first = true;; first = false) {
95
+ var token = cm.getTokenAt(pos);
96
+ var after = Pos(pos.line, dir < 0 ? token.start : token.end);
97
+ if (first && dir > 0 && token.end == pos.ch || !/\w/.test(token.string)) {
98
+ var newPos = cm.findPosH(after, dir, "char");
99
+ if (posEq(after, newPos)) return pos;
100
+ else pos = newPos;
101
+ } else {
102
+ return after;
103
+ }
104
+ }
105
+ }
106
+
107
+ // Prefixes (only crudely supported)
108
+
109
+ function getPrefix(cm, precise) {
110
+ var digits = cm.state.emacsPrefix;
111
+ if (!digits) return precise ? null : 1;
112
+ clearPrefix(cm);
113
+ return digits == "-" ? -1 : Number(digits);
114
+ }
115
+
116
+ function repeated(cmd) {
117
+ var f = typeof cmd == "string" ? function(cm) { cm.execCommand(cmd); } : cmd;
118
+ return function(cm) {
119
+ var prefix = getPrefix(cm);
120
+ f(cm);
121
+ for (var i = 1; i < prefix; ++i) f(cm);
122
+ };
123
+ }
124
+
125
+ function findEnd(cm, by, dir) {
126
+ var pos = cm.getCursor(), prefix = getPrefix(cm);
127
+ if (prefix < 0) { dir = -dir; prefix = -prefix; }
128
+ for (var i = 0; i < prefix; ++i) {
129
+ var newPos = by(cm, pos, dir);
130
+ if (posEq(newPos, pos)) break;
131
+ pos = newPos;
132
+ }
133
+ return pos;
134
+ }
135
+
136
+ function move(by, dir) {
137
+ var f = function(cm) {
138
+ cm.extendSelection(findEnd(cm, by, dir));
139
+ };
140
+ f.motion = true;
141
+ return f;
142
+ }
143
+
144
+ function killTo(cm, by, dir) {
145
+ kill(cm, cm.getCursor(), findEnd(cm, by, dir), true);
146
+ }
147
+
148
+ function addPrefix(cm, digit) {
149
+ if (cm.state.emacsPrefix) {
150
+ if (digit != "-") cm.state.emacsPrefix += digit;
151
+ return;
152
+ }
153
+ // Not active yet
154
+ cm.state.emacsPrefix = digit;
155
+ cm.on("keyHandled", maybeClearPrefix);
156
+ cm.on("inputRead", maybeDuplicateInput);
157
+ }
158
+
159
+ var prefixPreservingKeys = {"Alt-G": true, "Ctrl-X": true, "Ctrl-Q": true, "Ctrl-U": true};
160
+
161
+ function maybeClearPrefix(cm, arg) {
162
+ if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))
163
+ clearPrefix(cm);
164
+ }
165
+
166
+ function clearPrefix(cm) {
167
+ cm.state.emacsPrefix = null;
168
+ cm.off("keyHandled", maybeClearPrefix);
169
+ cm.off("inputRead", maybeDuplicateInput);
170
+ }
171
+
172
+ function maybeDuplicateInput(cm, event) {
173
+ var dup = getPrefix(cm);
174
+ if (dup > 1 && event.origin == "+input") {
175
+ var one = event.text.join("\n"), txt = "";
176
+ for (var i = 1; i < dup; ++i) txt += one;
177
+ cm.replaceSelection(txt, "end", "+input");
178
+ }
179
+ }
180
+
181
+ function addPrefixMap(cm) {
182
+ cm.state.emacsPrefixMap = true;
183
+ cm.addKeyMap(prefixMap);
184
+ cm.on("keyHandled", maybeRemovePrefixMap);
185
+ cm.on("inputRead", maybeRemovePrefixMap);
186
+ }
187
+
188
+ function maybeRemovePrefixMap(cm, arg) {
189
+ if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return;
190
+ cm.removeKeyMap(prefixMap);
191
+ cm.state.emacsPrefixMap = false;
192
+ cm.off("keyHandled", maybeRemovePrefixMap);
193
+ cm.off("inputRead", maybeRemovePrefixMap);
194
+ }
195
+
196
+ // Utilities
197
+
198
+ function setMark(cm) {
199
+ cm.setCursor(cm.getCursor());
200
+ cm.setExtending(true);
201
+ cm.on("change", function() { cm.setExtending(false); });
202
+ }
203
+
204
+ function getInput(cm, msg, f) {
205
+ if (cm.openDialog)
206
+ cm.openDialog(msg + ": <input type=\"text\" style=\"width: 10em\"/>", f, {bottom: true});
207
+ else
208
+ f(prompt(msg, ""));
209
+ }
210
+
211
+ function operateOnWord(cm, op) {
212
+ var start = cm.getCursor(), end = cm.findPosH(start, 1, "word");
213
+ cm.replaceRange(op(cm.getRange(start, end)), start, end);
214
+ cm.setCursor(end);
215
+ }
216
+
217
+ function toEnclosingExpr(cm) {
218
+ var pos = cm.getCursor(), line = pos.line, ch = pos.ch;
219
+ var stack = [];
220
+ while (line >= cm.firstLine()) {
221
+ var text = cm.getLine(line);
222
+ for (var i = ch == null ? text.length : ch; i > 0;) {
223
+ var ch = text.charAt(--i);
224
+ if (ch == ")")
225
+ stack.push("(");
226
+ else if (ch == "]")
227
+ stack.push("[");
228
+ else if (ch == "}")
229
+ stack.push("{");
230
+ else if (/[\(\{\[]/.test(ch) && (!stack.length || stack.pop() != ch))
231
+ return cm.extendSelection(Pos(line, i));
232
+ }
233
+ --line; ch = null;
234
+ }
235
+ }
236
+
237
+ // Actual keymap
238
+
239
+ var keyMap = CodeMirror.keyMap.emacs = {
240
+ "Ctrl-W": function(cm) {kill(cm, cm.getCursor("start"), cm.getCursor("end"));},
241
+ "Ctrl-K": repeated(function(cm) {
242
+ var start = cm.getCursor(), end = cm.clipPos(Pos(start.line));
243
+ var text = cm.getRange(start, end);
244
+ if (!/\S/.test(text)) {
245
+ text += "\n";
246
+ end = Pos(start.line + 1, 0);
247
+ }
248
+ kill(cm, start, end, true, text);
249
+ }),
250
+ "Alt-W": function(cm) {
251
+ addToRing(cm.getSelection());
252
+ },
253
+ "Ctrl-Y": function(cm) {
254
+ var start = cm.getCursor();
255
+ cm.replaceRange(getFromRing(getPrefix(cm)), start, start, "paste");
256
+ cm.setSelection(start, cm.getCursor());
257
+ },
258
+ "Alt-Y": function(cm) {cm.replaceSelection(popFromRing());},
259
+
260
+ "Ctrl-Space": setMark, "Ctrl-Shift-2": setMark,
261
+
262
+ "Ctrl-F": move(byChar, 1), "Ctrl-B": move(byChar, -1),
263
+ "Right": move(byChar, 1), "Left": move(byChar, -1),
264
+ "Ctrl-D": function(cm) { killTo(cm, byChar, 1); },
265
+ "Delete": function(cm) { killTo(cm, byChar, 1); },
266
+ "Ctrl-H": function(cm) { killTo(cm, byChar, -1); },
267
+ "Backspace": function(cm) { killTo(cm, byChar, -1); },
268
+
269
+ "Alt-F": move(byWord, 1), "Alt-B": move(byWord, -1),
270
+ "Alt-D": function(cm) { killTo(cm, byWord, 1); },
271
+ "Alt-Backspace": function(cm) { killTo(cm, byWord, -1); },
272
+
273
+ "Ctrl-N": move(byLine, 1), "Ctrl-P": move(byLine, -1),
274
+ "Down": move(byLine, 1), "Up": move(byLine, -1),
275
+ "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
276
+ "End": "goLineEnd", "Home": "goLineStart",
277
+
278
+ "Alt-V": move(byPage, -1), "Ctrl-V": move(byPage, 1),
279
+ "PageUp": move(byPage, -1), "PageDown": move(byPage, 1),
280
+
281
+ "Ctrl-Up": move(byParagraph, -1), "Ctrl-Down": move(byParagraph, 1),
282
+
283
+ "Alt-A": move(bySentence, -1), "Alt-E": move(bySentence, 1),
284
+ "Alt-K": function(cm) { killTo(cm, bySentence, 1); },
285
+
286
+ "Ctrl-Alt-K": function(cm) { killTo(cm, byExpr, 1); },
287
+ "Ctrl-Alt-Backspace": function(cm) { killTo(cm, byExpr, -1); },
288
+ "Ctrl-Alt-F": move(byExpr, 1), "Ctrl-Alt-B": move(byExpr, -1),
289
+
290
+ "Shift-Ctrl-Alt-2": function(cm) {
291
+ cm.setSelection(findEnd(cm, byExpr, 1), cm.getCursor());
292
+ },
293
+ "Ctrl-Alt-T": function(cm) {
294
+ var leftStart = byExpr(cm, cm.getCursor(), -1), leftEnd = byExpr(cm, leftStart, 1);
295
+ var rightEnd = byExpr(cm, leftEnd, 1), rightStart = byExpr(cm, rightEnd, -1);
296
+ cm.replaceRange(cm.getRange(rightStart, rightEnd) + cm.getRange(leftEnd, rightStart) +
297
+ cm.getRange(leftStart, leftEnd), leftStart, rightEnd);
298
+ },
299
+ "Ctrl-Alt-U": repeated(toEnclosingExpr),
300
+
301
+ "Alt-Space": function(cm) {
302
+ var pos = cm.getCursor(), from = pos.ch, to = pos.ch, text = cm.getLine(pos.line);
303
+ while (from && /\s/.test(text.charAt(from - 1))) --from;
304
+ while (to < text.length && /\s/.test(text.charAt(to))) ++to;
305
+ cm.replaceRange(" ", Pos(pos.line, from), Pos(pos.line, to));
306
+ },
307
+ "Ctrl-O": repeated(function(cm) { cm.replaceSelection("\n", "start"); }),
308
+ "Ctrl-T": repeated(function(cm) {
309
+ var pos = cm.getCursor();
310
+ if (pos.ch < cm.getLine(pos.line).length) pos = Pos(pos.line, pos.ch + 1);
311
+ var from = cm.findPosH(pos, -2, "char");
312
+ var range = cm.getRange(from, pos);
313
+ if (range.length != 2) return;
314
+ cm.setSelection(from, pos);
315
+ cm.replaceSelection(range.charAt(1) + range.charAt(0), "end");
316
+ }),
317
+
318
+ "Alt-C": repeated(function(cm) {
319
+ operateOnWord(cm, function(w) {
320
+ var letter = w.search(/\w/);
321
+ if (letter == -1) return w;
322
+ return w.slice(0, letter) + w.charAt(letter).toUpperCase() + w.slice(letter + 1).toLowerCase();
323
+ });
324
+ }),
325
+ "Alt-U": repeated(function(cm) {
326
+ operateOnWord(cm, function(w) { return w.toUpperCase(); });
327
+ }),
328
+ "Alt-L": repeated(function(cm) {
329
+ operateOnWord(cm, function(w) { return w.toLowerCase(); });
330
+ }),
331
+
332
+ "Alt-;": "toggleComment",
333
+
334
+ "Ctrl-/": repeated("undo"), "Shift-Ctrl--": repeated("undo"),
335
+ "Ctrl-Z": repeated("undo"), "Cmd-Z": repeated("undo"),
336
+ "Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd",
337
+ "Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": "clearSearch", "Shift-Alt-5": "replace",
338
+ "Alt-/": "autocomplete",
339
+ "Ctrl-J": "newlineAndIndent", "Enter": false, "Tab": "indentAuto",
340
+
341
+ "Alt-G": function(cm) {cm.setOption("keyMap", "emacs-Alt-G");},
342
+ "Ctrl-X": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-X");},
343
+ "Ctrl-Q": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-Q");},
344
+ "Ctrl-U": addPrefixMap
345
+ };
346
+
347
+ CodeMirror.keyMap["emacs-Ctrl-X"] = {
348
+ "Tab": function(cm) {
349
+ cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit"));
350
+ },
351
+ "Ctrl-X": function(cm) {
352
+ cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor"));
353
+ },
354
+
355
+ "Ctrl-S": "save", "Ctrl-W": "save", "S": "saveAll", "F": "open", "U": repeated("undo"), "K": "close",
356
+ "Delete": function(cm) { kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), true); },
357
+ auto: "emacs", nofallthrough: true, disableInput: true
358
+ };
359
+
360
+ CodeMirror.keyMap["emacs-Alt-G"] = {
361
+ "G": function(cm) {
362
+ var prefix = getPrefix(cm, true);
363
+ if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1);
364
+
365
+ getInput(cm, "Goto line", function(str) {
366
+ var num;
367
+ if (str && !isNaN(num = Number(str)) && num == num|0 && num > 0)
368
+ cm.setCursor(num - 1);
369
+ });
370
+ },
371
+ auto: "emacs", nofallthrough: true, disableInput: true
372
+ };
373
+
374
+ CodeMirror.keyMap["emacs-Ctrl-Q"] = {
375
+ "Tab": repeated("insertTab"),
376
+ auto: "emacs", nofallthrough: true
377
+ };
378
+
379
+ var prefixMap = {"Ctrl-G": clearPrefix};
380
+ function regPrefix(d) {
381
+ prefixMap[d] = function(cm) { addPrefix(cm, d); };
382
+ keyMap["Ctrl-" + d] = function(cm) { addPrefix(cm, d); };
383
+ prefixPreservingKeys["Ctrl-" + d] = true;
384
+ }
385
+ for (var i = 0; i < 10; ++i) regPrefix(String(i));
386
+ regPrefix("-");
387
+ })();
@@ -0,0 +1,43 @@
1
+ // A number of additional default bindings that are too obscure to
2
+ // include in the core codemirror.js file.
3
+
4
+ (function() {
5
+ "use strict";
6
+
7
+ var Pos = CodeMirror.Pos;
8
+
9
+ function moveLines(cm, start, end, dist) {
10
+ if (!dist || start > end) return 0;
11
+
12
+ var from = cm.clipPos(Pos(start, 0)), to = cm.clipPos(Pos(end));
13
+ var text = cm.getRange(from, to);
14
+
15
+ if (start <= cm.firstLine())
16
+ cm.replaceRange("", from, Pos(to.line + 1, 0));
17
+ else
18
+ cm.replaceRange("", Pos(from.line - 1), to);
19
+ var target = from.line + dist;
20
+ if (target <= cm.firstLine()) {
21
+ cm.replaceRange(text + "\n", Pos(target, 0));
22
+ return cm.firstLine() - from.line;
23
+ } else {
24
+ var targetPos = cm.clipPos(Pos(target - 1));
25
+ cm.replaceRange("\n" + text, targetPos);
26
+ return targetPos.line + 1 - from.line;
27
+ }
28
+ }
29
+
30
+ function moveSelectedLines(cm, dist) {
31
+ var head = cm.getCursor("head"), anchor = cm.getCursor("anchor");
32
+ cm.operation(function() {
33
+ var moved = moveLines(cm, Math.min(head.line, anchor.line), Math.max(head.line, anchor.line), dist);
34
+ cm.setSelection(Pos(anchor.line + moved, anchor.ch), Pos(head.line + moved, head.ch));
35
+ });
36
+ }
37
+
38
+ CodeMirror.commands.moveLinesUp = function(cm) { moveSelectedLines(cm, -1); };
39
+ CodeMirror.commands.moveLinesDown = function(cm) { moveSelectedLines(cm, 1); };
40
+
41
+ CodeMirror.keyMap["default"]["Alt-Up"] = "moveLinesUp";
42
+ CodeMirror.keyMap["default"]["Alt-Down"] = "moveLinesDown";
43
+ })();
@@ -0,0 +1,3703 @@
1
+ /**
2
+ * Supported keybindings:
3
+ *
4
+ * Motion:
5
+ * h, j, k, l
6
+ * gj, gk
7
+ * e, E, w, W, b, B, ge, gE
8
+ * f<character>, F<character>, t<character>, T<character>
9
+ * $, ^, 0, -, +, _
10
+ * gg, G
11
+ * %
12
+ * '<character>, `<character>
13
+ *
14
+ * Operator:
15
+ * d, y, c
16
+ * dd, yy, cc
17
+ * g~, g~g~
18
+ * >, <, >>, <<
19
+ *
20
+ * Operator-Motion:
21
+ * x, X, D, Y, C, ~
22
+ *
23
+ * Action:
24
+ * a, i, s, A, I, S, o, O
25
+ * zz, z., z<CR>, zt, zb, z-
26
+ * J
27
+ * u, Ctrl-r
28
+ * m<character>
29
+ * r<character>
30
+ *
31
+ * Modes:
32
+ * ESC - leave insert mode, visual mode, and clear input state.
33
+ * Ctrl-[, Ctrl-c - same as ESC.
34
+ *
35
+ * Registers: unamed, -, a-z, A-Z, 0-9
36
+ * (Does not respect the special case for number registers when delete
37
+ * operator is made with these commands: %, (, ), , /, ?, n, N, {, } )
38
+ * TODO: Implement the remaining registers.
39
+ * Marks: a-z, A-Z, and 0-9
40
+ * TODO: Implement the remaining special marks. They have more complex
41
+ * behavior.
42
+ *
43
+ * Events:
44
+ * 'vim-mode-change' - raised on the editor anytime the current mode changes,
45
+ * Event object: {mode: "visual", subMode: "linewise"}
46
+ *
47
+ * Code structure:
48
+ * 1. Default keymap
49
+ * 2. Variable declarations and short basic helpers
50
+ * 3. Instance (External API) implementation
51
+ * 4. Internal state tracking objects (input state, counter) implementation
52
+ * and instanstiation
53
+ * 5. Key handler (the main command dispatcher) implementation
54
+ * 6. Motion, operator, and action implementations
55
+ * 7. Helper functions for the key handler, motions, operators, and actions
56
+ * 8. Set up Vim to work as a keymap for CodeMirror.
57
+ */
58
+
59
+ (function() {
60
+ 'use strict';
61
+
62
+ var defaultKeymap = [
63
+ // Key to key mapping. This goes first to make it possible to override
64
+ // existing mappings.
65
+ { keys: ['<Left>'], type: 'keyToKey', toKeys: ['h'] },
66
+ { keys: ['<Right>'], type: 'keyToKey', toKeys: ['l'] },
67
+ { keys: ['<Up>'], type: 'keyToKey', toKeys: ['k'] },
68
+ { keys: ['<Down>'], type: 'keyToKey', toKeys: ['j'] },
69
+ { keys: ['<Space>'], type: 'keyToKey', toKeys: ['l'] },
70
+ { keys: ['<BS>'], type: 'keyToKey', toKeys: ['h'] },
71
+ { keys: ['<C-Space>'], type: 'keyToKey', toKeys: ['W'] },
72
+ { keys: ['<C-BS>'], type: 'keyToKey', toKeys: ['B'] },
73
+ { keys: ['<S-Space>'], type: 'keyToKey', toKeys: ['w'] },
74
+ { keys: ['<S-BS>'], type: 'keyToKey', toKeys: ['b'] },
75
+ { keys: ['<C-n>'], type: 'keyToKey', toKeys: ['j'] },
76
+ { keys: ['<C-p>'], type: 'keyToKey', toKeys: ['k'] },
77
+ { keys: ['C-['], type: 'keyToKey', toKeys: ['<Esc>'] },
78
+ { keys: ['<C-c>'], type: 'keyToKey', toKeys: ['<Esc>'] },
79
+ { keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'], context: 'normal' },
80
+ { keys: ['s'], type: 'keyToKey', toKeys: ['x', 'i'], context: 'visual'},
81
+ { keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'], context: 'normal' },
82
+ { keys: ['S'], type: 'keyToKey', toKeys: ['d', 'c', 'c'], context: 'visual' },
83
+ { keys: ['<Home>'], type: 'keyToKey', toKeys: ['0'] },
84
+ { keys: ['<End>'], type: 'keyToKey', toKeys: ['$'] },
85
+ { keys: ['<PageUp>'], type: 'keyToKey', toKeys: ['<C-b>'] },
86
+ { keys: ['<PageDown>'], type: 'keyToKey', toKeys: ['<C-f>'] },
87
+ // Motions
88
+ { keys: ['H'], type: 'motion',
89
+ motion: 'moveToTopLine',
90
+ motionArgs: { linewise: true, toJumplist: true }},
91
+ { keys: ['M'], type: 'motion',
92
+ motion: 'moveToMiddleLine',
93
+ motionArgs: { linewise: true, toJumplist: true }},
94
+ { keys: ['L'], type: 'motion',
95
+ motion: 'moveToBottomLine',
96
+ motionArgs: { linewise: true, toJumplist: true }},
97
+ { keys: ['h'], type: 'motion',
98
+ motion: 'moveByCharacters',
99
+ motionArgs: { forward: false }},
100
+ { keys: ['l'], type: 'motion',
101
+ motion: 'moveByCharacters',
102
+ motionArgs: { forward: true }},
103
+ { keys: ['j'], type: 'motion',
104
+ motion: 'moveByLines',
105
+ motionArgs: { forward: true, linewise: true }},
106
+ { keys: ['k'], type: 'motion',
107
+ motion: 'moveByLines',
108
+ motionArgs: { forward: false, linewise: true }},
109
+ { keys: ['g','j'], type: 'motion',
110
+ motion: 'moveByDisplayLines',
111
+ motionArgs: { forward: true }},
112
+ { keys: ['g','k'], type: 'motion',
113
+ motion: 'moveByDisplayLines',
114
+ motionArgs: { forward: false }},
115
+ { keys: ['w'], type: 'motion',
116
+ motion: 'moveByWords',
117
+ motionArgs: { forward: true, wordEnd: false }},
118
+ { keys: ['W'], type: 'motion',
119
+ motion: 'moveByWords',
120
+ motionArgs: { forward: true, wordEnd: false, bigWord: true }},
121
+ { keys: ['e'], type: 'motion',
122
+ motion: 'moveByWords',
123
+ motionArgs: { forward: true, wordEnd: true, inclusive: true }},
124
+ { keys: ['E'], type: 'motion',
125
+ motion: 'moveByWords',
126
+ motionArgs: { forward: true, wordEnd: true, bigWord: true,
127
+ inclusive: true }},
128
+ { keys: ['b'], type: 'motion',
129
+ motion: 'moveByWords',
130
+ motionArgs: { forward: false, wordEnd: false }},
131
+ { keys: ['B'], type: 'motion',
132
+ motion: 'moveByWords',
133
+ motionArgs: { forward: false, wordEnd: false, bigWord: true }},
134
+ { keys: ['g', 'e'], type: 'motion',
135
+ motion: 'moveByWords',
136
+ motionArgs: { forward: false, wordEnd: true, inclusive: true }},
137
+ { keys: ['g', 'E'], type: 'motion',
138
+ motion: 'moveByWords',
139
+ motionArgs: { forward: false, wordEnd: true, bigWord: true,
140
+ inclusive: true }},
141
+ { keys: ['{'], type: 'motion', motion: 'moveByParagraph',
142
+ motionArgs: { forward: false, toJumplist: true }},
143
+ { keys: ['}'], type: 'motion', motion: 'moveByParagraph',
144
+ motionArgs: { forward: true, toJumplist: true }},
145
+ { keys: ['<C-f>'], type: 'motion',
146
+ motion: 'moveByPage', motionArgs: { forward: true }},
147
+ { keys: ['<C-b>'], type: 'motion',
148
+ motion: 'moveByPage', motionArgs: { forward: false }},
149
+ { keys: ['<C-d>'], type: 'motion',
150
+ motion: 'moveByScroll',
151
+ motionArgs: { forward: true, explicitRepeat: true }},
152
+ { keys: ['<C-u>'], type: 'motion',
153
+ motion: 'moveByScroll',
154
+ motionArgs: { forward: false, explicitRepeat: true }},
155
+ { keys: ['g', 'g'], type: 'motion',
156
+ motion: 'moveToLineOrEdgeOfDocument',
157
+ motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
158
+ { keys: ['G'], type: 'motion',
159
+ motion: 'moveToLineOrEdgeOfDocument',
160
+ motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
161
+ { keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' },
162
+ { keys: ['^'], type: 'motion',
163
+ motion: 'moveToFirstNonWhiteSpaceCharacter' },
164
+ { keys: ['+'], type: 'motion',
165
+ motion: 'moveByLines',
166
+ motionArgs: { forward: true, toFirstChar:true }},
167
+ { keys: ['-'], type: 'motion',
168
+ motion: 'moveByLines',
169
+ motionArgs: { forward: false, toFirstChar:true }},
170
+ { keys: ['_'], type: 'motion',
171
+ motion: 'moveByLines',
172
+ motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
173
+ { keys: ['$'], type: 'motion',
174
+ motion: 'moveToEol',
175
+ motionArgs: { inclusive: true }},
176
+ { keys: ['%'], type: 'motion',
177
+ motion: 'moveToMatchedSymbol',
178
+ motionArgs: { inclusive: true, toJumplist: true }},
179
+ { keys: ['f', 'character'], type: 'motion',
180
+ motion: 'moveToCharacter',
181
+ motionArgs: { forward: true , inclusive: true }},
182
+ { keys: ['F', 'character'], type: 'motion',
183
+ motion: 'moveToCharacter',
184
+ motionArgs: { forward: false }},
185
+ { keys: ['t', 'character'], type: 'motion',
186
+ motion: 'moveTillCharacter',
187
+ motionArgs: { forward: true, inclusive: true }},
188
+ { keys: ['T', 'character'], type: 'motion',
189
+ motion: 'moveTillCharacter',
190
+ motionArgs: { forward: false }},
191
+ { keys: [';'], type: 'motion', motion: 'repeatLastCharacterSearch',
192
+ motionArgs: { forward: true }},
193
+ { keys: [','], type: 'motion', motion: 'repeatLastCharacterSearch',
194
+ motionArgs: { forward: false }},
195
+ { keys: ['\'', 'character'], type: 'motion', motion: 'goToMark',
196
+ motionArgs: {toJumplist: true}},
197
+ { keys: ['`', 'character'], type: 'motion', motion: 'goToMark',
198
+ motionArgs: {toJumplist: true}},
199
+ { keys: [']', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
200
+ { keys: ['[', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
201
+ { keys: [']', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
202
+ { keys: ['[', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
203
+ { keys: [']', 'character'], type: 'motion',
204
+ motion: 'moveToSymbol',
205
+ motionArgs: { forward: true, toJumplist: true}},
206
+ { keys: ['[', 'character'], type: 'motion',
207
+ motion: 'moveToSymbol',
208
+ motionArgs: { forward: false, toJumplist: true}},
209
+ { keys: ['|'], type: 'motion',
210
+ motion: 'moveToColumn',
211
+ motionArgs: { }},
212
+ // Operators
213
+ { keys: ['d'], type: 'operator', operator: 'delete' },
214
+ { keys: ['y'], type: 'operator', operator: 'yank' },
215
+ { keys: ['c'], type: 'operator', operator: 'change' },
216
+ { keys: ['>'], type: 'operator', operator: 'indent',
217
+ operatorArgs: { indentRight: true }},
218
+ { keys: ['<'], type: 'operator', operator: 'indent',
219
+ operatorArgs: { indentRight: false }},
220
+ { keys: ['g', '~'], type: 'operator', operator: 'swapcase' },
221
+ { keys: ['n'], type: 'motion', motion: 'findNext',
222
+ motionArgs: { forward: true, toJumplist: true }},
223
+ { keys: ['N'], type: 'motion', motion: 'findNext',
224
+ motionArgs: { forward: false, toJumplist: true }},
225
+ // Operator-Motion dual commands
226
+ { keys: ['x'], type: 'operatorMotion', operator: 'delete',
227
+ motion: 'moveByCharacters', motionArgs: { forward: true },
228
+ operatorMotionArgs: { visualLine: false }},
229
+ { keys: ['X'], type: 'operatorMotion', operator: 'delete',
230
+ motion: 'moveByCharacters', motionArgs: { forward: false },
231
+ operatorMotionArgs: { visualLine: true }},
232
+ { keys: ['D'], type: 'operatorMotion', operator: 'delete',
233
+ motion: 'moveToEol', motionArgs: { inclusive: true },
234
+ operatorMotionArgs: { visualLine: true }},
235
+ { keys: ['Y'], type: 'operatorMotion', operator: 'yank',
236
+ motion: 'moveToEol', motionArgs: { inclusive: true },
237
+ operatorMotionArgs: { visualLine: true }},
238
+ { keys: ['C'], type: 'operatorMotion',
239
+ operator: 'change',
240
+ motion: 'moveToEol', motionArgs: { inclusive: true },
241
+ operatorMotionArgs: { visualLine: true }},
242
+ { keys: ['~'], type: 'operatorMotion',
243
+ operator: 'swapcase', operatorArgs: { shouldMoveCursor: true },
244
+ motion: 'moveByCharacters', motionArgs: { forward: true }},
245
+ // Actions
246
+ { keys: ['<C-i>'], type: 'action', action: 'jumpListWalk',
247
+ actionArgs: { forward: true }},
248
+ { keys: ['<C-o>'], type: 'action', action: 'jumpListWalk',
249
+ actionArgs: { forward: false }},
250
+ { keys: ['a'], type: 'action', action: 'enterInsertMode', isEdit: true,
251
+ actionArgs: { insertAt: 'charAfter' }},
252
+ { keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true,
253
+ actionArgs: { insertAt: 'eol' }},
254
+ { keys: ['i'], type: 'action', action: 'enterInsertMode', isEdit: true,
255
+ actionArgs: { insertAt: 'inplace' }},
256
+ { keys: ['I'], type: 'action', action: 'enterInsertMode', isEdit: true,
257
+ actionArgs: { insertAt: 'firstNonBlank' }},
258
+ { keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode',
259
+ isEdit: true, interlaceInsertRepeat: true,
260
+ actionArgs: { after: true }},
261
+ { keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode',
262
+ isEdit: true, interlaceInsertRepeat: true,
263
+ actionArgs: { after: false }},
264
+ { keys: ['v'], type: 'action', action: 'toggleVisualMode' },
265
+ { keys: ['V'], type: 'action', action: 'toggleVisualMode',
266
+ actionArgs: { linewise: true }},
267
+ { keys: ['J'], type: 'action', action: 'joinLines', isEdit: true },
268
+ { keys: ['p'], type: 'action', action: 'paste', isEdit: true,
269
+ actionArgs: { after: true, isEdit: true }},
270
+ { keys: ['P'], type: 'action', action: 'paste', isEdit: true,
271
+ actionArgs: { after: false, isEdit: true }},
272
+ { keys: ['r', 'character'], type: 'action', action: 'replace', isEdit: true },
273
+ { keys: ['@', 'character'], type: 'action', action: 'replayMacro' },
274
+ { keys: ['q', 'character'], type: 'action', action: 'enterMacroRecordMode' },
275
+ // Handle Replace-mode as a special case of insert mode.
276
+ { keys: ['R'], type: 'action', action: 'enterInsertMode', isEdit: true,
277
+ actionArgs: { replace: true }},
278
+ { keys: ['u'], type: 'action', action: 'undo' },
279
+ { keys: ['<C-r>'], type: 'action', action: 'redo' },
280
+ { keys: ['m', 'character'], type: 'action', action: 'setMark' },
281
+ { keys: ['"', 'character'], type: 'action', action: 'setRegister' },
282
+ { keys: ['z', 'z'], type: 'action', action: 'scrollToCursor',
283
+ actionArgs: { position: 'center' }},
284
+ { keys: ['z', '.'], type: 'action', action: 'scrollToCursor',
285
+ actionArgs: { position: 'center' },
286
+ motion: 'moveToFirstNonWhiteSpaceCharacter' },
287
+ { keys: ['z', 't'], type: 'action', action: 'scrollToCursor',
288
+ actionArgs: { position: 'top' }},
289
+ { keys: ['z', '<CR>'], type: 'action', action: 'scrollToCursor',
290
+ actionArgs: { position: 'top' },
291
+ motion: 'moveToFirstNonWhiteSpaceCharacter' },
292
+ { keys: ['z', '-'], type: 'action', action: 'scrollToCursor',
293
+ actionArgs: { position: 'bottom' }},
294
+ { keys: ['z', 'b'], type: 'action', action: 'scrollToCursor',
295
+ actionArgs: { position: 'bottom' },
296
+ motion: 'moveToFirstNonWhiteSpaceCharacter' },
297
+ { keys: ['.'], type: 'action', action: 'repeatLastEdit' },
298
+ { keys: ['<C-a>'], type: 'action', action: 'incrementNumberToken',
299
+ isEdit: true,
300
+ actionArgs: {increase: true, backtrack: false}},
301
+ { keys: ['<C-x>'], type: 'action', action: 'incrementNumberToken',
302
+ isEdit: true,
303
+ actionArgs: {increase: false, backtrack: false}},
304
+ // Text object motions
305
+ { keys: ['a', 'character'], type: 'motion',
306
+ motion: 'textObjectManipulation' },
307
+ { keys: ['i', 'character'], type: 'motion',
308
+ motion: 'textObjectManipulation',
309
+ motionArgs: { textObjectInner: true }},
310
+ // Search
311
+ { keys: ['/'], type: 'search',
312
+ searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
313
+ { keys: ['?'], type: 'search',
314
+ searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
315
+ { keys: ['*'], type: 'search',
316
+ searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
317
+ { keys: ['#'], type: 'search',
318
+ searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
319
+ // Ex command
320
+ { keys: [':'], type: 'ex' }
321
+ ];
322
+
323
+ var Vim = function() {
324
+ CodeMirror.defineOption('vimMode', false, function(cm, val) {
325
+ if (val) {
326
+ cm.setOption('keyMap', 'vim');
327
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
328
+ cm.on('beforeSelectionChange', beforeSelectionChange);
329
+ maybeInitVimState(cm);
330
+ } else if (cm.state.vim) {
331
+ cm.setOption('keyMap', 'default');
332
+ cm.off('beforeSelectionChange', beforeSelectionChange);
333
+ cm.state.vim = null;
334
+ }
335
+ });
336
+ function beforeSelectionChange(cm, cur) {
337
+ var vim = cm.state.vim;
338
+ if (vim.insertMode || vim.exMode) return;
339
+
340
+ var head = cur.head;
341
+ if (head.ch && head.ch == cm.doc.getLine(head.line).length) {
342
+ head.ch--;
343
+ }
344
+ }
345
+
346
+ var numberRegex = /[\d]/;
347
+ var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)];
348
+ function makeKeyRange(start, size) {
349
+ var keys = [];
350
+ for (var i = start; i < start + size; i++) {
351
+ keys.push(String.fromCharCode(i));
352
+ }
353
+ return keys;
354
+ }
355
+ var upperCaseAlphabet = makeKeyRange(65, 26);
356
+ var lowerCaseAlphabet = makeKeyRange(97, 26);
357
+ var numbers = makeKeyRange(48, 10);
358
+ var specialSymbols = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;"\''.split('');
359
+ var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace',
360
+ 'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter'];
361
+ var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
362
+ var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"']);
363
+
364
+ function isLine(cm, line) {
365
+ return line >= cm.firstLine() && line <= cm.lastLine();
366
+ }
367
+ function isLowerCase(k) {
368
+ return (/^[a-z]$/).test(k);
369
+ }
370
+ function isMatchableSymbol(k) {
371
+ return '()[]{}'.indexOf(k) != -1;
372
+ }
373
+ function isNumber(k) {
374
+ return numberRegex.test(k);
375
+ }
376
+ function isUpperCase(k) {
377
+ return (/^[A-Z]$/).test(k);
378
+ }
379
+ function isWhiteSpaceString(k) {
380
+ return (/^\s*$/).test(k);
381
+ }
382
+ function inArray(val, arr) {
383
+ for (var i = 0; i < arr.length; i++) {
384
+ if (arr[i] == val) {
385
+ return true;
386
+ }
387
+ }
388
+ return false;
389
+ }
390
+
391
+ var createCircularJumpList = function() {
392
+ var size = 100;
393
+ var pointer = -1;
394
+ var head = 0;
395
+ var tail = 0;
396
+ var buffer = new Array(size);
397
+ function add(cm, oldCur, newCur) {
398
+ var current = pointer % size;
399
+ var curMark = buffer[current];
400
+ function useNextSlot(cursor) {
401
+ var next = ++pointer % size;
402
+ var trashMark = buffer[next];
403
+ if (trashMark) {
404
+ trashMark.clear();
405
+ }
406
+ buffer[next] = cm.setBookmark(cursor);
407
+ }
408
+ if (curMark) {
409
+ var markPos = curMark.find();
410
+ // avoid recording redundant cursor position
411
+ if (markPos && !cursorEqual(markPos, oldCur)) {
412
+ useNextSlot(oldCur);
413
+ }
414
+ } else {
415
+ useNextSlot(oldCur);
416
+ }
417
+ useNextSlot(newCur);
418
+ head = pointer;
419
+ tail = pointer - size + 1;
420
+ if (tail < 0) {
421
+ tail = 0;
422
+ }
423
+ }
424
+ function move(cm, offset) {
425
+ pointer += offset;
426
+ if (pointer > head) {
427
+ pointer = head;
428
+ } else if (pointer < tail) {
429
+ pointer = tail;
430
+ }
431
+ var mark = buffer[(size + pointer) % size];
432
+ // skip marks that are temporarily removed from text buffer
433
+ if (mark && !mark.find()) {
434
+ var inc = offset > 0 ? 1 : -1;
435
+ var newCur;
436
+ var oldCur = cm.getCursor();
437
+ do {
438
+ pointer += inc;
439
+ mark = buffer[(size + pointer) % size];
440
+ // skip marks that are the same as current position
441
+ if (mark &&
442
+ (newCur = mark.find()) &&
443
+ !cursorEqual(oldCur, newCur)) {
444
+ break;
445
+ }
446
+ } while (pointer < head && pointer > tail);
447
+ }
448
+ return mark;
449
+ }
450
+ return {
451
+ cachedCursor: undefined, //used for # and * jumps
452
+ add: add,
453
+ move: move
454
+ };
455
+ };
456
+
457
+ var createMacroState = function() {
458
+ return {
459
+ macroKeyBuffer: [],
460
+ latestRegister: undefined,
461
+ inReplay: false,
462
+ lastInsertModeChanges: {
463
+ changes: [], // Change list
464
+ expectCursorActivityForChange: false // Set to true on change, false on cursorActivity.
465
+ },
466
+ enteredMacroMode: undefined,
467
+ isMacroPlaying: false,
468
+ toggle: function(cm, registerName) {
469
+ if (this.enteredMacroMode) { //onExit
470
+ this.enteredMacroMode(); // close dialog
471
+ this.enteredMacroMode = undefined;
472
+ } else { //onEnter
473
+ this.latestRegister = registerName;
474
+ this.enteredMacroMode = cm.openDialog(
475
+ '(recording)['+registerName+']', null, {bottom:true});
476
+ }
477
+ }
478
+ };
479
+ };
480
+
481
+
482
+ function maybeInitVimState(cm) {
483
+ if (!cm.state.vim) {
484
+ // Store instance state in the CodeMirror object.
485
+ cm.state.vim = {
486
+ inputState: new InputState(),
487
+ // Vim's input state that triggered the last edit, used to repeat
488
+ // motions and operators with '.'.
489
+ lastEditInputState: undefined,
490
+ // Vim's action command before the last edit, used to repeat actions
491
+ // with '.' and insert mode repeat.
492
+ lastEditActionCommand: undefined,
493
+ // When using jk for navigation, if you move from a longer line to a
494
+ // shorter line, the cursor may clip to the end of the shorter line.
495
+ // If j is pressed again and cursor goes to the next line, the
496
+ // cursor should go back to its horizontal position on the longer
497
+ // line if it can. This is to keep track of the horizontal position.
498
+ lastHPos: -1,
499
+ // Doing the same with screen-position for gj/gk
500
+ lastHSPos: -1,
501
+ // The last motion command run. Cleared if a non-motion command gets
502
+ // executed in between.
503
+ lastMotion: null,
504
+ marks: {},
505
+ insertMode: false,
506
+ // Repeat count for changes made in insert mode, triggered by key
507
+ // sequences like 3,i. Only exists when insertMode is true.
508
+ insertModeRepeat: undefined,
509
+ visualMode: false,
510
+ // If we are in visual line mode. No effect if visualMode is false.
511
+ visualLine: false
512
+ };
513
+ }
514
+ return cm.state.vim;
515
+ }
516
+ var vimGlobalState;
517
+ function resetVimGlobalState() {
518
+ vimGlobalState = {
519
+ // The current search query.
520
+ searchQuery: null,
521
+ // Whether we are searching backwards.
522
+ searchIsReversed: false,
523
+ jumpList: createCircularJumpList(),
524
+ macroModeState: createMacroState(),
525
+ // Recording latest f, t, F or T motion command.
526
+ lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
527
+ registerController: new RegisterController({})
528
+ };
529
+ }
530
+
531
+ var vimApi= {
532
+ buildKeyMap: function() {
533
+ // TODO: Convert keymap into dictionary format for fast lookup.
534
+ },
535
+ // Testing hook, though it might be useful to expose the register
536
+ // controller anyways.
537
+ getRegisterController: function() {
538
+ return vimGlobalState.registerController;
539
+ },
540
+ // Testing hook.
541
+ resetVimGlobalState_: resetVimGlobalState,
542
+
543
+ // Testing hook.
544
+ getVimGlobalState_: function() {
545
+ return vimGlobalState;
546
+ },
547
+
548
+ // Testing hook.
549
+ maybeInitVimState_: maybeInitVimState,
550
+
551
+ InsertModeKey: InsertModeKey,
552
+ map: function(lhs, rhs) {
553
+ // Add user defined key bindings.
554
+ exCommandDispatcher.map(lhs, rhs);
555
+ },
556
+ defineEx: function(name, prefix, func){
557
+ if (name.indexOf(prefix) !== 0) {
558
+ throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
559
+ }
560
+ exCommands[name]=func;
561
+ exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
562
+ },
563
+ // This is the outermost function called by CodeMirror, after keys have
564
+ // been mapped to their Vim equivalents.
565
+ handleKey: function(cm, key) {
566
+ var command;
567
+ var vim = maybeInitVimState(cm);
568
+ var macroModeState = vimGlobalState.macroModeState;
569
+ if (macroModeState.enteredMacroMode) {
570
+ if (key == 'q') {
571
+ actions.exitMacroRecordMode();
572
+ vim.inputState = new InputState();
573
+ return;
574
+ }
575
+ }
576
+ if (key == '<Esc>') {
577
+ // Clear input state and get back to normal mode.
578
+ vim.inputState = new InputState();
579
+ if (vim.visualMode) {
580
+ exitVisualMode(cm);
581
+ }
582
+ return;
583
+ }
584
+ // Enter visual mode when the mouse selects text.
585
+ if (!vim.visualMode &&
586
+ !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
587
+ vim.visualMode = true;
588
+ vim.visualLine = false;
589
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
590
+ cm.on('mousedown', exitVisualMode);
591
+ }
592
+ if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) {
593
+ // Have to special case 0 since it's both a motion and a number.
594
+ command = commandDispatcher.matchCommand(key, defaultKeymap, vim);
595
+ }
596
+ if (!command) {
597
+ if (isNumber(key)) {
598
+ // Increment count unless count is 0 and key is 0.
599
+ vim.inputState.pushRepeatDigit(key);
600
+ }
601
+ return;
602
+ }
603
+ if (command.type == 'keyToKey') {
604
+ // TODO: prevent infinite recursion.
605
+ for (var i = 0; i < command.toKeys.length; i++) {
606
+ this.handleKey(cm, command.toKeys[i]);
607
+ }
608
+ } else {
609
+ if (macroModeState.enteredMacroMode) {
610
+ logKey(macroModeState, key);
611
+ }
612
+ commandDispatcher.processCommand(cm, vim, command);
613
+ }
614
+ },
615
+ handleEx: function(cm, input) {
616
+ exCommandDispatcher.processCommand(cm, input);
617
+ }
618
+ };
619
+
620
+ // Represents the current input state.
621
+ function InputState() {
622
+ this.prefixRepeat = [];
623
+ this.motionRepeat = [];
624
+
625
+ this.operator = null;
626
+ this.operatorArgs = null;
627
+ this.motion = null;
628
+ this.motionArgs = null;
629
+ this.keyBuffer = []; // For matching multi-key commands.
630
+ this.registerName = null; // Defaults to the unamed register.
631
+ }
632
+ InputState.prototype.pushRepeatDigit = function(n) {
633
+ if (!this.operator) {
634
+ this.prefixRepeat = this.prefixRepeat.concat(n);
635
+ } else {
636
+ this.motionRepeat = this.motionRepeat.concat(n);
637
+ }
638
+ };
639
+ InputState.prototype.getRepeat = function() {
640
+ var repeat = 0;
641
+ if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
642
+ repeat = 1;
643
+ if (this.prefixRepeat.length > 0) {
644
+ repeat *= parseInt(this.prefixRepeat.join(''), 10);
645
+ }
646
+ if (this.motionRepeat.length > 0) {
647
+ repeat *= parseInt(this.motionRepeat.join(''), 10);
648
+ }
649
+ }
650
+ return repeat;
651
+ };
652
+
653
+ /*
654
+ * Register stores information about copy and paste registers. Besides
655
+ * text, a register must store whether it is linewise (i.e., when it is
656
+ * pasted, should it insert itself into a new line, or should the text be
657
+ * inserted at the cursor position.)
658
+ */
659
+ function Register(text, linewise) {
660
+ this.clear();
661
+ if (text) {
662
+ this.set(text, linewise);
663
+ }
664
+ }
665
+ Register.prototype = {
666
+ set: function(text, linewise) {
667
+ this.text = text;
668
+ this.linewise = !!linewise;
669
+ },
670
+ append: function(text, linewise) {
671
+ // if this register has ever been set to linewise, use linewise.
672
+ if (linewise || this.linewise) {
673
+ this.text += '\n' + text;
674
+ this.linewise = true;
675
+ } else {
676
+ this.text += text;
677
+ }
678
+ },
679
+ clear: function() {
680
+ this.text = '';
681
+ this.linewise = false;
682
+ },
683
+ toString: function() { return this.text; }
684
+ };
685
+
686
+ /*
687
+ * vim registers allow you to keep many independent copy and paste buffers.
688
+ * See http://usevim.com/2012/04/13/registers/ for an introduction.
689
+ *
690
+ * RegisterController keeps the state of all the registers. An initial
691
+ * state may be passed in. The unnamed register '"' will always be
692
+ * overridden.
693
+ */
694
+ function RegisterController(registers) {
695
+ this.registers = registers;
696
+ this.unamedRegister = registers['"'] = new Register();
697
+ }
698
+ RegisterController.prototype = {
699
+ pushText: function(registerName, operator, text, linewise) {
700
+ if (linewise && text.charAt(0) == '\n') {
701
+ text = text.slice(1) + '\n';
702
+ }
703
+ if(linewise && text.charAt(text.length - 1) !== '\n'){
704
+ text += '\n';
705
+ }
706
+ // Lowercase and uppercase registers refer to the same register.
707
+ // Uppercase just means append.
708
+ var register = this.isValidRegister(registerName) ?
709
+ this.getRegister(registerName) : null;
710
+ // if no register/an invalid register was specified, things go to the
711
+ // default registers
712
+ if (!register) {
713
+ switch (operator) {
714
+ case 'yank':
715
+ // The 0 register contains the text from the most recent yank.
716
+ this.registers['0'] = new Register(text, linewise);
717
+ break;
718
+ case 'delete':
719
+ case 'change':
720
+ if (text.indexOf('\n') == -1) {
721
+ // Delete less than 1 line. Update the small delete register.
722
+ this.registers['-'] = new Register(text, linewise);
723
+ } else {
724
+ // Shift down the contents of the numbered registers and put the
725
+ // deleted text into register 1.
726
+ this.shiftNumericRegisters_();
727
+ this.registers['1'] = new Register(text, linewise);
728
+ }
729
+ break;
730
+ }
731
+ // Make sure the unnamed register is set to what just happened
732
+ this.unamedRegister.set(text, linewise);
733
+ return;
734
+ }
735
+
736
+ // If we've gotten to this point, we've actually specified a register
737
+ var append = isUpperCase(registerName);
738
+ if (append) {
739
+ register.append(text, linewise);
740
+ // The unamed register always has the same value as the last used
741
+ // register.
742
+ this.unamedRegister.append(text, linewise);
743
+ } else {
744
+ register.set(text, linewise);
745
+ this.unamedRegister.set(text, linewise);
746
+ }
747
+ },
748
+ setRegisterText: function(name, text, linewise) {
749
+ this.getRegister(name).set(text, linewise);
750
+ },
751
+ // Gets the register named @name. If one of @name doesn't already exist,
752
+ // create it. If @name is invalid, return the unamedRegister.
753
+ getRegister: function(name) {
754
+ if (!this.isValidRegister(name)) {
755
+ return this.unamedRegister;
756
+ }
757
+ name = name.toLowerCase();
758
+ if (!this.registers[name]) {
759
+ this.registers[name] = new Register();
760
+ }
761
+ return this.registers[name];
762
+ },
763
+ isValidRegister: function(name) {
764
+ return name && inArray(name, validRegisters);
765
+ },
766
+ shiftNumericRegisters_: function() {
767
+ for (var i = 9; i >= 2; i--) {
768
+ this.registers[i] = this.getRegister('' + (i - 1));
769
+ }
770
+ }
771
+ };
772
+
773
+ var commandDispatcher = {
774
+ matchCommand: function(key, keyMap, vim) {
775
+ var inputState = vim.inputState;
776
+ var keys = inputState.keyBuffer.concat(key);
777
+ var matchedCommands = [];
778
+ var selectedCharacter;
779
+ for (var i = 0; i < keyMap.length; i++) {
780
+ var command = keyMap[i];
781
+ if (matchKeysPartial(keys, command.keys)) {
782
+ if (inputState.operator && command.type == 'action') {
783
+ // Ignore matched action commands after an operator. Operators
784
+ // only operate on motions. This check is really for text
785
+ // objects since aW, a[ etcs conflicts with a.
786
+ continue;
787
+ }
788
+ // Match commands that take <character> as an argument.
789
+ if (command.keys[keys.length - 1] == 'character') {
790
+ selectedCharacter = keys[keys.length - 1];
791
+ if(selectedCharacter.length>1){
792
+ switch(selectedCharacter){
793
+ case '<CR>':
794
+ selectedCharacter='\n';
795
+ break;
796
+ case '<Space>':
797
+ selectedCharacter=' ';
798
+ break;
799
+ default:
800
+ continue;
801
+ }
802
+ }
803
+ }
804
+ // Add the command to the list of matched commands. Choose the best
805
+ // command later.
806
+ matchedCommands.push(command);
807
+ }
808
+ }
809
+
810
+ // Returns the command if it is a full match, or null if not.
811
+ function getFullyMatchedCommandOrNull(command) {
812
+ if (keys.length < command.keys.length) {
813
+ // Matches part of a multi-key command. Buffer and wait for next
814
+ // stroke.
815
+ inputState.keyBuffer.push(key);
816
+ return null;
817
+ } else {
818
+ if (command.keys[keys.length - 1] == 'character') {
819
+ inputState.selectedCharacter = selectedCharacter;
820
+ }
821
+ // Clear the buffer since a full match was found.
822
+ inputState.keyBuffer = [];
823
+ return command;
824
+ }
825
+ }
826
+
827
+ if (!matchedCommands.length) {
828
+ // Clear the buffer since there were no matches.
829
+ inputState.keyBuffer = [];
830
+ return null;
831
+ } else if (matchedCommands.length == 1) {
832
+ return getFullyMatchedCommandOrNull(matchedCommands[0]);
833
+ } else {
834
+ // Find the best match in the list of matchedCommands.
835
+ var context = vim.visualMode ? 'visual' : 'normal';
836
+ var bestMatch = matchedCommands[0]; // Default to first in the list.
837
+ for (var i = 0; i < matchedCommands.length; i++) {
838
+ if (matchedCommands[i].context == context) {
839
+ bestMatch = matchedCommands[i];
840
+ break;
841
+ }
842
+ }
843
+ return getFullyMatchedCommandOrNull(bestMatch);
844
+ }
845
+ },
846
+ processCommand: function(cm, vim, command) {
847
+ vim.inputState.repeatOverride = command.repeatOverride;
848
+ switch (command.type) {
849
+ case 'motion':
850
+ this.processMotion(cm, vim, command);
851
+ break;
852
+ case 'operator':
853
+ this.processOperator(cm, vim, command);
854
+ break;
855
+ case 'operatorMotion':
856
+ this.processOperatorMotion(cm, vim, command);
857
+ break;
858
+ case 'action':
859
+ this.processAction(cm, vim, command);
860
+ break;
861
+ case 'search':
862
+ this.processSearch(cm, vim, command);
863
+ break;
864
+ case 'ex':
865
+ case 'keyToEx':
866
+ this.processEx(cm, vim, command);
867
+ break;
868
+ default:
869
+ break;
870
+ }
871
+ },
872
+ processMotion: function(cm, vim, command) {
873
+ vim.inputState.motion = command.motion;
874
+ vim.inputState.motionArgs = copyArgs(command.motionArgs);
875
+ this.evalInput(cm, vim);
876
+ },
877
+ processOperator: function(cm, vim, command) {
878
+ var inputState = vim.inputState;
879
+ if (inputState.operator) {
880
+ if (inputState.operator == command.operator) {
881
+ // Typing an operator twice like 'dd' makes the operator operate
882
+ // linewise
883
+ inputState.motion = 'expandToLine';
884
+ inputState.motionArgs = { linewise: true };
885
+ this.evalInput(cm, vim);
886
+ return;
887
+ } else {
888
+ // 2 different operators in a row doesn't make sense.
889
+ vim.inputState = new InputState();
890
+ }
891
+ }
892
+ inputState.operator = command.operator;
893
+ inputState.operatorArgs = copyArgs(command.operatorArgs);
894
+ if (vim.visualMode) {
895
+ // Operating on a selection in visual mode. We don't need a motion.
896
+ this.evalInput(cm, vim);
897
+ }
898
+ },
899
+ processOperatorMotion: function(cm, vim, command) {
900
+ var visualMode = vim.visualMode;
901
+ var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
902
+ if (operatorMotionArgs) {
903
+ // Operator motions may have special behavior in visual mode.
904
+ if (visualMode && operatorMotionArgs.visualLine) {
905
+ vim.visualLine = true;
906
+ }
907
+ }
908
+ this.processOperator(cm, vim, command);
909
+ if (!visualMode) {
910
+ this.processMotion(cm, vim, command);
911
+ }
912
+ },
913
+ processAction: function(cm, vim, command) {
914
+ var inputState = vim.inputState;
915
+ var repeat = inputState.getRepeat();
916
+ var repeatIsExplicit = !!repeat;
917
+ var actionArgs = copyArgs(command.actionArgs) || {};
918
+ if (inputState.selectedCharacter) {
919
+ actionArgs.selectedCharacter = inputState.selectedCharacter;
920
+ }
921
+ // Actions may or may not have motions and operators. Do these first.
922
+ if (command.operator) {
923
+ this.processOperator(cm, vim, command);
924
+ }
925
+ if (command.motion) {
926
+ this.processMotion(cm, vim, command);
927
+ }
928
+ if (command.motion || command.operator) {
929
+ this.evalInput(cm, vim);
930
+ }
931
+ actionArgs.repeat = repeat || 1;
932
+ actionArgs.repeatIsExplicit = repeatIsExplicit;
933
+ actionArgs.registerName = inputState.registerName;
934
+ vim.inputState = new InputState();
935
+ vim.lastMotion = null;
936
+ if (command.isEdit) {
937
+ this.recordLastEdit(vim, inputState, command);
938
+ }
939
+ actions[command.action](cm, actionArgs, vim);
940
+ },
941
+ processSearch: function(cm, vim, command) {
942
+ if (!cm.getSearchCursor) {
943
+ // Search depends on SearchCursor.
944
+ return;
945
+ }
946
+ var forward = command.searchArgs.forward;
947
+ getSearchState(cm).setReversed(!forward);
948
+ var promptPrefix = (forward) ? '/' : '?';
949
+ var originalQuery = getSearchState(cm).getQuery();
950
+ var originalScrollPos = cm.getScrollInfo();
951
+ function handleQuery(query, ignoreCase, smartCase) {
952
+ try {
953
+ updateSearchQuery(cm, query, ignoreCase, smartCase);
954
+ } catch (e) {
955
+ showConfirm(cm, 'Invalid regex: ' + query);
956
+ return;
957
+ }
958
+ commandDispatcher.processMotion(cm, vim, {
959
+ type: 'motion',
960
+ motion: 'findNext',
961
+ motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
962
+ });
963
+ }
964
+ function onPromptClose(query) {
965
+ cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
966
+ handleQuery(query, true /** ignoreCase */, true /** smartCase */);
967
+ }
968
+ function onPromptKeyUp(_e, query) {
969
+ var parsedQuery;
970
+ try {
971
+ parsedQuery = updateSearchQuery(cm, query,
972
+ true /** ignoreCase */, true /** smartCase */);
973
+ } catch (e) {
974
+ // Swallow bad regexes for incremental search.
975
+ }
976
+ if (parsedQuery) {
977
+ cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
978
+ } else {
979
+ clearSearchHighlight(cm);
980
+ cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
981
+ }
982
+ }
983
+ function onPromptKeyDown(e, _query, close) {
984
+ var keyName = CodeMirror.keyName(e);
985
+ if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
986
+ updateSearchQuery(cm, originalQuery);
987
+ clearSearchHighlight(cm);
988
+ cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
989
+
990
+ CodeMirror.e_stop(e);
991
+ close();
992
+ cm.focus();
993
+ }
994
+ }
995
+ switch (command.searchArgs.querySrc) {
996
+ case 'prompt':
997
+ showPrompt(cm, {
998
+ onClose: onPromptClose,
999
+ prefix: promptPrefix,
1000
+ desc: searchPromptDesc,
1001
+ onKeyUp: onPromptKeyUp,
1002
+ onKeyDown: onPromptKeyDown
1003
+ });
1004
+ break;
1005
+ case 'wordUnderCursor':
1006
+ var word = expandWordUnderCursor(cm, false /** inclusive */,
1007
+ true /** forward */, false /** bigWord */,
1008
+ true /** noSymbol */);
1009
+ var isKeyword = true;
1010
+ if (!word) {
1011
+ word = expandWordUnderCursor(cm, false /** inclusive */,
1012
+ true /** forward */, false /** bigWord */,
1013
+ false /** noSymbol */);
1014
+ isKeyword = false;
1015
+ }
1016
+ if (!word) {
1017
+ return;
1018
+ }
1019
+ var query = cm.getLine(word.start.line).substring(word.start.ch,
1020
+ word.end.ch);
1021
+ if (isKeyword) {
1022
+ query = '\\b' + query + '\\b';
1023
+ } else {
1024
+ query = escapeRegex(query);
1025
+ }
1026
+
1027
+ // cachedCursor is used to save the old position of the cursor
1028
+ // when * or # causes vim to seek for the nearest word and shift
1029
+ // the cursor before entering the motion.
1030
+ vimGlobalState.jumpList.cachedCursor = cm.getCursor();
1031
+ cm.setCursor(word.start);
1032
+
1033
+ handleQuery(query, true /** ignoreCase */, false /** smartCase */);
1034
+ break;
1035
+ }
1036
+ },
1037
+ processEx: function(cm, vim, command) {
1038
+ function onPromptClose(input) {
1039
+ // Give the prompt some time to close so that if processCommand shows
1040
+ // an error, the elements don't overlap.
1041
+ exCommandDispatcher.processCommand(cm, input);
1042
+ }
1043
+ function onPromptKeyDown(e, _input, close) {
1044
+ var keyName = CodeMirror.keyName(e);
1045
+ if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
1046
+ CodeMirror.e_stop(e);
1047
+ close();
1048
+ cm.focus();
1049
+ }
1050
+ }
1051
+ if (command.type == 'keyToEx') {
1052
+ // Handle user defined Ex to Ex mappings
1053
+ exCommandDispatcher.processCommand(cm, command.exArgs.input);
1054
+ } else {
1055
+ if (vim.visualMode) {
1056
+ showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
1057
+ onKeyDown: onPromptKeyDown});
1058
+ } else {
1059
+ showPrompt(cm, { onClose: onPromptClose, prefix: ':',
1060
+ onKeyDown: onPromptKeyDown});
1061
+ }
1062
+ }
1063
+ },
1064
+ evalInput: function(cm, vim) {
1065
+ // If the motion comand is set, execute both the operator and motion.
1066
+ // Otherwise return.
1067
+ var inputState = vim.inputState;
1068
+ var motion = inputState.motion;
1069
+ var motionArgs = inputState.motionArgs || {};
1070
+ var operator = inputState.operator;
1071
+ var operatorArgs = inputState.operatorArgs || {};
1072
+ var registerName = inputState.registerName;
1073
+ var selectionEnd = cm.getCursor('head');
1074
+ var selectionStart = cm.getCursor('anchor');
1075
+ // The difference between cur and selection cursors are that cur is
1076
+ // being operated on and ignores that there is a selection.
1077
+ var curStart = copyCursor(selectionEnd);
1078
+ var curOriginal = copyCursor(curStart);
1079
+ var curEnd;
1080
+ var repeat;
1081
+ if (operator) {
1082
+ this.recordLastEdit(vim, inputState);
1083
+ }
1084
+ if (inputState.repeatOverride !== undefined) {
1085
+ // If repeatOverride is specified, that takes precedence over the
1086
+ // input state's repeat. Used by Ex mode and can be user defined.
1087
+ repeat = inputState.repeatOverride;
1088
+ } else {
1089
+ repeat = inputState.getRepeat();
1090
+ }
1091
+ if (repeat > 0 && motionArgs.explicitRepeat) {
1092
+ motionArgs.repeatIsExplicit = true;
1093
+ } else if (motionArgs.noRepeat ||
1094
+ (!motionArgs.explicitRepeat && repeat === 0)) {
1095
+ repeat = 1;
1096
+ motionArgs.repeatIsExplicit = false;
1097
+ }
1098
+ if (inputState.selectedCharacter) {
1099
+ // If there is a character input, stick it in all of the arg arrays.
1100
+ motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
1101
+ inputState.selectedCharacter;
1102
+ }
1103
+ motionArgs.repeat = repeat;
1104
+ vim.inputState = new InputState();
1105
+ if (motion) {
1106
+ var motionResult = motions[motion](cm, motionArgs, vim);
1107
+ vim.lastMotion = motions[motion];
1108
+ if (!motionResult) {
1109
+ return;
1110
+ }
1111
+ if (motionArgs.toJumplist) {
1112
+ var jumpList = vimGlobalState.jumpList;
1113
+ // if the current motion is # or *, use cachedCursor
1114
+ var cachedCursor = jumpList.cachedCursor;
1115
+ if (cachedCursor) {
1116
+ recordJumpPosition(cm, cachedCursor, motionResult);
1117
+ delete jumpList.cachedCursor;
1118
+ } else {
1119
+ recordJumpPosition(cm, curOriginal, motionResult);
1120
+ }
1121
+ }
1122
+ if (motionResult instanceof Array) {
1123
+ curStart = motionResult[0];
1124
+ curEnd = motionResult[1];
1125
+ } else {
1126
+ curEnd = motionResult;
1127
+ }
1128
+ // TODO: Handle null returns from motion commands better.
1129
+ if (!curEnd) {
1130
+ curEnd = { ch: curStart.ch, line: curStart.line };
1131
+ }
1132
+ if (vim.visualMode) {
1133
+ // Check if the selection crossed over itself. Will need to shift
1134
+ // the start point if that happened.
1135
+ if (cursorIsBefore(selectionStart, selectionEnd) &&
1136
+ (cursorEqual(selectionStart, curEnd) ||
1137
+ cursorIsBefore(curEnd, selectionStart))) {
1138
+ // The end of the selection has moved from after the start to
1139
+ // before the start. We will shift the start right by 1.
1140
+ selectionStart.ch += 1;
1141
+ } else if (cursorIsBefore(selectionEnd, selectionStart) &&
1142
+ (cursorEqual(selectionStart, curEnd) ||
1143
+ cursorIsBefore(selectionStart, curEnd))) {
1144
+ // The opposite happened. We will shift the start left by 1.
1145
+ selectionStart.ch -= 1;
1146
+ }
1147
+ selectionEnd = curEnd;
1148
+ if (vim.visualLine) {
1149
+ if (cursorIsBefore(selectionStart, selectionEnd)) {
1150
+ selectionStart.ch = 0;
1151
+
1152
+ var lastLine = cm.lastLine();
1153
+ if (selectionEnd.line > lastLine) {
1154
+ selectionEnd.line = lastLine;
1155
+ }
1156
+ selectionEnd.ch = lineLength(cm, selectionEnd.line);
1157
+ } else {
1158
+ selectionEnd.ch = 0;
1159
+ selectionStart.ch = lineLength(cm, selectionStart.line);
1160
+ }
1161
+ }
1162
+ cm.setSelection(selectionStart, selectionEnd);
1163
+ updateMark(cm, vim, '<',
1164
+ cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
1165
+ : selectionEnd);
1166
+ updateMark(cm, vim, '>',
1167
+ cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
1168
+ : selectionStart);
1169
+ } else if (!operator) {
1170
+ curEnd = clipCursorToContent(cm, curEnd);
1171
+ cm.setCursor(curEnd.line, curEnd.ch);
1172
+ }
1173
+ }
1174
+
1175
+ if (operator) {
1176
+ var inverted = false;
1177
+ vim.lastMotion = null;
1178
+ operatorArgs.repeat = repeat; // Indent in visual mode needs this.
1179
+ if (vim.visualMode) {
1180
+ curStart = selectionStart;
1181
+ curEnd = selectionEnd;
1182
+ motionArgs.inclusive = true;
1183
+ }
1184
+ // Swap start and end if motion was backward.
1185
+ if (cursorIsBefore(curEnd, curStart)) {
1186
+ var tmp = curStart;
1187
+ curStart = curEnd;
1188
+ curEnd = tmp;
1189
+ inverted = true;
1190
+ }
1191
+ if (motionArgs.inclusive && !(vim.visualMode && inverted)) {
1192
+ // Move the selection end one to the right to include the last
1193
+ // character.
1194
+ curEnd.ch++;
1195
+ }
1196
+ var linewise = motionArgs.linewise ||
1197
+ (vim.visualMode && vim.visualLine);
1198
+ if (linewise) {
1199
+ // Expand selection to entire line.
1200
+ expandSelectionToLine(cm, curStart, curEnd);
1201
+ } else if (motionArgs.forward) {
1202
+ // Clip to trailing newlines only if the motion goes forward.
1203
+ clipToLine(cm, curStart, curEnd);
1204
+ }
1205
+ operatorArgs.registerName = registerName;
1206
+ // Keep track of linewise as it affects how paste and change behave.
1207
+ operatorArgs.linewise = linewise;
1208
+ operators[operator](cm, operatorArgs, vim, curStart,
1209
+ curEnd, curOriginal);
1210
+ if (vim.visualMode) {
1211
+ exitVisualMode(cm);
1212
+ }
1213
+ }
1214
+ },
1215
+ recordLastEdit: function(vim, inputState, actionCommand) {
1216
+ var macroModeState = vimGlobalState.macroModeState;
1217
+ if (macroModeState.inReplay) { return; }
1218
+ vim.lastEditInputState = inputState;
1219
+ vim.lastEditActionCommand = actionCommand;
1220
+ macroModeState.lastInsertModeChanges.changes = [];
1221
+ macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
1222
+ }
1223
+ };
1224
+
1225
+ /**
1226
+ * typedef {Object{line:number,ch:number}} Cursor An object containing the
1227
+ * position of the cursor.
1228
+ */
1229
+ // All of the functions below return Cursor objects.
1230
+ var motions = {
1231
+ moveToTopLine: function(cm, motionArgs) {
1232
+ var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
1233
+ return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1234
+ },
1235
+ moveToMiddleLine: function(cm) {
1236
+ var range = getUserVisibleLines(cm);
1237
+ var line = Math.floor((range.top + range.bottom) * 0.5);
1238
+ return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1239
+ },
1240
+ moveToBottomLine: function(cm, motionArgs) {
1241
+ var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
1242
+ return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
1243
+ },
1244
+ expandToLine: function(cm, motionArgs) {
1245
+ // Expands forward to end of line, and then to next line if repeat is
1246
+ // >1. Does not handle backward motion!
1247
+ var cur = cm.getCursor();
1248
+ return { line: cur.line + motionArgs.repeat - 1, ch: Infinity };
1249
+ },
1250
+ findNext: function(cm, motionArgs) {
1251
+ var state = getSearchState(cm);
1252
+ var query = state.getQuery();
1253
+ if (!query) {
1254
+ return;
1255
+ }
1256
+ var prev = !motionArgs.forward;
1257
+ // If search is initiated with ? instead of /, negate direction.
1258
+ prev = (state.isReversed()) ? !prev : prev;
1259
+ highlightSearchMatches(cm, query);
1260
+ return findNext(cm, prev/** prev */, query, motionArgs.repeat);
1261
+ },
1262
+ goToMark: function(_cm, motionArgs, vim) {
1263
+ var mark = vim.marks[motionArgs.selectedCharacter];
1264
+ if (mark) {
1265
+ return mark.find();
1266
+ }
1267
+ return null;
1268
+ },
1269
+ jumpToMark: function(cm, motionArgs, vim) {
1270
+ var best = cm.getCursor();
1271
+ for (var i = 0; i < motionArgs.repeat; i++) {
1272
+ var cursor = best;
1273
+ for (var key in vim.marks) {
1274
+ if (!isLowerCase(key)) {
1275
+ continue;
1276
+ }
1277
+ var mark = vim.marks[key].find();
1278
+ var isWrongDirection = (motionArgs.forward) ?
1279
+ cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
1280
+
1281
+ if (isWrongDirection) {
1282
+ continue;
1283
+ }
1284
+ if (motionArgs.linewise && (mark.line == cursor.line)) {
1285
+ continue;
1286
+ }
1287
+
1288
+ var equal = cursorEqual(cursor, best);
1289
+ var between = (motionArgs.forward) ?
1290
+ cusrorIsBetween(cursor, mark, best) :
1291
+ cusrorIsBetween(best, mark, cursor);
1292
+
1293
+ if (equal || between) {
1294
+ best = mark;
1295
+ }
1296
+ }
1297
+ }
1298
+
1299
+ if (motionArgs.linewise) {
1300
+ // Vim places the cursor on the first non-whitespace character of
1301
+ // the line if there is one, else it places the cursor at the end
1302
+ // of the line, regardless of whether a mark was found.
1303
+ best.ch = findFirstNonWhiteSpaceCharacter(cm.getLine(best.line));
1304
+ }
1305
+ return best;
1306
+ },
1307
+ moveByCharacters: function(cm, motionArgs) {
1308
+ var cur = cm.getCursor();
1309
+ var repeat = motionArgs.repeat;
1310
+ var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
1311
+ return { line: cur.line, ch: ch };
1312
+ },
1313
+ moveByLines: function(cm, motionArgs, vim) {
1314
+ var cur = cm.getCursor();
1315
+ var endCh = cur.ch;
1316
+ // Depending what our last motion was, we may want to do different
1317
+ // things. If our last motion was moving vertically, we want to
1318
+ // preserve the HPos from our last horizontal move. If our last motion
1319
+ // was going to the end of a line, moving vertically we should go to
1320
+ // the end of the line, etc.
1321
+ switch (vim.lastMotion) {
1322
+ case this.moveByLines:
1323
+ case this.moveByDisplayLines:
1324
+ case this.moveByScroll:
1325
+ case this.moveToColumn:
1326
+ case this.moveToEol:
1327
+ endCh = vim.lastHPos;
1328
+ break;
1329
+ default:
1330
+ vim.lastHPos = endCh;
1331
+ }
1332
+ var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
1333
+ var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
1334
+ var first = cm.firstLine();
1335
+ var last = cm.lastLine();
1336
+ // Vim cancels linewise motions that start on an edge and move beyond
1337
+ // that edge. It does not cancel motions that do not start on an edge.
1338
+ if ((line < first && cur.line == first) ||
1339
+ (line > last && cur.line == last)) {
1340
+ return;
1341
+ }
1342
+ if(motionArgs.toFirstChar){
1343
+ endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
1344
+ vim.lastHPos = endCh;
1345
+ }
1346
+ vim.lastHSPos = cm.charCoords({line:line, ch:endCh},'div').left;
1347
+ return { line: line, ch: endCh };
1348
+ },
1349
+ moveByDisplayLines: function(cm, motionArgs, vim) {
1350
+ var cur = cm.getCursor();
1351
+ switch (vim.lastMotion) {
1352
+ case this.moveByDisplayLines:
1353
+ case this.moveByScroll:
1354
+ case this.moveByLines:
1355
+ case this.moveToColumn:
1356
+ case this.moveToEol:
1357
+ break;
1358
+ default:
1359
+ vim.lastHSPos = cm.charCoords(cur,'div').left;
1360
+ }
1361
+ var repeat = motionArgs.repeat;
1362
+ var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
1363
+ if (res.hitSide) {
1364
+ if (motionArgs.forward) {
1365
+ var lastCharCoords = cm.charCoords(res, 'div');
1366
+ var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
1367
+ var res = cm.coordsChar(goalCoords, 'div');
1368
+ } else {
1369
+ var resCoords = cm.charCoords({ line: cm.firstLine(), ch: 0}, 'div');
1370
+ resCoords.left = vim.lastHSPos;
1371
+ res = cm.coordsChar(resCoords, 'div');
1372
+ }
1373
+ }
1374
+ vim.lastHPos = res.ch;
1375
+ return res;
1376
+ },
1377
+ moveByPage: function(cm, motionArgs) {
1378
+ // CodeMirror only exposes functions that move the cursor page down, so
1379
+ // doing this bad hack to move the cursor and move it back. evalInput
1380
+ // will move the cursor to where it should be in the end.
1381
+ var curStart = cm.getCursor();
1382
+ var repeat = motionArgs.repeat;
1383
+ cm.moveV((motionArgs.forward ? repeat : -repeat), 'page');
1384
+ var curEnd = cm.getCursor();
1385
+ cm.setCursor(curStart);
1386
+ return curEnd;
1387
+ },
1388
+ moveByParagraph: function(cm, motionArgs) {
1389
+ var line = cm.getCursor().line;
1390
+ var repeat = motionArgs.repeat;
1391
+ var inc = motionArgs.forward ? 1 : -1;
1392
+ for (var i = 0; i < repeat; i++) {
1393
+ if ((!motionArgs.forward && line === cm.firstLine() ) ||
1394
+ (motionArgs.forward && line == cm.lastLine())) {
1395
+ break;
1396
+ }
1397
+ line += inc;
1398
+ while (line !== cm.firstLine() && line != cm.lastLine() && cm.getLine(line)) {
1399
+ line += inc;
1400
+ }
1401
+ }
1402
+ return { line: line, ch: 0 };
1403
+ },
1404
+ moveByScroll: function(cm, motionArgs, vim) {
1405
+ var scrollbox = cm.getScrollInfo();
1406
+ var curEnd = null;
1407
+ var repeat = motionArgs.repeat;
1408
+ if (!repeat) {
1409
+ repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
1410
+ }
1411
+ var orig = cm.charCoords(cm.getCursor(), 'local');
1412
+ motionArgs.repeat = repeat;
1413
+ var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim);
1414
+ if (!curEnd) {
1415
+ return null;
1416
+ }
1417
+ var dest = cm.charCoords(curEnd, 'local');
1418
+ cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
1419
+ return curEnd;
1420
+ },
1421
+ moveByWords: function(cm, motionArgs) {
1422
+ return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward,
1423
+ !!motionArgs.wordEnd, !!motionArgs.bigWord);
1424
+ },
1425
+ moveTillCharacter: function(cm, motionArgs) {
1426
+ var repeat = motionArgs.repeat;
1427
+ var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
1428
+ motionArgs.selectedCharacter);
1429
+ var increment = motionArgs.forward ? -1 : 1;
1430
+ recordLastCharacterSearch(increment, motionArgs);
1431
+ if(!curEnd)return cm.getCursor();
1432
+ curEnd.ch += increment;
1433
+ return curEnd;
1434
+ },
1435
+ moveToCharacter: function(cm, motionArgs) {
1436
+ var repeat = motionArgs.repeat;
1437
+ recordLastCharacterSearch(0, motionArgs);
1438
+ return moveToCharacter(cm, repeat, motionArgs.forward,
1439
+ motionArgs.selectedCharacter) || cm.getCursor();
1440
+ },
1441
+ moveToSymbol: function(cm, motionArgs) {
1442
+ var repeat = motionArgs.repeat;
1443
+ return findSymbol(cm, repeat, motionArgs.forward,
1444
+ motionArgs.selectedCharacter) || cm.getCursor();
1445
+ },
1446
+ moveToColumn: function(cm, motionArgs, vim) {
1447
+ var repeat = motionArgs.repeat;
1448
+ // repeat is equivalent to which column we want to move to!
1449
+ vim.lastHPos = repeat - 1;
1450
+ vim.lastHSPos = cm.charCoords(cm.getCursor(),'div').left;
1451
+ return moveToColumn(cm, repeat);
1452
+ },
1453
+ moveToEol: function(cm, motionArgs, vim) {
1454
+ var cur = cm.getCursor();
1455
+ vim.lastHPos = Infinity;
1456
+ var retval={ line: cur.line + motionArgs.repeat - 1, ch: Infinity };
1457
+ var end=cm.clipPos(retval);
1458
+ end.ch--;
1459
+ vim.lastHSPos = cm.charCoords(end,'div').left;
1460
+ return retval;
1461
+ },
1462
+ moveToFirstNonWhiteSpaceCharacter: function(cm) {
1463
+ // Go to the start of the line where the text begins, or the end for
1464
+ // whitespace-only lines
1465
+ var cursor = cm.getCursor();
1466
+ return { line: cursor.line,
1467
+ ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)) };
1468
+ },
1469
+ moveToMatchedSymbol: function(cm) {
1470
+ var cursor = cm.getCursor();
1471
+ var line = cursor.line;
1472
+ var ch = cursor.ch;
1473
+ var lineText = cm.getLine(line);
1474
+ var symbol;
1475
+ var startContext = cm.getTokenAt(cursor).type;
1476
+ var startCtxLevel = getContextLevel(startContext);
1477
+ do {
1478
+ symbol = lineText.charAt(ch++);
1479
+ if (symbol && isMatchableSymbol(symbol)) {
1480
+ var endContext = cm.getTokenAt({line:line, ch:ch}).type;
1481
+ var endCtxLevel = getContextLevel(endContext);
1482
+ if (startCtxLevel >= endCtxLevel) {
1483
+ break;
1484
+ }
1485
+ }
1486
+ } while (symbol);
1487
+ if (symbol) {
1488
+ return findMatchedSymbol(cm, {line:line, ch:ch-1}, symbol);
1489
+ } else {
1490
+ return cursor;
1491
+ }
1492
+ },
1493
+ moveToStartOfLine: function(cm) {
1494
+ var cursor = cm.getCursor();
1495
+ return { line: cursor.line, ch: 0 };
1496
+ },
1497
+ moveToLineOrEdgeOfDocument: function(cm, motionArgs) {
1498
+ var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
1499
+ if (motionArgs.repeatIsExplicit) {
1500
+ lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
1501
+ }
1502
+ return { line: lineNum,
1503
+ ch: findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)) };
1504
+ },
1505
+ textObjectManipulation: function(cm, motionArgs) {
1506
+ var character = motionArgs.selectedCharacter;
1507
+ // Inclusive is the difference between a and i
1508
+ // TODO: Instead of using the additional text object map to perform text
1509
+ // object operations, merge the map into the defaultKeyMap and use
1510
+ // motionArgs to define behavior. Define separate entries for 'aw',
1511
+ // 'iw', 'a[', 'i[', etc.
1512
+ var inclusive = !motionArgs.textObjectInner;
1513
+ if (!textObjects[character]) {
1514
+ // No text object defined for this, don't move.
1515
+ return null;
1516
+ }
1517
+ var tmp = textObjects[character](cm, inclusive);
1518
+ var start = tmp.start;
1519
+ var end = tmp.end;
1520
+ return [start, end];
1521
+ },
1522
+ repeatLastCharacterSearch: function(cm, motionArgs) {
1523
+ var lastSearch = vimGlobalState.lastChararacterSearch;
1524
+ var repeat = motionArgs.repeat;
1525
+ var forward = motionArgs.forward === lastSearch.forward;
1526
+ var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
1527
+ cm.moveH(-increment, 'char');
1528
+ motionArgs.inclusive = forward ? true : false;
1529
+ var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
1530
+ if (!curEnd) {
1531
+ cm.moveH(increment, 'char');
1532
+ return cm.getCursor();
1533
+ }
1534
+ curEnd.ch += increment;
1535
+ return curEnd;
1536
+ }
1537
+ };
1538
+
1539
+ var operators = {
1540
+ change: function(cm, operatorArgs, _vim, curStart, curEnd) {
1541
+ vimGlobalState.registerController.pushText(
1542
+ operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd),
1543
+ operatorArgs.linewise);
1544
+ if (operatorArgs.linewise) {
1545
+ // Push the next line back down, if there is a next line.
1546
+ var replacement = curEnd.line > cm.lastLine() ? '' : '\n';
1547
+ cm.replaceRange(replacement, curStart, curEnd);
1548
+ cm.indentLine(curStart.line, 'smart');
1549
+ // null ch so setCursor moves to end of line.
1550
+ curStart.ch = null;
1551
+ } else {
1552
+ // Exclude trailing whitespace if the range is not all whitespace.
1553
+ var text = cm.getRange(curStart, curEnd);
1554
+ if (!isWhiteSpaceString(text)) {
1555
+ var match = (/\s+$/).exec(text);
1556
+ if (match) {
1557
+ curEnd = offsetCursor(curEnd, 0, - match[0].length);
1558
+ }
1559
+ }
1560
+ cm.replaceRange('', curStart, curEnd);
1561
+ }
1562
+ actions.enterInsertMode(cm, {}, cm.state.vim);
1563
+ cm.setCursor(curStart);
1564
+ },
1565
+ // delete is a javascript keyword.
1566
+ 'delete': function(cm, operatorArgs, _vim, curStart, curEnd) {
1567
+ // If the ending line is past the last line, inclusive, instead of
1568
+ // including the trailing \n, include the \n before the starting line
1569
+ if (operatorArgs.linewise &&
1570
+ curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) {
1571
+ curStart.line--;
1572
+ curStart.ch = lineLength(cm, curStart.line);
1573
+ }
1574
+ vimGlobalState.registerController.pushText(
1575
+ operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd),
1576
+ operatorArgs.linewise);
1577
+ cm.replaceRange('', curStart, curEnd);
1578
+ if (operatorArgs.linewise) {
1579
+ cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1580
+ } else {
1581
+ cm.setCursor(curStart);
1582
+ }
1583
+ },
1584
+ indent: function(cm, operatorArgs, vim, curStart, curEnd) {
1585
+ var startLine = curStart.line;
1586
+ var endLine = curEnd.line;
1587
+ // In visual mode, n> shifts the selection right n times, instead of
1588
+ // shifting n lines right once.
1589
+ var repeat = (vim.visualMode) ? operatorArgs.repeat : 1;
1590
+ if (operatorArgs.linewise) {
1591
+ // The only way to delete a newline is to delete until the start of
1592
+ // the next line, so in linewise mode evalInput will include the next
1593
+ // line. We don't want this in indent, so we go back a line.
1594
+ endLine--;
1595
+ }
1596
+ for (var i = startLine; i <= endLine; i++) {
1597
+ for (var j = 0; j < repeat; j++) {
1598
+ cm.indentLine(i, operatorArgs.indentRight);
1599
+ }
1600
+ }
1601
+ cm.setCursor(curStart);
1602
+ cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1603
+ },
1604
+ swapcase: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
1605
+ var toSwap = cm.getRange(curStart, curEnd);
1606
+ var swapped = '';
1607
+ for (var i = 0; i < toSwap.length; i++) {
1608
+ var character = toSwap.charAt(i);
1609
+ swapped += isUpperCase(character) ? character.toLowerCase() :
1610
+ character.toUpperCase();
1611
+ }
1612
+ cm.replaceRange(swapped, curStart, curEnd);
1613
+ if (!operatorArgs.shouldMoveCursor) {
1614
+ cm.setCursor(curOriginal);
1615
+ }
1616
+ },
1617
+ yank: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
1618
+ vimGlobalState.registerController.pushText(
1619
+ operatorArgs.registerName, 'yank',
1620
+ cm.getRange(curStart, curEnd), operatorArgs.linewise);
1621
+ cm.setCursor(curOriginal);
1622
+ }
1623
+ };
1624
+
1625
+ var actions = {
1626
+ jumpListWalk: function(cm, actionArgs, vim) {
1627
+ if (vim.visualMode) {
1628
+ return;
1629
+ }
1630
+ var repeat = actionArgs.repeat;
1631
+ var forward = actionArgs.forward;
1632
+ var jumpList = vimGlobalState.jumpList;
1633
+
1634
+ var mark = jumpList.move(cm, forward ? repeat : -repeat);
1635
+ var markPos = mark ? mark.find() : undefined;
1636
+ markPos = markPos ? markPos : cm.getCursor();
1637
+ cm.setCursor(markPos);
1638
+ },
1639
+ scrollToCursor: function(cm, actionArgs) {
1640
+ var lineNum = cm.getCursor().line;
1641
+ var charCoords = cm.charCoords({line: lineNum, ch: 0}, 'local');
1642
+ var height = cm.getScrollInfo().clientHeight;
1643
+ var y = charCoords.top;
1644
+ var lineHeight = charCoords.bottom - y;
1645
+ switch (actionArgs.position) {
1646
+ case 'center': y = y - (height / 2) + lineHeight;
1647
+ break;
1648
+ case 'bottom': y = y - height + lineHeight*1.4;
1649
+ break;
1650
+ case 'top': y = y + lineHeight*0.4;
1651
+ break;
1652
+ }
1653
+ cm.scrollTo(null, y);
1654
+ },
1655
+ replayMacro: function(cm, actionArgs) {
1656
+ var registerName = actionArgs.selectedCharacter;
1657
+ var repeat = actionArgs.repeat;
1658
+ var macroModeState = vimGlobalState.macroModeState;
1659
+ if (registerName == '@') {
1660
+ registerName = macroModeState.latestRegister;
1661
+ }
1662
+ var keyBuffer = parseRegisterToKeyBuffer(macroModeState, registerName);
1663
+ while(repeat--){
1664
+ executeMacroKeyBuffer(cm, macroModeState, keyBuffer);
1665
+ }
1666
+ },
1667
+ exitMacroRecordMode: function() {
1668
+ var macroModeState = vimGlobalState.macroModeState;
1669
+ macroModeState.toggle();
1670
+ parseKeyBufferToRegister(macroModeState.latestRegister,
1671
+ macroModeState.macroKeyBuffer);
1672
+ },
1673
+ enterMacroRecordMode: function(cm, actionArgs) {
1674
+ var macroModeState = vimGlobalState.macroModeState;
1675
+ var registerName = actionArgs.selectedCharacter;
1676
+ macroModeState.toggle(cm, registerName);
1677
+ emptyMacroKeyBuffer(macroModeState);
1678
+ },
1679
+ enterInsertMode: function(cm, actionArgs, vim) {
1680
+ if (cm.getOption('readOnly')) { return; }
1681
+ vim.insertMode = true;
1682
+ vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
1683
+ var insertAt = (actionArgs) ? actionArgs.insertAt : null;
1684
+ if (insertAt == 'eol') {
1685
+ var cursor = cm.getCursor();
1686
+ cursor = { line: cursor.line, ch: lineLength(cm, cursor.line) };
1687
+ cm.setCursor(cursor);
1688
+ } else if (insertAt == 'charAfter') {
1689
+ cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
1690
+ } else if (insertAt == 'firstNonBlank') {
1691
+ cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
1692
+ }
1693
+ cm.setOption('keyMap', 'vim-insert');
1694
+ if (actionArgs && actionArgs.replace) {
1695
+ // Handle Replace-mode as a special case of insert mode.
1696
+ cm.toggleOverwrite(true);
1697
+ cm.setOption('keyMap', 'vim-replace');
1698
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
1699
+ } else {
1700
+ cm.setOption('keyMap', 'vim-insert');
1701
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
1702
+ }
1703
+ if (!vimGlobalState.macroModeState.inReplay) {
1704
+ // Only record if not replaying.
1705
+ cm.on('change', onChange);
1706
+ cm.on('cursorActivity', onCursorActivity);
1707
+ CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
1708
+ }
1709
+ },
1710
+ toggleVisualMode: function(cm, actionArgs, vim) {
1711
+ var repeat = actionArgs.repeat;
1712
+ var curStart = cm.getCursor();
1713
+ var curEnd;
1714
+ // TODO: The repeat should actually select number of characters/lines
1715
+ // equal to the repeat times the size of the previous visual
1716
+ // operation.
1717
+ if (!vim.visualMode) {
1718
+ cm.on('mousedown', exitVisualMode);
1719
+ vim.visualMode = true;
1720
+ vim.visualLine = !!actionArgs.linewise;
1721
+ if (vim.visualLine) {
1722
+ curStart.ch = 0;
1723
+ curEnd = clipCursorToContent(cm, {
1724
+ line: curStart.line + repeat - 1,
1725
+ ch: lineLength(cm, curStart.line)
1726
+ }, true /** includeLineBreak */);
1727
+ } else {
1728
+ curEnd = clipCursorToContent(cm, {
1729
+ line: curStart.line,
1730
+ ch: curStart.ch + repeat
1731
+ }, true /** includeLineBreak */);
1732
+ }
1733
+ // Make the initial selection.
1734
+ if (!actionArgs.repeatIsExplicit && !vim.visualLine) {
1735
+ // This is a strange case. Here the implicit repeat is 1. The
1736
+ // following commands lets the cursor hover over the 1 character
1737
+ // selection.
1738
+ cm.setCursor(curEnd);
1739
+ cm.setSelection(curEnd, curStart);
1740
+ } else {
1741
+ cm.setSelection(curStart, curEnd);
1742
+ }
1743
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : ""});
1744
+ } else {
1745
+ curStart = cm.getCursor('anchor');
1746
+ curEnd = cm.getCursor('head');
1747
+ if (!vim.visualLine && actionArgs.linewise) {
1748
+ // Shift-V pressed in characterwise visual mode. Switch to linewise
1749
+ // visual mode instead of exiting visual mode.
1750
+ vim.visualLine = true;
1751
+ curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 :
1752
+ lineLength(cm, curStart.line);
1753
+ curEnd.ch = cursorIsBefore(curStart, curEnd) ?
1754
+ lineLength(cm, curEnd.line) : 0;
1755
+ cm.setSelection(curStart, curEnd);
1756
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: "linewise"});
1757
+ } else if (vim.visualLine && !actionArgs.linewise) {
1758
+ // v pressed in linewise visual mode. Switch to characterwise visual
1759
+ // mode instead of exiting visual mode.
1760
+ vim.visualLine = false;
1761
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
1762
+ } else {
1763
+ exitVisualMode(cm);
1764
+ }
1765
+ }
1766
+ updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
1767
+ : curEnd);
1768
+ updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
1769
+ : curStart);
1770
+ },
1771
+ joinLines: function(cm, actionArgs, vim) {
1772
+ var curStart, curEnd;
1773
+ if (vim.visualMode) {
1774
+ curStart = cm.getCursor('anchor');
1775
+ curEnd = cm.getCursor('head');
1776
+ curEnd.ch = lineLength(cm, curEnd.line) - 1;
1777
+ } else {
1778
+ // Repeat is the number of lines to join. Minimum 2 lines.
1779
+ var repeat = Math.max(actionArgs.repeat, 2);
1780
+ curStart = cm.getCursor();
1781
+ curEnd = clipCursorToContent(cm, { line: curStart.line + repeat - 1,
1782
+ ch: Infinity });
1783
+ }
1784
+ var finalCh = 0;
1785
+ cm.operation(function() {
1786
+ for (var i = curStart.line; i < curEnd.line; i++) {
1787
+ finalCh = lineLength(cm, curStart.line);
1788
+ var tmp = { line: curStart.line + 1,
1789
+ ch: lineLength(cm, curStart.line + 1) };
1790
+ var text = cm.getRange(curStart, tmp);
1791
+ text = text.replace(/\n\s*/g, ' ');
1792
+ cm.replaceRange(text, curStart, tmp);
1793
+ }
1794
+ var curFinalPos = { line: curStart.line, ch: finalCh };
1795
+ cm.setCursor(curFinalPos);
1796
+ });
1797
+ },
1798
+ newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
1799
+ vim.insertMode = true;
1800
+ var insertAt = cm.getCursor();
1801
+ if (insertAt.line === cm.firstLine() && !actionArgs.after) {
1802
+ // Special case for inserting newline before start of document.
1803
+ cm.replaceRange('\n', { line: cm.firstLine(), ch: 0 });
1804
+ cm.setCursor(cm.firstLine(), 0);
1805
+ } else {
1806
+ insertAt.line = (actionArgs.after) ? insertAt.line :
1807
+ insertAt.line - 1;
1808
+ insertAt.ch = lineLength(cm, insertAt.line);
1809
+ cm.setCursor(insertAt);
1810
+ var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
1811
+ CodeMirror.commands.newlineAndIndent;
1812
+ newlineFn(cm);
1813
+ }
1814
+ this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
1815
+ },
1816
+ paste: function(cm, actionArgs) {
1817
+ var cur = cm.getCursor();
1818
+ var register = vimGlobalState.registerController.getRegister(
1819
+ actionArgs.registerName);
1820
+ if (!register.text) {
1821
+ return;
1822
+ }
1823
+ for (var text = '', i = 0; i < actionArgs.repeat; i++) {
1824
+ text += register.text;
1825
+ }
1826
+ var linewise = register.linewise;
1827
+ if (linewise) {
1828
+ if (actionArgs.after) {
1829
+ // Move the newline at the end to the start instead, and paste just
1830
+ // before the newline character of the line we are on right now.
1831
+ text = '\n' + text.slice(0, text.length - 1);
1832
+ cur.ch = lineLength(cm, cur.line);
1833
+ } else {
1834
+ cur.ch = 0;
1835
+ }
1836
+ } else {
1837
+ cur.ch += actionArgs.after ? 1 : 0;
1838
+ }
1839
+ cm.replaceRange(text, cur);
1840
+ // Now fine tune the cursor to where we want it.
1841
+ var curPosFinal;
1842
+ var idx;
1843
+ if (linewise && actionArgs.after) {
1844
+ curPosFinal = { line: cur.line + 1,
1845
+ ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)) };
1846
+ } else if (linewise && !actionArgs.after) {
1847
+ curPosFinal = { line: cur.line,
1848
+ ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)) };
1849
+ } else if (!linewise && actionArgs.after) {
1850
+ idx = cm.indexFromPos(cur);
1851
+ curPosFinal = cm.posFromIndex(idx + text.length - 1);
1852
+ } else {
1853
+ idx = cm.indexFromPos(cur);
1854
+ curPosFinal = cm.posFromIndex(idx + text.length);
1855
+ }
1856
+ cm.setCursor(curPosFinal);
1857
+ },
1858
+ undo: function(cm, actionArgs) {
1859
+ cm.operation(function() {
1860
+ repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
1861
+ cm.setCursor(cm.getCursor('anchor'));
1862
+ });
1863
+ },
1864
+ redo: function(cm, actionArgs) {
1865
+ repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
1866
+ },
1867
+ setRegister: function(_cm, actionArgs, vim) {
1868
+ vim.inputState.registerName = actionArgs.selectedCharacter;
1869
+ },
1870
+ setMark: function(cm, actionArgs, vim) {
1871
+ var markName = actionArgs.selectedCharacter;
1872
+ updateMark(cm, vim, markName, cm.getCursor());
1873
+ },
1874
+ replace: function(cm, actionArgs, vim) {
1875
+ var replaceWith = actionArgs.selectedCharacter;
1876
+ var curStart = cm.getCursor();
1877
+ var replaceTo;
1878
+ var curEnd;
1879
+ if(vim.visualMode){
1880
+ curStart=cm.getCursor('start');
1881
+ curEnd=cm.getCursor('end');
1882
+ // workaround to catch the character under the cursor
1883
+ // existing workaround doesn't cover actions
1884
+ curEnd=cm.clipPos({line: curEnd.line, ch: curEnd.ch+1});
1885
+ }else{
1886
+ var line = cm.getLine(curStart.line);
1887
+ replaceTo = curStart.ch + actionArgs.repeat;
1888
+ if (replaceTo > line.length) {
1889
+ replaceTo=line.length;
1890
+ }
1891
+ curEnd = { line: curStart.line, ch: replaceTo };
1892
+ }
1893
+ if(replaceWith=='\n'){
1894
+ if(!vim.visualMode) cm.replaceRange('', curStart, curEnd);
1895
+ // special case, where vim help says to replace by just one line-break
1896
+ (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
1897
+ }else {
1898
+ var replaceWithStr=cm.getRange(curStart, curEnd);
1899
+ //replace all characters in range by selected, but keep linebreaks
1900
+ replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith);
1901
+ cm.replaceRange(replaceWithStr, curStart, curEnd);
1902
+ if(vim.visualMode){
1903
+ cm.setCursor(curStart);
1904
+ exitVisualMode(cm);
1905
+ }else{
1906
+ cm.setCursor(offsetCursor(curEnd, 0, -1));
1907
+ }
1908
+ }
1909
+ },
1910
+ incrementNumberToken: function(cm, actionArgs) {
1911
+ var cur = cm.getCursor();
1912
+ var lineStr = cm.getLine(cur.line);
1913
+ var re = /-?\d+/g;
1914
+ var match;
1915
+ var start;
1916
+ var end;
1917
+ var numberStr;
1918
+ var token;
1919
+ while ((match = re.exec(lineStr)) !== null) {
1920
+ token = match[0];
1921
+ start = match.index;
1922
+ end = start + token.length;
1923
+ if(cur.ch < end)break;
1924
+ }
1925
+ if(!actionArgs.backtrack && (end <= cur.ch))return;
1926
+ if (token) {
1927
+ var increment = actionArgs.increase ? 1 : -1;
1928
+ var number = parseInt(token) + (increment * actionArgs.repeat);
1929
+ var from = {ch:start, line:cur.line};
1930
+ var to = {ch:end, line:cur.line};
1931
+ numberStr = number.toString();
1932
+ cm.replaceRange(numberStr, from, to);
1933
+ } else {
1934
+ return;
1935
+ }
1936
+ cm.setCursor({line: cur.line, ch: start + numberStr.length - 1});
1937
+ },
1938
+ repeatLastEdit: function(cm, actionArgs, vim) {
1939
+ var lastEditInputState = vim.lastEditInputState;
1940
+ if (!lastEditInputState) { return; }
1941
+ var repeat = actionArgs.repeat;
1942
+ if (repeat && actionArgs.repeatIsExplicit) {
1943
+ vim.lastEditInputState.repeatOverride = repeat;
1944
+ } else {
1945
+ repeat = vim.lastEditInputState.repeatOverride || repeat;
1946
+ }
1947
+ repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
1948
+ }
1949
+ };
1950
+
1951
+ var textObjects = {
1952
+ // TODO: lots of possible exceptions that can be thrown here. Try da(
1953
+ // outside of a () block.
1954
+ // TODO: implement text objects for the reverse like }. Should just be
1955
+ // an additional mapping after moving to the defaultKeyMap.
1956
+ 'w': function(cm, inclusive) {
1957
+ return expandWordUnderCursor(cm, inclusive, true /** forward */,
1958
+ false /** bigWord */);
1959
+ },
1960
+ 'W': function(cm, inclusive) {
1961
+ return expandWordUnderCursor(cm, inclusive,
1962
+ true /** forward */, true /** bigWord */);
1963
+ },
1964
+ '{': function(cm, inclusive) {
1965
+ return selectCompanionObject(cm, '}', inclusive);
1966
+ },
1967
+ '(': function(cm, inclusive) {
1968
+ return selectCompanionObject(cm, ')', inclusive);
1969
+ },
1970
+ '[': function(cm, inclusive) {
1971
+ return selectCompanionObject(cm, ']', inclusive);
1972
+ },
1973
+ '\'': function(cm, inclusive) {
1974
+ return findBeginningAndEnd(cm, "'", inclusive);
1975
+ },
1976
+ '"': function(cm, inclusive) {
1977
+ return findBeginningAndEnd(cm, '"', inclusive);
1978
+ }
1979
+ };
1980
+
1981
+ /*
1982
+ * Below are miscellaneous utility functions used by vim.js
1983
+ */
1984
+
1985
+ /**
1986
+ * Clips cursor to ensure that line is within the buffer's range
1987
+ * If includeLineBreak is true, then allow cur.ch == lineLength.
1988
+ */
1989
+ function clipCursorToContent(cm, cur, includeLineBreak) {
1990
+ var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
1991
+ var maxCh = lineLength(cm, line) - 1;
1992
+ maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
1993
+ var ch = Math.min(Math.max(0, cur.ch), maxCh);
1994
+ return { line: line, ch: ch };
1995
+ }
1996
+ function copyArgs(args) {
1997
+ var ret = {};
1998
+ for (var prop in args) {
1999
+ if (args.hasOwnProperty(prop)) {
2000
+ ret[prop] = args[prop];
2001
+ }
2002
+ }
2003
+ return ret;
2004
+ }
2005
+ function offsetCursor(cur, offsetLine, offsetCh) {
2006
+ return { line: cur.line + offsetLine, ch: cur.ch + offsetCh };
2007
+ }
2008
+ function matchKeysPartial(pressed, mapped) {
2009
+ for (var i = 0; i < pressed.length; i++) {
2010
+ // 'character' means any character. For mark, register commads, etc.
2011
+ if (pressed[i] != mapped[i] && mapped[i] != 'character') {
2012
+ return false;
2013
+ }
2014
+ }
2015
+ return true;
2016
+ }
2017
+ function repeatFn(cm, fn, repeat) {
2018
+ return function() {
2019
+ for (var i = 0; i < repeat; i++) {
2020
+ fn(cm);
2021
+ }
2022
+ };
2023
+ }
2024
+ function copyCursor(cur) {
2025
+ return { line: cur.line, ch: cur.ch };
2026
+ }
2027
+ function cursorEqual(cur1, cur2) {
2028
+ return cur1.ch == cur2.ch && cur1.line == cur2.line;
2029
+ }
2030
+ function cursorIsBefore(cur1, cur2) {
2031
+ if (cur1.line < cur2.line) {
2032
+ return true;
2033
+ }
2034
+ if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
2035
+ return true;
2036
+ }
2037
+ return false;
2038
+ }
2039
+ function cusrorIsBetween(cur1, cur2, cur3) {
2040
+ // returns true if cur2 is between cur1 and cur3.
2041
+ var cur1before2 = cursorIsBefore(cur1, cur2);
2042
+ var cur2before3 = cursorIsBefore(cur2, cur3);
2043
+ return cur1before2 && cur2before3;
2044
+ }
2045
+ function lineLength(cm, lineNum) {
2046
+ return cm.getLine(lineNum).length;
2047
+ }
2048
+ function reverse(s){
2049
+ return s.split('').reverse().join('');
2050
+ }
2051
+ function trim(s) {
2052
+ if (s.trim) {
2053
+ return s.trim();
2054
+ }
2055
+ return s.replace(/^\s+|\s+$/g, '');
2056
+ }
2057
+ function escapeRegex(s) {
2058
+ return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
2059
+ }
2060
+
2061
+ function exitVisualMode(cm) {
2062
+ cm.off('mousedown', exitVisualMode);
2063
+ var vim = cm.state.vim;
2064
+ vim.visualMode = false;
2065
+ vim.visualLine = false;
2066
+ var selectionStart = cm.getCursor('anchor');
2067
+ var selectionEnd = cm.getCursor('head');
2068
+ if (!cursorEqual(selectionStart, selectionEnd)) {
2069
+ // Clear the selection and set the cursor only if the selection has not
2070
+ // already been cleared. Otherwise we risk moving the cursor somewhere
2071
+ // it's not supposed to be.
2072
+ cm.setCursor(clipCursorToContent(cm, selectionEnd));
2073
+ }
2074
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
2075
+ }
2076
+
2077
+ // Remove any trailing newlines from the selection. For
2078
+ // example, with the caret at the start of the last word on the line,
2079
+ // 'dw' should word, but not the newline, while 'w' should advance the
2080
+ // caret to the first character of the next line.
2081
+ function clipToLine(cm, curStart, curEnd) {
2082
+ var selection = cm.getRange(curStart, curEnd);
2083
+ // Only clip if the selection ends with trailing newline + whitespace
2084
+ if (/\n\s*$/.test(selection)) {
2085
+ var lines = selection.split('\n');
2086
+ // We know this is all whitepsace.
2087
+ lines.pop();
2088
+
2089
+ // Cases:
2090
+ // 1. Last word is an empty line - do not clip the trailing '\n'
2091
+ // 2. Last word is not an empty line - clip the trailing '\n'
2092
+ var line;
2093
+ // Find the line containing the last word, and clip all whitespace up
2094
+ // to it.
2095
+ for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
2096
+ curEnd.line--;
2097
+ curEnd.ch = 0;
2098
+ }
2099
+ // If the last word is not an empty line, clip an additional newline
2100
+ if (line) {
2101
+ curEnd.line--;
2102
+ curEnd.ch = lineLength(cm, curEnd.line);
2103
+ } else {
2104
+ curEnd.ch = 0;
2105
+ }
2106
+ }
2107
+ }
2108
+
2109
+ // Expand the selection to line ends.
2110
+ function expandSelectionToLine(_cm, curStart, curEnd) {
2111
+ curStart.ch = 0;
2112
+ curEnd.ch = 0;
2113
+ curEnd.line++;
2114
+ }
2115
+
2116
+ function findFirstNonWhiteSpaceCharacter(text) {
2117
+ if (!text) {
2118
+ return 0;
2119
+ }
2120
+ var firstNonWS = text.search(/\S/);
2121
+ return firstNonWS == -1 ? text.length : firstNonWS;
2122
+ }
2123
+
2124
+ function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
2125
+ var cur = cm.getCursor();
2126
+ var line = cm.getLine(cur.line);
2127
+ var idx = cur.ch;
2128
+
2129
+ // Seek to first word or non-whitespace character, depending on if
2130
+ // noSymbol is true.
2131
+ var textAfterIdx = line.substring(idx);
2132
+ var firstMatchedChar;
2133
+ if (noSymbol) {
2134
+ firstMatchedChar = textAfterIdx.search(/\w/);
2135
+ } else {
2136
+ firstMatchedChar = textAfterIdx.search(/\S/);
2137
+ }
2138
+ if (firstMatchedChar == -1) {
2139
+ return null;
2140
+ }
2141
+ idx += firstMatchedChar;
2142
+ textAfterIdx = line.substring(idx);
2143
+ var textBeforeIdx = line.substring(0, idx);
2144
+
2145
+ var matchRegex;
2146
+ // Greedy matchers for the "word" we are trying to expand.
2147
+ if (bigWord) {
2148
+ matchRegex = /^\S+/;
2149
+ } else {
2150
+ if ((/\w/).test(line.charAt(idx))) {
2151
+ matchRegex = /^\w+/;
2152
+ } else {
2153
+ matchRegex = /^[^\w\s]+/;
2154
+ }
2155
+ }
2156
+
2157
+ var wordAfterRegex = matchRegex.exec(textAfterIdx);
2158
+ var wordStart = idx;
2159
+ var wordEnd = idx + wordAfterRegex[0].length;
2160
+ // TODO: Find a better way to do this. It will be slow on very long lines.
2161
+ var revTextBeforeIdx = reverse(textBeforeIdx);
2162
+ var wordBeforeRegex = matchRegex.exec(revTextBeforeIdx);
2163
+ if (wordBeforeRegex) {
2164
+ wordStart -= wordBeforeRegex[0].length;
2165
+ }
2166
+
2167
+ if (inclusive) {
2168
+ // If present, trim all whitespace after word.
2169
+ // Otherwise, trim all whitespace before word.
2170
+ var textAfterWordEnd = line.substring(wordEnd);
2171
+ var whitespacesAfterWord = textAfterWordEnd.match(/^\s*/)[0].length;
2172
+ if (whitespacesAfterWord > 0) {
2173
+ wordEnd += whitespacesAfterWord;
2174
+ } else {
2175
+ var revTrim = revTextBeforeIdx.length - wordStart;
2176
+ var textBeforeWordStart = revTextBeforeIdx.substring(revTrim);
2177
+ var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length;
2178
+ wordStart -= whitespacesBeforeWord;
2179
+ }
2180
+ }
2181
+
2182
+ return { start: { line: cur.line, ch: wordStart },
2183
+ end: { line: cur.line, ch: wordEnd }};
2184
+ }
2185
+
2186
+ function recordJumpPosition(cm, oldCur, newCur) {
2187
+ if(!cursorEqual(oldCur, newCur)) {
2188
+ vimGlobalState.jumpList.add(cm, oldCur, newCur);
2189
+ }
2190
+ }
2191
+
2192
+ function recordLastCharacterSearch(increment, args) {
2193
+ vimGlobalState.lastChararacterSearch.increment = increment;
2194
+ vimGlobalState.lastChararacterSearch.forward = args.forward;
2195
+ vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
2196
+ }
2197
+
2198
+ var symbolToMode = {
2199
+ '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
2200
+ '[': 'section', ']': 'section',
2201
+ '*': 'comment', '/': 'comment',
2202
+ 'm': 'method', 'M': 'method',
2203
+ '#': 'preprocess'
2204
+ };
2205
+ var findSymbolModes = {
2206
+ bracket: {
2207
+ isComplete: function(state) {
2208
+ if (state.nextCh === state.symb) {
2209
+ state.depth++;
2210
+ if(state.depth >= 1)return true;
2211
+ } else if (state.nextCh === state.reverseSymb) {
2212
+ state.depth--;
2213
+ }
2214
+ return false;
2215
+ }
2216
+ },
2217
+ section: {
2218
+ init: function(state) {
2219
+ state.curMoveThrough = true;
2220
+ state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
2221
+ },
2222
+ isComplete: function(state) {
2223
+ return state.index === 0 && state.nextCh === state.symb;
2224
+ }
2225
+ },
2226
+ comment: {
2227
+ isComplete: function(state) {
2228
+ var found = state.lastCh === '*' && state.nextCh === '/';
2229
+ state.lastCh = state.nextCh;
2230
+ return found;
2231
+ }
2232
+ },
2233
+ // TODO: The original Vim implementation only operates on level 1 and 2.
2234
+ // The current implementation doesn't check for code block level and
2235
+ // therefore it operates on any levels.
2236
+ method: {
2237
+ init: function(state) {
2238
+ state.symb = (state.symb === 'm' ? '{' : '}');
2239
+ state.reverseSymb = state.symb === '{' ? '}' : '{';
2240
+ },
2241
+ isComplete: function(state) {
2242
+ if(state.nextCh === state.symb)return true;
2243
+ return false;
2244
+ }
2245
+ },
2246
+ preprocess: {
2247
+ init: function(state) {
2248
+ state.index = 0;
2249
+ },
2250
+ isComplete: function(state) {
2251
+ if (state.nextCh === '#') {
2252
+ var token = state.lineText.match(/#(\w+)/)[1];
2253
+ if (token === 'endif') {
2254
+ if (state.forward && state.depth === 0) {
2255
+ return true;
2256
+ }
2257
+ state.depth++;
2258
+ } else if (token === 'if') {
2259
+ if (!state.forward && state.depth === 0) {
2260
+ return true;
2261
+ }
2262
+ state.depth--;
2263
+ }
2264
+ if(token === 'else' && state.depth === 0)return true;
2265
+ }
2266
+ return false;
2267
+ }
2268
+ }
2269
+ };
2270
+ function findSymbol(cm, repeat, forward, symb) {
2271
+ var cur = cm.getCursor();
2272
+ var increment = forward ? 1 : -1;
2273
+ var endLine = forward ? cm.lineCount() : -1;
2274
+ var curCh = cur.ch;
2275
+ var line = cur.line;
2276
+ var lineText = cm.getLine(line);
2277
+ var state = {
2278
+ lineText: lineText,
2279
+ nextCh: lineText.charAt(curCh),
2280
+ lastCh: null,
2281
+ index: curCh,
2282
+ symb: symb,
2283
+ reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
2284
+ forward: forward,
2285
+ depth: 0,
2286
+ curMoveThrough: false
2287
+ };
2288
+ var mode = symbolToMode[symb];
2289
+ if(!mode)return cur;
2290
+ var init = findSymbolModes[mode].init;
2291
+ var isComplete = findSymbolModes[mode].isComplete;
2292
+ if(init)init(state);
2293
+ while (line !== endLine && repeat) {
2294
+ state.index += increment;
2295
+ state.nextCh = state.lineText.charAt(state.index);
2296
+ if (!state.nextCh) {
2297
+ line += increment;
2298
+ state.lineText = cm.getLine(line) || '';
2299
+ if (increment > 0) {
2300
+ state.index = 0;
2301
+ } else {
2302
+ var lineLen = state.lineText.length;
2303
+ state.index = (lineLen > 0) ? (lineLen-1) : 0;
2304
+ }
2305
+ state.nextCh = state.lineText.charAt(state.index);
2306
+ }
2307
+ if (isComplete(state)) {
2308
+ cur.line = line;
2309
+ cur.ch = state.index;
2310
+ repeat--;
2311
+ }
2312
+ }
2313
+ if (state.nextCh || state.curMoveThrough) {
2314
+ return { line: line, ch: state.index };
2315
+ }
2316
+ return cur;
2317
+ }
2318
+
2319
+ /*
2320
+ * Returns the boundaries of the next word. If the cursor in the middle of
2321
+ * the word, then returns the boundaries of the current word, starting at
2322
+ * the cursor. If the cursor is at the start/end of a word, and we are going
2323
+ * forward/backward, respectively, find the boundaries of the next word.
2324
+ *
2325
+ * @param {CodeMirror} cm CodeMirror object.
2326
+ * @param {Cursor} cur The cursor position.
2327
+ * @param {boolean} forward True to search forward. False to search
2328
+ * backward.
2329
+ * @param {boolean} bigWord True if punctuation count as part of the word.
2330
+ * False if only [a-zA-Z0-9] characters count as part of the word.
2331
+ * @param {boolean} emptyLineIsWord True if empty lines should be treated
2332
+ * as words.
2333
+ * @return {Object{from:number, to:number, line: number}} The boundaries of
2334
+ * the word, or null if there are no more words.
2335
+ */
2336
+ function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
2337
+ var lineNum = cur.line;
2338
+ var pos = cur.ch;
2339
+ var line = cm.getLine(lineNum);
2340
+ var dir = forward ? 1 : -1;
2341
+ var regexps = bigWord ? bigWordRegexp : wordRegexp;
2342
+
2343
+ if (emptyLineIsWord && line == '') {
2344
+ lineNum += dir;
2345
+ line = cm.getLine(lineNum);
2346
+ if (!isLine(cm, lineNum)) {
2347
+ return null;
2348
+ }
2349
+ pos = (forward) ? 0 : line.length;
2350
+ }
2351
+
2352
+ while (true) {
2353
+ if (emptyLineIsWord && line == '') {
2354
+ return { from: 0, to: 0, line: lineNum };
2355
+ }
2356
+ var stop = (dir > 0) ? line.length : -1;
2357
+ var wordStart = stop, wordEnd = stop;
2358
+ // Find bounds of next word.
2359
+ while (pos != stop) {
2360
+ var foundWord = false;
2361
+ for (var i = 0; i < regexps.length && !foundWord; ++i) {
2362
+ if (regexps[i].test(line.charAt(pos))) {
2363
+ wordStart = pos;
2364
+ // Advance to end of word.
2365
+ while (pos != stop && regexps[i].test(line.charAt(pos))) {
2366
+ pos += dir;
2367
+ }
2368
+ wordEnd = pos;
2369
+ foundWord = wordStart != wordEnd;
2370
+ if (wordStart == cur.ch && lineNum == cur.line &&
2371
+ wordEnd == wordStart + dir) {
2372
+ // We started at the end of a word. Find the next one.
2373
+ continue;
2374
+ } else {
2375
+ return {
2376
+ from: Math.min(wordStart, wordEnd + 1),
2377
+ to: Math.max(wordStart, wordEnd),
2378
+ line: lineNum };
2379
+ }
2380
+ }
2381
+ }
2382
+ if (!foundWord) {
2383
+ pos += dir;
2384
+ }
2385
+ }
2386
+ // Advance to next/prev line.
2387
+ lineNum += dir;
2388
+ if (!isLine(cm, lineNum)) {
2389
+ return null;
2390
+ }
2391
+ line = cm.getLine(lineNum);
2392
+ pos = (dir > 0) ? 0 : line.length;
2393
+ }
2394
+ // Should never get here.
2395
+ throw new Error('The impossible happened.');
2396
+ }
2397
+
2398
+ /**
2399
+ * @param {CodeMirror} cm CodeMirror object.
2400
+ * @param {int} repeat Number of words to move past.
2401
+ * @param {boolean} forward True to search forward. False to search
2402
+ * backward.
2403
+ * @param {boolean} wordEnd True to move to end of word. False to move to
2404
+ * beginning of word.
2405
+ * @param {boolean} bigWord True if punctuation count as part of the word.
2406
+ * False if only alphabet characters count as part of the word.
2407
+ * @return {Cursor} The position the cursor should move to.
2408
+ */
2409
+ function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
2410
+ var cur = cm.getCursor();
2411
+ var curStart = copyCursor(cur);
2412
+ var words = [];
2413
+ if (forward && !wordEnd || !forward && wordEnd) {
2414
+ repeat++;
2415
+ }
2416
+ // For 'e', empty lines are not considered words, go figure.
2417
+ var emptyLineIsWord = !(forward && wordEnd);
2418
+ for (var i = 0; i < repeat; i++) {
2419
+ var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
2420
+ if (!word) {
2421
+ var eodCh = lineLength(cm, cm.lastLine());
2422
+ words.push(forward
2423
+ ? {line: cm.lastLine(), from: eodCh, to: eodCh}
2424
+ : {line: 0, from: 0, to: 0});
2425
+ break;
2426
+ }
2427
+ words.push(word);
2428
+ cur = {line: word.line, ch: forward ? (word.to - 1) : word.from};
2429
+ }
2430
+ var shortCircuit = words.length != repeat;
2431
+ var firstWord = words[0];
2432
+ var lastWord = words.pop();
2433
+ if (forward && !wordEnd) {
2434
+ // w
2435
+ if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
2436
+ // We did not start in the middle of a word. Discard the extra word at the end.
2437
+ lastWord = words.pop();
2438
+ }
2439
+ return {line: lastWord.line, ch: lastWord.from};
2440
+ } else if (forward && wordEnd) {
2441
+ return {line: lastWord.line, ch: lastWord.to - 1};
2442
+ } else if (!forward && wordEnd) {
2443
+ // ge
2444
+ if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
2445
+ // We did not start in the middle of a word. Discard the extra word at the end.
2446
+ lastWord = words.pop();
2447
+ }
2448
+ return {line: lastWord.line, ch: lastWord.to};
2449
+ } else {
2450
+ // b
2451
+ return {line: lastWord.line, ch: lastWord.from};
2452
+ }
2453
+ }
2454
+
2455
+ function moveToCharacter(cm, repeat, forward, character) {
2456
+ var cur = cm.getCursor();
2457
+ var start = cur.ch;
2458
+ var idx;
2459
+ for (var i = 0; i < repeat; i ++) {
2460
+ var line = cm.getLine(cur.line);
2461
+ idx = charIdxInLine(start, line, character, forward, true);
2462
+ if (idx == -1) {
2463
+ return null;
2464
+ }
2465
+ start = idx;
2466
+ }
2467
+ return { line: cm.getCursor().line, ch: idx };
2468
+ }
2469
+
2470
+ function moveToColumn(cm, repeat) {
2471
+ // repeat is always >= 1, so repeat - 1 always corresponds
2472
+ // to the column we want to go to.
2473
+ var line = cm.getCursor().line;
2474
+ return clipCursorToContent(cm, { line: line, ch: repeat - 1 });
2475
+ }
2476
+
2477
+ function updateMark(cm, vim, markName, pos) {
2478
+ if (!inArray(markName, validMarks)) {
2479
+ return;
2480
+ }
2481
+ if (vim.marks[markName]) {
2482
+ vim.marks[markName].clear();
2483
+ }
2484
+ vim.marks[markName] = cm.setBookmark(pos);
2485
+ }
2486
+
2487
+ function charIdxInLine(start, line, character, forward, includeChar) {
2488
+ // Search for char in line.
2489
+ // motion_options: {forward, includeChar}
2490
+ // If includeChar = true, include it too.
2491
+ // If forward = true, search forward, else search backwards.
2492
+ // If char is not found on this line, do nothing
2493
+ var idx;
2494
+ if (forward) {
2495
+ idx = line.indexOf(character, start + 1);
2496
+ if (idx != -1 && !includeChar) {
2497
+ idx -= 1;
2498
+ }
2499
+ } else {
2500
+ idx = line.lastIndexOf(character, start - 1);
2501
+ if (idx != -1 && !includeChar) {
2502
+ idx += 1;
2503
+ }
2504
+ }
2505
+ return idx;
2506
+ }
2507
+
2508
+ function getContextLevel(ctx) {
2509
+ return (ctx === 'string' || ctx === 'comment') ? 1 : 0;
2510
+ }
2511
+
2512
+ function findMatchedSymbol(cm, cur, symb) {
2513
+ var line = cur.line;
2514
+ var ch = cur.ch;
2515
+ symb = symb ? symb : cm.getLine(line).charAt(ch);
2516
+
2517
+ var symbContext = cm.getTokenAt({line:line, ch:ch+1}).type;
2518
+ var symbCtxLevel = getContextLevel(symbContext);
2519
+
2520
+ var reverseSymb = ({
2521
+ '(': ')', ')': '(',
2522
+ '[': ']', ']': '[',
2523
+ '{': '}', '}': '{'})[symb];
2524
+
2525
+ // Couldn't find a matching symbol, abort
2526
+ if (!reverseSymb) {
2527
+ return cur;
2528
+ }
2529
+
2530
+ // set our increment to move forward (+1) or backwards (-1)
2531
+ // depending on which bracket we're matching
2532
+ var increment = ({'(': 1, '{': 1, '[': 1})[symb] || -1;
2533
+ var endLine = increment === 1 ? cm.lineCount() : -1;
2534
+ var depth = 1, nextCh = symb, index = ch, lineText = cm.getLine(line);
2535
+ // Simple search for closing paren--just count openings and closings till
2536
+ // we find our match
2537
+ // TODO: use info from CodeMirror to ignore closing brackets in comments
2538
+ // and quotes, etc.
2539
+ while (line !== endLine && depth > 0) {
2540
+ index += increment;
2541
+ nextCh = lineText.charAt(index);
2542
+ if (!nextCh) {
2543
+ line += increment;
2544
+ lineText = cm.getLine(line) || '';
2545
+ if (increment > 0) {
2546
+ index = 0;
2547
+ } else {
2548
+ var lineLen = lineText.length;
2549
+ index = (lineLen > 0) ? (lineLen-1) : 0;
2550
+ }
2551
+ nextCh = lineText.charAt(index);
2552
+ }
2553
+ var revSymbContext = cm.getTokenAt({line:line, ch:index+1}).type;
2554
+ var revSymbCtxLevel = getContextLevel(revSymbContext);
2555
+ if (symbCtxLevel >= revSymbCtxLevel) {
2556
+ if (nextCh === symb) {
2557
+ depth++;
2558
+ } else if (nextCh === reverseSymb) {
2559
+ depth--;
2560
+ }
2561
+ }
2562
+ }
2563
+
2564
+ if (nextCh) {
2565
+ return { line: line, ch: index };
2566
+ }
2567
+ return cur;
2568
+ }
2569
+
2570
+ function selectCompanionObject(cm, revSymb, inclusive) {
2571
+ var cur = cm.getCursor();
2572
+
2573
+ var end = findMatchedSymbol(cm, cur, revSymb);
2574
+ var start = findMatchedSymbol(cm, end);
2575
+ start.ch += inclusive ? 1 : 0;
2576
+ end.ch += inclusive ? 0 : 1;
2577
+
2578
+ return { start: start, end: end };
2579
+ }
2580
+
2581
+ // Takes in a symbol and a cursor and tries to simulate text objects that
2582
+ // have identical opening and closing symbols
2583
+ // TODO support across multiple lines
2584
+ function findBeginningAndEnd(cm, symb, inclusive) {
2585
+ var cur = cm.getCursor();
2586
+ var line = cm.getLine(cur.line);
2587
+ var chars = line.split('');
2588
+ var start, end, i, len;
2589
+ var firstIndex = chars.indexOf(symb);
2590
+
2591
+ // the decision tree is to always look backwards for the beginning first,
2592
+ // but if the cursor is in front of the first instance of the symb,
2593
+ // then move the cursor forward
2594
+ if (cur.ch < firstIndex) {
2595
+ cur.ch = firstIndex;
2596
+ // Why is this line even here???
2597
+ // cm.setCursor(cur.line, firstIndex+1);
2598
+ }
2599
+ // otherwise if the cursor is currently on the closing symbol
2600
+ else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
2601
+ end = cur.ch; // assign end to the current cursor
2602
+ --cur.ch; // make sure to look backwards
2603
+ }
2604
+
2605
+ // if we're currently on the symbol, we've got a start
2606
+ if (chars[cur.ch] == symb && !end) {
2607
+ start = cur.ch + 1; // assign start to ahead of the cursor
2608
+ } else {
2609
+ // go backwards to find the start
2610
+ for (i = cur.ch; i > -1 && !start; i--) {
2611
+ if (chars[i] == symb) {
2612
+ start = i + 1;
2613
+ }
2614
+ }
2615
+ }
2616
+
2617
+ // look forwards for the end symbol
2618
+ if (start && !end) {
2619
+ for (i = start, len = chars.length; i < len && !end; i++) {
2620
+ if (chars[i] == symb) {
2621
+ end = i;
2622
+ }
2623
+ }
2624
+ }
2625
+
2626
+ // nothing found
2627
+ if (!start || !end) {
2628
+ return { start: cur, end: cur };
2629
+ }
2630
+
2631
+ // include the symbols
2632
+ if (inclusive) {
2633
+ --start; ++end;
2634
+ }
2635
+
2636
+ return {
2637
+ start: { line: cur.line, ch: start },
2638
+ end: { line: cur.line, ch: end }
2639
+ };
2640
+ }
2641
+
2642
+ // Search functions
2643
+ function SearchState() {}
2644
+ SearchState.prototype = {
2645
+ getQuery: function() {
2646
+ return vimGlobalState.query;
2647
+ },
2648
+ setQuery: function(query) {
2649
+ vimGlobalState.query = query;
2650
+ },
2651
+ getOverlay: function() {
2652
+ return this.searchOverlay;
2653
+ },
2654
+ setOverlay: function(overlay) {
2655
+ this.searchOverlay = overlay;
2656
+ },
2657
+ isReversed: function() {
2658
+ return vimGlobalState.isReversed;
2659
+ },
2660
+ setReversed: function(reversed) {
2661
+ vimGlobalState.isReversed = reversed;
2662
+ }
2663
+ };
2664
+ function getSearchState(cm) {
2665
+ var vim = cm.state.vim;
2666
+ return vim.searchState_ || (vim.searchState_ = new SearchState());
2667
+ }
2668
+ function dialog(cm, template, shortText, onClose, options) {
2669
+ if (cm.openDialog) {
2670
+ cm.openDialog(template, onClose, { bottom: true, value: options.value,
2671
+ onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp });
2672
+ }
2673
+ else {
2674
+ onClose(prompt(shortText, ''));
2675
+ }
2676
+ }
2677
+
2678
+ function findUnescapedSlashes(str) {
2679
+ var escapeNextChar = false;
2680
+ var slashes = [];
2681
+ for (var i = 0; i < str.length; i++) {
2682
+ var c = str.charAt(i);
2683
+ if (!escapeNextChar && c == '/') {
2684
+ slashes.push(i);
2685
+ }
2686
+ escapeNextChar = (c == '\\');
2687
+ }
2688
+ return slashes;
2689
+ }
2690
+ /**
2691
+ * Extract the regular expression from the query and return a Regexp object.
2692
+ * Returns null if the query is blank.
2693
+ * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
2694
+ * If smartCase is passed in, and the query contains upper case letters,
2695
+ * then ignoreCase is overridden, and the 'i' flag will not be set.
2696
+ * If the query contains the /i in the flag part of the regular expression,
2697
+ * then both ignoreCase and smartCase are ignored, and 'i' will be passed
2698
+ * through to the Regex object.
2699
+ */
2700
+ function parseQuery(query, ignoreCase, smartCase) {
2701
+ // Check if the query is already a regex.
2702
+ if (query instanceof RegExp) { return query; }
2703
+ // First try to extract regex + flags from the input. If no flags found,
2704
+ // extract just the regex. IE does not accept flags directly defined in
2705
+ // the regex string in the form /regex/flags
2706
+ var slashes = findUnescapedSlashes(query);
2707
+ var regexPart;
2708
+ var forceIgnoreCase;
2709
+ if (!slashes.length) {
2710
+ // Query looks like 'regexp'
2711
+ regexPart = query;
2712
+ } else {
2713
+ // Query looks like 'regexp/...'
2714
+ regexPart = query.substring(0, slashes[0]);
2715
+ var flagsPart = query.substring(slashes[0]);
2716
+ forceIgnoreCase = (flagsPart.indexOf('i') != -1);
2717
+ }
2718
+ if (!regexPart) {
2719
+ return null;
2720
+ }
2721
+ if (smartCase) {
2722
+ ignoreCase = (/^[^A-Z]*$/).test(regexPart);
2723
+ }
2724
+ var regexp = new RegExp(regexPart,
2725
+ (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
2726
+ return regexp;
2727
+ }
2728
+ function showConfirm(cm, text) {
2729
+ if (cm.openNotification) {
2730
+ cm.openNotification('<span style="color: red">' + text + '</span>',
2731
+ {bottom: true, duration: 5000});
2732
+ } else {
2733
+ alert(text);
2734
+ }
2735
+ }
2736
+ function makePrompt(prefix, desc) {
2737
+ var raw = '';
2738
+ if (prefix) {
2739
+ raw += '<span style="font-family: monospace">' + prefix + '</span>';
2740
+ }
2741
+ raw += '<input type="text"/> ' +
2742
+ '<span style="color: #888">';
2743
+ if (desc) {
2744
+ raw += '<span style="color: #888">';
2745
+ raw += desc;
2746
+ raw += '</span>';
2747
+ }
2748
+ return raw;
2749
+ }
2750
+ var searchPromptDesc = '(Javascript regexp)';
2751
+ function showPrompt(cm, options) {
2752
+ var shortText = (options.prefix || '') + ' ' + (options.desc || '');
2753
+ var prompt = makePrompt(options.prefix, options.desc);
2754
+ dialog(cm, prompt, shortText, options.onClose, options);
2755
+ }
2756
+ function regexEqual(r1, r2) {
2757
+ if (r1 instanceof RegExp && r2 instanceof RegExp) {
2758
+ var props = ['global', 'multiline', 'ignoreCase', 'source'];
2759
+ for (var i = 0; i < props.length; i++) {
2760
+ var prop = props[i];
2761
+ if (r1[prop] !== r2[prop]) {
2762
+ return false;
2763
+ }
2764
+ }
2765
+ return true;
2766
+ }
2767
+ return false;
2768
+ }
2769
+ // Returns true if the query is valid.
2770
+ function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
2771
+ if (!rawQuery) {
2772
+ return;
2773
+ }
2774
+ var state = getSearchState(cm);
2775
+ var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
2776
+ if (!query) {
2777
+ return;
2778
+ }
2779
+ highlightSearchMatches(cm, query);
2780
+ if (regexEqual(query, state.getQuery())) {
2781
+ return query;
2782
+ }
2783
+ state.setQuery(query);
2784
+ return query;
2785
+ }
2786
+ function searchOverlay(query) {
2787
+ if (query.source.charAt(0) == '^') {
2788
+ var matchSol = true;
2789
+ }
2790
+ return {
2791
+ token: function(stream) {
2792
+ if (matchSol && !stream.sol()) {
2793
+ stream.skipToEnd();
2794
+ return;
2795
+ }
2796
+ var match = stream.match(query, false);
2797
+ if (match) {
2798
+ if (match[0].length == 0) {
2799
+ // Matched empty string, skip to next.
2800
+ stream.next();
2801
+ return 'searching';
2802
+ }
2803
+ if (!stream.sol()) {
2804
+ // Backtrack 1 to match \b
2805
+ stream.backUp(1);
2806
+ if (!query.exec(stream.next() + match[0])) {
2807
+ stream.next();
2808
+ return null;
2809
+ }
2810
+ }
2811
+ stream.match(query);
2812
+ return 'searching';
2813
+ }
2814
+ while (!stream.eol()) {
2815
+ stream.next();
2816
+ if (stream.match(query, false)) break;
2817
+ }
2818
+ },
2819
+ query: query
2820
+ };
2821
+ }
2822
+ function highlightSearchMatches(cm, query) {
2823
+ var overlay = getSearchState(cm).getOverlay();
2824
+ if (!overlay || query != overlay.query) {
2825
+ if (overlay) {
2826
+ cm.removeOverlay(overlay);
2827
+ }
2828
+ overlay = searchOverlay(query);
2829
+ cm.addOverlay(overlay);
2830
+ getSearchState(cm).setOverlay(overlay);
2831
+ }
2832
+ }
2833
+ function findNext(cm, prev, query, repeat) {
2834
+ if (repeat === undefined) { repeat = 1; }
2835
+ return cm.operation(function() {
2836
+ var pos = cm.getCursor();
2837
+ var cursor = cm.getSearchCursor(query, pos);
2838
+ for (var i = 0; i < repeat; i++) {
2839
+ var found = cursor.find(prev);
2840
+ if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
2841
+ if (!found) {
2842
+ // SearchCursor may have returned null because it hit EOF, wrap
2843
+ // around and try again.
2844
+ cursor = cm.getSearchCursor(query,
2845
+ (prev) ? { line: cm.lastLine() } : {line: cm.firstLine(), ch: 0} );
2846
+ if (!cursor.find(prev)) {
2847
+ return;
2848
+ }
2849
+ }
2850
+ }
2851
+ return cursor.from();
2852
+ });
2853
+ }
2854
+ function clearSearchHighlight(cm) {
2855
+ cm.removeOverlay(getSearchState(cm).getOverlay());
2856
+ getSearchState(cm).setOverlay(null);
2857
+ }
2858
+ /**
2859
+ * Check if pos is in the specified range, INCLUSIVE.
2860
+ * Range can be specified with 1 or 2 arguments.
2861
+ * If the first range argument is an array, treat it as an array of line
2862
+ * numbers. Match pos against any of the lines.
2863
+ * If the first range argument is a number,
2864
+ * if there is only 1 range argument, check if pos has the same line
2865
+ * number
2866
+ * if there are 2 range arguments, then check if pos is in between the two
2867
+ * range arguments.
2868
+ */
2869
+ function isInRange(pos, start, end) {
2870
+ if (typeof pos != 'number') {
2871
+ // Assume it is a cursor position. Get the line number.
2872
+ pos = pos.line;
2873
+ }
2874
+ if (start instanceof Array) {
2875
+ return inArray(pos, start);
2876
+ } else {
2877
+ if (end) {
2878
+ return (pos >= start && pos <= end);
2879
+ } else {
2880
+ return pos == start;
2881
+ }
2882
+ }
2883
+ }
2884
+ function getUserVisibleLines(cm) {
2885
+ var scrollInfo = cm.getScrollInfo();
2886
+ var occludeToleranceTop = 6;
2887
+ var occludeToleranceBottom = 10;
2888
+ var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
2889
+ var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
2890
+ var to = cm.coordsChar({left:0, top: bottomY}, 'local');
2891
+ return {top: from.line, bottom: to.line};
2892
+ }
2893
+
2894
+ // Ex command handling
2895
+ // Care must be taken when adding to the default Ex command map. For any
2896
+ // pair of commands that have a shared prefix, at least one of their
2897
+ // shortNames must not match the prefix of the other command.
2898
+ var defaultExCommandMap = [
2899
+ { name: 'map', type: 'builtIn' },
2900
+ { name: 'write', shortName: 'w', type: 'builtIn' },
2901
+ { name: 'undo', shortName: 'u', type: 'builtIn' },
2902
+ { name: 'redo', shortName: 'red', type: 'builtIn' },
2903
+ { name: 'sort', shortName: 'sor', type: 'builtIn'},
2904
+ { name: 'substitute', shortName: 's', type: 'builtIn'},
2905
+ { name: 'nohlsearch', shortName: 'noh', type: 'builtIn'},
2906
+ { name: 'delmarks', shortName: 'delm', type: 'builtin'}
2907
+ ];
2908
+ Vim.ExCommandDispatcher = function() {
2909
+ this.buildCommandMap_();
2910
+ };
2911
+ Vim.ExCommandDispatcher.prototype = {
2912
+ processCommand: function(cm, input) {
2913
+ var vim = cm.state.vim;
2914
+ if (vim.visualMode) {
2915
+ exitVisualMode(cm);
2916
+ }
2917
+ var inputStream = new CodeMirror.StringStream(input);
2918
+ var params = {};
2919
+ params.input = input;
2920
+ try {
2921
+ this.parseInput_(cm, inputStream, params);
2922
+ } catch(e) {
2923
+ showConfirm(cm, e);
2924
+ return;
2925
+ }
2926
+ var commandName;
2927
+ if (!params.commandName) {
2928
+ // If only a line range is defined, move to the line.
2929
+ if (params.line !== undefined) {
2930
+ commandName = 'move';
2931
+ }
2932
+ } else {
2933
+ var command = this.matchCommand_(params.commandName);
2934
+ if (command) {
2935
+ commandName = command.name;
2936
+ this.parseCommandArgs_(inputStream, params, command);
2937
+ if (command.type == 'exToKey') {
2938
+ // Handle Ex to Key mapping.
2939
+ for (var i = 0; i < command.toKeys.length; i++) {
2940
+ CodeMirror.Vim.handleKey(cm, command.toKeys[i]);
2941
+ }
2942
+ return;
2943
+ } else if (command.type == 'exToEx') {
2944
+ // Handle Ex to Ex mapping.
2945
+ this.processCommand(cm, command.toInput);
2946
+ return;
2947
+ }
2948
+ }
2949
+ }
2950
+ if (!commandName) {
2951
+ showConfirm(cm, 'Not an editor command ":' + input + '"');
2952
+ return;
2953
+ }
2954
+ try {
2955
+ exCommands[commandName](cm, params);
2956
+ } catch(e) {
2957
+ showConfirm(cm, e);
2958
+ }
2959
+ },
2960
+ parseInput_: function(cm, inputStream, result) {
2961
+ inputStream.eatWhile(':');
2962
+ // Parse range.
2963
+ if (inputStream.eat('%')) {
2964
+ result.line = cm.firstLine();
2965
+ result.lineEnd = cm.lastLine();
2966
+ } else {
2967
+ result.line = this.parseLineSpec_(cm, inputStream);
2968
+ if (result.line !== undefined && inputStream.eat(',')) {
2969
+ result.lineEnd = this.parseLineSpec_(cm, inputStream);
2970
+ }
2971
+ }
2972
+
2973
+ // Parse command name.
2974
+ var commandMatch = inputStream.match(/^(\w+)/);
2975
+ if (commandMatch) {
2976
+ result.commandName = commandMatch[1];
2977
+ } else {
2978
+ result.commandName = inputStream.match(/.*/)[0];
2979
+ }
2980
+
2981
+ return result;
2982
+ },
2983
+ parseLineSpec_: function(cm, inputStream) {
2984
+ var numberMatch = inputStream.match(/^(\d+)/);
2985
+ if (numberMatch) {
2986
+ return parseInt(numberMatch[1], 10) - 1;
2987
+ }
2988
+ switch (inputStream.next()) {
2989
+ case '.':
2990
+ return cm.getCursor().line;
2991
+ case '$':
2992
+ return cm.lastLine();
2993
+ case '\'':
2994
+ var mark = cm.state.vim.marks[inputStream.next()];
2995
+ if (mark && mark.find()) {
2996
+ return mark.find().line;
2997
+ }
2998
+ throw new Error('Mark not set');
2999
+ default:
3000
+ inputStream.backUp(1);
3001
+ return undefined;
3002
+ }
3003
+ },
3004
+ parseCommandArgs_: function(inputStream, params, command) {
3005
+ if (inputStream.eol()) {
3006
+ return;
3007
+ }
3008
+ params.argString = inputStream.match(/.*/)[0];
3009
+ // Parse command-line arguments
3010
+ var delim = command.argDelimiter || /\s+/;
3011
+ var args = trim(params.argString).split(delim);
3012
+ if (args.length && args[0]) {
3013
+ params.args = args;
3014
+ }
3015
+ },
3016
+ matchCommand_: function(commandName) {
3017
+ // Return the command in the command map that matches the shortest
3018
+ // prefix of the passed in command name. The match is guaranteed to be
3019
+ // unambiguous if the defaultExCommandMap's shortNames are set up
3020
+ // correctly. (see @code{defaultExCommandMap}).
3021
+ for (var i = commandName.length; i > 0; i--) {
3022
+ var prefix = commandName.substring(0, i);
3023
+ if (this.commandMap_[prefix]) {
3024
+ var command = this.commandMap_[prefix];
3025
+ if (command.name.indexOf(commandName) === 0) {
3026
+ return command;
3027
+ }
3028
+ }
3029
+ }
3030
+ return null;
3031
+ },
3032
+ buildCommandMap_: function() {
3033
+ this.commandMap_ = {};
3034
+ for (var i = 0; i < defaultExCommandMap.length; i++) {
3035
+ var command = defaultExCommandMap[i];
3036
+ var key = command.shortName || command.name;
3037
+ this.commandMap_[key] = command;
3038
+ }
3039
+ },
3040
+ map: function(lhs, rhs) {
3041
+ if (lhs != ':' && lhs.charAt(0) == ':') {
3042
+ var commandName = lhs.substring(1);
3043
+ if (rhs != ':' && rhs.charAt(0) == ':') {
3044
+ // Ex to Ex mapping
3045
+ this.commandMap_[commandName] = {
3046
+ name: commandName,
3047
+ type: 'exToEx',
3048
+ toInput: rhs.substring(1)
3049
+ };
3050
+ } else {
3051
+ // Ex to key mapping
3052
+ this.commandMap_[commandName] = {
3053
+ name: commandName,
3054
+ type: 'exToKey',
3055
+ toKeys: parseKeyString(rhs)
3056
+ };
3057
+ }
3058
+ } else {
3059
+ if (rhs != ':' && rhs.charAt(0) == ':') {
3060
+ // Key to Ex mapping.
3061
+ defaultKeymap.unshift({
3062
+ keys: parseKeyString(lhs),
3063
+ type: 'keyToEx',
3064
+ exArgs: { input: rhs.substring(1) }});
3065
+ } else {
3066
+ // Key to key mapping
3067
+ defaultKeymap.unshift({
3068
+ keys: parseKeyString(lhs),
3069
+ type: 'keyToKey',
3070
+ toKeys: parseKeyString(rhs)
3071
+ });
3072
+ }
3073
+ }
3074
+ }
3075
+ };
3076
+
3077
+ // Converts a key string sequence of the form a<C-w>bd<Left> into Vim's
3078
+ // keymap representation.
3079
+ function parseKeyString(str) {
3080
+ var key, match;
3081
+ var keys = [];
3082
+ while (str) {
3083
+ match = (/<\w+-.+?>|<\w+>|./).exec(str);
3084
+ if(match === null)break;
3085
+ key = match[0];
3086
+ str = str.substring(match.index + key.length);
3087
+ keys.push(key);
3088
+ }
3089
+ return keys;
3090
+ }
3091
+
3092
+ var exCommands = {
3093
+ map: function(cm, params) {
3094
+ var mapArgs = params.args;
3095
+ if (!mapArgs || mapArgs.length < 2) {
3096
+ if (cm) {
3097
+ showConfirm(cm, 'Invalid mapping: ' + params.input);
3098
+ }
3099
+ return;
3100
+ }
3101
+ exCommandDispatcher.map(mapArgs[0], mapArgs[1], cm);
3102
+ },
3103
+ move: function(cm, params) {
3104
+ commandDispatcher.processCommand(cm, cm.state.vim, {
3105
+ type: 'motion',
3106
+ motion: 'moveToLineOrEdgeOfDocument',
3107
+ motionArgs: { forward: false, explicitRepeat: true,
3108
+ linewise: true },
3109
+ repeatOverride: params.line+1});
3110
+ },
3111
+ sort: function(cm, params) {
3112
+ var reverse, ignoreCase, unique, number;
3113
+ function parseArgs() {
3114
+ if (params.argString) {
3115
+ var args = new CodeMirror.StringStream(params.argString);
3116
+ if (args.eat('!')) { reverse = true; }
3117
+ if (args.eol()) { return; }
3118
+ if (!args.eatSpace()) { throw new Error('invalid arguments ' + args.match(/.*/)[0]); }
3119
+ var opts = args.match(/[a-z]+/);
3120
+ if (opts) {
3121
+ opts = opts[0];
3122
+ ignoreCase = opts.indexOf('i') != -1;
3123
+ unique = opts.indexOf('u') != -1;
3124
+ var decimal = opts.indexOf('d') != -1 && 1;
3125
+ var hex = opts.indexOf('x') != -1 && 1;
3126
+ var octal = opts.indexOf('o') != -1 && 1;
3127
+ if (decimal + hex + octal > 1) { throw new Error('invalid arguments'); }
3128
+ number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
3129
+ }
3130
+ if (args.eatSpace() && args.match(/\/.*\//)) { throw new Error('patterns not supported'); }
3131
+ }
3132
+ }
3133
+ parseArgs();
3134
+ var lineStart = params.line || cm.firstLine();
3135
+ var lineEnd = params.lineEnd || params.line || cm.lastLine();
3136
+ if (lineStart == lineEnd) { return; }
3137
+ var curStart = { line: lineStart, ch: 0 };
3138
+ var curEnd = { line: lineEnd, ch: lineLength(cm, lineEnd) };
3139
+ var text = cm.getRange(curStart, curEnd).split('\n');
3140
+ var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
3141
+ (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
3142
+ (number == 'octal') ? /([0-7]+)/ : null;
3143
+ var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
3144
+ var numPart = [], textPart = [];
3145
+ if (number) {
3146
+ for (var i = 0; i < text.length; i++) {
3147
+ if (numberRegex.exec(text[i])) {
3148
+ numPart.push(text[i]);
3149
+ } else {
3150
+ textPart.push(text[i]);
3151
+ }
3152
+ }
3153
+ } else {
3154
+ textPart = text;
3155
+ }
3156
+ function compareFn(a, b) {
3157
+ if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
3158
+ if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
3159
+ var anum = number && numberRegex.exec(a);
3160
+ var bnum = number && numberRegex.exec(b);
3161
+ if (!anum) { return a < b ? -1 : 1; }
3162
+ anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
3163
+ bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
3164
+ return anum - bnum;
3165
+ }
3166
+ numPart.sort(compareFn);
3167
+ textPart.sort(compareFn);
3168
+ text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
3169
+ if (unique) { // Remove duplicate lines
3170
+ var textOld = text;
3171
+ var lastLine;
3172
+ text = [];
3173
+ for (var i = 0; i < textOld.length; i++) {
3174
+ if (textOld[i] != lastLine) {
3175
+ text.push(textOld[i]);
3176
+ }
3177
+ lastLine = textOld[i];
3178
+ }
3179
+ }
3180
+ cm.replaceRange(text.join('\n'), curStart, curEnd);
3181
+ },
3182
+ substitute: function(cm, params) {
3183
+ if (!cm.getSearchCursor) {
3184
+ throw new Error('Search feature not available. Requires searchcursor.js or ' +
3185
+ 'any other getSearchCursor implementation.');
3186
+ }
3187
+ var argString = params.argString;
3188
+ var slashes = findUnescapedSlashes(argString);
3189
+ if (slashes[0] !== 0) {
3190
+ showConfirm(cm, 'Substitutions should be of the form ' +
3191
+ ':s/pattern/replace/');
3192
+ return;
3193
+ }
3194
+ var regexPart = argString.substring(slashes[0] + 1, slashes[1]);
3195
+ var replacePart = '';
3196
+ var flagsPart;
3197
+ var count;
3198
+ var confirm = false; // Whether to confirm each replace.
3199
+ if (slashes[1]) {
3200
+ replacePart = argString.substring(slashes[1] + 1, slashes[2]);
3201
+ }
3202
+ if (slashes[2]) {
3203
+ // After the 3rd slash, we can have flags followed by a space followed
3204
+ // by count.
3205
+ var trailing = argString.substring(slashes[2] + 1).split(' ');
3206
+ flagsPart = trailing[0];
3207
+ count = parseInt(trailing[1]);
3208
+ }
3209
+ if (flagsPart) {
3210
+ if (flagsPart.indexOf('c') != -1) {
3211
+ confirm = true;
3212
+ flagsPart.replace('c', '');
3213
+ }
3214
+ regexPart = regexPart + '/' + flagsPart;
3215
+ }
3216
+ if (regexPart) {
3217
+ // If regex part is empty, then use the previous query. Otherwise use
3218
+ // the regex part as the new query.
3219
+ try {
3220
+ updateSearchQuery(cm, regexPart, true /** ignoreCase */,
3221
+ true /** smartCase */);
3222
+ } catch (e) {
3223
+ showConfirm(cm, 'Invalid regex: ' + regexPart);
3224
+ return;
3225
+ }
3226
+ }
3227
+ var state = getSearchState(cm);
3228
+ var query = state.getQuery();
3229
+ var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
3230
+ var lineEnd = params.lineEnd || lineStart;
3231
+ if (count) {
3232
+ lineStart = lineEnd;
3233
+ lineEnd = lineStart + count - 1;
3234
+ }
3235
+ var startPos = clipCursorToContent(cm, { line: lineStart, ch: 0 });
3236
+ var cursor = cm.getSearchCursor(query, startPos);
3237
+ doReplace(cm, confirm, lineStart, lineEnd, cursor, query, replacePart);
3238
+ },
3239
+ redo: CodeMirror.commands.redo,
3240
+ undo: CodeMirror.commands.undo,
3241
+ write: function(cm) {
3242
+ if (CodeMirror.commands.save) {
3243
+ // If a save command is defined, call it.
3244
+ CodeMirror.commands.save(cm);
3245
+ } else {
3246
+ // Saves to text area if no save command is defined.
3247
+ cm.save();
3248
+ }
3249
+ },
3250
+ nohlsearch: function(cm) {
3251
+ clearSearchHighlight(cm);
3252
+ },
3253
+ delmarks: function(cm, params) {
3254
+ if (!params.argString || !params.argString.trim()) {
3255
+ showConfirm(cm, 'Argument required');
3256
+ return;
3257
+ }
3258
+
3259
+ var state = cm.state.vim;
3260
+ var stream = new CodeMirror.StringStream(params.argString.trim());
3261
+ while (!stream.eol()) {
3262
+ stream.eatSpace();
3263
+
3264
+ // Record the streams position at the beginning of the loop for use
3265
+ // in error messages.
3266
+ var count = stream.pos;
3267
+
3268
+ if (!stream.match(/[a-zA-Z]/, false)) {
3269
+ showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3270
+ return;
3271
+ }
3272
+
3273
+ var sym = stream.next();
3274
+ // Check if this symbol is part of a range
3275
+ if (stream.match('-', true)) {
3276
+ // This symbol is part of a range.
3277
+
3278
+ // The range must terminate at an alphabetic character.
3279
+ if (!stream.match(/[a-zA-Z]/, false)) {
3280
+ showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3281
+ return;
3282
+ }
3283
+
3284
+ var startMark = sym;
3285
+ var finishMark = stream.next();
3286
+ // The range must terminate at an alphabetic character which
3287
+ // shares the same case as the start of the range.
3288
+ if (isLowerCase(startMark) && isLowerCase(finishMark) ||
3289
+ isUpperCase(startMark) && isUpperCase(finishMark)) {
3290
+ var start = startMark.charCodeAt(0);
3291
+ var finish = finishMark.charCodeAt(0);
3292
+ if (start >= finish) {
3293
+ showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
3294
+ return;
3295
+ }
3296
+
3297
+ // Because marks are always ASCII values, and we have
3298
+ // determined that they are the same case, we can use
3299
+ // their char codes to iterate through the defined range.
3300
+ for (var j = 0; j <= finish - start; j++) {
3301
+ var mark = String.fromCharCode(start + j);
3302
+ delete state.marks[mark];
3303
+ }
3304
+ } else {
3305
+ showConfirm(cm, 'Invalid argument: ' + startMark + '-');
3306
+ return;
3307
+ }
3308
+ } else {
3309
+ // This symbol is a valid mark, and is not part of a range.
3310
+ delete state.marks[sym];
3311
+ }
3312
+ }
3313
+ }
3314
+ };
3315
+
3316
+ var exCommandDispatcher = new Vim.ExCommandDispatcher();
3317
+
3318
+ /**
3319
+ * @param {CodeMirror} cm CodeMirror instance we are in.
3320
+ * @param {boolean} confirm Whether to confirm each replace.
3321
+ * @param {Cursor} lineStart Line to start replacing from.
3322
+ * @param {Cursor} lineEnd Line to stop replacing at.
3323
+ * @param {RegExp} query Query for performing matches with.
3324
+ * @param {string} replaceWith Text to replace matches with. May contain $1,
3325
+ * $2, etc for replacing captured groups using Javascript replace.
3326
+ */
3327
+ function doReplace(cm, confirm, lineStart, lineEnd, searchCursor, query,
3328
+ replaceWith) {
3329
+ // Set up all the functions.
3330
+ cm.state.vim.exMode = true;
3331
+ var done = false;
3332
+ var lastPos = searchCursor.from();
3333
+ function replaceAll() {
3334
+ cm.operation(function() {
3335
+ while (!done) {
3336
+ replace();
3337
+ next();
3338
+ }
3339
+ stop();
3340
+ });
3341
+ }
3342
+ function replace() {
3343
+ var text = cm.getRange(searchCursor.from(), searchCursor.to());
3344
+ var newText = text.replace(query, replaceWith);
3345
+ searchCursor.replace(newText);
3346
+ }
3347
+ function next() {
3348
+ var found = searchCursor.findNext();
3349
+ if (!found) {
3350
+ done = true;
3351
+ } else if (isInRange(searchCursor.from(), lineStart, lineEnd)) {
3352
+ cm.scrollIntoView(searchCursor.from(), 30);
3353
+ cm.setSelection(searchCursor.from(), searchCursor.to());
3354
+ lastPos = searchCursor.from();
3355
+ done = false;
3356
+ } else {
3357
+ done = true;
3358
+ }
3359
+ }
3360
+ function stop(close) {
3361
+ if (close) { close(); }
3362
+ cm.focus();
3363
+ if (lastPos) {
3364
+ cm.setCursor(lastPos);
3365
+ var vim = cm.state.vim;
3366
+ vim.exMode = false;
3367
+ vim.lastHPos = vim.lastHSPos = lastPos.ch;
3368
+ }
3369
+ }
3370
+ function onPromptKeyDown(e, _value, close) {
3371
+ // Swallow all keys.
3372
+ CodeMirror.e_stop(e);
3373
+ var keyName = CodeMirror.keyName(e);
3374
+ switch (keyName) {
3375
+ case 'Y':
3376
+ replace(); next(); break;
3377
+ case 'N':
3378
+ next(); break;
3379
+ case 'A':
3380
+ cm.operation(replaceAll); break;
3381
+ case 'L':
3382
+ replace();
3383
+ // fall through and exit.
3384
+ case 'Q':
3385
+ case 'Esc':
3386
+ case 'Ctrl-C':
3387
+ case 'Ctrl-[':
3388
+ stop(close);
3389
+ break;
3390
+ }
3391
+ if (done) { stop(close); }
3392
+ }
3393
+
3394
+ // Actually do replace.
3395
+ next();
3396
+ if (done) {
3397
+ throw new Error('No matches for ' + query.source);
3398
+ }
3399
+ if (!confirm) {
3400
+ replaceAll();
3401
+ return;
3402
+ }
3403
+ showPrompt(cm, {
3404
+ prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
3405
+ onKeyDown: onPromptKeyDown
3406
+ });
3407
+ }
3408
+
3409
+ // Register Vim with CodeMirror
3410
+ function buildVimKeyMap() {
3411
+ /**
3412
+ * Handle the raw key event from CodeMirror. Translate the
3413
+ * Shift + key modifier to the resulting letter, while preserving other
3414
+ * modifers.
3415
+ */
3416
+ // TODO: Figure out a way to catch capslock.
3417
+ function cmKeyToVimKey(key, modifier) {
3418
+ var vimKey = key;
3419
+ if (isUpperCase(vimKey)) {
3420
+ // Convert to lower case if shift is not the modifier since the key
3421
+ // we get from CodeMirror is always upper case.
3422
+ if (modifier == 'Shift') {
3423
+ modifier = null;
3424
+ }
3425
+ else {
3426
+ vimKey = vimKey.toLowerCase();
3427
+ }
3428
+ }
3429
+ if (modifier) {
3430
+ // Vim will parse modifier+key combination as a single key.
3431
+ vimKey = modifier.charAt(0) + '-' + vimKey;
3432
+ }
3433
+ var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
3434
+ vimKey = specialKey ? specialKey : vimKey;
3435
+ vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
3436
+ return vimKey;
3437
+ }
3438
+
3439
+ // Closure to bind CodeMirror, key, modifier.
3440
+ function keyMapper(vimKey) {
3441
+ return function(cm) {
3442
+ CodeMirror.Vim.handleKey(cm, vimKey);
3443
+ };
3444
+ }
3445
+
3446
+ var cmToVimKeymap = {
3447
+ 'nofallthrough': true,
3448
+ 'disableInput': true,
3449
+ 'style': 'fat-cursor'
3450
+ };
3451
+ function bindKeys(keys, modifier) {
3452
+ for (var i = 0; i < keys.length; i++) {
3453
+ var key = keys[i];
3454
+ if (!modifier && inArray(key, specialSymbols)) {
3455
+ // Wrap special symbols with '' because that's how CodeMirror binds
3456
+ // them.
3457
+ key = "'" + key + "'";
3458
+ }
3459
+ var vimKey = cmKeyToVimKey(keys[i], modifier);
3460
+ var cmKey = modifier ? modifier + '-' + key : key;
3461
+ cmToVimKeymap[cmKey] = keyMapper(vimKey);
3462
+ }
3463
+ }
3464
+ bindKeys(upperCaseAlphabet);
3465
+ bindKeys(upperCaseAlphabet, 'Shift');
3466
+ bindKeys(upperCaseAlphabet, 'Ctrl');
3467
+ bindKeys(specialSymbols);
3468
+ bindKeys(specialSymbols, 'Ctrl');
3469
+ bindKeys(numbers);
3470
+ bindKeys(numbers, 'Ctrl');
3471
+ bindKeys(specialKeys);
3472
+ bindKeys(specialKeys, 'Ctrl');
3473
+ return cmToVimKeymap;
3474
+ }
3475
+ CodeMirror.keyMap.vim = buildVimKeyMap();
3476
+
3477
+ function exitInsertMode(cm) {
3478
+ var vim = cm.state.vim;
3479
+ var inReplay = vimGlobalState.macroModeState.inReplay;
3480
+ if (!inReplay) {
3481
+ cm.off('change', onChange);
3482
+ cm.off('cursorActivity', onCursorActivity);
3483
+ CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
3484
+ }
3485
+ if (!inReplay && vim.insertModeRepeat > 1) {
3486
+ // Perform insert mode repeat for commands like 3,a and 3,o.
3487
+ repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
3488
+ true /** repeatForInsert */);
3489
+ vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
3490
+ }
3491
+ delete vim.insertModeRepeat;
3492
+ cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
3493
+ vim.insertMode = false;
3494
+ cm.setOption('keyMap', 'vim');
3495
+ cm.toggleOverwrite(false); // exit replace mode if we were in it.
3496
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
3497
+ }
3498
+
3499
+ CodeMirror.keyMap['vim-insert'] = {
3500
+ // TODO: override navigation keys so that Esc will cancel automatic
3501
+ // indentation from o, O, i_<CR>
3502
+ 'Esc': exitInsertMode,
3503
+ 'Ctrl-[': exitInsertMode,
3504
+ 'Ctrl-C': exitInsertMode,
3505
+ 'Ctrl-N': 'autocomplete',
3506
+ 'Ctrl-P': 'autocomplete',
3507
+ 'Enter': function(cm) {
3508
+ var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
3509
+ CodeMirror.commands.newlineAndIndent;
3510
+ fn(cm);
3511
+ },
3512
+ fallthrough: ['default']
3513
+ };
3514
+
3515
+ CodeMirror.keyMap['vim-replace'] = {
3516
+ 'Backspace': 'goCharLeft',
3517
+ fallthrough: ['vim-insert']
3518
+ };
3519
+
3520
+ function parseRegisterToKeyBuffer(macroModeState, registerName) {
3521
+ var match, key;
3522
+ var register = vimGlobalState.registerController.getRegister(registerName);
3523
+ var text = register.toString();
3524
+ var macroKeyBuffer = macroModeState.macroKeyBuffer;
3525
+ emptyMacroKeyBuffer(macroModeState);
3526
+ do {
3527
+ match = (/<\w+-.+?>|<\w+>|./).exec(text);
3528
+ if(match === null)break;
3529
+ key = match[0];
3530
+ text = text.substring(match.index + key.length);
3531
+ macroKeyBuffer.push(key);
3532
+ } while (text);
3533
+ return macroKeyBuffer;
3534
+ }
3535
+
3536
+ function parseKeyBufferToRegister(registerName, keyBuffer) {
3537
+ var text = keyBuffer.join('');
3538
+ vimGlobalState.registerController.setRegisterText(registerName, text);
3539
+ }
3540
+
3541
+ function emptyMacroKeyBuffer(macroModeState) {
3542
+ if(macroModeState.isMacroPlaying)return;
3543
+ var macroKeyBuffer = macroModeState.macroKeyBuffer;
3544
+ macroKeyBuffer.length = 0;
3545
+ }
3546
+
3547
+ function executeMacroKeyBuffer(cm, macroModeState, keyBuffer) {
3548
+ macroModeState.isMacroPlaying = true;
3549
+ for (var i = 0, len = keyBuffer.length; i < len; i++) {
3550
+ CodeMirror.Vim.handleKey(cm, keyBuffer[i]);
3551
+ };
3552
+ macroModeState.isMacroPlaying = false;
3553
+ }
3554
+
3555
+ function logKey(macroModeState, key) {
3556
+ if(macroModeState.isMacroPlaying)return;
3557
+ var macroKeyBuffer = macroModeState.macroKeyBuffer;
3558
+ macroKeyBuffer.push(key);
3559
+ }
3560
+
3561
+ /**
3562
+ * Listens for changes made in insert mode.
3563
+ * Should only be active in insert mode.
3564
+ */
3565
+ function onChange(_cm, changeObj) {
3566
+ var macroModeState = vimGlobalState.macroModeState;
3567
+ var lastChange = macroModeState.lastInsertModeChanges;
3568
+ while (changeObj) {
3569
+ lastChange.expectCursorActivityForChange = true;
3570
+ if (changeObj.origin == '+input' || changeObj.origin == 'paste'
3571
+ || changeObj.origin === undefined /* only in testing */) {
3572
+ var text = changeObj.text.join('\n');
3573
+ lastChange.changes.push(text);
3574
+ }
3575
+ // Change objects may be chained with next.
3576
+ changeObj = changeObj.next;
3577
+ }
3578
+ }
3579
+
3580
+ /**
3581
+ * Listens for any kind of cursor activity on CodeMirror.
3582
+ * - For tracking cursor activity in insert mode.
3583
+ * - Should only be active in insert mode.
3584
+ */
3585
+ function onCursorActivity() {
3586
+ var macroModeState = vimGlobalState.macroModeState;
3587
+ var lastChange = macroModeState.lastInsertModeChanges;
3588
+ if (lastChange.expectCursorActivityForChange) {
3589
+ lastChange.expectCursorActivityForChange = false;
3590
+ } else {
3591
+ // Cursor moved outside the context of an edit. Reset the change.
3592
+ lastChange.changes = [];
3593
+ }
3594
+ }
3595
+
3596
+ /** Wrapper for special keys pressed in insert mode */
3597
+ function InsertModeKey(keyName) {
3598
+ this.keyName = keyName;
3599
+ }
3600
+
3601
+ /**
3602
+ * Handles raw key down events from the text area.
3603
+ * - Should only be active in insert mode.
3604
+ * - For recording deletes in insert mode.
3605
+ */
3606
+ function onKeyEventTargetKeyDown(e) {
3607
+ var macroModeState = vimGlobalState.macroModeState;
3608
+ var lastChange = macroModeState.lastInsertModeChanges;
3609
+ var keyName = CodeMirror.keyName(e);
3610
+ function onKeyFound() {
3611
+ lastChange.changes.push(new InsertModeKey(keyName));
3612
+ return true;
3613
+ }
3614
+ if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
3615
+ CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
3616
+ }
3617
+ }
3618
+
3619
+ /**
3620
+ * Repeats the last edit, which includes exactly 1 command and at most 1
3621
+ * insert. Operator and motion commands are read from lastEditInputState,
3622
+ * while action commands are read from lastEditActionCommand.
3623
+ *
3624
+ * If repeatForInsert is true, then the function was called by
3625
+ * exitInsertMode to repeat the insert mode changes the user just made. The
3626
+ * corresponding enterInsertMode call was made with a count.
3627
+ */
3628
+ function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
3629
+ var macroModeState = vimGlobalState.macroModeState;
3630
+ macroModeState.inReplay = true;
3631
+ var isAction = !!vim.lastEditActionCommand;
3632
+ var cachedInputState = vim.inputState;
3633
+ function repeatCommand() {
3634
+ if (isAction) {
3635
+ commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
3636
+ } else {
3637
+ commandDispatcher.evalInput(cm, vim);
3638
+ }
3639
+ }
3640
+ function repeatInsert(repeat) {
3641
+ if (macroModeState.lastInsertModeChanges.changes.length > 0) {
3642
+ // For some reason, repeat cw in desktop VIM will does not repeat
3643
+ // insert mode changes. Will conform to that behavior.
3644
+ repeat = !vim.lastEditActionCommand ? 1 : repeat;
3645
+ repeatLastInsertModeChanges(cm, repeat, macroModeState);
3646
+ }
3647
+ }
3648
+ vim.inputState = vim.lastEditInputState;
3649
+ if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
3650
+ // o and O repeat have to be interlaced with insert repeats so that the
3651
+ // insertions appear on separate lines instead of the last line.
3652
+ for (var i = 0; i < repeat; i++) {
3653
+ repeatCommand();
3654
+ repeatInsert(1);
3655
+ }
3656
+ } else {
3657
+ if (!repeatForInsert) {
3658
+ // Hack to get the cursor to end up at the right place. If I is
3659
+ // repeated in insert mode repeat, cursor will be 1 insert
3660
+ // change set left of where it should be.
3661
+ repeatCommand();
3662
+ }
3663
+ repeatInsert(repeat);
3664
+ }
3665
+ vim.inputState = cachedInputState;
3666
+ if (vim.insertMode && !repeatForInsert) {
3667
+ // Don't exit insert mode twice. If repeatForInsert is set, then we
3668
+ // were called by an exitInsertMode call lower on the stack.
3669
+ exitInsertMode(cm);
3670
+ }
3671
+ macroModeState.inReplay = false;
3672
+ };
3673
+
3674
+ function repeatLastInsertModeChanges(cm, repeat, macroModeState) {
3675
+ var lastChange = macroModeState.lastInsertModeChanges;
3676
+ function keyHandler(binding) {
3677
+ if (typeof binding == 'string') {
3678
+ CodeMirror.commands[binding](cm);
3679
+ } else {
3680
+ binding(cm);
3681
+ }
3682
+ return true;
3683
+ }
3684
+ for (var i = 0; i < repeat; i++) {
3685
+ for (var j = 0; j < lastChange.changes.length; j++) {
3686
+ var change = lastChange.changes[j];
3687
+ if (change instanceof InsertModeKey) {
3688
+ CodeMirror.lookupKey(change.keyName, ['vim-insert'], keyHandler);
3689
+ } else {
3690
+ var cur = cm.getCursor();
3691
+ cm.replaceRange(change, cur, cur);
3692
+ }
3693
+ }
3694
+ }
3695
+ }
3696
+
3697
+ resetVimGlobalState();
3698
+ return vimApi;
3699
+ };
3700
+ // Initialize Vim and make it available as an API.
3701
+ CodeMirror.Vim = Vim();
3702
+ }
3703
+ )();