sunrise-locales 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (259) hide show
  1. data/Gemfile +36 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.rdoc +15 -0
  4. data/Rakefile +27 -0
  5. data/app/controllers/manage/locales_controller.rb +43 -0
  6. data/app/views/manage/locales/_locale.html.erb +21 -0
  7. data/app/views/manage/locales/edit.html.erb +101 -0
  8. data/app/views/manage/locales/index.html.erb +24 -0
  9. data/config/locales/ru.yml +20 -0
  10. data/config/locales/uk.yml +20 -0
  11. data/config/routes.rb +5 -0
  12. data/lib/generators/sunrise/locales/USAGE +6 -0
  13. data/lib/generators/sunrise/locales/install_generator.rb +20 -0
  14. data/lib/generators/sunrise/locales/templates/codemirror.css +107 -0
  15. data/lib/generators/sunrise/locales/templates/codemirror.js +2157 -0
  16. data/lib/generators/sunrise/locales/templates/yaml.js +95 -0
  17. data/lib/sunrise-locales.rb +1 -0
  18. data/lib/sunrise/locales.rb +13 -0
  19. data/lib/sunrise/locales/engine.rb +19 -0
  20. data/lib/sunrise/locales/version.rb +5 -0
  21. data/lib/sunrise/locales/yml_locale.rb +43 -0
  22. data/spec/controllers/manage/locales_controller_spec.rb +59 -0
  23. data/spec/dummy/Rakefile +7 -0
  24. data/spec/dummy/app/controllers/application_controller.rb +3 -0
  25. data/spec/dummy/app/helpers/application_helper.rb +2 -0
  26. data/spec/dummy/app/helpers/manage/assets_helper.rb +2 -0
  27. data/spec/dummy/app/helpers/manage/base_helper.rb +81 -0
  28. data/spec/dummy/app/helpers/manage/pages_helper.rb +2 -0
  29. data/spec/dummy/app/helpers/manage/settings_helper.rb +2 -0
  30. data/spec/dummy/app/helpers/manage/structures_helper.rb +12 -0
  31. data/spec/dummy/app/helpers/manage/users_helper.rb +6 -0
  32. data/spec/dummy/app/models/defaults/ability.rb +39 -0
  33. data/spec/dummy/app/models/defaults/asset.rb +9 -0
  34. data/spec/dummy/app/models/defaults/attachment_file.rb +31 -0
  35. data/spec/dummy/app/models/defaults/avatar.rb +33 -0
  36. data/spec/dummy/app/models/defaults/header.rb +5 -0
  37. data/spec/dummy/app/models/defaults/page.rb +5 -0
  38. data/spec/dummy/app/models/defaults/picture.rb +31 -0
  39. data/spec/dummy/app/models/defaults/position_type.rb +7 -0
  40. data/spec/dummy/app/models/defaults/role.rb +20 -0
  41. data/spec/dummy/app/models/defaults/role_type.rb +8 -0
  42. data/spec/dummy/app/models/defaults/structure.rb +16 -0
  43. data/spec/dummy/app/models/defaults/structure_type.rb +9 -0
  44. data/spec/dummy/app/models/defaults/user.rb +47 -0
  45. data/spec/dummy/app/uploaders/attachment_file_uploader.rb +5 -0
  46. data/spec/dummy/app/uploaders/avatar_uploader.rb +17 -0
  47. data/spec/dummy/app/uploaders/picture_uploader.rb +17 -0
  48. data/spec/dummy/app/views/layouts/application.html.erb +37 -0
  49. data/spec/dummy/app/views/pages/show.html.erb +2 -0
  50. data/spec/dummy/app/views/shared/_notice.html.erb +17 -0
  51. data/spec/dummy/config.ru +4 -0
  52. data/spec/dummy/config/application.rb +46 -0
  53. data/spec/dummy/config/application.yml.sample +4 -0
  54. data/spec/dummy/config/boot.rb +10 -0
  55. data/spec/dummy/config/database.yml +22 -0
  56. data/spec/dummy/config/database.yml.sample +34 -0
  57. data/spec/dummy/config/environment.rb +5 -0
  58. data/spec/dummy/config/environments/development.rb +26 -0
  59. data/spec/dummy/config/environments/production.rb +49 -0
  60. data/spec/dummy/config/environments/test.rb +35 -0
  61. data/spec/dummy/config/initializers/backtrace_silencers.rb +7 -0
  62. data/spec/dummy/config/initializers/devise.rb +204 -0
  63. data/spec/dummy/config/initializers/inflections.rb +10 -0
  64. data/spec/dummy/config/initializers/mime_types.rb +5 -0
  65. data/spec/dummy/config/initializers/secret_token.rb +7 -0
  66. data/spec/dummy/config/initializers/session_store.rb +8 -0
  67. data/spec/dummy/config/initializers/simple_form.rb +93 -0
  68. data/spec/dummy/config/initializers/sunrise.rb +9 -0
  69. data/spec/dummy/config/locales/devise.en.yml +53 -0
  70. data/spec/dummy/config/locales/en.yml +3 -0
  71. data/spec/dummy/config/locales/ru.yml +3 -0
  72. data/spec/dummy/config/locales/simple_form.en.yml +24 -0
  73. data/spec/dummy/config/locales/uk.yml +2 -0
  74. data/spec/dummy/config/logrotate-config.sample +9 -0
  75. data/spec/dummy/config/nginx-config-passenger.sample +51 -0
  76. data/spec/dummy/config/routes.rb +64 -0
  77. data/spec/dummy/db/migrate/20110801124809_sunrise_create_users.rb +29 -0
  78. data/spec/dummy/db/migrate/20110801124909_sunrise_create_roles.rb +16 -0
  79. data/spec/dummy/db/migrate/20110801125009_sunrise_create_structures.rb +27 -0
  80. data/spec/dummy/db/migrate/20110801125109_sunrise_create_pages.rb +17 -0
  81. data/spec/dummy/db/migrate/20110801125209_sunrise_create_assets.rb +28 -0
  82. data/spec/dummy/db/migrate/20110801125309_sunrise_create_headers.rb +20 -0
  83. data/spec/dummy/db/seeds.rb +25 -0
  84. data/spec/dummy/db/test.sqlite3 +0 -0
  85. data/spec/dummy/lib/templates/erb/scaffold/_form.html.erb +13 -0
  86. data/spec/dummy/log/test.log +1678 -0
  87. data/spec/dummy/public/404.html +26 -0
  88. data/spec/dummy/public/422.html +26 -0
  89. data/spec/dummy/public/500.html +26 -0
  90. data/spec/dummy/public/favicon.ico +0 -0
  91. data/spec/dummy/public/images/manage/add_post_bot.gif +0 -0
  92. data/spec/dummy/public/images/manage/add_post_top.gif +0 -0
  93. data/spec/dummy/public/images/manage/add_white_bot.gif +0 -0
  94. data/spec/dummy/public/images/manage/add_white_top.gif +0 -0
  95. data/spec/dummy/public/images/manage/arrow.png +0 -0
  96. data/spec/dummy/public/images/manage/back_but_lc.gif +0 -0
  97. data/spec/dummy/public/images/manage/back_but_rc.gif +0 -0
  98. data/spec/dummy/public/images/manage/bot_corn.gif +0 -0
  99. data/spec/dummy/public/images/manage/bot_duo_corn.gif +0 -0
  100. data/spec/dummy/public/images/manage/but_bg.png +0 -0
  101. data/spec/dummy/public/images/manage/but_block_lc.gif +0 -0
  102. data/spec/dummy/public/images/manage/but_block_rc.gif +0 -0
  103. data/spec/dummy/public/images/manage/but_freze_lc.gif +0 -0
  104. data/spec/dummy/public/images/manage/but_freze_rc.gif +0 -0
  105. data/spec/dummy/public/images/manage/but_gr.gif +0 -0
  106. data/spec/dummy/public/images/manage/but_gr_l.gif +0 -0
  107. data/spec/dummy/public/images/manage/but_gr_r.gif +0 -0
  108. data/spec/dummy/public/images/manage/but_search.gif +0 -0
  109. data/spec/dummy/public/images/manage/but_unfreze_lc.gif +0 -0
  110. data/spec/dummy/public/images/manage/but_unfreze_rc.gif +0 -0
  111. data/spec/dummy/public/images/manage/button_add_foto.gif +0 -0
  112. data/spec/dummy/public/images/manage/button_add_foto_ru.gif +0 -0
  113. data/spec/dummy/public/images/manage/button_add_foto_ua.gif +0 -0
  114. data/spec/dummy/public/images/manage/button_add_foto_uk.gif +0 -0
  115. data/spec/dummy/public/images/manage/cancelbutton.gif +0 -0
  116. data/spec/dummy/public/images/manage/dark_arr.gif +0 -0
  117. data/spec/dummy/public/images/manage/dark_arr_left.gif +0 -0
  118. data/spec/dummy/public/images/manage/dark_cross_ico.gif +0 -0
  119. data/spec/dummy/public/images/manage/dot.gif +0 -0
  120. data/spec/dummy/public/images/manage/duo_bg.gif +0 -0
  121. data/spec/dummy/public/images/manage/duo_bg_small.gif +0 -0
  122. data/spec/dummy/public/images/manage/duo_bg_small_blocked.gif +0 -0
  123. data/spec/dummy/public/images/manage/duo_bg_small_frozed.gif +0 -0
  124. data/spec/dummy/public/images/manage/duo_bg_small_notact.gif +0 -0
  125. data/spec/dummy/public/images/manage/duo_bot_small.gif +0 -0
  126. data/spec/dummy/public/images/manage/duo_bot_small_blocked.gif +0 -0
  127. data/spec/dummy/public/images/manage/duo_bot_small_frozed.gif +0 -0
  128. data/spec/dummy/public/images/manage/duo_bot_small_notact.gif +0 -0
  129. data/spec/dummy/public/images/manage/duo_top_small.gif +0 -0
  130. data/spec/dummy/public/images/manage/duo_top_small_blocked.gif +0 -0
  131. data/spec/dummy/public/images/manage/duo_top_small_frozed.gif +0 -0
  132. data/spec/dummy/public/images/manage/duo_top_small_notact.gif +0 -0
  133. data/spec/dummy/public/images/manage/edit_white_top.gif +0 -0
  134. data/spec/dummy/public/images/manage/empty.gif +0 -0
  135. data/spec/dummy/public/images/manage/filter_bot_bg.gif +0 -0
  136. data/spec/dummy/public/images/manage/filter_top_bg.gif +0 -0
  137. data/spec/dummy/public/images/manage/flag_en.gif +0 -0
  138. data/spec/dummy/public/images/manage/flag_en_nonact.gif +0 -0
  139. data/spec/dummy/public/images/manage/flag_ru.gif +0 -0
  140. data/spec/dummy/public/images/manage/flag_ru_nonact.gif +0 -0
  141. data/spec/dummy/public/images/manage/flag_ua.gif +0 -0
  142. data/spec/dummy/public/images/manage/flag_ua_nonact.gif +0 -0
  143. data/spec/dummy/public/images/manage/foto.jpg +0 -0
  144. data/spec/dummy/public/images/manage/ico_add.gif +0 -0
  145. data/spec/dummy/public/images/manage/ico_del.gif +0 -0
  146. data/spec/dummy/public/images/manage/ico_down.gif +0 -0
  147. data/spec/dummy/public/images/manage/ico_edit.gif +0 -0
  148. data/spec/dummy/public/images/manage/ico_settings.gif +0 -0
  149. data/spec/dummy/public/images/manage/ico_up.gif +0 -0
  150. data/spec/dummy/public/images/manage/input_bg.gif +0 -0
  151. data/spec/dummy/public/images/manage/l_but_corn.gif +0 -0
  152. data/spec/dummy/public/images/manage/minimise_but.gif +0 -0
  153. data/spec/dummy/public/images/manage/mp3.png +0 -0
  154. data/spec/dummy/public/images/manage/page_arr_hover.png +0 -0
  155. data/spec/dummy/public/images/manage/page_next_arr.gif +0 -0
  156. data/spec/dummy/public/images/manage/page_num_hover.gif +0 -0
  157. data/spec/dummy/public/images/manage/page_prev_arr.gif +0 -0
  158. data/spec/dummy/public/images/manage/panel/l_but_corn.gif +0 -0
  159. data/spec/dummy/public/images/manage/panel/maximise_but.gif +0 -0
  160. data/spec/dummy/public/images/manage/panel/r_but_corn.gif +0 -0
  161. data/spec/dummy/public/images/manage/panel/top_menu_arr.gif +0 -0
  162. data/spec/dummy/public/images/manage/panel/user_pic.gif +0 -0
  163. data/spec/dummy/public/images/manage/preloader.gif +0 -0
  164. data/spec/dummy/public/images/manage/r_but_corn.gif +0 -0
  165. data/spec/dummy/public/images/manage/select_bg.gif +0 -0
  166. data/spec/dummy/public/images/manage/select_corn.gif +0 -0
  167. data/spec/dummy/public/images/manage/struct_corn_lg.gif +0 -0
  168. data/spec/dummy/public/images/manage/struct_corn_llg.gif +0 -0
  169. data/spec/dummy/public/images/manage/struct_corn_lw.gif +0 -0
  170. data/spec/dummy/public/images/manage/struct_corn_rg.gif +0 -0
  171. data/spec/dummy/public/images/manage/struct_corn_rlg.gif +0 -0
  172. data/spec/dummy/public/images/manage/struct_corn_rw.gif +0 -0
  173. data/spec/dummy/public/images/manage/tab_gl.gif +0 -0
  174. data/spec/dummy/public/images/manage/tab_gr.gif +0 -0
  175. data/spec/dummy/public/images/manage/tab_wl.gif +0 -0
  176. data/spec/dummy/public/images/manage/tab_wr.gif +0 -0
  177. data/spec/dummy/public/images/manage/top_corn.gif +0 -0
  178. data/spec/dummy/public/images/manage/top_duo_corn.gif +0 -0
  179. data/spec/dummy/public/images/manage/top_menu_arr.gif +0 -0
  180. data/spec/dummy/public/images/manage/transp_cross.png +0 -0
  181. data/spec/dummy/public/images/manage/upload_progress.gif +0 -0
  182. data/spec/dummy/public/images/manage/user_act_lc.gif +0 -0
  183. data/spec/dummy/public/images/manage/user_act_rc.gif +0 -0
  184. data/spec/dummy/public/images/manage/user_ico.gif +0 -0
  185. data/spec/dummy/public/images/manage/user_pic.gif +0 -0
  186. data/spec/dummy/public/images/manage/user_pic_small.gif +0 -0
  187. data/spec/dummy/public/images/manage/user_pic_thumb.gif +0 -0
  188. data/spec/dummy/public/javascripts/application.js +2 -0
  189. data/spec/dummy/public/javascripts/controls.js +965 -0
  190. data/spec/dummy/public/javascripts/datepicker/jquery-ui-i18n.js +1176 -0
  191. data/spec/dummy/public/javascripts/datepicker/jquery.ui.datepicker-ru.js +37 -0
  192. data/spec/dummy/public/javascripts/datepicker/jquery.ui.datepicker-uk.js +37 -0
  193. data/spec/dummy/public/javascripts/dragdrop.js +974 -0
  194. data/spec/dummy/public/javascripts/effects.js +1123 -0
  195. data/spec/dummy/public/javascripts/fileupload/fileuploader-input.js +217 -0
  196. data/spec/dummy/public/javascripts/fileupload/fileuploader.css +31 -0
  197. data/spec/dummy/public/javascripts/fileupload/fileuploader.js +1288 -0
  198. data/spec/dummy/public/javascripts/jquery-ui-timepicker-addon.js +911 -0
  199. data/spec/dummy/public/javascripts/jquery.cookie.js +97 -0
  200. data/spec/dummy/public/javascripts/jquery.fancybox-1.3.4.pack.js +46 -0
  201. data/spec/dummy/public/javascripts/jquery.tmpl.min.js +10 -0
  202. data/spec/dummy/public/javascripts/manage-fileuploader.js +182 -0
  203. data/spec/dummy/public/javascripts/manage.js +294 -0
  204. data/spec/dummy/public/javascripts/preloader.js +47 -0
  205. data/spec/dummy/public/javascripts/prototype.js +6001 -0
  206. data/spec/dummy/public/javascripts/rails.js +331 -0
  207. data/spec/dummy/public/stylesheets/application.css +1 -0
  208. data/spec/dummy/public/stylesheets/fancybox/images/blank.gif +0 -0
  209. data/spec/dummy/public/stylesheets/fancybox/images/fancy_close.png +0 -0
  210. data/spec/dummy/public/stylesheets/fancybox/images/fancy_loading.png +0 -0
  211. data/spec/dummy/public/stylesheets/fancybox/images/fancy_nav_left.png +0 -0
  212. data/spec/dummy/public/stylesheets/fancybox/images/fancy_nav_right.png +0 -0
  213. data/spec/dummy/public/stylesheets/fancybox/images/fancy_shadow_e.png +0 -0
  214. data/spec/dummy/public/stylesheets/fancybox/images/fancy_shadow_n.png +0 -0
  215. data/spec/dummy/public/stylesheets/fancybox/images/fancy_shadow_ne.png +0 -0
  216. data/spec/dummy/public/stylesheets/fancybox/images/fancy_shadow_nw.png +0 -0
  217. data/spec/dummy/public/stylesheets/fancybox/images/fancy_shadow_s.png +0 -0
  218. data/spec/dummy/public/stylesheets/fancybox/images/fancy_shadow_se.png +0 -0
  219. data/spec/dummy/public/stylesheets/fancybox/images/fancy_shadow_sw.png +0 -0
  220. data/spec/dummy/public/stylesheets/fancybox/images/fancy_shadow_w.png +0 -0
  221. data/spec/dummy/public/stylesheets/fancybox/images/fancy_title_left.png +0 -0
  222. data/spec/dummy/public/stylesheets/fancybox/images/fancy_title_main.png +0 -0
  223. data/spec/dummy/public/stylesheets/fancybox/images/fancy_title_over.png +0 -0
  224. data/spec/dummy/public/stylesheets/fancybox/images/fancy_title_right.png +0 -0
  225. data/spec/dummy/public/stylesheets/fancybox/images/fancybox-x.png +0 -0
  226. data/spec/dummy/public/stylesheets/fancybox/images/fancybox-y.png +0 -0
  227. data/spec/dummy/public/stylesheets/fancybox/images/fancybox.png +0 -0
  228. data/spec/dummy/public/stylesheets/fancybox/jquery.fancybox-1.3.4.css +359 -0
  229. data/spec/dummy/public/stylesheets/manage/buttons.css +42 -0
  230. data/spec/dummy/public/stylesheets/manage/ie.css +16 -0
  231. data/spec/dummy/public/stylesheets/manage/main.css +1108 -0
  232. data/spec/dummy/public/stylesheets/manage/panel.css +126 -0
  233. data/spec/dummy/public/stylesheets/smoothness/images/ui-bg_flat_0_aaaaaa_40x100.png +0 -0
  234. data/spec/dummy/public/stylesheets/smoothness/images/ui-bg_flat_75_ffffff_40x100.png +0 -0
  235. data/spec/dummy/public/stylesheets/smoothness/images/ui-bg_glass_55_fbf9ee_1x400.png +0 -0
  236. data/spec/dummy/public/stylesheets/smoothness/images/ui-bg_glass_65_ffffff_1x400.png +0 -0
  237. data/spec/dummy/public/stylesheets/smoothness/images/ui-bg_glass_75_dadada_1x400.png +0 -0
  238. data/spec/dummy/public/stylesheets/smoothness/images/ui-bg_glass_75_e6e6e6_1x400.png +0 -0
  239. data/spec/dummy/public/stylesheets/smoothness/images/ui-bg_glass_95_fef1ec_1x400.png +0 -0
  240. data/spec/dummy/public/stylesheets/smoothness/images/ui-bg_highlight-soft_75_cccccc_1x100.png +0 -0
  241. data/spec/dummy/public/stylesheets/smoothness/images/ui-icons_222222_256x240.png +0 -0
  242. data/spec/dummy/public/stylesheets/smoothness/images/ui-icons_2e83ff_256x240.png +0 -0
  243. data/spec/dummy/public/stylesheets/smoothness/images/ui-icons_454545_256x240.png +0 -0
  244. data/spec/dummy/public/stylesheets/smoothness/images/ui-icons_888888_256x240.png +0 -0
  245. data/spec/dummy/public/stylesheets/smoothness/images/ui-icons_cd0a0a_256x240.png +0 -0
  246. data/spec/dummy/public/stylesheets/smoothness/jquery-ui-1.8.13.custom.css +578 -0
  247. data/spec/dummy/script/rails +6 -0
  248. data/spec/factories/structure_factory.rb +22 -0
  249. data/spec/factories/user_factory.rb +48 -0
  250. data/spec/generators/install_generator_spec.rb +18 -0
  251. data/spec/integration/navigation_spec.rb +9 -0
  252. data/spec/spec.opts +2 -0
  253. data/spec/spec_helper.rb +57 -0
  254. data/spec/sunrise_locales_spec.rb +7 -0
  255. data/spec/support/helpers/controller_macros.rb +40 -0
  256. data/spec/tmp/public/javascripts/codemirror.js +2157 -0
  257. data/spec/tmp/public/javascripts/yaml.js +95 -0
  258. data/spec/tmp/public/stylesheets/codemirror.css +107 -0
  259. metadata +575 -0
@@ -0,0 +1,2157 @@
1
+ // All functions that need access to the editor's state live inside
2
+ // the CodeMirror function. Below that, at the bottom of the file,
3
+ // some utilities are defined.
4
+
5
+ // CodeMirror is the only global var we claim
6
+ var CodeMirror = (function() {
7
+ // This is the function that produces an editor instance. It's
8
+ // closure is used to store the editor state.
9
+ function CodeMirror(place, givenOptions) {
10
+ // Determine effective options based on given values and defaults.
11
+ var options = {}, defaults = CodeMirror.defaults;
12
+ for (var opt in defaults)
13
+ if (defaults.hasOwnProperty(opt))
14
+ options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
15
+
16
+ var targetDocument = options["document"];
17
+ // The element in which the editor lives.
18
+ var wrapper = targetDocument.createElement("div");
19
+ wrapper.className = "CodeMirror";
20
+ // This mess creates the base DOM structure for the editor.
21
+ wrapper.innerHTML =
22
+ '<div style="overflow: hidden; position: relative; width: 1px; height: 0px;">' + // Wraps and hides input textarea
23
+ '<textarea style="position: absolute; width: 2px;" wrap="off"></textarea></div>' +
24
+ '<div class="CodeMirror-scroll cm-s-' + options.theme + '">' +
25
+ '<div style="position: relative">' + // Set to the height of the text, causes scrolling
26
+ '<div style="position: absolute; height: 0; width: 0; overflow: hidden;"></div>' +
27
+ '<div style="position: relative">' + // Moved around its parent to cover visible view
28
+ '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
29
+ // Provides positioning relative to (visible) text origin
30
+ '<div class="CodeMirror-lines"><div style="position: relative">' +
31
+ '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
32
+ '<div></div>' + // This DIV contains the actual code
33
+ '</div></div></div></div></div>';
34
+ if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
35
+ // I've never seen more elegant code in my life.
36
+ var inputDiv = wrapper.firstChild, input = inputDiv.firstChild,
37
+ scroller = wrapper.lastChild, code = scroller.firstChild,
38
+ measure = code.firstChild, mover = measure.nextSibling,
39
+ gutter = mover.firstChild, gutterText = gutter.firstChild,
40
+ lineSpace = gutter.nextSibling.firstChild,
41
+ cursor = lineSpace.firstChild, lineDiv = cursor.nextSibling;
42
+ if (options.tabindex != null) input.tabindex = options.tabindex;
43
+ if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
44
+
45
+ // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
46
+ var poll = new Delayed(), highlight = new Delayed(), blinker;
47
+
48
+ // mode holds a mode API object. lines an array of Line objects
49
+ // (see Line constructor), work an array of lines that should be
50
+ // parsed, and history the undo history (instance of History
51
+ // constructor).
52
+ var mode, lines = [new Line("")], work, history = new History(), focused;
53
+ loadMode();
54
+ // The selection. These are always maintained to point at valid
55
+ // positions. Inverted is used to remember that the user is
56
+ // selecting bottom-to-top.
57
+ var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
58
+ // Selection-related flags. shiftSelecting obviously tracks
59
+ // whether the user is holding shift. reducedSelection is a hack
60
+ // to get around the fact that we can't create inverted
61
+ // selections. See below.
62
+ var shiftSelecting, reducedSelection, lastDoubleClick;
63
+ // Variables used by startOperation/endOperation to track what
64
+ // happened during the operation.
65
+ var updateInput, changes, textChanged, selectionChanged, leaveInputAlone;
66
+ // Current visible range (may be bigger than the view window).
67
+ var showingFrom = 0, showingTo = 0, lastHeight = 0, curKeyId = null;
68
+ // editing will hold an object describing the things we put in the
69
+ // textarea, to help figure out whether something changed.
70
+ // bracketHighlighted is used to remember that a backet has been
71
+ // marked.
72
+ var editing, bracketHighlighted;
73
+ // Tracks the maximum line length so that the horizontal scrollbar
74
+ // can be kept static when scrolling.
75
+ var maxLine = "", maxWidth;
76
+
77
+ // Initialize the content.
78
+ operation(function(){setValue(options.value || ""); updateInput = false;})();
79
+
80
+ // Register our event handlers.
81
+ connect(scroller, "mousedown", operation(onMouseDown));
82
+ // Gecko browsers fire contextmenu *after* opening the menu, at
83
+ // which point we can't mess with it anymore. Context menu is
84
+ // handled in onMouseDown for Gecko.
85
+ if (!gecko) connect(scroller, "contextmenu", onContextMenu);
86
+ connect(code, "dblclick", operation(onDblClick));
87
+ connect(scroller, "scroll", function() {updateDisplay([]); if (options.onScroll) options.onScroll(instance);});
88
+ connect(window, "resize", function() {updateDisplay(true);});
89
+ connect(input, "keyup", operation(onKeyUp));
90
+ connect(input, "keydown", operation(onKeyDown));
91
+ connect(input, "keypress", operation(onKeyPress));
92
+ connect(input, "focus", onFocus);
93
+ connect(input, "blur", onBlur);
94
+
95
+ connect(scroller, "dragenter", e_stop);
96
+ connect(scroller, "dragover", e_stop);
97
+ connect(scroller, "drop", operation(onDrop));
98
+ connect(scroller, "paste", function(){focusInput(); fastPoll();});
99
+ connect(input, "paste", function(){fastPoll();});
100
+ connect(input, "cut", function(){fastPoll();});
101
+
102
+ // IE throws unspecified error in certain cases, when
103
+ // trying to access activeElement before onload
104
+ var hasFocus; try { hasFocus = (targetDocument.activeElement == input); } catch(e) { }
105
+ if (hasFocus) setTimeout(onFocus, 20);
106
+ else onBlur();
107
+
108
+ function isLine(l) {return l >= 0 && l < lines.length;}
109
+ // The instance object that we'll return. Mostly calls out to
110
+ // local functions in the CodeMirror function. Some do some extra
111
+ // range checking and/or clipping. operation is used to wrap the
112
+ // call so that changes it makes are tracked, and the display is
113
+ // updated afterwards.
114
+ var instance = {
115
+ getValue: getValue,
116
+ setValue: operation(setValue),
117
+ getSelection: getSelection,
118
+ replaceSelection: operation(replaceSelection),
119
+ focus: function(){focusInput(); onFocus(); fastPoll();},
120
+ setOption: function(option, value) {
121
+ options[option] = value;
122
+ if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber") gutterChanged();
123
+ else if (option == "mode" || option == "indentUnit") loadMode();
124
+ else if (option == "readOnly" && value == "nocursor") input.blur();
125
+ else if (option == "theme") scroller.className = scroller.className.replace(/cm-s-\w+/, "cm-s-" + value);
126
+ },
127
+ getOption: function(option) {return options[option];},
128
+ undo: operation(undo),
129
+ redo: operation(redo),
130
+ indentLine: operation(function(n, dir) {
131
+ if (isLine(n)) indentLine(n, dir == null ? "smart" : dir ? "add" : "subtract");
132
+ }),
133
+ historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
134
+ matchBrackets: operation(function(){matchBrackets(true);}),
135
+ getTokenAt: function(pos) {
136
+ pos = clipPos(pos);
137
+ return lines[pos.line].getTokenAt(mode, getStateBefore(pos.line), pos.ch);
138
+ },
139
+ getStateAfter: function(line) {
140
+ line = clipLine(line == null ? lines.length - 1: line);
141
+ return getStateBefore(line + 1);
142
+ },
143
+ cursorCoords: function(start){
144
+ if (start == null) start = sel.inverted;
145
+ return pageCoords(start ? sel.from : sel.to);
146
+ },
147
+ charCoords: function(pos){return pageCoords(clipPos(pos));},
148
+ coordsChar: function(coords) {
149
+ var off = eltOffset(lineSpace);
150
+ var line = clipLine(Math.min(lines.length - 1, showingFrom + Math.floor((coords.y - off.top) / lineHeight())));
151
+ return clipPos({line: line, ch: charFromX(clipLine(line), coords.x - off.left)});
152
+ },
153
+ getSearchCursor: function(query, pos, caseFold) {return new SearchCursor(query, pos, caseFold);},
154
+ markText: operation(function(a, b, c){return operation(markText(a, b, c));}),
155
+ setMarker: addGutterMarker,
156
+ clearMarker: removeGutterMarker,
157
+ setLineClass: operation(setLineClass),
158
+ lineInfo: lineInfo,
159
+ addWidget: function(pos, node, scroll, where) {
160
+ pos = localCoords(clipPos(pos));
161
+ var top = pos.yBot, left = pos.x;
162
+ node.style.position = "absolute";
163
+ code.appendChild(node);
164
+ node.style.left = left + "px";
165
+ if (where == "over") top = pos.y;
166
+ else if (where == "near") {
167
+ var vspace = Math.max(scroller.offsetHeight, lines.length * lineHeight()),
168
+ hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft();
169
+ if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
170
+ top = pos.y - node.offsetHeight;
171
+ if (left + node.offsetWidth > hspace)
172
+ left = hspace - node.offsetWidth;
173
+ }
174
+ node.style.top = (top + paddingTop()) + "px";
175
+ node.style.left = (left + paddingLeft()) + "px";
176
+ if (scroll)
177
+ scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
178
+ },
179
+
180
+ lineCount: function() {return lines.length;},
181
+ getCursor: function(start) {
182
+ if (start == null) start = sel.inverted;
183
+ return copyPos(start ? sel.from : sel.to);
184
+ },
185
+ somethingSelected: function() {return !posEq(sel.from, sel.to);},
186
+ setCursor: operation(function(line, ch) {
187
+ if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch);
188
+ else setCursor(line, ch);
189
+ }),
190
+ setSelection: operation(function(from, to) {setSelection(clipPos(from), clipPos(to || from));}),
191
+ getLine: function(line) {if (isLine(line)) return lines[line].text;},
192
+ setLine: operation(function(line, text) {
193
+ if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: lines[line].text.length});
194
+ }),
195
+ removeLine: operation(function(line) {
196
+ if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
197
+ }),
198
+ replaceRange: operation(replaceRange),
199
+ getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
200
+
201
+ operation: function(f){return operation(f)();},
202
+ refresh: function(){updateDisplay(true);},
203
+ getInputField: function(){return input;},
204
+ getWrapperElement: function(){return wrapper;},
205
+ getScrollerElement: function(){return scroller;},
206
+ getGutterElement: function(){return gutter;}
207
+ };
208
+
209
+ function setValue(code) {
210
+ history = null;
211
+ var top = {line: 0, ch: 0};
212
+ updateLines(top, {line: lines.length - 1, ch: lines[lines.length-1].text.length},
213
+ splitLines(code), top, top);
214
+ history = new History();
215
+ }
216
+ function getValue(code) {
217
+ var text = [];
218
+ for (var i = 0, l = lines.length; i < l; ++i)
219
+ text.push(lines[i].text);
220
+ return text.join("\n");
221
+ }
222
+
223
+ function onMouseDown(e) {
224
+ // Check whether this is a click in a widget
225
+ for (var n = e_target(e); n != wrapper; n = n.parentNode)
226
+ if (n.parentNode == code && n != mover) return;
227
+ var ld = lastDoubleClick; lastDoubleClick = null;
228
+ // First, see if this is a click in the gutter
229
+ for (var n = e_target(e); n != wrapper; n = n.parentNode)
230
+ if (n.parentNode == gutterText) {
231
+ if (options.onGutterClick)
232
+ options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom);
233
+ return e_preventDefault(e);
234
+ }
235
+
236
+ var start = posFromMouse(e);
237
+
238
+ switch (e_button(e)) {
239
+ case 3:
240
+ if (gecko && !mac) onContextMenu(e);
241
+ return;
242
+ case 2:
243
+ if (start) setCursor(start.line, start.ch, true);
244
+ return;
245
+ }
246
+ // For button 1, if it was clicked inside the editor
247
+ // (posFromMouse returning non-null), we have to adjust the
248
+ // selection.
249
+ if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
250
+
251
+ if (!focused) onFocus();
252
+ e_preventDefault(e);
253
+ if (ld && +new Date - ld < 400) return selectLine(start.line);
254
+
255
+ setCursor(start.line, start.ch, true);
256
+ var last = start, going;
257
+ // And then we have to see if it's a drag event, in which case
258
+ // the dragged-over text must be selected.
259
+ function end() {
260
+ focusInput();
261
+ updateInput = true;
262
+ move(); up();
263
+ }
264
+ function extend(e) {
265
+ var cur = posFromMouse(e, true);
266
+ if (cur && !posEq(cur, last)) {
267
+ if (!focused) onFocus();
268
+ last = cur;
269
+ setSelectionUser(start, cur);
270
+ updateInput = false;
271
+ var visible = visibleLines();
272
+ if (cur.line >= visible.to || cur.line < visible.from)
273
+ going = setTimeout(operation(function(){extend(e);}), 150);
274
+ }
275
+ }
276
+
277
+ var move = connect(targetDocument, "mousemove", operation(function(e) {
278
+ clearTimeout(going);
279
+ e_preventDefault(e);
280
+ extend(e);
281
+ }), true);
282
+ var up = connect(targetDocument, "mouseup", operation(function(e) {
283
+ clearTimeout(going);
284
+ var cur = posFromMouse(e);
285
+ if (cur) setSelectionUser(start, cur);
286
+ e_preventDefault(e);
287
+ end();
288
+ }), true);
289
+ }
290
+ function onDblClick(e) {
291
+ var pos = posFromMouse(e);
292
+ if (!pos) return;
293
+ selectWordAt(pos);
294
+ e_preventDefault(e);
295
+ lastDoubleClick = +new Date;
296
+ }
297
+ function onDrop(e) {
298
+ e.preventDefault();
299
+ var pos = posFromMouse(e, true), files = e.dataTransfer.files;
300
+ if (!pos || options.readOnly) return;
301
+ if (files && files.length && window.FileReader && window.File) {
302
+ function loadFile(file, i) {
303
+ var reader = new FileReader;
304
+ reader.onload = function() {
305
+ text[i] = reader.result;
306
+ if (++read == n) replaceRange(text.join(""), clipPos(pos), clipPos(pos));
307
+ };
308
+ reader.readAsText(file);
309
+ }
310
+ var n = files.length, text = Array(n), read = 0;
311
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
312
+ }
313
+ else {
314
+ try {
315
+ var text = e.dataTransfer.getData("Text");
316
+ if (text) replaceRange(text, pos, pos);
317
+ }
318
+ catch(e){}
319
+ }
320
+ }
321
+ function onKeyDown(e) {
322
+ if (!focused) onFocus();
323
+
324
+ var code = e.keyCode;
325
+ // IE does strange things with escape.
326
+ if (ie && code == 27) { e.returnValue = false; }
327
+ // Tries to detect ctrl on non-mac, cmd on mac.
328
+ var mod = (mac ? e.metaKey : e.ctrlKey) && !e.altKey, anyMod = e.ctrlKey || e.altKey || e.metaKey;
329
+ if (code == 16 || e.shiftKey) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
330
+ else shiftSelecting = null;
331
+ // First give onKeyEvent option a chance to handle this.
332
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
333
+
334
+ if (code == 33 || code == 34) {scrollPage(code == 34); return e_preventDefault(e);} // page up/down
335
+ if (mod && ((code == 36 || code == 35) || // ctrl-home/end
336
+ mac && (code == 38 || code == 40))) { // cmd-up/down
337
+ scrollEnd(code == 36 || code == 38); return e_preventDefault(e);
338
+ }
339
+ if (mod && code == 65) {selectAll(); return e_preventDefault(e);} // ctrl-a
340
+ if (!options.readOnly) {
341
+ if (!anyMod && code == 13) {return;} // enter
342
+ if (!anyMod && code == 9 && handleTab(e.shiftKey)) return e_preventDefault(e); // tab
343
+ if (mod && code == 90) {undo(); return e_preventDefault(e);} // ctrl-z
344
+ if (mod && ((e.shiftKey && code == 90) || code == 89)) {redo(); return e_preventDefault(e);} // ctrl-shift-z, ctrl-y
345
+ }
346
+ if (code == 36) { if (options.smartHome) { smartHome(); return e_preventDefault(e); } }
347
+
348
+ // Key id to use in the movementKeys map. We also pass it to
349
+ // fastPoll in order to 'self learn'. We need this because
350
+ // reducedSelection, the hack where we collapse the selection to
351
+ // its start when it is inverted and a movement key is pressed
352
+ // (and later restore it again), shouldn't be used for
353
+ // non-movement keys.
354
+ curKeyId = (mod ? "c" : "") + (e.altKey ? "a" : "") + code;
355
+ if (sel.inverted && movementKeys[curKeyId] === true) {
356
+ var range = selRange(input);
357
+ if (range) {
358
+ reducedSelection = {anchor: range.start};
359
+ setSelRange(input, range.start, range.start);
360
+ }
361
+ }
362
+ // Don't save the key as a movementkey unless it had a modifier
363
+ if (!mod && !e.altKey) curKeyId = null;
364
+ fastPoll(curKeyId);
365
+ }
366
+ function onKeyUp(e) {
367
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
368
+ if (reducedSelection) {
369
+ reducedSelection = null;
370
+ updateInput = true;
371
+ }
372
+ if (e.keyCode == 16) shiftSelecting = null;
373
+ }
374
+ function onKeyPress(e) {
375
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
376
+ if (options.electricChars && mode.electricChars) {
377
+ var ch = String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode);
378
+ if (mode.electricChars.indexOf(ch) > -1)
379
+ setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 50);
380
+ }
381
+ var code = e.keyCode;
382
+ // Re-stop tab and enter. Necessary on some browsers.
383
+ if (code == 13) {if (!options.readOnly) handleEnter(); e_preventDefault(e);}
384
+ else if (!e.ctrlKey && !e.altKey && !e.metaKey && code == 9 && options.tabMode != "default") e_preventDefault(e);
385
+ else fastPoll(curKeyId);
386
+ }
387
+
388
+ function onFocus() {
389
+ if (options.readOnly == "nocursor") return;
390
+ if (!focused) {
391
+ if (options.onFocus) options.onFocus(instance);
392
+ focused = true;
393
+ if (wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
394
+ wrapper.className += " CodeMirror-focused";
395
+ if (!leaveInputAlone) prepareInput();
396
+ }
397
+ slowPoll();
398
+ restartBlink();
399
+ }
400
+ function onBlur() {
401
+ if (focused) {
402
+ if (options.onBlur) options.onBlur(instance);
403
+ focused = false;
404
+ wrapper.className = wrapper.className.replace(" CodeMirror-focused", "");
405
+ }
406
+ clearInterval(blinker);
407
+ setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
408
+ }
409
+
410
+ // Replace the range from from to to by the strings in newText.
411
+ // Afterwards, set the selection to selFrom, selTo.
412
+ function updateLines(from, to, newText, selFrom, selTo) {
413
+ if (history) {
414
+ var old = [];
415
+ for (var i = from.line, e = to.line + 1; i < e; ++i) old.push(lines[i].text);
416
+ history.addChange(from.line, newText.length, old);
417
+ while (history.done.length > options.undoDepth) history.done.shift();
418
+ }
419
+ updateLinesNoUndo(from, to, newText, selFrom, selTo);
420
+ }
421
+ function unredoHelper(from, to) {
422
+ var change = from.pop();
423
+ if (change) {
424
+ var replaced = [], end = change.start + change.added;
425
+ for (var i = change.start; i < end; ++i) replaced.push(lines[i].text);
426
+ to.push({start: change.start, added: change.old.length, old: replaced});
427
+ var pos = clipPos({line: change.start + change.old.length - 1,
428
+ ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])});
429
+ updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: lines[end-1].text.length}, change.old, pos, pos);
430
+ updateInput = true;
431
+ }
432
+ }
433
+ function undo() {unredoHelper(history.done, history.undone);}
434
+ function redo() {unredoHelper(history.undone, history.done);}
435
+
436
+ function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
437
+ var recomputeMaxLength = false, maxLineLength = maxLine.length;
438
+ for (var i = from.line; i <= to.line; ++i) {
439
+ if (lines[i].text.length == maxLineLength) {recomputeMaxLength = true; break;}
440
+ }
441
+
442
+ var nlines = to.line - from.line, firstLine = lines[from.line], lastLine = lines[to.line];
443
+ // First adjust the line structure, taking some care to leave highlighting intact.
444
+ if (firstLine == lastLine) {
445
+ if (newText.length == 1)
446
+ firstLine.replace(from.ch, to.ch, newText[0]);
447
+ else {
448
+ lastLine = firstLine.split(to.ch, newText[newText.length-1]);
449
+ var spliceargs = [from.line + 1, nlines];
450
+ firstLine.replace(from.ch, firstLine.text.length, newText[0]);
451
+ for (var i = 1, e = newText.length - 1; i < e; ++i) spliceargs.push(new Line(newText[i]));
452
+ spliceargs.push(lastLine);
453
+ lines.splice.apply(lines, spliceargs);
454
+ }
455
+ }
456
+ else if (newText.length == 1) {
457
+ firstLine.replace(from.ch, firstLine.text.length, newText[0] + lastLine.text.slice(to.ch));
458
+ lines.splice(from.line + 1, nlines);
459
+ }
460
+ else {
461
+ var spliceargs = [from.line + 1, nlines - 1];
462
+ firstLine.replace(from.ch, firstLine.text.length, newText[0]);
463
+ lastLine.replace(0, to.ch, newText[newText.length-1]);
464
+ for (var i = 1, e = newText.length - 1; i < e; ++i) spliceargs.push(new Line(newText[i]));
465
+ lines.splice.apply(lines, spliceargs);
466
+ }
467
+
468
+
469
+ for (var i = from.line, e = i + newText.length; i < e; ++i) {
470
+ var l = lines[i].text;
471
+ if (l.length > maxLineLength) {
472
+ maxLine = l; maxLineLength = l.length; maxWidth = null;
473
+ recomputeMaxLength = false;
474
+ }
475
+ }
476
+ if (recomputeMaxLength) {
477
+ maxLineLength = 0; maxLine = ""; maxWidth = null;
478
+ for (var i = 0, e = lines.length; i < e; ++i) {
479
+ var l = lines[i].text;
480
+ if (l.length > maxLineLength) {
481
+ maxLineLength = l.length; maxLine = l;
482
+ }
483
+ }
484
+ }
485
+
486
+ // Add these lines to the work array, so that they will be
487
+ // highlighted. Adjust work lines if lines were added/removed.
488
+ var newWork = [], lendiff = newText.length - nlines - 1;
489
+ for (var i = 0, l = work.length; i < l; ++i) {
490
+ var task = work[i];
491
+ if (task < from.line) newWork.push(task);
492
+ else if (task > to.line) newWork.push(task + lendiff);
493
+ }
494
+ if (newText.length < 5) {
495
+ highlightLines(from.line, from.line + newText.length);
496
+ newWork.push(from.line + newText.length);
497
+ } else {
498
+ newWork.push(from.line);
499
+ }
500
+ work = newWork;
501
+ startWorker(100);
502
+ // Remember that these lines changed, for updating the display
503
+ changes.push({from: from.line, to: to.line + 1, diff: lendiff});
504
+ textChanged = {from: from, to: to, text: newText};
505
+
506
+ // Update the selection
507
+ function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
508
+ setSelection(selFrom, selTo, updateLine(sel.from.line), updateLine(sel.to.line));
509
+
510
+ // Make sure the scroll-size div has the correct height.
511
+ code.style.height = (lines.length * lineHeight() + 2 * paddingTop()) + "px";
512
+ }
513
+
514
+ function replaceRange(code, from, to) {
515
+ from = clipPos(from);
516
+ if (!to) to = from; else to = clipPos(to);
517
+ code = splitLines(code);
518
+ function adjustPos(pos) {
519
+ if (posLess(pos, from)) return pos;
520
+ if (!posLess(to, pos)) return end;
521
+ var line = pos.line + code.length - (to.line - from.line) - 1;
522
+ var ch = pos.ch;
523
+ if (pos.line == to.line)
524
+ ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
525
+ return {line: line, ch: ch};
526
+ }
527
+ var end;
528
+ replaceRange1(code, from, to, function(end1) {
529
+ end = end1;
530
+ return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
531
+ });
532
+ return end;
533
+ }
534
+ function replaceSelection(code, collapse) {
535
+ replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
536
+ if (collapse == "end") return {from: end, to: end};
537
+ else if (collapse == "start") return {from: sel.from, to: sel.from};
538
+ else return {from: sel.from, to: end};
539
+ });
540
+ }
541
+ function replaceRange1(code, from, to, computeSel) {
542
+ var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
543
+ var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
544
+ updateLines(from, to, code, newSel.from, newSel.to);
545
+ }
546
+
547
+ function getRange(from, to) {
548
+ var l1 = from.line, l2 = to.line;
549
+ if (l1 == l2) return lines[l1].text.slice(from.ch, to.ch);
550
+ var code = [lines[l1].text.slice(from.ch)];
551
+ for (var i = l1 + 1; i < l2; ++i) code.push(lines[i].text);
552
+ code.push(lines[l2].text.slice(0, to.ch));
553
+ return code.join("\n");
554
+ }
555
+ function getSelection() {
556
+ return getRange(sel.from, sel.to);
557
+ }
558
+
559
+ var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
560
+ function slowPoll() {
561
+ if (pollingFast) return;
562
+ poll.set(2000, function() {
563
+ startOperation();
564
+ readInput();
565
+ if (focused) slowPoll();
566
+ endOperation();
567
+ });
568
+ }
569
+ function fastPoll(keyId) {
570
+ var missed = false;
571
+ pollingFast = true;
572
+ function p() {
573
+ startOperation();
574
+ var changed = readInput();
575
+ if (changed && keyId) {
576
+ if (changed == "moved" && movementKeys[keyId] == null) movementKeys[keyId] = true;
577
+ if (changed == "changed") movementKeys[keyId] = false;
578
+ }
579
+ if (!changed && !missed) {missed = true; poll.set(80, p);}
580
+ else {pollingFast = false; slowPoll();}
581
+ endOperation();
582
+ }
583
+ poll.set(20, p);
584
+ }
585
+
586
+ // Inspects the textarea, compares its state (content, selection)
587
+ // to the data in the editing variable, and updates the editor
588
+ // content or cursor if something changed.
589
+ function readInput() {
590
+ if (leaveInputAlone || !focused) return;
591
+ var changed = false, text = input.value, sr = selRange(input);
592
+ if (!sr) return false;
593
+ var changed = editing.text != text, rs = reducedSelection;
594
+ var moved = changed || sr.start != editing.start || sr.end != (rs ? editing.start : editing.end);
595
+ if (!moved && !rs) return false;
596
+ if (changed) {
597
+ shiftSelecting = reducedSelection = null;
598
+ if (options.readOnly) {updateInput = true; return "changed";}
599
+ }
600
+
601
+ // Compute selection start and end based on start/end offsets in textarea
602
+ function computeOffset(n, startLine) {
603
+ var pos = 0;
604
+ for (;;) {
605
+ var found = text.indexOf("\n", pos);
606
+ if (found == -1 || (text.charAt(found-1) == "\r" ? found - 1 : found) >= n)
607
+ return {line: startLine, ch: n - pos};
608
+ ++startLine;
609
+ pos = found + 1;
610
+ }
611
+ }
612
+ var from = computeOffset(sr.start, editing.from),
613
+ to = computeOffset(sr.end, editing.from);
614
+ // Here we have to take the reducedSelection hack into account,
615
+ // so that you can, for example, press shift-up at the start of
616
+ // your selection and have the right thing happen.
617
+ if (rs) {
618
+ var head = sr.start == rs.anchor ? to : from;
619
+ var tail = shiftSelecting ? sel.to : sr.start == rs.anchor ? from : to;
620
+ if (sel.inverted = posLess(head, tail)) { from = head; to = tail; }
621
+ else { reducedSelection = null; from = tail; to = head; }
622
+ }
623
+
624
+ // In some cases (cursor on same line as before), we don't have
625
+ // to update the textarea content at all.
626
+ if (from.line == to.line && from.line == sel.from.line && from.line == sel.to.line && !shiftSelecting)
627
+ updateInput = false;
628
+
629
+ // Magic mess to extract precise edited range from the changed
630
+ // string.
631
+ if (changed) {
632
+ var start = 0, end = text.length, len = Math.min(end, editing.text.length);
633
+ var c, line = editing.from, nl = -1;
634
+ while (start < len && (c = text.charAt(start)) == editing.text.charAt(start)) {
635
+ ++start;
636
+ if (c == "\n") {line++; nl = start;}
637
+ }
638
+ var ch = nl > -1 ? start - nl : start, endline = editing.to - 1, edend = editing.text.length;
639
+ for (;;) {
640
+ c = editing.text.charAt(edend);
641
+ if (text.charAt(end) != c) {++end; ++edend; break;}
642
+ if (c == "\n") endline--;
643
+ if (edend <= start || end <= start) break;
644
+ --end; --edend;
645
+ }
646
+ var nl = editing.text.lastIndexOf("\n", edend - 1), endch = nl == -1 ? edend : edend - nl - 1;
647
+ updateLines({line: line, ch: ch}, {line: endline, ch: endch}, splitLines(text.slice(start, end)), from, to);
648
+ if (line != endline || from.line != line) updateInput = true;
649
+ }
650
+ else setSelection(from, to);
651
+
652
+ editing.text = text; editing.start = sr.start; editing.end = sr.end;
653
+ return changed ? "changed" : moved ? "moved" : false;
654
+ }
655
+
656
+ // Set the textarea content and selection range to match the
657
+ // editor state.
658
+ function prepareInput() {
659
+ var text = [];
660
+ var from = Math.max(0, sel.from.line - 1), to = Math.min(lines.length, sel.to.line + 2);
661
+ for (var i = from; i < to; ++i) text.push(lines[i].text);
662
+ text = input.value = text.join(lineSep);
663
+ var startch = sel.from.ch, endch = sel.to.ch;
664
+ for (var i = from; i < sel.from.line; ++i)
665
+ startch += lineSep.length + lines[i].text.length;
666
+ for (var i = from; i < sel.to.line; ++i)
667
+ endch += lineSep.length + lines[i].text.length;
668
+ editing = {text: text, from: from, to: to, start: startch, end: endch};
669
+ setSelRange(input, startch, reducedSelection ? startch : endch);
670
+ }
671
+ function focusInput() {
672
+ if (options.readOnly != "nocursor") input.focus();
673
+ }
674
+
675
+ function scrollEditorIntoView() {
676
+ if (!cursor.getBoundingClientRect) return;
677
+ var rect = cursor.getBoundingClientRect();
678
+ var winH = window.innerHeight || document.body.offsetHeight || document.documentElement.offsetHeight;
679
+ if (rect.top < 0 || rect.bottom > winH) cursor.scrollIntoView();
680
+ }
681
+ function scrollCursorIntoView() {
682
+ var cursor = localCoords(sel.inverted ? sel.from : sel.to);
683
+ return scrollIntoView(cursor.x, cursor.y, cursor.x, cursor.yBot);
684
+ }
685
+ function scrollIntoView(x1, y1, x2, y2) {
686
+ var pl = paddingLeft(), pt = paddingTop(), lh = lineHeight();
687
+ y1 += pt; y2 += pt; x1 += pl; x2 += pl;
688
+ var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true;
689
+ if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1 - 2*lh); scrolled = true;}
690
+ else if (y2 > screentop + screen) {scroller.scrollTop = y2 + lh - screen; scrolled = true;}
691
+
692
+ var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
693
+ if (x1 < screenleft) {
694
+ if (x1 < 50) x1 = 0;
695
+ scroller.scrollLeft = Math.max(0, x1 - 10);
696
+ scrolled = true;
697
+ }
698
+ else if (x2 > screenw + screenleft) {
699
+ scroller.scrollLeft = x2 + 10 - screenw;
700
+ scrolled = true;
701
+ if (x2 > code.clientWidth) result = false;
702
+ }
703
+ if (scrolled && options.onScroll) options.onScroll(instance);
704
+ return result;
705
+ }
706
+
707
+ function visibleLines() {
708
+ var lh = lineHeight(), top = scroller.scrollTop - paddingTop();
709
+ return {from: Math.min(lines.length, Math.max(0, Math.floor(top / lh))),
710
+ to: Math.min(lines.length, Math.ceil((top + scroller.clientHeight) / lh))};
711
+ }
712
+ // Uses a set of changes plus the current scroll position to
713
+ // determine which DOM updates have to be made, and makes the
714
+ // updates.
715
+ function updateDisplay(changes) {
716
+ if (!scroller.clientWidth) {
717
+ showingFrom = showingTo = 0;
718
+ return;
719
+ }
720
+ // First create a range of theoretically intact lines, and punch
721
+ // holes in that using the change info.
722
+ var intact = changes === true ? [] : [{from: showingFrom, to: showingTo, domStart: 0}];
723
+ for (var i = 0, l = changes.length || 0; i < l; ++i) {
724
+ var change = changes[i], intact2 = [], diff = change.diff || 0;
725
+ for (var j = 0, l2 = intact.length; j < l2; ++j) {
726
+ var range = intact[j];
727
+ if (change.to <= range.from)
728
+ intact2.push({from: range.from + diff, to: range.to + diff, domStart: range.domStart});
729
+ else if (range.to <= change.from)
730
+ intact2.push(range);
731
+ else {
732
+ if (change.from > range.from)
733
+ intact2.push({from: range.from, to: change.from, domStart: range.domStart})
734
+ if (change.to < range.to)
735
+ intact2.push({from: change.to + diff, to: range.to + diff,
736
+ domStart: range.domStart + (change.to - range.from)});
737
+ }
738
+ }
739
+ intact = intact2;
740
+ }
741
+
742
+ // Then, determine which lines we'd want to see, and which
743
+ // updates have to be made to get there.
744
+ var visible = visibleLines();
745
+ var from = Math.min(showingFrom, Math.max(visible.from - 3, 0)),
746
+ to = Math.min(lines.length, Math.max(showingTo, visible.to + 3)),
747
+ updates = [], domPos = 0, domEnd = showingTo - showingFrom, pos = from, changedLines = 0;
748
+
749
+ for (var i = 0, l = intact.length; i < l; ++i) {
750
+ var range = intact[i];
751
+ if (range.to <= from) continue;
752
+ if (range.from >= to) break;
753
+ if (range.domStart > domPos || range.from > pos) {
754
+ updates.push({from: pos, to: range.from, domSize: range.domStart - domPos, domStart: domPos});
755
+ changedLines += range.from - pos;
756
+ }
757
+ pos = range.to;
758
+ domPos = range.domStart + (range.to - range.from);
759
+ }
760
+ if (domPos != domEnd || pos != to) {
761
+ changedLines += Math.abs(to - pos);
762
+ updates.push({from: pos, to: to, domSize: domEnd - domPos, domStart: domPos});
763
+ }
764
+
765
+ if (!updates.length) return;
766
+ lineDiv.style.display = "none";
767
+ // If more than 30% of the screen needs update, just do a full
768
+ // redraw (which is quicker than patching)
769
+ if (changedLines > (visible.to - visible.from) * .3)
770
+ refreshDisplay(from = Math.max(visible.from - 10, 0), to = Math.min(visible.to + 7, lines.length));
771
+ // Otherwise, only update the stuff that needs updating.
772
+ else
773
+ patchDisplay(updates);
774
+ lineDiv.style.display = "";
775
+
776
+ // Position the mover div to align with the lines it's supposed
777
+ // to be showing (which will cover the visible display)
778
+ var different = from != showingFrom || to != showingTo || lastHeight != scroller.clientHeight;
779
+ showingFrom = from; showingTo = to;
780
+ mover.style.top = (from * lineHeight()) + "px";
781
+ if (different) {
782
+ lastHeight = scroller.clientHeight;
783
+ code.style.height = (lines.length * lineHeight() + 2 * paddingTop()) + "px";
784
+ }
785
+ if (different || updates.length) updateGutter();
786
+
787
+ if (maxWidth == null) maxWidth = stringWidth(maxLine);
788
+ if (maxWidth > scroller.clientWidth) {
789
+ lineSpace.style.width = maxWidth + "px";
790
+ // Needed to prevent odd wrapping/hiding of widgets placed in here.
791
+ code.style.width = "";
792
+ code.style.width = scroller.scrollWidth + "px";
793
+ } else {
794
+ lineSpace.style.width = code.style.width = "";
795
+ }
796
+
797
+ // Since this is all rather error prone, it is honoured with the
798
+ // only assertion in the whole file.
799
+ if (lineDiv.childNodes.length != showingTo - showingFrom)
800
+ throw new Error("BAD PATCH! " + JSON.stringify(updates) + " size=" + (showingTo - showingFrom) +
801
+ " nodes=" + lineDiv.childNodes.length);
802
+ updateCursor();
803
+ }
804
+
805
+ function refreshDisplay(from, to) {
806
+ var html = [], start = {line: from, ch: 0}, inSel = posLess(sel.from, start) && !posLess(sel.to, start);
807
+ for (var i = from; i < to; ++i) {
808
+ var ch1 = null, ch2 = null;
809
+ if (inSel) {
810
+ ch1 = 0;
811
+ if (sel.to.line == i) {inSel = false; ch2 = sel.to.ch;}
812
+ }
813
+ else if (sel.from.line == i) {
814
+ if (sel.to.line == i) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
815
+ else {inSel = true; ch1 = sel.from.ch;}
816
+ }
817
+ html.push(lines[i].getHTML(ch1, ch2, true));
818
+ }
819
+ lineDiv.innerHTML = html.join("");
820
+ }
821
+ function patchDisplay(updates) {
822
+ // Slightly different algorithm for IE (badInnerHTML), since
823
+ // there .innerHTML on PRE nodes is dumb, and discards
824
+ // whitespace.
825
+ var sfrom = sel.from.line, sto = sel.to.line, off = 0,
826
+ scratch = badInnerHTML && targetDocument.createElement("div");
827
+ for (var i = 0, e = updates.length; i < e; ++i) {
828
+ var rec = updates[i];
829
+ var extra = (rec.to - rec.from) - rec.domSize;
830
+ var nodeAfter = lineDiv.childNodes[rec.domStart + rec.domSize + off] || null;
831
+ if (badInnerHTML)
832
+ for (var j = Math.max(-extra, rec.domSize); j > 0; --j)
833
+ lineDiv.removeChild(nodeAfter ? nodeAfter.previousSibling : lineDiv.lastChild);
834
+ else if (extra) {
835
+ for (var j = Math.max(0, extra); j > 0; --j)
836
+ lineDiv.insertBefore(targetDocument.createElement("pre"), nodeAfter);
837
+ for (var j = Math.max(0, -extra); j > 0; --j)
838
+ lineDiv.removeChild(nodeAfter ? nodeAfter.previousSibling : lineDiv.lastChild);
839
+ }
840
+ var node = lineDiv.childNodes[rec.domStart + off], inSel = sfrom < rec.from && sto >= rec.from;
841
+ for (var j = rec.from; j < rec.to; ++j) {
842
+ var ch1 = null, ch2 = null;
843
+ if (inSel) {
844
+ ch1 = 0;
845
+ if (sto == j) {inSel = false; ch2 = sel.to.ch;}
846
+ }
847
+ else if (sfrom == j) {
848
+ if (sto == j) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
849
+ else {inSel = true; ch1 = sel.from.ch;}
850
+ }
851
+ if (badInnerHTML) {
852
+ scratch.innerHTML = lines[j].getHTML(ch1, ch2, true);
853
+ lineDiv.insertBefore(scratch.firstChild, nodeAfter);
854
+ }
855
+ else {
856
+ node.innerHTML = lines[j].getHTML(ch1, ch2, false);
857
+ node.className = lines[j].className || "";
858
+ node = node.nextSibling;
859
+ }
860
+ }
861
+ off += extra;
862
+ }
863
+ }
864
+
865
+ function updateGutter() {
866
+ if (!options.gutter && !options.lineNumbers) return;
867
+ var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
868
+ gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
869
+ var html = [];
870
+ for (var i = showingFrom; i < Math.max(showingTo, showingFrom + 1); ++i) {
871
+ var marker = lines[i].gutterMarker;
872
+ var text = options.lineNumbers ? i + options.firstLineNumber : null;
873
+ if (marker && marker.text)
874
+ text = marker.text.replace("%N%", text != null ? text : "");
875
+ else if (text == null)
876
+ text = "\u00a0";
877
+ html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text, "</pre>");
878
+ }
879
+ gutter.style.display = "none";
880
+ gutterText.innerHTML = html.join("");
881
+ var minwidth = String(lines.length).length, firstNode = gutterText.firstChild, val = eltText(firstNode), pad = "";
882
+ while (val.length + pad.length < minwidth) pad += "\u00a0";
883
+ if (pad) firstNode.insertBefore(targetDocument.createTextNode(pad), firstNode.firstChild);
884
+ gutter.style.display = "";
885
+ lineSpace.style.marginLeft = gutter.offsetWidth + "px";
886
+ }
887
+ function updateCursor() {
888
+ var head = sel.inverted ? sel.from : sel.to, lh = lineHeight();
889
+ var x = charX(head.line, head.ch);
890
+ inputDiv.style.top = (head.line * lh - scroller.scrollTop) + "px";
891
+ inputDiv.style.left = (x - scroller.scrollLeft) + "px";
892
+ if (posEq(sel.from, sel.to)) {
893
+ cursor.style.top = (head.line - showingFrom) * lh + "px";
894
+ cursor.style.left = x + "px";
895
+ cursor.style.display = "";
896
+ }
897
+ else cursor.style.display = "none";
898
+ }
899
+
900
+ function setSelectionUser(from, to) {
901
+ var sh = shiftSelecting && clipPos(shiftSelecting);
902
+ if (sh) {
903
+ if (posLess(sh, from)) from = sh;
904
+ else if (posLess(to, sh)) to = sh;
905
+ }
906
+ setSelection(from, to);
907
+ }
908
+ // Update the selection. Last two args are only used by
909
+ // updateLines, since they have to be expressed in the line
910
+ // numbers before the update.
911
+ function setSelection(from, to, oldFrom, oldTo) {
912
+ if (posEq(sel.from, from) && posEq(sel.to, to)) return;
913
+ if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
914
+
915
+ if (posEq(from, to)) sel.inverted = false;
916
+ else if (posEq(from, sel.to)) sel.inverted = false;
917
+ else if (posEq(to, sel.from)) sel.inverted = true;
918
+
919
+ // Some ugly logic used to only mark the lines that actually did
920
+ // see a change in selection as changed, rather than the whole
921
+ // selected range.
922
+ if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
923
+ if (posEq(from, to)) {
924
+ if (!posEq(sel.from, sel.to))
925
+ changes.push({from: oldFrom, to: oldTo + 1});
926
+ }
927
+ else if (posEq(sel.from, sel.to)) {
928
+ changes.push({from: from.line, to: to.line + 1});
929
+ }
930
+ else {
931
+ if (!posEq(from, sel.from)) {
932
+ if (from.line < oldFrom)
933
+ changes.push({from: from.line, to: Math.min(to.line, oldFrom) + 1});
934
+ else
935
+ changes.push({from: oldFrom, to: Math.min(oldTo, from.line) + 1});
936
+ }
937
+ if (!posEq(to, sel.to)) {
938
+ if (to.line < oldTo)
939
+ changes.push({from: Math.max(oldFrom, from.line), to: oldTo + 1});
940
+ else
941
+ changes.push({from: Math.max(from.line, oldTo), to: to.line + 1});
942
+ }
943
+ }
944
+ sel.from = from; sel.to = to;
945
+ selectionChanged = true;
946
+ }
947
+ function setCursor(line, ch, user) {
948
+ var pos = clipPos({line: line, ch: ch || 0});
949
+ (user ? setSelectionUser : setSelection)(pos, pos);
950
+ }
951
+
952
+ function clipLine(n) {return Math.max(0, Math.min(n, lines.length-1));}
953
+ function clipPos(pos) {
954
+ if (pos.line < 0) return {line: 0, ch: 0};
955
+ if (pos.line >= lines.length) return {line: lines.length-1, ch: lines[lines.length-1].text.length};
956
+ var ch = pos.ch, linelen = lines[pos.line].text.length;
957
+ if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
958
+ else if (ch < 0) return {line: pos.line, ch: 0};
959
+ else return pos;
960
+ }
961
+
962
+ function scrollPage(down) {
963
+ var linesPerPage = Math.floor(scroller.clientHeight / lineHeight()), head = sel.inverted ? sel.from : sel.to;
964
+ setCursor(head.line + (Math.max(linesPerPage - 1, 1) * (down ? 1 : -1)), head.ch, true);
965
+ }
966
+ function scrollEnd(top) {
967
+ var pos = top ? {line: 0, ch: 0} : {line: lines.length - 1, ch: lines[lines.length-1].text.length};
968
+ setSelectionUser(pos, pos);
969
+ }
970
+ function selectAll() {
971
+ var endLine = lines.length - 1;
972
+ setSelection({line: 0, ch: 0}, {line: endLine, ch: lines[endLine].text.length});
973
+ }
974
+ function selectWordAt(pos) {
975
+ var line = lines[pos.line].text;
976
+ var start = pos.ch, end = pos.ch;
977
+ while (start > 0 && /\w/.test(line.charAt(start - 1))) --start;
978
+ while (end < line.length && /\w/.test(line.charAt(end))) ++end;
979
+ setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
980
+ }
981
+ function selectLine(line) {
982
+ setSelectionUser({line: line, ch: 0}, {line: line, ch: lines[line].text.length});
983
+ }
984
+ function handleEnter() {
985
+ replaceSelection("\n", "end");
986
+ if (options.enterMode != "flat")
987
+ indentLine(sel.from.line, options.enterMode == "keep" ? "prev" : "smart");
988
+ }
989
+ function handleTab(shift) {
990
+ function indentSelected(mode) {
991
+ if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
992
+ var e = sel.to.line - (sel.to.ch ? 0 : 1);
993
+ for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
994
+ }
995
+ shiftSelecting = null;
996
+ switch (options.tabMode) {
997
+ case "default":
998
+ return false;
999
+ case "indent":
1000
+ indentSelected("smart");
1001
+ break;
1002
+ case "classic":
1003
+ if (posEq(sel.from, sel.to)) {
1004
+ if (shift) indentLine(sel.from.line, "smart");
1005
+ else replaceSelection("\t", "end");
1006
+ break;
1007
+ }
1008
+ case "shift":
1009
+ indentSelected(shift ? "subtract" : "add");
1010
+ break;
1011
+ }
1012
+ return true;
1013
+ }
1014
+ function smartHome() {
1015
+ var firstNonWS = Math.max(0, lines[sel.from.line].text.search(/\S/));
1016
+ setCursor(sel.from.line, sel.from.ch <= firstNonWS && sel.from.ch ? 0 : firstNonWS, true);
1017
+ }
1018
+
1019
+ function indentLine(n, how) {
1020
+ if (how == "smart") {
1021
+ if (!mode.indent) how = "prev";
1022
+ else var state = getStateBefore(n);
1023
+ }
1024
+
1025
+ var line = lines[n], curSpace = line.indentation(), curSpaceString = line.text.match(/^\s*/)[0], indentation;
1026
+ if (how == "prev") {
1027
+ if (n) indentation = lines[n-1].indentation();
1028
+ else indentation = 0;
1029
+ }
1030
+ else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length));
1031
+ else if (how == "add") indentation = curSpace + options.indentUnit;
1032
+ else if (how == "subtract") indentation = curSpace - options.indentUnit;
1033
+ indentation = Math.max(0, indentation);
1034
+ var diff = indentation - curSpace;
1035
+
1036
+ if (!diff) {
1037
+ if (sel.from.line != n && sel.to.line != n) return;
1038
+ var indentString = curSpaceString;
1039
+ }
1040
+ else {
1041
+ var indentString = "", pos = 0;
1042
+ if (options.indentWithTabs)
1043
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
1044
+ while (pos < indentation) {++pos; indentString += " ";}
1045
+ }
1046
+
1047
+ replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
1048
+ }
1049
+
1050
+ function loadMode() {
1051
+ mode = CodeMirror.getMode(options, options.mode);
1052
+ for (var i = 0, l = lines.length; i < l; ++i)
1053
+ lines[i].stateAfter = null;
1054
+ work = [0];
1055
+ startWorker();
1056
+ }
1057
+ function gutterChanged() {
1058
+ var visible = options.gutter || options.lineNumbers;
1059
+ gutter.style.display = visible ? "" : "none";
1060
+ if (visible) updateGutter();
1061
+ else lineDiv.parentNode.style.marginLeft = 0;
1062
+ }
1063
+
1064
+ function markText(from, to, className) {
1065
+ from = clipPos(from); to = clipPos(to);
1066
+ var accum = [];
1067
+ function add(line, from, to, className) {
1068
+ var line = lines[line], mark = line.addMark(from, to, className);
1069
+ mark.line = line;
1070
+ accum.push(mark);
1071
+ }
1072
+ if (from.line == to.line) add(from.line, from.ch, to.ch, className);
1073
+ else {
1074
+ add(from.line, from.ch, null, className);
1075
+ for (var i = from.line + 1, e = to.line; i < e; ++i)
1076
+ add(i, 0, null, className);
1077
+ add(to.line, 0, to.ch, className);
1078
+ }
1079
+ changes.push({from: from.line, to: to.line + 1});
1080
+ return function() {
1081
+ var start, end;
1082
+ for (var i = 0; i < accum.length; ++i) {
1083
+ var mark = accum[i], found = indexOf(lines, mark.line);
1084
+ mark.line.removeMark(mark);
1085
+ if (found > -1) {
1086
+ if (start == null) start = found;
1087
+ end = found;
1088
+ }
1089
+ }
1090
+ if (start != null) changes.push({from: start, to: end + 1});
1091
+ };
1092
+ }
1093
+
1094
+ function addGutterMarker(line, text, className) {
1095
+ if (typeof line == "number") line = lines[clipLine(line)];
1096
+ line.gutterMarker = {text: text, style: className};
1097
+ updateGutter();
1098
+ return line;
1099
+ }
1100
+ function removeGutterMarker(line) {
1101
+ if (typeof line == "number") line = lines[clipLine(line)];
1102
+ line.gutterMarker = null;
1103
+ updateGutter();
1104
+ }
1105
+ function setLineClass(line, className) {
1106
+ if (typeof line == "number") {
1107
+ var no = line;
1108
+ line = lines[clipLine(line)];
1109
+ }
1110
+ else {
1111
+ var no = indexOf(lines, line);
1112
+ if (no == -1) return null;
1113
+ }
1114
+ if (line.className != className) {
1115
+ line.className = className;
1116
+ changes.push({from: no, to: no + 1});
1117
+ }
1118
+ return line;
1119
+ }
1120
+
1121
+ function lineInfo(line) {
1122
+ if (typeof line == "number") {
1123
+ var n = line;
1124
+ line = lines[line];
1125
+ if (!line) return null;
1126
+ }
1127
+ else {
1128
+ var n = indexOf(lines, line);
1129
+ if (n == -1) return null;
1130
+ }
1131
+ var marker = line.gutterMarker;
1132
+ return {line: n, text: line.text, markerText: marker && marker.text, markerClass: marker && marker.style};
1133
+ }
1134
+
1135
+ function stringWidth(str) {
1136
+ measure.innerHTML = "<pre><span>x</span></pre>";
1137
+ measure.firstChild.firstChild.firstChild.nodeValue = str;
1138
+ return measure.firstChild.firstChild.offsetWidth || 10;
1139
+ }
1140
+ // These are used to go from pixel positions to character
1141
+ // positions, taking varying character widths into account.
1142
+ function charX(line, pos) {
1143
+ if (pos == 0) return 0;
1144
+ measure.innerHTML = "<pre><span>" + lines[line].getHTML(null, null, false, pos) + "</span></pre>";
1145
+ return measure.firstChild.firstChild.offsetWidth;
1146
+ }
1147
+ function charFromX(line, x) {
1148
+ if (x <= 0) return 0;
1149
+ var lineObj = lines[line], text = lineObj.text;
1150
+ function getX(len) {
1151
+ measure.innerHTML = "<pre><span>" + lineObj.getHTML(null, null, false, len) + "</span></pre>";
1152
+ return measure.firstChild.firstChild.offsetWidth;
1153
+ }
1154
+ var from = 0, fromX = 0, to = text.length, toX;
1155
+ // Guess a suitable upper bound for our search.
1156
+ var estimated = Math.min(to, Math.ceil(x / stringWidth("x")));
1157
+ for (;;) {
1158
+ var estX = getX(estimated);
1159
+ if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1160
+ else {toX = estX; to = estimated; break;}
1161
+ }
1162
+ if (x > toX) return to;
1163
+ // Try to guess a suitable lower bound as well.
1164
+ estimated = Math.floor(to * 0.8); estX = getX(estimated);
1165
+ if (estX < x) {from = estimated; fromX = estX;}
1166
+ // Do a binary search between these bounds.
1167
+ for (;;) {
1168
+ if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
1169
+ var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1170
+ if (middleX > x) {to = middle; toX = middleX;}
1171
+ else {from = middle; fromX = middleX;}
1172
+ }
1173
+ }
1174
+
1175
+ function localCoords(pos, inLineWrap) {
1176
+ var lh = lineHeight(), line = pos.line - (inLineWrap ? showingFrom : 0);
1177
+ return {x: charX(pos.line, pos.ch), y: line * lh, yBot: (line + 1) * lh};
1178
+ }
1179
+ function pageCoords(pos) {
1180
+ var local = localCoords(pos, true), off = eltOffset(lineSpace);
1181
+ return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
1182
+ }
1183
+
1184
+ function lineHeight() {
1185
+ var nlines = lineDiv.childNodes.length;
1186
+ if (nlines) return (lineDiv.offsetHeight / nlines) || 1;
1187
+ measure.innerHTML = "<pre>x</pre>";
1188
+ return measure.firstChild.offsetHeight || 1;
1189
+ }
1190
+ function paddingTop() {return lineSpace.offsetTop;}
1191
+ function paddingLeft() {return lineSpace.offsetLeft;}
1192
+
1193
+ function posFromMouse(e, liberal) {
1194
+ var offW = eltOffset(scroller, true), x, y;
1195
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1196
+ try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1197
+ // This is a mess of a heuristic to try and determine whether a
1198
+ // scroll-bar was clicked or not, and to return null if one was
1199
+ // (and !liberal).
1200
+ if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
1201
+ return null;
1202
+ var offL = eltOffset(lineSpace, true);
1203
+ var line = showingFrom + Math.floor((y - offL.top) / lineHeight());
1204
+ return clipPos({line: line, ch: charFromX(clipLine(line), x - offL.left)});
1205
+ }
1206
+ function onContextMenu(e) {
1207
+ var pos = posFromMouse(e);
1208
+ if (!pos || window.opera) return; // Opera is difficult.
1209
+ if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
1210
+ operation(setCursor)(pos.line, pos.ch);
1211
+
1212
+ var oldCSS = input.style.cssText;
1213
+ inputDiv.style.position = "absolute";
1214
+ input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1215
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " +
1216
+ "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1217
+ leaveInputAlone = true;
1218
+ var val = input.value = getSelection();
1219
+ focusInput();
1220
+ setSelRange(input, 0, input.value.length);
1221
+ function rehide() {
1222
+ var newVal = splitLines(input.value).join("\n");
1223
+ if (newVal != val) operation(replaceSelection)(newVal, "end");
1224
+ inputDiv.style.position = "relative";
1225
+ input.style.cssText = oldCSS;
1226
+ leaveInputAlone = false;
1227
+ prepareInput();
1228
+ slowPoll();
1229
+ }
1230
+
1231
+ if (gecko) {
1232
+ e_stop(e);
1233
+ var mouseup = connect(window, "mouseup", function() {
1234
+ mouseup();
1235
+ setTimeout(rehide, 20);
1236
+ }, true);
1237
+ }
1238
+ else {
1239
+ setTimeout(rehide, 50);
1240
+ }
1241
+ }
1242
+
1243
+ // Cursor-blinking
1244
+ function restartBlink() {
1245
+ clearInterval(blinker);
1246
+ var on = true;
1247
+ cursor.style.visibility = "";
1248
+ blinker = setInterval(function() {
1249
+ cursor.style.visibility = (on = !on) ? "" : "hidden";
1250
+ }, 650);
1251
+ }
1252
+
1253
+ var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
1254
+ function matchBrackets(autoclear) {
1255
+ var head = sel.inverted ? sel.from : sel.to, line = lines[head.line], pos = head.ch - 1;
1256
+ var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
1257
+ if (!match) return;
1258
+ var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
1259
+ for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
1260
+ if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
1261
+
1262
+ var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
1263
+ function scan(line, from, to) {
1264
+ if (!line.text) return;
1265
+ var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
1266
+ for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
1267
+ var text = st[i];
1268
+ if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;}
1269
+ for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
1270
+ if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
1271
+ var match = matching[cur];
1272
+ if (match.charAt(1) == ">" == forward) stack.push(cur);
1273
+ else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
1274
+ else if (!stack.length) return {pos: pos, match: true};
1275
+ }
1276
+ }
1277
+ }
1278
+ }
1279
+ for (var i = head.line, e = forward ? Math.min(i + 100, lines.length) : Math.max(-1, i - 100); i != e; i+=d) {
1280
+ var line = lines[i], first = i == head.line;
1281
+ var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
1282
+ if (found) break;
1283
+ }
1284
+ if (!found) found = {pos: null, match: false};
1285
+ var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
1286
+ var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
1287
+ two = found.pos != null
1288
+ ? markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style)
1289
+ : function() {};
1290
+ var clear = operation(function(){one(); two();});
1291
+ if (autoclear) setTimeout(clear, 800);
1292
+ else bracketHighlighted = clear;
1293
+ }
1294
+
1295
+ // Finds the line to start with when starting a parse. Tries to
1296
+ // find a line with a stateAfter, so that it can start with a
1297
+ // valid state. If that fails, it returns the line with the
1298
+ // smallest indentation, which tends to need the least context to
1299
+ // parse correctly.
1300
+ function findStartLine(n) {
1301
+ var minindent, minline;
1302
+ for (var search = n, lim = n - 40; search > lim; --search) {
1303
+ if (search == 0) return 0;
1304
+ var line = lines[search-1];
1305
+ if (line.stateAfter) return search;
1306
+ var indented = line.indentation();
1307
+ if (minline == null || minindent > indented) {
1308
+ minline = search - 1;
1309
+ minindent = indented;
1310
+ }
1311
+ }
1312
+ return minline;
1313
+ }
1314
+ function getStateBefore(n) {
1315
+ var start = findStartLine(n), state = start && lines[start-1].stateAfter;
1316
+ if (!state) state = startState(mode);
1317
+ else state = copyState(mode, state);
1318
+ for (var i = start; i < n; ++i) {
1319
+ var line = lines[i];
1320
+ line.highlight(mode, state);
1321
+ line.stateAfter = copyState(mode, state);
1322
+ }
1323
+ if (n < lines.length && !lines[n].stateAfter) work.push(n);
1324
+ return state;
1325
+ }
1326
+ function highlightLines(start, end) {
1327
+ var state = getStateBefore(start);
1328
+ for (var i = start; i < end; ++i) {
1329
+ var line = lines[i];
1330
+ line.highlight(mode, state);
1331
+ line.stateAfter = copyState(mode, state);
1332
+ }
1333
+ }
1334
+ function highlightWorker() {
1335
+ var end = +new Date + options.workTime;
1336
+ var foundWork = work.length;
1337
+ while (work.length) {
1338
+ if (!lines[showingFrom].stateAfter) var task = showingFrom;
1339
+ else var task = work.pop();
1340
+ if (task >= lines.length) continue;
1341
+ var start = findStartLine(task), state = start && lines[start-1].stateAfter;
1342
+ if (state) state = copyState(mode, state);
1343
+ else state = startState(mode);
1344
+
1345
+ var unchanged = 0, compare = mode.compareStates, realChange = false;
1346
+ for (var i = start, l = lines.length; i < l; ++i) {
1347
+ var line = lines[i], hadState = line.stateAfter;
1348
+ if (+new Date > end) {
1349
+ work.push(i);
1350
+ startWorker(options.workDelay);
1351
+ if (realChange) changes.push({from: task, to: i + 1});
1352
+ return;
1353
+ }
1354
+ var changed = line.highlight(mode, state);
1355
+ if (changed) realChange = true;
1356
+ line.stateAfter = copyState(mode, state);
1357
+ if (compare) {
1358
+ if (hadState && compare(hadState, state)) break;
1359
+ } else {
1360
+ if (changed !== false || !hadState) unchanged = 0;
1361
+ else if (++unchanged > 3) break;
1362
+ }
1363
+ }
1364
+ if (realChange) changes.push({from: task, to: i + 1});
1365
+ }
1366
+ if (foundWork && options.onHighlightComplete)
1367
+ options.onHighlightComplete(instance);
1368
+ }
1369
+ function startWorker(time) {
1370
+ if (!work.length) return;
1371
+ highlight.set(time, operation(highlightWorker));
1372
+ }
1373
+
1374
+ // Operations are used to wrap changes in such a way that each
1375
+ // change won't have to update the cursor and display (which would
1376
+ // be awkward, slow, and error-prone), but instead updates are
1377
+ // batched and then all combined and executed at once.
1378
+ function startOperation() {
1379
+ updateInput = null; changes = []; textChanged = selectionChanged = false;
1380
+ }
1381
+ function endOperation() {
1382
+ var reScroll = false;
1383
+ if (selectionChanged) reScroll = !scrollCursorIntoView();
1384
+ if (changes.length) updateDisplay(changes);
1385
+ else if (selectionChanged) updateCursor();
1386
+ if (reScroll) scrollCursorIntoView();
1387
+ if (selectionChanged) {scrollEditorIntoView(); restartBlink();}
1388
+
1389
+ // updateInput can be set to a boolean value to force/prevent an
1390
+ // update.
1391
+ if (focused && !leaveInputAlone &&
1392
+ (updateInput === true || (updateInput !== false && selectionChanged)))
1393
+ prepareInput();
1394
+
1395
+ if (selectionChanged && options.matchBrackets)
1396
+ setTimeout(operation(function() {
1397
+ if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
1398
+ matchBrackets(false);
1399
+ }), 20);
1400
+ var tc = textChanged; // textChanged can be reset by cursoractivity callback
1401
+ if (selectionChanged && options.onCursorActivity)
1402
+ options.onCursorActivity(instance);
1403
+ if (tc && options.onChange && instance)
1404
+ options.onChange(instance, tc);
1405
+ }
1406
+ var nestedOperation = 0;
1407
+ function operation(f) {
1408
+ return function() {
1409
+ if (!nestedOperation++) startOperation();
1410
+ try {var result = f.apply(this, arguments);}
1411
+ finally {if (!--nestedOperation) endOperation();}
1412
+ return result;
1413
+ };
1414
+ }
1415
+
1416
+ function SearchCursor(query, pos, caseFold) {
1417
+ this.atOccurrence = false;
1418
+ if (caseFold == null) caseFold = typeof query == "string" && query == query.toLowerCase();
1419
+
1420
+ if (pos && typeof pos == "object") pos = clipPos(pos);
1421
+ else pos = {line: 0, ch: 0};
1422
+ this.pos = {from: pos, to: pos};
1423
+
1424
+ // The matches method is filled in based on the type of query.
1425
+ // It takes a position and a direction, and returns an object
1426
+ // describing the next occurrence of the query, or null if no
1427
+ // more matches were found.
1428
+ if (typeof query != "string") // Regexp match
1429
+ this.matches = function(reverse, pos) {
1430
+ if (reverse) {
1431
+ var line = lines[pos.line].text.slice(0, pos.ch), match = line.match(query), start = 0;
1432
+ while (match) {
1433
+ var ind = line.indexOf(match[0]);
1434
+ start += ind;
1435
+ line = line.slice(ind + 1);
1436
+ var newmatch = line.match(query);
1437
+ if (newmatch) match = newmatch;
1438
+ else break;
1439
+ start++;
1440
+ }
1441
+ }
1442
+ else {
1443
+ var line = lines[pos.line].text.slice(pos.ch), match = line.match(query),
1444
+ start = match && pos.ch + line.indexOf(match[0]);
1445
+ }
1446
+ if (match)
1447
+ return {from: {line: pos.line, ch: start},
1448
+ to: {line: pos.line, ch: start + match[0].length},
1449
+ match: match};
1450
+ };
1451
+ else { // String query
1452
+ if (caseFold) query = query.toLowerCase();
1453
+ var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
1454
+ var target = query.split("\n");
1455
+ // Different methods for single-line and multi-line queries
1456
+ if (target.length == 1)
1457
+ this.matches = function(reverse, pos) {
1458
+ var line = fold(lines[pos.line].text), len = query.length, match;
1459
+ if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
1460
+ : (match = line.indexOf(query, pos.ch)) != -1)
1461
+ return {from: {line: pos.line, ch: match},
1462
+ to: {line: pos.line, ch: match + len}};
1463
+ };
1464
+ else
1465
+ this.matches = function(reverse, pos) {
1466
+ var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(lines[ln].text);
1467
+ var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
1468
+ if (reverse ? offsetA >= pos.ch || offsetA != match.length
1469
+ : offsetA <= pos.ch || offsetA != line.length - match.length)
1470
+ return;
1471
+ for (;;) {
1472
+ if (reverse ? !ln : ln == lines.length - 1) return;
1473
+ line = fold(lines[ln += reverse ? -1 : 1].text);
1474
+ match = target[reverse ? --idx : ++idx];
1475
+ if (idx > 0 && idx < target.length - 1) {
1476
+ if (line != match) return;
1477
+ else continue;
1478
+ }
1479
+ var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
1480
+ if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
1481
+ return;
1482
+ var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB};
1483
+ return {from: reverse ? end : start, to: reverse ? start : end};
1484
+ }
1485
+ };
1486
+ }
1487
+ }
1488
+
1489
+ SearchCursor.prototype = {
1490
+ findNext: function() {return this.find(false);},
1491
+ findPrevious: function() {return this.find(true);},
1492
+
1493
+ find: function(reverse) {
1494
+ var self = this, pos = clipPos(reverse ? this.pos.from : this.pos.to);
1495
+ function savePosAndFail(line) {
1496
+ var pos = {line: line, ch: 0};
1497
+ self.pos = {from: pos, to: pos};
1498
+ self.atOccurrence = false;
1499
+ return false;
1500
+ }
1501
+
1502
+ for (;;) {
1503
+ if (this.pos = this.matches(reverse, pos)) {
1504
+ this.atOccurrence = true;
1505
+ return this.pos.match || true;
1506
+ }
1507
+ if (reverse) {
1508
+ if (!pos.line) return savePosAndFail(0);
1509
+ pos = {line: pos.line-1, ch: lines[pos.line-1].text.length};
1510
+ }
1511
+ else {
1512
+ if (pos.line == lines.length - 1) return savePosAndFail(lines.length);
1513
+ pos = {line: pos.line+1, ch: 0};
1514
+ }
1515
+ }
1516
+ },
1517
+
1518
+ from: function() {if (this.atOccurrence) return copyPos(this.pos.from);},
1519
+ to: function() {if (this.atOccurrence) return copyPos(this.pos.to);},
1520
+
1521
+ replace: function(newText) {
1522
+ var self = this;
1523
+ if (this.atOccurrence)
1524
+ operation(function() {
1525
+ self.pos.to = replaceRange(newText, self.pos.from, self.pos.to);
1526
+ })();
1527
+ }
1528
+ };
1529
+
1530
+ for (var ext in extensions)
1531
+ if (extensions.propertyIsEnumerable(ext) &&
1532
+ !instance.propertyIsEnumerable(ext))
1533
+ instance[ext] = extensions[ext];
1534
+ return instance;
1535
+ } // (end of function CodeMirror)
1536
+
1537
+ // The default configuration options.
1538
+ CodeMirror.defaults = {
1539
+ value: "",
1540
+ mode: null,
1541
+ theme: "default",
1542
+ indentUnit: 2,
1543
+ indentWithTabs: false,
1544
+ tabMode: "classic",
1545
+ enterMode: "indent",
1546
+ electricChars: true,
1547
+ onKeyEvent: null,
1548
+ lineNumbers: false,
1549
+ gutter: false,
1550
+ firstLineNumber: 1,
1551
+ readOnly: false,
1552
+ smartHome: true,
1553
+ onChange: null,
1554
+ onCursorActivity: null,
1555
+ onGutterClick: null,
1556
+ onHighlightComplete: null,
1557
+ onFocus: null, onBlur: null, onScroll: null,
1558
+ matchBrackets: false,
1559
+ workTime: 100,
1560
+ workDelay: 200,
1561
+ undoDepth: 40,
1562
+ tabindex: null,
1563
+ document: window.document
1564
+ };
1565
+
1566
+ // Known modes, by name and by MIME
1567
+ var modes = {}, mimeModes = {};
1568
+ CodeMirror.defineMode = function(name, mode) {
1569
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
1570
+ modes[name] = mode;
1571
+ };
1572
+ CodeMirror.defineMIME = function(mime, spec) {
1573
+ mimeModes[mime] = spec;
1574
+ };
1575
+ CodeMirror.getMode = function(options, spec) {
1576
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
1577
+ spec = mimeModes[spec];
1578
+ if (typeof spec == "string")
1579
+ var mname = spec, config = {};
1580
+ else if (spec != null)
1581
+ var mname = spec.name, config = spec;
1582
+ var mfactory = modes[mname];
1583
+ if (!mfactory) {
1584
+ if (window.console) console.warn("No mode " + mname + " found, falling back to plain text.");
1585
+ return CodeMirror.getMode(options, "text/plain");
1586
+ }
1587
+ return mfactory(options, config || {});
1588
+ };
1589
+ CodeMirror.listModes = function() {
1590
+ var list = [];
1591
+ for (var m in modes)
1592
+ if (modes.propertyIsEnumerable(m)) list.push(m);
1593
+ return list;
1594
+ };
1595
+ CodeMirror.listMIMEs = function() {
1596
+ var list = [];
1597
+ for (var m in mimeModes)
1598
+ if (mimeModes.propertyIsEnumerable(m)) list.push(m);
1599
+ return list;
1600
+ };
1601
+
1602
+ var extensions = {};
1603
+ CodeMirror.defineExtension = function(name, func) {
1604
+ extensions[name] = func;
1605
+ };
1606
+
1607
+ CodeMirror.fromTextArea = function(textarea, options) {
1608
+ if (!options) options = {};
1609
+ options.value = textarea.value;
1610
+ if (!options.tabindex && textarea.tabindex)
1611
+ options.tabindex = textarea.tabindex;
1612
+
1613
+ function save() {textarea.value = instance.getValue();}
1614
+ if (textarea.form) {
1615
+ // Deplorable hack to make the submit method do the right thing.
1616
+ var rmSubmit = connect(textarea.form, "submit", save, true);
1617
+ if (typeof textarea.form.submit == "function") {
1618
+ var realSubmit = textarea.form.submit;
1619
+ function wrappedSubmit() {
1620
+ save();
1621
+ textarea.form.submit = realSubmit;
1622
+ textarea.form.submit();
1623
+ textarea.form.submit = wrappedSubmit;
1624
+ }
1625
+ textarea.form.submit = wrappedSubmit;
1626
+ }
1627
+ }
1628
+
1629
+ textarea.style.display = "none";
1630
+ var instance = CodeMirror(function(node) {
1631
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
1632
+ }, options);
1633
+ instance.save = save;
1634
+ instance.toTextArea = function() {
1635
+ save();
1636
+ textarea.parentNode.removeChild(instance.getWrapperElement());
1637
+ textarea.style.display = "";
1638
+ if (textarea.form) {
1639
+ rmSubmit();
1640
+ if (typeof textarea.form.submit == "function")
1641
+ textarea.form.submit = realSubmit;
1642
+ }
1643
+ };
1644
+ return instance;
1645
+ };
1646
+
1647
+ // Utility functions for working with state. Exported because modes
1648
+ // sometimes need to do this.
1649
+ function copyState(mode, state) {
1650
+ if (state === true) return state;
1651
+ if (mode.copyState) return mode.copyState(state);
1652
+ var nstate = {};
1653
+ for (var n in state) {
1654
+ var val = state[n];
1655
+ if (val instanceof Array) val = val.concat([]);
1656
+ nstate[n] = val;
1657
+ }
1658
+ return nstate;
1659
+ }
1660
+ CodeMirror.startState = startState;
1661
+ function startState(mode, a1, a2) {
1662
+ return mode.startState ? mode.startState(a1, a2) : true;
1663
+ }
1664
+ CodeMirror.copyState = copyState;
1665
+
1666
+ // The character stream used by a mode's parser.
1667
+ function StringStream(string) {
1668
+ this.pos = this.start = 0;
1669
+ this.string = string;
1670
+ }
1671
+ StringStream.prototype = {
1672
+ eol: function() {return this.pos >= this.string.length;},
1673
+ sol: function() {return this.pos == 0;},
1674
+ peek: function() {return this.string.charAt(this.pos);},
1675
+ next: function() {
1676
+ if (this.pos < this.string.length)
1677
+ return this.string.charAt(this.pos++);
1678
+ },
1679
+ eat: function(match) {
1680
+ var ch = this.string.charAt(this.pos);
1681
+ if (typeof match == "string") var ok = ch == match;
1682
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
1683
+ if (ok) {++this.pos; return ch;}
1684
+ },
1685
+ eatWhile: function(match) {
1686
+ var start = this.pos;
1687
+ while (this.eat(match)){}
1688
+ return this.pos > start;
1689
+ },
1690
+ eatSpace: function() {
1691
+ var start = this.pos;
1692
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
1693
+ return this.pos > start;
1694
+ },
1695
+ skipToEnd: function() {this.pos = this.string.length;},
1696
+ skipTo: function(ch) {
1697
+ var found = this.string.indexOf(ch, this.pos);
1698
+ if (found > -1) {this.pos = found; return true;}
1699
+ },
1700
+ backUp: function(n) {this.pos -= n;},
1701
+ column: function() {return countColumn(this.string, this.start);},
1702
+ indentation: function() {return countColumn(this.string);},
1703
+ match: function(pattern, consume, caseInsensitive) {
1704
+ if (typeof pattern == "string") {
1705
+ function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
1706
+ if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
1707
+ if (consume !== false) this.pos += pattern.length;
1708
+ return true;
1709
+ }
1710
+ }
1711
+ else {
1712
+ var match = this.string.slice(this.pos).match(pattern);
1713
+ if (match && consume !== false) this.pos += match[0].length;
1714
+ return match;
1715
+ }
1716
+ },
1717
+ current: function(){return this.string.slice(this.start, this.pos);}
1718
+ };
1719
+ CodeMirror.StringStream = StringStream;
1720
+
1721
+ // Line objects. These hold state related to a line, including
1722
+ // highlighting info (the styles array).
1723
+ function Line(text, styles) {
1724
+ this.styles = styles || [text, null];
1725
+ this.stateAfter = null;
1726
+ this.text = text;
1727
+ this.marked = this.gutterMarker = this.className = null;
1728
+ }
1729
+ Line.prototype = {
1730
+ // Replace a piece of a line, keeping the styles around it intact.
1731
+ replace: function(from, to, text) {
1732
+ var st = [], mk = this.marked;
1733
+ copyStyles(0, from, this.styles, st);
1734
+ if (text) st.push(text, null);
1735
+ copyStyles(to, this.text.length, this.styles, st);
1736
+ this.styles = st;
1737
+ this.text = this.text.slice(0, from) + text + this.text.slice(to);
1738
+ this.stateAfter = null;
1739
+ if (mk) {
1740
+ var diff = text.length - (to - from), end = this.text.length;
1741
+ function fix(n) {return n <= Math.min(to, to + diff) ? n : n + diff;}
1742
+ for (var i = 0; i < mk.length; ++i) {
1743
+ var mark = mk[i], del = false;
1744
+ if (mark.from >= end) del = true;
1745
+ else {mark.from = fix(mark.from); if (mark.to != null) mark.to = fix(mark.to);}
1746
+ if (del || mark.from >= mark.to) {mk.splice(i, 1); i--;}
1747
+ }
1748
+ }
1749
+ },
1750
+ // Split a line in two, again keeping styles intact.
1751
+ split: function(pos, textBefore) {
1752
+ var st = [textBefore, null];
1753
+ copyStyles(pos, this.text.length, this.styles, st);
1754
+ return new Line(textBefore + this.text.slice(pos), st);
1755
+ },
1756
+ addMark: function(from, to, style) {
1757
+ var mk = this.marked, mark = {from: from, to: to, style: style};
1758
+ if (this.marked == null) this.marked = [];
1759
+ this.marked.push(mark);
1760
+ this.marked.sort(function(a, b){return a.from - b.from;});
1761
+ return mark;
1762
+ },
1763
+ removeMark: function(mark) {
1764
+ var mk = this.marked;
1765
+ if (!mk) return;
1766
+ for (var i = 0; i < mk.length; ++i)
1767
+ if (mk[i] == mark) {mk.splice(i, 1); break;}
1768
+ },
1769
+ // Run the given mode's parser over a line, update the styles
1770
+ // array, which contains alternating fragments of text and CSS
1771
+ // classes.
1772
+ highlight: function(mode, state) {
1773
+ var stream = new StringStream(this.text), st = this.styles, pos = 0;
1774
+ var changed = false, curWord = st[0], prevWord;
1775
+ if (this.text == "" && mode.blankLine) mode.blankLine(state);
1776
+ while (!stream.eol()) {
1777
+ var style = mode.token(stream, state);
1778
+ var substr = this.text.slice(stream.start, stream.pos);
1779
+ stream.start = stream.pos;
1780
+ if (pos && st[pos-1] == style)
1781
+ st[pos-2] += substr;
1782
+ else if (substr) {
1783
+ if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
1784
+ st[pos++] = substr; st[pos++] = style;
1785
+ prevWord = curWord; curWord = st[pos];
1786
+ }
1787
+ // Give up when line is ridiculously long
1788
+ if (stream.pos > 5000) {
1789
+ st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
1790
+ break;
1791
+ }
1792
+ }
1793
+ if (st.length != pos) {st.length = pos; changed = true;}
1794
+ if (pos && st[pos-2] != prevWord) changed = true;
1795
+ // Short lines with simple highlights return null, and are
1796
+ // counted as changed by the driver because they are likely to
1797
+ // highlight the same way in various contexts.
1798
+ return changed || (st.length < 5 && this.text.length < 10 ? null : false);
1799
+ },
1800
+ // Fetch the parser token for a given character. Useful for hacks
1801
+ // that want to inspect the mode state (say, for completion).
1802
+ getTokenAt: function(mode, state, ch) {
1803
+ var txt = this.text, stream = new StringStream(txt);
1804
+ while (stream.pos < ch && !stream.eol()) {
1805
+ stream.start = stream.pos;
1806
+ var style = mode.token(stream, state);
1807
+ }
1808
+ return {start: stream.start,
1809
+ end: stream.pos,
1810
+ string: stream.current(),
1811
+ className: style || null,
1812
+ state: state};
1813
+ },
1814
+ indentation: function() {return countColumn(this.text);},
1815
+ // Produces an HTML fragment for the line, taking selection,
1816
+ // marking, and highlighting into account.
1817
+ getHTML: function(sfrom, sto, includePre, endAt) {
1818
+ var html = [];
1819
+ if (includePre)
1820
+ html.push(this.className ? '<pre class="' + this.className + '">': "<pre>");
1821
+ function span(text, style) {
1822
+ if (!text) return;
1823
+ if (style) html.push('<span class="', style, '">', htmlEscape(text), "</span>");
1824
+ else html.push(htmlEscape(text));
1825
+ }
1826
+ var st = this.styles, allText = this.text, marked = this.marked;
1827
+ if (sfrom == sto) sfrom = null;
1828
+ var len = allText.length;
1829
+ if (endAt != null) len = Math.min(endAt, len);
1830
+
1831
+ if (!allText && endAt == null)
1832
+ span(" ", sfrom != null && sto == null ? "CodeMirror-selected" : null);
1833
+ else if (!marked && sfrom == null)
1834
+ for (var i = 0, ch = 0; ch < len; i+=2) {
1835
+ var str = st[i], l = str.length;
1836
+ if (ch + l > len) str = str.slice(0, len - ch);
1837
+ ch += l;
1838
+ span(str, "cm-" + st[i+1]);
1839
+ }
1840
+ else {
1841
+ var pos = 0, i = 0, text = "", style, sg = 0;
1842
+ var markpos = -1, mark = null;
1843
+ function nextMark() {
1844
+ if (marked) {
1845
+ markpos += 1;
1846
+ mark = (markpos < marked.length) ? marked[markpos] : null;
1847
+ }
1848
+ }
1849
+ nextMark();
1850
+ while (pos < len) {
1851
+ var upto = len;
1852
+ var extraStyle = "";
1853
+ if (sfrom != null) {
1854
+ if (sfrom > pos) upto = sfrom;
1855
+ else if (sto == null || sto > pos) {
1856
+ extraStyle = " CodeMirror-selected";
1857
+ if (sto != null) upto = Math.min(upto, sto);
1858
+ }
1859
+ }
1860
+ while (mark && mark.to != null && mark.to <= pos) nextMark();
1861
+ if (mark) {
1862
+ if (mark.from > pos) upto = Math.min(upto, mark.from);
1863
+ else {
1864
+ extraStyle += " " + mark.style;
1865
+ if (mark.to != null) upto = Math.min(upto, mark.to);
1866
+ }
1867
+ }
1868
+ for (;;) {
1869
+ var end = pos + text.length;
1870
+ var appliedStyle = style;
1871
+ if (extraStyle) appliedStyle = style ? style + extraStyle : extraStyle;
1872
+ span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
1873
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
1874
+ pos = end;
1875
+ text = st[i++]; style = "cm-" + st[i++];
1876
+ }
1877
+ }
1878
+ if (sfrom != null && sto == null) span(" ", "CodeMirror-selected");
1879
+ }
1880
+ if (includePre) html.push("</pre>");
1881
+ return html.join("");
1882
+ }
1883
+ };
1884
+ // Utility used by replace and split above
1885
+ function copyStyles(from, to, source, dest) {
1886
+ for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
1887
+ var part = source[i], end = pos + part.length;
1888
+ if (state == 0) {
1889
+ if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
1890
+ if (end >= from) state = 1;
1891
+ }
1892
+ else if (state == 1) {
1893
+ if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
1894
+ else dest.push(part, source[i+1]);
1895
+ }
1896
+ pos = end;
1897
+ }
1898
+ }
1899
+
1900
+ // The history object 'chunks' changes that are made close together
1901
+ // and at almost the same time into bigger undoable units.
1902
+ function History() {
1903
+ this.time = 0;
1904
+ this.done = []; this.undone = [];
1905
+ }
1906
+ History.prototype = {
1907
+ addChange: function(start, added, old) {
1908
+ this.undone.length = 0;
1909
+ var time = +new Date, last = this.done[this.done.length - 1];
1910
+ if (time - this.time > 400 || !last ||
1911
+ last.start > start + added || last.start + last.added < start - last.added + last.old.length)
1912
+ this.done.push({start: start, added: added, old: old});
1913
+ else {
1914
+ var oldoff = 0;
1915
+ if (start < last.start) {
1916
+ for (var i = last.start - start - 1; i >= 0; --i)
1917
+ last.old.unshift(old[i]);
1918
+ last.added += last.start - start;
1919
+ last.start = start;
1920
+ }
1921
+ else if (last.start < start) {
1922
+ oldoff = start - last.start;
1923
+ added += oldoff;
1924
+ }
1925
+ for (var i = last.added - oldoff, e = old.length; i < e; ++i)
1926
+ last.old.push(old[i]);
1927
+ if (last.added < added) last.added = added;
1928
+ }
1929
+ this.time = time;
1930
+ }
1931
+ };
1932
+
1933
+ function stopMethod() {e_stop(this);}
1934
+ // Ensure an event has a stop method.
1935
+ function addStop(event) {
1936
+ if (!event.stop) event.stop = stopMethod;
1937
+ return event;
1938
+ }
1939
+
1940
+ function e_preventDefault(e) {
1941
+ if (e.preventDefault) e.preventDefault();
1942
+ else e.returnValue = false;
1943
+ }
1944
+ function e_stopPropagation(e) {
1945
+ if (e.stopPropagation) e.stopPropagation();
1946
+ else e.cancelBubble = true;
1947
+ }
1948
+ function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
1949
+ function e_target(e) {return e.target || e.srcElement;}
1950
+ function e_button(e) {
1951
+ if (e.which) return e.which;
1952
+ else if (e.button & 1) return 1;
1953
+ else if (e.button & 2) return 3;
1954
+ else if (e.button & 4) return 2;
1955
+ }
1956
+
1957
+ // Event handler registration. If disconnect is true, it'll return a
1958
+ // function that unregisters the handler.
1959
+ function connect(node, type, handler, disconnect) {
1960
+ function wrapHandler(event) {handler(event || window.event);}
1961
+ if (typeof node.addEventListener == "function") {
1962
+ node.addEventListener(type, wrapHandler, false);
1963
+ if (disconnect) return function() {node.removeEventListener(type, wrapHandler, false);};
1964
+ }
1965
+ else {
1966
+ node.attachEvent("on" + type, wrapHandler);
1967
+ if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
1968
+ }
1969
+ }
1970
+
1971
+ function Delayed() {this.id = null;}
1972
+ Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
1973
+
1974
+ // Some IE versions don't preserve whitespace when setting the
1975
+ // innerHTML of a PRE tag.
1976
+ var badInnerHTML = (function() {
1977
+ var pre = document.createElement("pre");
1978
+ pre.innerHTML = " "; return !pre.innerHTML;
1979
+ })();
1980
+
1981
+ var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
1982
+ var ie = /MSIE \d/.test(navigator.userAgent);
1983
+ var safari = /Apple Computer/.test(navigator.vendor);
1984
+
1985
+ var lineSep = "\n";
1986
+ // Feature-detect whether newlines in textareas are converted to \r\n
1987
+ (function () {
1988
+ var te = document.createElement("textarea");
1989
+ te.value = "foo\nbar";
1990
+ if (te.value.indexOf("\r") > -1) lineSep = "\r\n";
1991
+ }());
1992
+
1993
+ var tabSize = 8;
1994
+ var mac = /Mac/.test(navigator.platform);
1995
+ var movementKeys = {};
1996
+ for (var i = 35; i <= 40; ++i)
1997
+ movementKeys[i] = movementKeys["c" + i] = true;
1998
+
1999
+ // Counts the column offset in a string, taking tabs into account.
2000
+ // Used mostly to find indentation.
2001
+ function countColumn(string, end) {
2002
+ if (end == null) {
2003
+ end = string.search(/[^\s\u00a0]/);
2004
+ if (end == -1) end = string.length;
2005
+ }
2006
+ for (var i = 0, n = 0; i < end; ++i) {
2007
+ if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
2008
+ else ++n;
2009
+ }
2010
+ return n;
2011
+ }
2012
+
2013
+ function computedStyle(elt) {
2014
+ if (elt.currentStyle) return elt.currentStyle;
2015
+ return window.getComputedStyle(elt, null);
2016
+ }
2017
+ // Find the position of an element by following the offsetParent chain.
2018
+ // If screen==true, it returns screen (rather than page) coordinates.
2019
+ function eltOffset(node, screen) {
2020
+ var doc = node.ownerDocument.body;
2021
+ var x = 0, y = 0, skipDoc = false;
2022
+ for (var n = node; n; n = n.offsetParent) {
2023
+ x += n.offsetLeft; y += n.offsetTop;
2024
+ if (screen && computedStyle(n).position == "fixed")
2025
+ skipDoc = true;
2026
+ }
2027
+ var e = screen && !skipDoc ? null : doc;
2028
+ for (var n = node.parentNode; n != e; n = n.parentNode)
2029
+ if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;}
2030
+ return {left: x, top: y};
2031
+ }
2032
+ // Get a node's text content.
2033
+ function eltText(node) {
2034
+ return node.textContent || node.innerText || node.nodeValue || "";
2035
+ }
2036
+
2037
+ // Operations on {line, ch} objects.
2038
+ function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
2039
+ function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
2040
+ function copyPos(x) {return {line: x.line, ch: x.ch};}
2041
+
2042
+ var escapeElement = document.createElement("div");
2043
+ function htmlEscape(str) {
2044
+ escapeElement.innerText = escapeElement.textContent = str;
2045
+ return escapeElement.innerHTML;
2046
+ }
2047
+ CodeMirror.htmlEscape = htmlEscape;
2048
+
2049
+ // Used to position the cursor after an undo/redo by finding the
2050
+ // last edited character.
2051
+ function editEnd(from, to) {
2052
+ if (!to) return from ? from.length : 0;
2053
+ if (!from) return to.length;
2054
+ for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
2055
+ if (from.charAt(i) != to.charAt(j)) break;
2056
+ return j + 1;
2057
+ }
2058
+
2059
+ function indexOf(collection, elt) {
2060
+ if (collection.indexOf) return collection.indexOf(elt);
2061
+ for (var i = 0, e = collection.length; i < e; ++i)
2062
+ if (collection[i] == elt) return i;
2063
+ return -1;
2064
+ }
2065
+
2066
+ // See if "".split is the broken IE version, if so, provide an
2067
+ // alternative way to split lines.
2068
+ var splitLines, selRange, setSelRange;
2069
+ if ("\n\nb".split(/\n/).length != 3)
2070
+ splitLines = function(string) {
2071
+ var pos = 0, nl, result = [];
2072
+ while ((nl = string.indexOf("\n", pos)) > -1) {
2073
+ result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl));
2074
+ pos = nl + 1;
2075
+ }
2076
+ result.push(string.slice(pos));
2077
+ return result;
2078
+ };
2079
+ else
2080
+ splitLines = function(string){return string.split(/\r?\n/);};
2081
+ CodeMirror.splitLines = splitLines;
2082
+
2083
+ // Sane model of finding and setting the selection in a textarea
2084
+ if (window.getSelection) {
2085
+ selRange = function(te) {
2086
+ try {return {start: te.selectionStart, end: te.selectionEnd};}
2087
+ catch(e) {return null;}
2088
+ };
2089
+ if (safari)
2090
+ // On Safari, selection set with setSelectionRange are in a sort
2091
+ // of limbo wrt their anchor. If you press shift-left in them,
2092
+ // the anchor is put at the end, and the selection expanded to
2093
+ // the left. If you press shift-right, the anchor ends up at the
2094
+ // front. This is not what CodeMirror wants, so it does a
2095
+ // spurious modify() call to get out of limbo.
2096
+ setSelRange = function(te, start, end) {
2097
+ if (start == end)
2098
+ te.setSelectionRange(start, end);
2099
+ else {
2100
+ te.setSelectionRange(start, end - 1);
2101
+ window.getSelection().modify("extend", "forward", "character");
2102
+ }
2103
+ };
2104
+ else
2105
+ setSelRange = function(te, start, end) {
2106
+ try {te.setSelectionRange(start, end);}
2107
+ catch(e) {} // Fails on Firefox when textarea isn't part of the document
2108
+ };
2109
+ }
2110
+ // IE model. Don't ask.
2111
+ else {
2112
+ selRange = function(te) {
2113
+ try {var range = te.ownerDocument.selection.createRange();}
2114
+ catch(e) {return null;}
2115
+ if (!range || range.parentElement() != te) return null;
2116
+ var val = te.value, len = val.length, localRange = te.createTextRange();
2117
+ localRange.moveToBookmark(range.getBookmark());
2118
+ var endRange = te.createTextRange();
2119
+ endRange.collapse(false);
2120
+
2121
+ if (localRange.compareEndPoints("StartToEnd", endRange) > -1)
2122
+ return {start: len, end: len};
2123
+
2124
+ var start = -localRange.moveStart("character", -len);
2125
+ for (var i = val.indexOf("\r"); i > -1 && i < start; i = val.indexOf("\r", i+1), start++) {}
2126
+
2127
+ if (localRange.compareEndPoints("EndToEnd", endRange) > -1)
2128
+ return {start: start, end: len};
2129
+
2130
+ var end = -localRange.moveEnd("character", -len);
2131
+ for (var i = val.indexOf("\r"); i > -1 && i < end; i = val.indexOf("\r", i+1), end++) {}
2132
+ return {start: start, end: end};
2133
+ };
2134
+ setSelRange = function(te, start, end) {
2135
+ var range = te.createTextRange();
2136
+ range.collapse(true);
2137
+ var endrange = range.duplicate();
2138
+ var newlines = 0, txt = te.value;
2139
+ for (var pos = txt.indexOf("\n"); pos > -1 && pos < start; pos = txt.indexOf("\n", pos + 1))
2140
+ ++newlines;
2141
+ range.move("character", start - newlines);
2142
+ for (; pos > -1 && pos < end; pos = txt.indexOf("\n", pos + 1))
2143
+ ++newlines;
2144
+ endrange.move("character", end - newlines);
2145
+ range.setEndPoint("EndToEnd", endrange);
2146
+ range.select();
2147
+ };
2148
+ }
2149
+
2150
+ CodeMirror.defineMode("null", function() {
2151
+ return {token: function(stream) {stream.skipToEnd();}};
2152
+ });
2153
+ CodeMirror.defineMIME("text/plain", "null");
2154
+
2155
+ return CodeMirror;
2156
+ })()
2157
+ ;