vimamsa 0.1.26 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/appimage.yml +93 -0
  3. data/.gitignore +4 -1
  4. data/Dockerfile +7 -4
  5. data/README.md +195 -99
  6. data/custom_example.rb +59 -17
  7. data/doc/TODO.md +678 -0
  8. data/doc/action_names_plan.md +442 -0
  9. data/doc/bundling_plan.md +570 -0
  10. data/doc/delta_syntax_plan.md +293 -0
  11. data/doc/demo_recording_plan.md +288 -0
  12. data/doc/design_goals.md +27 -0
  13. data/doc/intro_page_plan.md +266 -0
  14. data/doc/key_bindings_report_plan.md +213 -0
  15. data/doc/line_tree_plan.md +89 -0
  16. data/doc/missing_vim_bindings.md +61 -0
  17. data/doc/modules_settings_plan.md +433 -0
  18. data/doc/refactor_dedup_plan.md +117 -0
  19. data/doc/registries_plan.md +202 -0
  20. data/doc/startup_speed_plan.md +97 -0
  21. data/doc/treap_visualizer.html +585 -0
  22. data/doc/unused_code_plan.md +120 -0
  23. data/doc/vim_compatibility_plan.md +451 -0
  24. data/doc/vimlike_vim_conflicts.md +262 -0
  25. data/doc/vm_snapshots_plan.md +146 -0
  26. data/doc/wysiwyg_plan.md +231 -0
  27. data/exe/run_tests.rb +124 -3
  28. data/exe/vimamsa +68 -5
  29. data/fonts/OFL-Oxanium.txt +93 -0
  30. data/fonts/Oxanium[wght].ttf +0 -0
  31. data/help/intro.txt +30 -0
  32. data/help/vim_intro.txt +31 -0
  33. data/icon.png +0 -0
  34. data/img/demo.gif +0 -0
  35. data/img/demo.mp4 +0 -0
  36. data/lang/hyperplaintext.lang +7 -1
  37. data/lib/vimamsa/ack.rb +13 -1
  38. data/lib/vimamsa/actions.rb +385 -37
  39. data/lib/vimamsa/appimage_env.rb +35 -0
  40. data/lib/vimamsa/audio.rb +2 -5
  41. data/lib/vimamsa/bookmarks.rb +302 -0
  42. data/lib/vimamsa/buffer.rb +675 -118
  43. data/lib/vimamsa/buffer_changetext.rb +150 -68
  44. data/lib/vimamsa/buffer_cursor.rb +7 -0
  45. data/lib/vimamsa/buffer_list.rb +6 -2
  46. data/lib/vimamsa/buffer_manager.rb +10 -7
  47. data/lib/vimamsa/bundled_fonts.rb +32 -0
  48. data/lib/vimamsa/cli_help.rb +75 -0
  49. data/lib/vimamsa/clipboard.rb +9 -3
  50. data/lib/vimamsa/conf.rb +68 -3
  51. data/lib/vimamsa/constants.rb +3 -0
  52. data/lib/vimamsa/crash_handler.rb +149 -0
  53. data/lib/vimamsa/debug.rb +6 -3
  54. data/lib/vimamsa/demo_player.rb +458 -0
  55. data/lib/vimamsa/demo_recorder.rb +277 -0
  56. data/lib/vimamsa/desktop_install.rb +96 -0
  57. data/lib/vimamsa/diff_buffer.rb +40 -11
  58. data/lib/vimamsa/dot_repeat.rb +104 -0
  59. data/lib/vimamsa/easy_jump.rb +57 -3
  60. data/lib/vimamsa/editor.rb +327 -78
  61. data/lib/vimamsa/encrypt.rb +78 -29
  62. data/lib/vimamsa/file_finder.rb +4 -19
  63. data/lib/vimamsa/file_history.rb +4 -1
  64. data/lib/vimamsa/file_manager.rb +46 -31
  65. data/lib/vimamsa/fold.rb +226 -0
  66. data/lib/vimamsa/form_input.rb +388 -0
  67. data/lib/vimamsa/gui.rb +603 -119
  68. data/lib/vimamsa/gui_command_line.rb +247 -0
  69. data/lib/vimamsa/gui_dialog.rb +94 -42
  70. data/lib/vimamsa/gui_file_panel.rb +356 -25
  71. data/lib/vimamsa/gui_form_generator.rb +75 -40
  72. data/lib/vimamsa/gui_func_panel.rb +67 -22
  73. data/lib/vimamsa/gui_image.rb +3 -0
  74. data/lib/vimamsa/gui_key_hint.rb +165 -0
  75. data/lib/vimamsa/gui_keylog_panel.rb +408 -0
  76. data/lib/vimamsa/gui_menu.rb +84 -53
  77. data/lib/vimamsa/gui_select_window.rb +80 -75
  78. data/lib/vimamsa/gui_settings.rb +86 -41
  79. data/lib/vimamsa/gui_sourceview.rb +280 -92
  80. data/lib/vimamsa/gui_sourceview_autocomplete.rb +319 -90
  81. data/lib/vimamsa/gui_text.rb +63 -2
  82. data/lib/vimamsa/gui_theme.rb +615 -0
  83. data/lib/vimamsa/hook.rb +5 -0
  84. data/lib/vimamsa/hyper_plain_text.rb +3 -0
  85. data/lib/vimamsa/intro_page.rb +368 -0
  86. data/lib/vimamsa/key_actions.rb +382 -193
  87. data/lib/vimamsa/key_binding_tree.rb +467 -273
  88. data/lib/vimamsa/key_bindings_notepad.rb +45 -0
  89. data/lib/vimamsa/key_bindings_report.rb +484 -0
  90. data/lib/vimamsa/key_bindings_vim.rb +104 -0
  91. data/lib/vimamsa/key_bindings_vimlike.rb +353 -289
  92. data/lib/vimamsa/key_names.rb +80 -0
  93. data/lib/vimamsa/langservp.rb +271 -54
  94. data/lib/vimamsa/line_tree.rb +367 -0
  95. data/lib/vimamsa/macro.rb +23 -3
  96. data/lib/vimamsa/main.rb +14 -8
  97. data/lib/vimamsa/rbvma.rb +41 -1
  98. data/lib/vimamsa/registers.rb +125 -0
  99. data/lib/vimamsa/run_ruby.rb +64 -0
  100. data/lib/vimamsa/search.rb +3 -0
  101. data/lib/vimamsa/search_replace.rb +15 -14
  102. data/lib/vimamsa/string_util.rb +134 -40
  103. data/lib/vimamsa/terminal.rb +3 -0
  104. data/lib/vimamsa/test_framework.rb +28 -2
  105. data/lib/vimamsa/tests.rb +11 -8
  106. data/lib/vimamsa/text_objects.rb +310 -0
  107. data/lib/vimamsa/text_transforms.rb +18 -0
  108. data/lib/vimamsa/tmp_user_dir.rb +39 -0
  109. data/lib/vimamsa/user_dirs.rb +83 -0
  110. data/lib/vimamsa/util.rb +46 -7
  111. data/lib/vimamsa/version.rb +1 -1
  112. data/lib/vimamsa/vim_core.rb +355 -0
  113. data/lib/vimamsa/vim_operators.rb +365 -0
  114. data/lib/vimamsa.rb +0 -1
  115. data/modules/calculator/calculator.rb +5 -5
  116. data/modules/color_highlight/color_highlight.rb +118 -0
  117. data/modules/color_highlight/color_highlight_info.rb +3 -0
  118. data/modules/dictation/dictation.rb +1054 -0
  119. data/modules/dictation/dictation_info.rb +3 -0
  120. data/modules/dictation/whisper_worker.py +273 -0
  121. data/modules/ollama/ollama.rb +107 -0
  122. data/modules/ollama/ollama_info.rb +3 -0
  123. data/modules/terminal/terminal.rb +5 -5
  124. data/modules/tts/tts.rb +119 -0
  125. data/modules/tts/tts_info.rb +3 -0
  126. data/run_e2e_vm.sh +28 -0
  127. data/run_tests_vm.rb +138 -0
  128. data/scripts/appimage/AppRun +54 -0
  129. data/scripts/appimage/Dockerfile +18 -0
  130. data/scripts/appimage/build.sh +19 -0
  131. data/scripts/appimage/build_in_container.sh +192 -0
  132. data/scripts/appimage/smoke_test.sh +27 -0
  133. data/scripts/demo/demo_easyjump_steps.txt +60 -0
  134. data/scripts/demo/demo_files_steps.txt +52 -0
  135. data/scripts/demo/demo_steps.txt +67 -0
  136. data/scripts/demo/notes.txt +6 -0
  137. data/scripts/demo/record_demo.rb +156 -0
  138. data/scripts/demo/report.rb +7 -0
  139. data/scripts/demo/shapes.rb +29 -0
  140. data/scripts/demo/square/shapes.rb +29 -0
  141. data/scripts/demo/square/steps.txt +185 -0
  142. data/scripts/lib/perf_startup.rb +138 -0
  143. data/scripts/lib/script_helpers.rb +53 -0
  144. data/scripts/perf_compare.rb +34 -0
  145. data/scripts/profile_startup.rb +72 -0
  146. data/styles/134272-molokai.xml +3 -0
  147. data/styles/molokai_cyber.xml +48 -0
  148. data/styles/molokai_edit.xml +1 -0
  149. data/tests/support/virtual_keyboard.rb +254 -0
  150. data/tests/support/virtual_mic.rb +67 -0
  151. data/tests/test_ack.rb +22 -0
  152. data/tests/test_action_ids.rb +232 -0
  153. data/tests/test_auto_format.rb +122 -0
  154. data/tests/test_autocomplete.rb +211 -0
  155. data/tests/test_autosave.rb +145 -0
  156. data/tests/test_basic_editing.rb +46 -16
  157. data/tests/test_bookmarks.rb +206 -0
  158. data/tests/test_bracket_match.rb +88 -0
  159. data/tests/test_bundling.rb +92 -0
  160. data/tests/test_cli_help.rb +64 -0
  161. data/tests/test_color_highlight.rb +92 -0
  162. data/tests/test_command_line.rb +79 -0
  163. data/tests/test_command_line_file.rb +27 -0
  164. data/tests/test_context_menu_file.rb +147 -0
  165. data/tests/test_copy_paste.rb +106 -26
  166. data/tests/test_crash_handler.rb +39 -0
  167. data/tests/test_custom_two_phase.rb +92 -0
  168. data/tests/test_demo_player.rb +301 -0
  169. data/tests/test_demo_recorder.rb +202 -0
  170. data/tests/test_dialog_callback_errors.rb +44 -0
  171. data/tests/test_dictation.rb +294 -0
  172. data/tests/test_diff_buffer_name.rb +51 -0
  173. data/tests/test_dot_repeat.rb +88 -0
  174. data/tests/test_double_click.rb +41 -0
  175. data/tests/test_drag_selection.rb +125 -0
  176. data/tests/test_e2e_cmdline.rb +116 -0
  177. data/tests/test_e2e_dictation.rb +98 -0
  178. data/tests/test_e2e_replace_char.rb +58 -0
  179. data/tests/test_easy_jump.rb +93 -0
  180. data/tests/test_extract_file_links.rb +55 -0
  181. data/tests/test_file_format.rb +217 -0
  182. data/tests/test_file_manager.rb +72 -0
  183. data/tests/test_file_panel.rb +269 -0
  184. data/tests/test_flash.rb +78 -0
  185. data/tests/test_fold.rb +111 -0
  186. data/tests/test_font_refresh.rb +56 -0
  187. data/tests/test_form_input.rb +203 -0
  188. data/tests/test_func_panel.rb +68 -0
  189. data/tests/test_grep_apply.rb +46 -0
  190. data/tests/test_gtk_sync.rb +126 -0
  191. data/tests/test_hpt_highlight_visible.rb +75 -0
  192. data/tests/test_hpt_link_highlight.rb +82 -0
  193. data/tests/test_intro_page.rb +437 -0
  194. data/tests/test_jump_to_file.rb +41 -0
  195. data/tests/test_key_bindings.rb +208 -0
  196. data/tests/test_key_categories.rb +163 -0
  197. data/tests/test_keylog_panel.rb +261 -0
  198. data/tests/test_line_ends.rb +51 -0
  199. data/tests/test_line_tree.rb +86 -0
  200. data/tests/test_lsp_clangd.rb +281 -0
  201. data/tests/test_lsp_jump.rb +87 -0
  202. data/tests/test_lsp_position_encoding.rb +49 -0
  203. data/tests/test_lsp_symbols.rb +68 -0
  204. data/tests/test_macro.rb +137 -0
  205. data/tests/test_markdown_highlight.rb +57 -0
  206. data/tests/test_mode_badge.rb +41 -0
  207. data/tests/test_module_interface.rb +9 -9
  208. data/tests/test_notepad_bindings.rb +67 -0
  209. data/tests/test_perf_startup.rb +28 -0
  210. data/tests/test_popup_queue.rb +51 -0
  211. data/tests/test_random_edit.rb +109 -0
  212. data/tests/test_registers.rb +122 -0
  213. data/tests/test_revert.rb +127 -0
  214. data/tests/test_run_ruby.rb +77 -0
  215. data/tests/test_startup_file.rb +58 -0
  216. data/tests/test_status_area.rb +50 -0
  217. data/tests/test_text_objects.rb +163 -0
  218. data/tests/test_text_transforms.rb +341 -0
  219. data/tests/test_tmp_user_dir.rb +79 -0
  220. data/tests/test_tts.rb +68 -0
  221. data/tests/test_undo.rb +34 -34
  222. data/tests/test_user_dirs.rb +122 -0
  223. data/tests/test_vim_bindings.rb +353 -0
  224. data/tests/test_vim_conflicts.rb +100 -0
  225. data/tests/test_vim_operators.rb +116 -0
  226. data/tests/test_window_layout.rb +302 -0
  227. data/vimamsa.gemspec +3 -1
  228. data/vm_guest_run.sh +129 -0
  229. metadata +167 -10
@@ -5,12 +5,18 @@ require "pathname"
5
5
  require "openssl"
6
6
  require "ripl/multi_line"
7
7
 
8
+ module Vimamsa
9
+
8
10
  $ifuncon = false
9
11
 
10
12
  class Buffer < String
11
- attr_reader :pos, :lpos, :cpos, :deltas, :edit_history, :fname, :call_func, :pathname, :basename, :dirname, :update_highlight, :marks, :is_highlighted, :syntax_detect_failed, :id, :lang, :images, :last_save, :access_time, :selection_active
13
+ attr_reader :pos, :lpos, :cpos, :deltas, :edit_history, :fname, :call_func, :pathname, :basename, :dirname, :update_highlight, :marks, :is_highlighted, :syntax_detect_failed, :id, :lang, :images, :last_save, :access_time, :selection_active, :lsp, :edit_version
12
14
  attr_writer :call_func, :update_highlight
13
- attr_accessor :gui_update_highlight, :update_hl_startpos, :update_hl_endpos, :hl_queue, :syntax_parser, :highlights, :gui_reset_highlight, :is_parsing_syntax, :line_ends, :bt, :line_action_handler, :module, :active_kbd_mode, :title, :subtitle, :paste_lines, :mode_stack, :default_mode
15
+ # help_page: the name of the help page shown (intro_page.rb), else nil.
16
+ # read_only: edits are refused (help pages). help_buttons: [[action,
17
+ # Gtk::Button]] of a help page's ⟦run:…⟧ links.
18
+ attr_accessor :help_page, :read_only, :help_buttons
19
+ attr_accessor :gui_update_highlight, :update_hl_startpos, :update_hl_endpos, :hl_queue, :syntax_parser, :highlights, :gui_reset_highlight, :is_parsing_syntax, :line_ends, :bt, :line_action_handler, :module, :active_kbd_mode, :title, :subtitle, :paste_lines, :mode_stack, :default_mode, :git_root, :needs_autosave_check
14
20
 
15
21
  @@num_buffers = 0
16
22
 
@@ -40,6 +46,11 @@ class Buffer < String
40
46
  @t_modified = @last_save
41
47
  @last_autosave = @last_save
42
48
  @autosave_thread = nil
49
+ # Set when a buffer is loaded via session restore: its autosave file is not
50
+ # checked at load time (that path bypasses check_autosave_load), so defer
51
+ # the check until the user first switches to the buffer. See
52
+ # check_session_restore and BufferList#set_current_buffer.
53
+ @needs_autosave_check = false
43
54
 
44
55
  @crypt = nil
45
56
  @update_highlight = true
@@ -80,7 +91,7 @@ class Buffer < String
80
91
  def is_active?
81
92
  for k in vma.gui.windows.keys
82
93
  next if vma.gui.windows[k][:sw].child.nil?
83
- return true if vma.gui.windows[k][:sw].child.bufo == self
94
+ return true if vma.gui.windows[k][:sw].child.bufo.equal?(self)
84
95
  end
85
96
  return false
86
97
  end
@@ -125,12 +136,23 @@ class Buffer < String
125
136
  r = @lsp.get_definition(fpuri, @lpos, @cpos)
126
137
  if !r.nil?
127
138
  jump_to_file(r[0], r[1])
139
+ else
140
+ line = get_current_line
141
+ w = line[0, @cpos + 1].to_s[/\w*\z/].to_s + line[@cpos + 1..].to_s[/\A\w*/].to_s
142
+ w = "" unless line[@cpos].to_s =~ /\w/
143
+ msg = w.empty? ? "No definition found" : "No definition found for `#{w}`"
144
+ hint = @lsp.definition_failure_hint(@fname)
145
+ message(hint ? "#{msg}: #{hint}" : msg)
128
146
  end
129
147
  end
130
148
  end
131
149
 
132
150
  def init_lsp()
133
151
  if cnf.lsp.enabled?
152
+ # LangSrv is loaded lazily here: buffers (e.g. the minibuffer) can be
153
+ # created during startup before editor.rb requires langservp, so require
154
+ # it on demand. require is idempotent, so this is cheap after first load.
155
+ require "vimamsa/langservp"
134
156
  @lsp = LangSrv.get(@lang)
135
157
 
136
158
  if @lang == "php"
@@ -145,7 +167,9 @@ class Buffer < String
145
167
 
146
168
  def detect_file_language
147
169
  @lang = nil
148
- @lang = "c" if @fname.match(/\.(c|h|cpp)$/)
170
+ @lang = "c" if @fname.match(/\.(c|h)$/)
171
+ # GtkSourceView (below) refines these; .hxx/.ipp/.inl it does not know
172
+ @lang = "cpp" if @fname.match(/\.(cpp|cc|cxx|hpp|hh|hxx|ipp|inl|tpp)$/)
149
173
  @lang = "java" if @fname.match(/\.(java)$/)
150
174
  @lang = "ruby" if @fname.match(/\.(rb)$/)
151
175
  @lang = "hyperplaintext" if @fname.match(/\.(txt)$/)
@@ -164,6 +188,8 @@ class Buffer < String
164
188
  debug "Guessed LANG: #{lang.id}"
165
189
  @lang = lang.id
166
190
  end
191
+ # No extension to go by (e.g. a script named "build"): the #! line
192
+ @lang ||= shebang_language
167
193
  debug @lang.inspect
168
194
 
169
195
  if @lang
@@ -172,6 +198,43 @@ class Buffer < String
172
198
  return @lang
173
199
  end
174
200
 
201
+ # Interpreter in a "#!" line → GtkSourceView language id
202
+ SHEBANG_LANGS = {
203
+ /\Aruby/ => "ruby", /\Apython/ => "python3", /\A(ba|da|z|k|mk)?sh\z/ => "sh",
204
+ /\Aperl/ => "perl", /\A(node|nodejs|deno|bun)\z/ => "js", /\Alua/ => "lua",
205
+ /\Aphp/ => "php", /\Afish\z/ => "fish", /\A(tclsh|wish)/ => "tcl",
206
+ /\A[gmn]?awk\z/ => "awk", /\ARscript\z/ => "r", /\Ajulia\z/ => "julia",
207
+ /\Amake\z/ => "makefile",
208
+ }
209
+
210
+ # Language from the first line, e.g. "#!/usr/bin/env ruby" or
211
+ # "#!/bin/bash -e". Reads the file when the buffer has no text yet
212
+ # (detection runs before the content is set).
213
+ def shebang_language
214
+ first = self.empty? ? nil : self[0, 200]
215
+ if first.nil? && @fname && File.file?(@fname) && File.readable?(@fname)
216
+ first = File.open(@fname, "rb") { |f| f.read(200) }.to_s.force_encoding("UTF-8").scrub
217
+ end
218
+ line = first.to_s.lines.first.to_s
219
+ return nil unless line.start_with?("#!")
220
+ words = line[2..].strip.split
221
+ cmd = File.basename(words.shift.to_s)
222
+ if cmd == "env" # skip env's options and VAR=value: "env -S ruby -w"
223
+ words.shift while words[0] && (words[0].start_with?("-") || words[0].include?("="))
224
+ cmd = File.basename(words.shift.to_s)
225
+ end
226
+ SHEBANG_LANGS.each { |re, lang| return lang if cmd.match?(re) }
227
+ nil
228
+ rescue StandardError => e
229
+ debug "shebang_language: #{e}"
230
+ nil
231
+ end
232
+
233
+ def set_language(lang_id)
234
+ @lang = lang_id
235
+ gui_set_file_lang(@id, @lang)
236
+ end
237
+
175
238
  def view()
176
239
  # Get the VSourceView < GtkSource::View object corresponding to this buffer
177
240
  return vma.gui.buffers[@id]
@@ -202,7 +265,7 @@ class Buffer < String
202
265
  provider = Gtk::CssProvider.new
203
266
  mc.add_css_class("medctr")
204
267
 
205
- provider.load(data: ".medctr { background-color:#353535; }")
268
+ provider.load(data: ".medctr { background-color:#{theme_color(:medctr_bg)}; }")
206
269
  mc.style_context.add_provider(provider)
207
270
 
208
271
  pp mf.set_prepared(true)
@@ -300,6 +363,10 @@ class Buffer < String
300
363
 
301
364
  def unindent
302
365
  debug("unindent", 2)
366
+ if visual_mode?
367
+ unindent_selection
368
+ return
369
+ end
303
370
  cnf.tab.width!.times {
304
371
  p = @pos - 1
305
372
  if p >= 0
@@ -312,6 +379,64 @@ class Buffer < String
312
379
  }
313
380
  end
314
381
 
382
+ # Map every line spanning the visual selection through the block and replace
383
+ # the range with the result, then restore the selection to cover the same
384
+ # lines. The block receives one line (with its trailing "\n") and returns the
385
+ # replacement line.
386
+ def transform_selected_lines
387
+ (startpos, endpos) = get_visual_mode_range2
388
+ first = get_line_start(startpos)
389
+ last = get_line_end(endpos - 1)
390
+ start_lpos = get_line_pos(first)
391
+ end_lpos = get_line_pos(last)
392
+ r = first..last
393
+ mod = self[r].lines.map { |line| yield(line) }.join
394
+ replace_range(r, mod)
395
+ @selection_start = line_range(start_lpos, 1).begin
396
+ set_pos(line_range(end_lpos, 1).begin)
397
+ end
398
+
399
+ def indent_selection
400
+ tw = cnf.tab.width!
401
+ convert = cnf.tab.to_spaces_default?
402
+ convert = true if cnf.tab.to_spaces_languages?.include?(@lang)
403
+ convert = false if cnf.tab.to_spaces_not_languages?.include?(@lang)
404
+ pad = convert ? " " * tw : "\t"
405
+ transform_selected_lines { |line| line == "\n" ? line : pad + line }
406
+ end
407
+
408
+ def unindent_selection
409
+ tw = cnf.tab.width!
410
+ transform_selected_lines { |line| line.sub(/^\t| {1,#{tw}}/, "") }
411
+ end
412
+
413
+ # Remove all leading whitespace from every line spanning the selection, or
414
+ # from the current line when not in visual mode. The cursor stays on the same
415
+ # character (or moves to the line start if it was inside the indentation).
416
+ def remove_indent_selection
417
+ return transform_selected_lines { |line| line.sub(/^[ \t]+/, "") } if visual_mode?
418
+ r = line_range(@lpos, 1, false)
419
+ indent = self[r][/\A[ \t]*/].size
420
+ return if indent == 0
421
+ newpos = [@pos - indent, r.begin].max
422
+ delete_range(r.begin, r.begin + indent - 1, register: false)
423
+ set_pos(newpos)
424
+ end
425
+
426
+ # Like remove_indent_selection, but remove only the indentation common to
427
+ # all selected lines: x leading whitespace chars from each line, where x is
428
+ # the smallest indent among the non-blank lines (relative indentation is
429
+ # kept). Blank lines lose at most x chars. On a single line this removes its
430
+ # whole indent, so outside visual mode it acts on the current line like g i.
431
+ def remove_common_indent_selection
432
+ return remove_indent_selection if !visual_mode?
433
+ (startpos, endpos) = get_visual_mode_range2
434
+ lines = self[get_line_start(startpos)..get_line_end(endpos - 1)].lines
435
+ x = lines.reject { |l| l.strip.empty? }.map { |l| l[/\A[ \t]*/].size }.min
436
+ return if x.nil? || x == 0
437
+ transform_selected_lines { |line| line.sub(/\A[ \t]{0,#{x}}/, "") }
438
+ end
439
+
315
440
  def handle_drag_and_drop(fname)
316
441
  debug "[buffer] Dropped file: #{fname}"
317
442
  if is_image_file(fname)
@@ -330,16 +455,264 @@ class Buffer < String
330
455
  return @lang
331
456
  end
332
457
 
458
+ # Encoding and line endings of the file on disk ({ encoding:, crlf: }, see
459
+ # read_file_with_format); nil = UTF-8 with \n. The buffer itself is always
460
+ # UTF-8 with \n; save converts back unless the user chooses to convert.
461
+ attr_reader :file_format
462
+
463
+ def file_format=(fmt)
464
+ @file_format = fmt
465
+ @keep_file_format = nil # ask again on the next save
466
+ end
467
+
468
+ # "ISO-8859-1 with CRLF line endings", or nil for UTF-8 with \n.
469
+ def file_format_desc
470
+ return nil if @file_format.nil?
471
+ enc = @file_format[:encoding]
472
+ parts = []
473
+ parts << enc.name unless [Encoding::UTF_8, Encoding::US_ASCII].include?(enc)
474
+ parts << "CRLF line endings" if @file_format[:crlf]
475
+ return nil if parts.empty?
476
+ parts.join(" with ")
477
+ end
478
+
479
+ # Save in the file's original format? The user's answer for this buffer
480
+ # (true = keep, false = convert to UTF-8 + LF), set when asked on save.
481
+ attr_accessor :keep_file_format
482
+
483
+ # The decision for the next save: the answer given for this buffer, else
484
+ # cnf.file_format.on_save ("keep" / "convert"); nil = ask.
485
+ def keep_file_format_on_save
486
+ return @keep_file_format unless @keep_file_format.nil?
487
+ case cnf.file_format.on_save!
488
+ when "keep" then true
489
+ when "convert" then false
490
+ end
491
+ end
492
+
493
+ # What saving will do with this file's format, for the message shown on load.
494
+ def file_format_save_note
495
+ case keep_file_format_on_save
496
+ when true then "it will be saved in that format"
497
+ when false then "it will be saved as UTF-8 with LF"
498
+ else "you will be asked on first save whether to keep it"
499
+ end
500
+ end
501
+
502
+ def ask_file_format(&after)
503
+ params = {}
504
+ params["title"] = "#{CGI.escapeHTML(File.basename(@fname))} is #{file_format_desc}.\nSave it in that format?"
505
+ params["inputs"] = {}
506
+ params["inputs"]["keep_btn"] = { :label => "Keep #{file_format_desc}", :type => :button, :default_focus => true }
507
+ params["inputs"]["convert_btn"] = { :label => "Convert to UTF-8 with LF", :type => :button }
508
+ params[:callback] = proc { |x|
509
+ @keep_file_format = x["keep_btn"] == "submit"
510
+ after&.call
511
+ }
512
+ PopupFormGenerator.new(params).run
513
+ end
514
+
515
+ # The bytes to write for content in the file's chosen format, or nil when
516
+ # saving as UTF-8 + \n. Falls back to UTF-8 (with a message) if the text has
517
+ # characters the original encoding cannot hold.
518
+ def encode_for_disk(content)
519
+ return nil if file_format_desc.nil? || !keep_file_format_on_save
520
+ s = @file_format[:crlf] ? content.gsub("\n", "\r\n") : content.dup
521
+ enc = @file_format[:encoding]
522
+ begin
523
+ s = s.encode(enc) unless [Encoding::UTF_8, Encoding::US_ASCII].include?(enc)
524
+ rescue Encoding::UndefinedConversionError => ex
525
+ message("Cannot save #{File.basename(@fname)} as #{enc.name} (#{ex.error_char.dump} has no #{enc.name} code); saved as UTF-8")
526
+ @file_format = { encoding: Encoding::UTF_8, crlf: @file_format[:crlf] }
527
+ end
528
+ s.b
529
+ end
530
+
333
531
  def revert()
334
532
  return if !@fname
335
533
  return if !File.exist?(@fname)
336
534
  message("Revert buffer #{@fname}")
337
- str = read_file("", @fname)
338
- self.set_content(str)
535
+ str, fmt = read_file_with_format(@fname)
536
+ @file_format = fmt
537
+ str << "\n" if str[-1] != "\n"
538
+ _fold_state
539
+ if !@folds.empty? || (cnf.fold.start_closed? && str =~ FOLD_START_RE)
540
+ # Folded text is not in the buffer as it is on disk, so a diff would
541
+ # not line up: replace wholesale, keep cursor and view by line number.
542
+ revert_by_replace(str)
543
+ else
544
+ revert_by_diff(str)
545
+ end
339
546
  @last_save = Time.now
340
547
  refresh_title
341
548
  end
342
549
 
550
+ # Reload by applying only the differences as deltas, so that cursor, marks
551
+ # and edit positions move with the text around them (e.g. after the file
552
+ # was edited by an external program). The reload is one undo step.
553
+ def revert_by_diff(str)
554
+ return if str == self.to_s
555
+ v = view
556
+ top = v&.top_visible_pos
557
+ nvis = v&.visible_line_count
558
+ cur = @pos
559
+ new_undo_group
560
+ @reloading = true
561
+ for d in diff_deltas(str)
562
+ top = shift_pos_by_delta(top, d) if top
563
+ cur = shift_pos_by_delta(cur, d)
564
+ add_delta(d, true)
565
+ end
566
+ @reloading = false
567
+ new_undo_group
568
+ set_pos(cur.clamp(0, [self.size - 1, 0].max))
569
+ return if v.nil?
570
+ # Keep the same text at the top of the view, unless that would leave the
571
+ # cursor off screen (many lines added between them).
572
+ top = nil if top && nvis && @pos >= top && get_line_and_col_pos(@pos)[0] - get_line_and_col_pos(top)[0] >= nvis
573
+ top = nil if top && @pos < top
574
+ v.handle_deltas(scroll: top.nil?)
575
+ v.scroll_to_top_pos(top) if top
576
+ end
577
+
578
+ def revert_by_replace(str)
579
+ v = view
580
+ top = v&.top_visible_pos
581
+ toplnum = top ? get_line_and_col_pos(top)[0] : nil
582
+ (lnum, col) = [@lpos, @cpos]
583
+ self.set_content(str)
584
+ lnum = lnum.clamp(0, @line_ends.size - 1)
585
+ set_line_and_column_pos(lnum, col)
586
+ if v && toplnum
587
+ toplnum = toplnum.clamp(0, @line_ends.size - 1)
588
+ v.scroll_to_top_pos(toplnum == 0 ? 0 : @line_ends[toplnum - 1] + 1)
589
+ end
590
+ end
591
+
592
+ # Map position p over delta d. An insert at p moves p only when it is a
593
+ # whole-line insert (ends in "\n"), so text added above a line start pushes
594
+ # it down but text added after the cursor on the same spot does not.
595
+ def shift_pos_by_delta(p, d)
596
+ if d[1] == INSERT
597
+ return p + d[2] if d[0] < p || (d[0] == p && d[3].end_with?("\n"))
598
+ elsif d[1] == DELETE
599
+ return d[0] if p >= d[0] && p < d[0] + d[2]
600
+ return p - d[2] if p >= d[0] + d[2]
601
+ end
602
+ p
603
+ end
604
+
605
+ # Deltas (in application order) that turn the buffer contents into newstr.
606
+ # Diffs by line, then by char inside each changed hunk so positions on
607
+ # lines that were only partly edited map precisely.
608
+ def diff_deltas(newstr)
609
+ deltas = []
610
+ pos = 0 # Position in the partially updated buffer
611
+ for (op, a, b) in myers_diff(self.lines, newstr.lines, 1000)
612
+ if op == :eq
613
+ pos += a.sum(&:size)
614
+ next
615
+ end
616
+ del = a.join
617
+ ins = b.join
618
+ parts = [[:change, del, ins]]
619
+ if !del.empty? && !ins.empty? && del.size + ins.size < 4000
620
+ parts = myers_diff(del.chars, ins.chars, 300).map { |(o, x, y)| [o, x.join, y.join] }
621
+ end
622
+ for (o, x, y) in parts
623
+ if o == :eq
624
+ pos += x.size
625
+ next
626
+ end
627
+ deltas << [pos, DELETE, x.size] if !x.empty?
628
+ if !y.empty?
629
+ deltas << [pos, INSERT, y.size, y]
630
+ pos += y.size
631
+ end
632
+ end
633
+ end
634
+ deltas
635
+ end
636
+
637
+ # Myers diff of arrays a and b. Returns [[:eq, items, items] or
638
+ # [:change, deleted, inserted], ...]. If more than max_d edits are needed,
639
+ # the differing middle is returned as one :change.
640
+ def myers_diff(a, b, max_d)
641
+ # Common prefix/suffix are cheap and usually most of the input
642
+ pre = 0
643
+ pre += 1 while pre < a.size && pre < b.size && a[pre] == b[pre]
644
+ suf = 0
645
+ suf += 1 while suf < a.size - pre && suf < b.size - pre && a[-1 - suf] == b[-1 - suf]
646
+ am = a[pre...(a.size - suf)]
647
+ bm = b[pre...(b.size - suf)]
648
+ ops = [] # [:eq|:del|:ins, item]
649
+ n = am.size
650
+ m = bm.size
651
+ trace = []
652
+ v = { 1 => 0 }
653
+ found = false
654
+ (0..[n + m, max_d].min).each { |d|
655
+ trace << v.dup
656
+ (-d..d).step(2) { |k|
657
+ x = (k == -d || (k != d && v[k - 1] < v[k + 1])) ? v[k + 1] : v[k - 1] + 1
658
+ y = x - k
659
+ while x < n && y < m && am[x] == bm[y]
660
+ x += 1
661
+ y += 1
662
+ end
663
+ v[k] = x
664
+ if x >= n && y >= m
665
+ found = true
666
+ break
667
+ end
668
+ }
669
+ break if found
670
+ }
671
+ if found
672
+ x = n
673
+ y = m
674
+ (trace.size - 1).downto(0) { |d|
675
+ vd = trace[d]
676
+ k = x - y
677
+ prev_k = (k == -d || (k != d && vd[k - 1] < vd[k + 1])) ? k + 1 : k - 1
678
+ prev_x = d == 0 ? 0 : vd[prev_k]
679
+ prev_y = prev_x - prev_k
680
+ while x > prev_x && y > prev_y
681
+ x -= 1
682
+ y -= 1
683
+ ops << [:eq, am[x]]
684
+ end
685
+ break if d == 0
686
+ if x == prev_x
687
+ ops << [:ins, bm[y - 1]]
688
+ else
689
+ ops << [:del, am[x - 1]]
690
+ end
691
+ x = prev_x
692
+ y = prev_y
693
+ }
694
+ ops.reverse!
695
+ else
696
+ am.each { |e| ops << [:del, e] }
697
+ bm.each { |e| ops << [:ins, e] }
698
+ end
699
+
700
+ res = []
701
+ res << [:eq, a[0...pre], a[0...pre]] if pre > 0
702
+ for (op, e) in ops
703
+ if op == :eq
704
+ res << [:eq, [], []] if res.empty? || res[-1][0] != :eq
705
+ res[-1][1] << e
706
+ res[-1][2] << e
707
+ else
708
+ res << [:change, [], []] if res.empty? || res[-1][0] != :change
709
+ res[-1][op == :del ? 1 : 2] << e
710
+ end
711
+ end
712
+ res << [:eq, a[(a.size - suf)..], a[(a.size - suf)..]] if suf > 0
713
+ res
714
+ end
715
+
343
716
  def init_encrypted(crypt:, filename:, encrypted:)
344
717
  @crypt = crypt
345
718
  @encrypted_str = encrypted
@@ -381,10 +754,15 @@ class Buffer < String
381
754
  str << "\n"
382
755
  end
383
756
 
757
+ # Any previously stashed folds refer to the text being replaced (fold.rb);
758
+ # with cnf.fold.start_closed the new content loads with all folds collapsed.
759
+ fold_reset
760
+ str = fold_collapse_all(str) if cnf.fold.start_closed?
761
+
384
762
  self.replace(str)
385
- @line_ends = scan_indexes(self, /\n/)
763
+ @line_ends = LineTree.from_string(self) # Array-like: see line_tree.rb
386
764
  words = scan_all_words
387
- Autocomplete.add_words(words)
765
+ Autocomplete.add_words(words, @id)
388
766
 
389
767
  if cnf.btree.experimental?
390
768
  @bt = BufferTree.new(self)
@@ -485,16 +863,20 @@ class Buffer < String
485
863
  @lsp.handle_delta(dc, @fname, @version)
486
864
  end
487
865
  pos = delta[0]
488
- if @edit_pos_history.any? and (@edit_pos_history.last - pos).abs <= 2
489
- @edit_pos_history.pop
490
- end
866
+ # Reloading from disk keeps the user's own edit positions (shifted by
867
+ # update_index) instead of recording the external changes.
868
+ if !@reloading
869
+ if @edit_pos_history.any? and (@edit_pos_history.last - pos).abs <= 2
870
+ @edit_pos_history.pop
871
+ end
491
872
 
492
- lsp = get_line_start(pos)
873
+ lsp = get_line_start(pos)
493
874
 
494
- if @edit_pos_history[-1] != lsp
495
- @edit_pos_history << lsp
875
+ if @edit_pos_history[-1] != lsp
876
+ @edit_pos_history << lsp
877
+ end
878
+ @edit_pos_history_i = 0
496
879
  end
497
- @edit_pos_history_i = 0
498
880
 
499
881
  if delta[1] == DELETE
500
882
  delta[3] = self.slice!(delta[0], delta[2])
@@ -560,6 +942,14 @@ class Buffer < String
560
942
  @marks[k] = @marks[k] + changeamount
561
943
  end
562
944
  end
945
+ # The panel shows each mark's line number and text
946
+ if equal?(vma.buf) && @marks.keys.any? { |k| k.is_a?(String) && k.size == 1 }
947
+ vma.gui&.file_panel_marks_changed
948
+ end
949
+ # Keep closed-fold placeholder anchors (fold.rb) in sync with edits elsewhere.
950
+ @fold_anchors&.each_key do |k|
951
+ @fold_anchors[k] = @fold_anchors[k] + changeamount if @fold_anchors[k] > pos
952
+ end
563
953
  end
564
954
 
565
955
  # Flush @current_group into @edit_history and start a new group.
@@ -608,23 +998,21 @@ class Buffer < String
608
998
  end
609
999
 
610
1000
  def get_com_str()
611
- # return nil if @syntax_detect_failed
612
-
613
1001
  com_str = nil
614
- # if get_file_type() == "c" or get_file_type() == "java"
615
- # com_str = "//"
616
- # elsif get_file_type() == "ruby"
617
- # com_str = "#"
618
- # else
619
- # com_str = "//"
620
- # end
621
1002
 
622
- if !@lang_nfo.nil?
623
- com_str = @lang_nfo.get_metadata("line-comment-start")
1003
+ # User config: rules matched against filename in order, first match wins.
1004
+ if @fname
1005
+ fname_base = File.basename(@fname)
1006
+ rules = cnf.comment_chars!
1007
+ if rules.is_a?(Array)
1008
+ match = rules.find { |r| fname_base.match?(r[:pattern]) }
1009
+ com_str = match[:char] if match
1010
+ end
624
1011
  end
625
1012
 
626
- # lang.get_metadata("block-comment-start")
627
- # lang.get_metadata("block-comment-end")
1013
+ if com_str.nil? && !@lang_nfo.nil?
1014
+ com_str = @lang_nfo.get_metadata("line-comment-start")
1015
+ end
628
1016
 
629
1017
  com_str = "//" if com_str.nil?
630
1018
 
@@ -661,11 +1049,8 @@ class Buffer < String
661
1049
 
662
1050
  a = @line_ends[-1] if a == nil
663
1051
  a = 0 if a == nil
664
- if a > 0
665
- a = a - 1
666
- else
667
- a = 0
668
- end
1052
+ return 0 if a == 0 # First line
1053
+ a = a - 1
669
1054
  ls = nil
670
1055
  ls = @line_ends[a] if a != nil
671
1056
  # if a != nil and ls != @line_ends[a]
@@ -681,7 +1066,7 @@ class Buffer < String
681
1066
  end
682
1067
 
683
1068
  def get_line_end(pos)
684
- return @line_ends.select { |x| x > pos }.min
1069
+ return @line_ends.bsearch { |x| x > pos } # @line_ends is sorted
685
1070
  end
686
1071
 
687
1072
  def comment_selection(op = :comment)
@@ -749,20 +1134,21 @@ class Buffer < String
749
1134
  return start.._End
750
1135
  end
751
1136
 
752
- def copy(range_id)
753
- @paste_lines = false
1137
+ def copy(range_id, mark = nil)
754
1138
  debug "range_id: #{range_id}"
755
1139
  debug range_id.inspect
756
- range = get_range(range_id)
1140
+ range = get_range(range_id, mark: mark)
1141
+ return if range.nil?
757
1142
  debug range.inspect
758
1143
  vma.clipboard.set(self[range])
1144
+ Gui.flash_range(self, range)
759
1145
  end
760
1146
 
761
1147
  def recalc_line_ends()
762
1148
  t1 = Time.now
763
- leo = @line_ends.clone
764
- @line_ends = scan_indexes(self, /\n/)
765
- if @line_ends == leo
1149
+ leo = @line_ends.to_a
1150
+ @line_ends = LineTree.from_string(self)
1151
+ if @line_ends.to_a == leo
766
1152
  debug "No change to line ends"
767
1153
  else
768
1154
  debug "CHANGES to line ends"
@@ -773,14 +1159,14 @@ class Buffer < String
773
1159
  end
774
1160
 
775
1161
  def sanity_check_line_ends()
776
- leo = @line_ends.clone
777
- @line_ends = scan_indexes(self, /\n/)
778
- if @line_ends == leo
1162
+ leo = @line_ends.to_a
1163
+ @line_ends = LineTree.from_string(self)
1164
+ if @line_ends.to_a == leo
779
1165
  debug "No change to line ends"
780
1166
  else
781
1167
  debug "CHANGES to line ends"
782
1168
  debug leo.inspect
783
- debug @line_ends.inspect
1169
+ debug @line_ends.to_a.inspect
784
1170
  crash("CHANGES to line ends")
785
1171
  end
786
1172
  end
@@ -815,25 +1201,13 @@ class Buffer < String
815
1201
  end
816
1202
  end
817
1203
 
1204
+ # changestr: the inserted text (changeamount >= 0) or the removed text.
1205
+ # O(log n) per edit (+ O(k) for k new lines), see line_tree.rb.
818
1206
  def update_line_ends(pos, changeamount, changestr)
819
1207
  if changeamount > -1
820
- changeamount = changestr.size
821
- i_nl = scan_indexes(changestr, /\n/)
822
- i_nl.collect! { |x| x + pos }
823
- end
824
- # debug "change:#{changeamount}"
825
- #TODO: this is the bottle neck in insert_txt action
826
- @line_ends.collect! { |x|
827
- r = nil
828
- r = x if x < pos
829
- r = x + changeamount if changeamount < 0 && x + changeamount >= pos
830
- r = x + changeamount if changeamount > 0 && x >= pos
831
- r
832
- }.compact!
833
-
834
- if changeamount > -1 && i_nl.size > 0
835
- @line_ends.concat(i_nl)
836
- @line_ends.sort!
1208
+ @line_ends.insert(pos, changestr)
1209
+ else
1210
+ @line_ends.delete(pos, changestr)
837
1211
  end
838
1212
  end
839
1213
 
@@ -865,6 +1239,17 @@ class Buffer < String
865
1239
  else
866
1240
  return nil
867
1241
  end
1242
+ elsif range_id == :to_char # vim d f <char>: up to and including next <char> on line
1243
+ lend = @line_ends[@lpos]
1244
+ cpos = self.index(mark, @pos + 1)
1245
+ return nil if cpos.nil? or cpos >= lend
1246
+ range = @pos..cpos
1247
+ elsif range_id == :to_char_backward # vim d F <char>: from prev <char> on line, excluding cursor
1248
+ lstart = @lpos == 0 ? 0 : @line_ends[@lpos - 1] + 1
1249
+ return nil if @pos <= lstart
1250
+ cpos = self.rindex(mark, @pos - 1)
1251
+ return nil if cpos.nil? or cpos < lstart
1252
+ range = cpos..(@pos - 1)
868
1253
  elsif range_id == :to_line_end
869
1254
  debug "TO LINE END"
870
1255
  range = @pos..(@line_ends[@lpos] - 1)
@@ -979,6 +1364,13 @@ class Buffer < String
979
1364
 
980
1365
  def mark_current_position(mark_char)
981
1366
  @marks[mark_char] = @pos
1367
+ vma.gui&.file_panel_marks_changed if equal?(vma.buf)
1368
+ end
1369
+
1370
+ # Marks set with m <char>, as { char => pos } sorted by char. @marks also
1371
+ # holds internal entries (e.g. bookmarks' "bm:<id>"), which are excluded.
1372
+ def user_marks
1373
+ @marks.select { |k, _| k.is_a?(String) && k.size == 1 }.sort.to_h
982
1374
  end
983
1375
 
984
1376
  # Get positions of last characters in words
@@ -1021,15 +1413,20 @@ class Buffer < String
1021
1413
  elsif wtype == :linepointer
1022
1414
  jump_to_file(word[0], word[1], word[2])
1023
1415
  elsif wtype == :textfile
1024
- open_existing_file(word)
1416
+ open_new_file(word)
1025
1417
  elsif wtype == :file
1026
1418
  open_with_default_program(word)
1027
1419
  elsif wtype == :hpt_link
1028
- open_existing_file(word)
1420
+ open_new_file(word)
1029
1421
  elsif wtype == :help
1030
- if word == "keybindings"
1031
- call_action(:show_key_bindings)
1422
+ case word
1423
+ when "keybindings" then call_action("help.keys")
1424
+ when "vim_conflicts" then call_action("help.vim_conflicts")
1425
+ when *HELP_PAGES then show_help_page(word)
1426
+ else message("No help page #{word}")
1032
1427
  end
1428
+ elsif wtype == :run
1429
+ hpt_run_link(word)
1033
1430
  else
1034
1431
  #TODO
1035
1432
  end
@@ -1044,7 +1441,8 @@ class Buffer < String
1044
1441
  # m << ["Sort", self.method("convert_selected_text"), :sortlines]
1045
1442
  m << ["Sort", method("call"), :sortlines]
1046
1443
  m << ["Filter: get numbers", method("call"), :getnums_on_lines]
1047
- m << ["Delete selection", method("call"), :delete_selection]
1444
+ m << ["To LaTeX itemize", method("call"), :latex_itemize]
1445
+ m << ["Delete selection", method("call"), "sel.delete"]
1048
1446
 
1049
1447
  # m << ["Search in dictionary", self.method("handle_word"), nil]
1050
1448
  # m << ["Search in google", self.method("handle_word"), nil]
@@ -1061,6 +1459,10 @@ class Buffer < String
1061
1459
  m << ["Open file (xdg-open)", self.method("handle_word"), [word, wtype]]
1062
1460
  elsif wtype == :hpt_link
1063
1461
  m << ["Jump to file", self.method("handle_word"), [word, wtype]]
1462
+ elsif wtype == :run
1463
+ m << ["Run: #{word.split("|", 2)[1] || word}", self.method("handle_word"), [word, wtype]]
1464
+ elsif wtype == :help
1465
+ m << ["Open help page", self.method("handle_word"), [word, wtype]]
1064
1466
  else
1065
1467
  # m << ["TODO", self.method("handle_word"), word]
1066
1468
  m << ["Paste", method("call"), :paste_after]
@@ -1071,6 +1473,8 @@ class Buffer < String
1071
1473
 
1072
1474
  # Activated when enter/return pressed
1073
1475
  def handle_line_action()
1476
+ # Enter on a fold-start ({{{) or a closed-fold placeholder toggles the fold.
1477
+ return if fold_toggle_at(lpos)
1074
1478
  if line_action_handler.class == Proc or line_action_handler.class == Method
1075
1479
  # Custom handler
1076
1480
  line_action_handler.call(lpos)
@@ -1108,6 +1512,19 @@ class Buffer < String
1108
1512
  end
1109
1513
 
1110
1514
  def get_cur_nonwhitespace_word()
1515
+ # ⟦run:…⟧ / ⟦help:…⟧ links may have spaces in them. On a help page the
1516
+ # cursor sits on a link's button, just before the (hidden) link.
1517
+ link = hpt_link_at(self, @pos)
1518
+ if link.nil? && self[@pos] == HPT_BUTTON_SLOT && hpt_link_at(self, @pos + 1)&.start_with?("⟦run:")
1519
+ link = hpt_link_at(self, @pos + 1)
1520
+ end
1521
+ if link
1522
+ if (m = link.match(/\A⟦run:(.*)⟧\z/))
1523
+ return [m[1], :run]
1524
+ elsif (m = link.match(/\A⟦help:(.*)⟧\z/))
1525
+ return [m[1], :help]
1526
+ end
1527
+ end
1111
1528
  (word, range) = get_word_in_pos(@pos, boundary: :space)
1112
1529
  debug "'WORD: #{word}'"
1113
1530
  # message("Open link #{word}")
@@ -1150,6 +1567,48 @@ class Buffer < String
1150
1567
  return [word, wtype]
1151
1568
  end
1152
1569
 
1570
+ # Existing file named by the whitespace-delimited word at pos, or nil.
1571
+ # Surrounding quotes, brackets and punctuation are ignored ("(foo.pdf)." ->
1572
+ # foo.pdf). Relative names resolve against this buffer's directory, then the
1573
+ # last used directory, then the working directory.
1574
+ def file_path_at(pos)
1575
+ word, _range = get_word_in_pos(pos, boundary: :space)
1576
+ return nil if word.nil?
1577
+ resolve_file_path(word)
1578
+ end
1579
+
1580
+ # Absolute path of the existing file that word names, or nil. See
1581
+ # file_path_at for the rules.
1582
+ def resolve_file_path(word)
1583
+ word = word.strip.sub(/\A[("'`\[<{]+/, "").sub(/[)"'`\]>},.;:!?]+\z/, "")
1584
+ return nil if word.empty? or is_url(word)
1585
+ if word.start_with?("/", "~")
1586
+ cands = [File.expand_path(word)]
1587
+ else
1588
+ dirs = [@fname && File.dirname(@fname), bufs.last_dir, Dir.pwd].compact.uniq
1589
+ cands = dirs.map { |d| File.expand_path(word, d) }
1590
+ end
1591
+ cands.find { |p| File.file?(p) }
1592
+ end
1593
+
1594
+ # Absolute paths of the existing files named in this buffer, unique, in
1595
+ # order of first appearance: whitespace-separated words (as for
1596
+ # file_path_at) and hyperplaintext links ⟦path⟧ / ⟦img:path⟧ / ⟦audio:path⟧.
1597
+ # Like hpt_check_cur_word, a link may leave out a ".txt" extension. Plain
1598
+ # words are only checked if they contain "." or "/", which skips most text.
1599
+ def file_links
1600
+ found = []
1601
+ to_s.scan(/⟦(?:(?:audio|img):)?([^⟧]+)⟧|(\S+)/).uniq.each do |link, word|
1602
+ if link
1603
+ p = resolve_file_path(link) || resolve_file_path("#{link}.txt")
1604
+ elsif word.include?(".") or word.include?("/")
1605
+ p = resolve_file_path(word)
1606
+ end
1607
+ found << p if p
1608
+ end
1609
+ found.uniq
1610
+ end
1611
+
1153
1612
  def cur_nonwhitespace_word_action()
1154
1613
 
1155
1614
  # (word, wtype) = get_cur_nonwhitespace_word()
@@ -1249,6 +1708,12 @@ class Buffer < String
1249
1708
  #need_redraw!
1250
1709
  #@pos += c.size
1251
1710
  # end_profiler
1711
+
1712
+ # Covers both the key binding path and the Wayland IM insert-text path
1713
+ if vma.kbd&.get_mode == :insert
1714
+ v = (self.view rescue nil)
1715
+ v.autocp_on_insert(c) if v.respond_to?(:autocp_on_insert)
1716
+ end
1252
1717
  end
1253
1718
 
1254
1719
  # Update buffer contents to newstr
@@ -1312,6 +1777,16 @@ class Buffer < String
1312
1777
  @visual_mode = true #TODO: change use of @visual_mode into @selection_active
1313
1778
  end
1314
1779
 
1780
+ # Select the whole buffer (cursor lands on the final char)
1781
+ def select_all()
1782
+ return false if self.size == 0
1783
+ @selection_start = 0
1784
+ @selection_active = true
1785
+ @visual_mode = true # copy/delete of SELECTION are guarded by @visual_mode
1786
+ set_pos(self.size - 1)
1787
+ return true
1788
+ end
1789
+
1315
1790
  # Start selection if not already started
1316
1791
  def continue_selection()
1317
1792
  start_selection if !@selection_active
@@ -1319,7 +1794,6 @@ class Buffer < String
1319
1794
 
1320
1795
  def copy_active_selection(x = nil)
1321
1796
  debug "!COPY SELECTION vm=#{@visual_mode}"
1322
- @paste_lines = false
1323
1797
  return if !@visual_mode
1324
1798
 
1325
1799
  debug "COPY SELECTION"
@@ -1334,19 +1808,60 @@ class Buffer < String
1334
1808
  return true
1335
1809
  end
1336
1810
 
1337
- def transform_selection(op)
1811
+ # Apply a text transform to the current visual selection: yields the selected
1812
+ # text, replaces the range with the block's return value, and ends visual
1813
+ # mode. No-op returning nil when not in visual mode; otherwise returns the
1814
+ # replacement text (truthy), so callers can guard follow-up work on it.
1815
+ def transform_visual_selection
1338
1816
  return if !@visual_mode
1339
1817
  r = get_visual_mode_range
1340
- txt = self[r]
1818
+ txt = yield(self[r])
1819
+ replace_range(r, txt)
1820
+ end_visual_mode
1821
+ txt
1822
+ end
1823
+
1824
+ # Wrap `txt` with hyperplaintext style markers for `op`, or strip all markers
1825
+ # when op == :clear. Shared by style_transform (selection) and set_line_style.
1826
+ def apply_style_markers(txt, op)
1827
+ txt = "⦁" + txt + "⦁" if op == :bold
1828
+ txt = "⟦" + txt + "⟧" if op == :link
1829
+ txt = "❙" + txt + "❙" if op == :title
1830
+ txt = "╱" + txt + "╱" if op == :italic
1831
+ txt.gsub!(/[❙◼⟦⟧⦁╱]/, "") if op == :clear
1832
+ txt
1833
+ end
1834
+
1835
+ def transform_text(txt, op)
1341
1836
  txt.upcase! if op == :upcase
1342
1837
  txt.downcase! if op == :downcase
1343
1838
  txt.gsub!(/\w+/, &:capitalize) if op == :capitalize
1344
1839
  txt.swapcase! if op == :swapcase
1345
1840
  txt.reverse! if op == :reverse
1346
1841
  txt = to_camel_case(txt) if op == :camelcase
1842
+ txt
1843
+ end
1347
1844
 
1348
- replace_range(r, txt)
1349
- end_visual_mode
1845
+ def transform_selection(op)
1846
+ transform_visual_selection { |txt| transform_text(txt, op) }
1847
+ end
1848
+
1849
+ # Apply transform `op` to a motion range, like vim's gU/gu/g~ operators.
1850
+ # range_id :line = current line without its newline (gUU); otherwise a
1851
+ # get_range id, e.g. :to_next_word (gUw). Cursor goes to the range start.
1852
+ def transform_range(range_id, op)
1853
+ if range_id == :line
1854
+ lstart = @lpos == 0 ? 0 : @line_ends[@lpos - 1] + 1
1855
+ lend = @line_ends[@lpos]
1856
+ range = lstart < lend ? lstart..(lend - 1) : nil
1857
+ else
1858
+ range = get_range(range_id)
1859
+ end
1860
+ return if range.nil?
1861
+ old = self[range]
1862
+ txt = transform_text(old.dup, op)
1863
+ replace_range(range, txt) if txt != old
1864
+ set_pos(range.first)
1350
1865
  end
1351
1866
 
1352
1867
  def eval_whole_buf(x = 888)
@@ -1359,40 +1874,35 @@ class Buffer < String
1359
1874
  end
1360
1875
  end
1361
1876
 
1877
+ # Apply converter to the visual selection, or to the current line (without
1878
+ # its newline) when not in visual mode.
1362
1879
  def convert_selected_text(converter_id)
1363
- return if !@visual_mode
1364
- r = get_visual_mode_range
1365
- txt = self[r]
1366
- txt = $vma.apply_conv(converter_id, txt)
1367
1880
  #TODO: Detect if changed?
1368
- replace_range(r, txt)
1369
- end_visual_mode
1881
+ if @visual_mode
1882
+ return if !transform_visual_selection { |txt| $vma.apply_conv(converter_id, txt) }
1883
+ else
1884
+ r = line_range(@lpos, 1, false)
1885
+ r = r.begin..(r.begin - 1) if self[r] == "\n" # empty line
1886
+ # Converters may add a trailing newline; the line already has one
1887
+ txt = $vma.apply_conv(converter_id, self[r]).chomp
1888
+ replace_range(r, txt)
1889
+ end
1890
+ view.after_action
1370
1891
  end
1371
1892
 
1372
1893
  def style_transform(op)
1373
- return if !@visual_mode
1374
- r = get_visual_mode_range
1375
1894
  #TODO: if txt[-1]=="\n"
1376
- txt = self[r]
1377
- txt = "⦁" + txt + "⦁" if op == :bold
1378
- txt = "⟦" + txt + "⟧" if op == :link
1379
- txt = "❙" + txt + "❙" if op == :title
1380
- txt.gsub!(/[❙◼⟦⟧⦁]/, "") if op == :clear
1381
-
1382
- replace_range(r, txt)
1383
- end_visual_mode
1895
+ transform_visual_selection { |txt| apply_style_markers(txt, op) }
1384
1896
  end
1385
1897
 
1386
1898
  def set_line_style(op)
1387
1899
  lrange = line_range(@lpos, 1, false)
1388
1900
  txt = self[lrange]
1389
- # txt = "◼ " + txt if op == :heading
1390
- txt = "⦁" + txt + "⦁" if op == :bold
1391
- txt = "❙" + txt + "❙" if op == :title
1392
1901
  txt.gsub!(/◼ /, "") if op == :clear
1393
- txt.gsub!(/[❙◼⟦⟧⦁]/, "") if op == :clear or [:h1, :h2, :h3, :h4].include?(op)
1902
+ txt = apply_style_markers(txt, op)
1394
1903
 
1395
1904
  if [:h1, :h2, :h3, :h4].include?(op)
1905
+ txt.gsub!(/[❙◼⟦⟧⦁╱]/, "")
1396
1906
  txt.strip!
1397
1907
  txt = "◼ " + txt if op == :h1
1398
1908
  txt = "◼◼ " + txt if op == :h2
@@ -1403,14 +1913,8 @@ class Buffer < String
1403
1913
  end
1404
1914
 
1405
1915
  def copy_line()
1406
- vma.kbd.method_handles_repeat = true
1407
- num_lines = 1
1408
- if !vma.kbd.next_command_count.nil? and vma.kbd.next_command_count > 0
1409
- num_lines = vma.kbd.next_command_count
1410
- debug "copy num_lines:#{num_lines}"
1411
- end
1412
- vma.clipboard.set(self[line_range(@lpos, num_lines)])
1413
- @paste_lines = true
1916
+ num_lines = get_repeat_num()
1917
+ vma.clipboard.set(self[line_range(@lpos, num_lines)], linewise: true)
1414
1918
  end
1415
1919
 
1416
1920
  def put_file_path_to_clipboard
@@ -1425,7 +1929,7 @@ class Buffer < String
1425
1929
  return if !@visual_mode #TODO: this should not happen
1426
1930
 
1427
1931
  _start, _end = get_visual_mode_range
1428
- vma.clipboard.set(self[_start, _end])
1932
+ vma.clipboard.set(self[_start, _end], kind: :delete)
1429
1933
  end_visual_mode
1430
1934
  end
1431
1935
 
@@ -1528,22 +2032,34 @@ class Buffer < String
1528
2032
 
1529
2033
  set_filename(fpath)
1530
2034
  save()
2035
+ # set_filename re-detects the language and drops the LSP client; attach the
2036
+ # one for the new language (e.g. an untitled buffer saved as foo.cpp).
2037
+ init_lsp if cnf.lsp.enabled?
1531
2038
  gui_set_window_title(@title, @subtitle) #TODO: if not active buffer?
1532
2039
  end
1533
2040
 
1534
- def write_contents_to_file(fpath)
1535
- if @crypt != nil
2041
+ # original_format: write in the file's own encoding / line endings when the
2042
+ # user chose to keep them (save only; backups etc. stay UTF-8).
2043
+ def write_contents_to_file(fpath, original_format: false)
2044
+ # content_for_disk re-inflates any closed folds so the file always holds the
2045
+ # fully expanded text (see fold.rb); equals self.to_s when nothing is folded.
2046
+ disk = content_for_disk
2047
+ raw = original_format && @crypt.nil? ? encode_for_disk(disk) : nil
2048
+ if raw
2049
+ mode = "wb"
2050
+ contents = raw
2051
+ elsif @crypt != nil
1536
2052
  mode = "wb+"
1537
- contents = "VMACRYPT001" + @crypt.encrypt(self.to_s)
2053
+ contents = Encrypt::HEADER_V2 + @crypt.encrypt(disk)
1538
2054
  else
1539
2055
  mode = "w+"
1540
- contents = self.to_s
2056
+ contents = disk
1541
2057
  end
1542
2058
 
1543
2059
  Thread.new {
1544
2060
  begin
1545
2061
  io = File.open(fpath, mode)
1546
- io.set_encoding(self.encoding)
2062
+ io.set_encoding(self.encoding) unless raw # raw: already encoded bytes
1547
2063
  io.write(contents)
1548
2064
  io.close
1549
2065
  rescue Encoding::UndefinedConversionError => ex
@@ -1556,11 +2072,19 @@ class Buffer < String
1556
2072
  io.set_encoding(Encoding::UTF_8)
1557
2073
  io.write(contents)
1558
2074
  rescue Errno::EACCES => ex
1559
- message("File #{fpath} not writeable")
2075
+ GLib::Idle.add { message("File #{fpath} not writeable"); false }
1560
2076
  #TODO: show message box
1561
2077
  end
1562
2078
  @last_save = Time.now
1563
- refresh_title
2079
+ GLib::Idle.add { refresh_title; false }
2080
+ if cnf.auto_chmod_exec? && !@crypt && contents.match?(%r{\A#!\s*/\S})
2081
+ begin
2082
+ FileUtils.chmod("+x", fpath)
2083
+ GLib::Idle.add { message("Set executable: #{fpath}"); false }
2084
+ rescue => e
2085
+ GLib::Idle.add { message("chmod failed: #{e}"); false }
2086
+ end
2087
+ end
1564
2088
  debug "file saved on #{@last_save}"
1565
2089
  sleep 3
1566
2090
  }
@@ -1574,22 +2098,24 @@ class Buffer < String
1574
2098
  end
1575
2099
 
1576
2100
  def unsaved_changes?
1577
- pp [@t_modified, @last_save]
1578
2101
  return true if @t_modified > @last_save
1579
2102
  return false
1580
2103
  end
1581
2104
 
1582
2105
  def refresh_title
1583
- if vma.buf == self
1584
- pfx = ""
1585
- pfx = "+ " if vma.buf.unsaved_changes?
1586
- gui_set_window_title(pfx + vma.buf.title, vma.buf.subtitle)
2106
+ if vma.buf.equal?(self) # a Buffer is a String: == compares the text
2107
+ mod = unsaved_changes?
2108
+ pfx = mod ? "+ " : ""
2109
+ gui_set_window_title(pfx + title, subtitle, modified: mod)
1587
2110
  end
1588
2111
  end
1589
2112
 
1590
2113
  def check_if_modified_outside
1591
2114
  # Don't check if less than 8 seconds since last checked
1592
2115
  return false if @fname.nil?
2116
+ # Tests write and reload files quickly; the reload prompt would pop up
2117
+ # unasked in the middle of a run and take the keyboard with it.
2118
+ return false if vma_test_mode?
1593
2119
  return false if Time.now - 8 < @file_last_cheked
1594
2120
  @file_last_cheked = Time.now
1595
2121
  return false if !File.exist?(@fname)
@@ -1626,7 +2152,7 @@ class Buffer < String
1626
2152
  return if @fname.nil?
1627
2153
  return if @t_modified <= @last_autosave
1628
2154
  apath = autosave_path
1629
- contents = self.to_s
2155
+ contents = content_for_disk # re-inflate closed folds (fold.rb)
1630
2156
  Thread.new {
1631
2157
  begin
1632
2158
  File.open(apath, "w+") { |io| io.set_encoding(self.encoding); io.write(contents) }
@@ -1655,10 +2181,27 @@ class Buffer < String
1655
2181
  debug "delete autosave failed: #{ex}"
1656
2182
  end
1657
2183
 
2184
+ # Run a deferred autosave check the first time a session-restored buffer is
2185
+ # entered. No-op unless flagged (see @needs_autosave_check). Cleared before
2186
+ # the check so it fires at most once.
2187
+ def check_autosave_load_if_pending
2188
+ return unless @needs_autosave_check
2189
+ @needs_autosave_check = false
2190
+ check_autosave_load
2191
+ end
2192
+
1658
2193
  def check_autosave_load
1659
2194
  apath = autosave_path
1660
2195
  return if apath.nil? || !File.exist?(apath)
1661
- if File.read(apath) == self.to_s
2196
+ if File.read(apath) == content_for_disk # autosave stores the inflated form
2197
+ delete_autosave_file
2198
+ return
2199
+ end
2200
+ # The autosave predates the file on disk: the file has been saved/changed
2201
+ # more recently, so the autosave holds an outdated version. Drop it silently
2202
+ # rather than prompting. (A newer autosave — unsaved changes from a crash —
2203
+ # still prompts below.)
2204
+ if File.exist?(@fname) && File.mtime(apath) < File.mtime(@fname)
1662
2205
  delete_autosave_file
1663
2206
  return
1664
2207
  end
@@ -1666,7 +2209,8 @@ class Buffer < String
1666
2209
  params = {
1667
2210
  "title" => title,
1668
2211
  "inputs" => {
1669
- "yes_btn" => { :label => "Load", :type => :button, :default_focus => true },
2212
+ "yes_btn" => { :label => "Load", :type => :button, :default_focus => true },
2213
+ "diff_btn" => { :label => "Review diff", :type => :button },
1670
2214
  "delete_btn" => { :label => "Delete autosave", :type => :button },
1671
2215
  },
1672
2216
  :callback => proc { |x| load_autosave_callback(x) },
@@ -1681,6 +2225,12 @@ class Buffer < String
1681
2225
  @t_modified = Time.now
1682
2226
  refresh_title
1683
2227
  message("Loaded autosave for #{@fname}")
2228
+ elsif x["diff_btn"] == "submit"
2229
+ apath = autosave_path
2230
+ diff_str = run_cmd("diff -u #{Shellwords.escape(@fname)} #{Shellwords.escape(apath)}")
2231
+ create_new_file(nil, diff_str.empty? ? "(no differences)\n" : diff_str)
2232
+ gui_set_file_lang(vma.buf.id, "diff") unless diff_str.empty?
2233
+ check_autosave_load
1684
2234
  elsif x["delete_btn"] == "submit"
1685
2235
  delete_autosave_file
1686
2236
  message("Deleted autosave for #{@fname}")
@@ -1688,13 +2238,18 @@ class Buffer < String
1688
2238
  end
1689
2239
 
1690
2240
  def save()
2241
+ return if @module.respond_to?(:on_save) and @module.on_save
1691
2242
  check_if_modified_outside #TODO
1692
2243
  if !@fname
1693
2244
  save_as()
1694
2245
  return
1695
2246
  end
2247
+ if file_format_desc && keep_file_format_on_save.nil?
2248
+ ask_file_format { save }
2249
+ return
2250
+ end
1696
2251
  message("Saving file #{@fname}")
1697
- write_contents_to_file(@fname)
2252
+ write_contents_to_file(@fname, original_format: true)
1698
2253
  delete_autosave_file
1699
2254
  hook.call(:file_saved, self)
1700
2255
  end
@@ -1708,7 +2263,8 @@ class Buffer < String
1708
2263
  fname = @fname
1709
2264
  return if !@fname
1710
2265
  spfx = fname.gsub("=", "==").gsub("/", "=:")
1711
- spath = File.expand_path("~/.vimamsa/backup")
2266
+ spath = get_data_path("backup")
2267
+ FileUtils.mkdir_p(spath) rescue nil
1712
2268
  return false if !can_save_to_directory?(spath)
1713
2269
  datetime = DateTime.now().strftime("%d%m%Y:%H%M%S")
1714
2270
  savepath = "#{spath}/#{spfx}_#{datetime}"
@@ -1735,3 +2291,4 @@ def backup_all_buffers()
1735
2291
  end
1736
2292
  message("Backup all buffers")
1737
2293
  end
2294
+ end # module Vimamsa