vimamsa 0.1.26 → 0.1.27

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 (170) 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 +62 -16
  6. data/custom_example.rb +43 -13
  7. data/doc/TODO.md +461 -0
  8. data/doc/bundling_plan.md +569 -0
  9. data/doc/key_bindings_report_plan.md +168 -0
  10. data/doc/missing_vim_bindings.md +71 -0
  11. data/doc/modules_settings_plan.md +433 -0
  12. data/doc/refactor_dedup_plan.md +117 -0
  13. data/doc/unused_code_plan.md +120 -0
  14. data/doc/vim_compatibility_plan.md +296 -0
  15. data/doc/vimlike_vim_conflicts.md +254 -0
  16. data/doc/vm_snapshots_plan.md +146 -0
  17. data/exe/run_tests.rb +117 -3
  18. data/exe/vimamsa +24 -4
  19. data/fonts/OFL-Oxanium.txt +93 -0
  20. data/fonts/Oxanium[wght].ttf +0 -0
  21. data/icon.png +0 -0
  22. data/img/demo.gif +0 -0
  23. data/lang/hyperplaintext.lang +6 -0
  24. data/lib/vimamsa/ack.rb +11 -1
  25. data/lib/vimamsa/actions.rb +4 -1
  26. data/lib/vimamsa/appimage_env.rb +35 -0
  27. data/lib/vimamsa/audio.rb +2 -5
  28. data/lib/vimamsa/bookmarks.rb +302 -0
  29. data/lib/vimamsa/buffer.rb +593 -82
  30. data/lib/vimamsa/buffer_changetext.rb +102 -42
  31. data/lib/vimamsa/buffer_cursor.rb +7 -0
  32. data/lib/vimamsa/buffer_list.rb +4 -0
  33. data/lib/vimamsa/buffer_manager.rb +4 -1
  34. data/lib/vimamsa/bundled_fonts.rb +32 -0
  35. data/lib/vimamsa/clipboard.rb +3 -0
  36. data/lib/vimamsa/conf.rb +59 -3
  37. data/lib/vimamsa/constants.rb +3 -0
  38. data/lib/vimamsa/crash_handler.rb +149 -0
  39. data/lib/vimamsa/debug.rb +4 -1
  40. data/lib/vimamsa/desktop_install.rb +96 -0
  41. data/lib/vimamsa/diff_buffer.rb +39 -10
  42. data/lib/vimamsa/easy_jump.rb +3 -0
  43. data/lib/vimamsa/editor.rb +263 -57
  44. data/lib/vimamsa/encrypt.rb +78 -29
  45. data/lib/vimamsa/file_finder.rb +4 -19
  46. data/lib/vimamsa/file_history.rb +3 -0
  47. data/lib/vimamsa/file_manager.rb +30 -15
  48. data/lib/vimamsa/fold.rb +226 -0
  49. data/lib/vimamsa/gui.rb +520 -106
  50. data/lib/vimamsa/gui_command_line.rb +208 -0
  51. data/lib/vimamsa/gui_dialog.rb +94 -42
  52. data/lib/vimamsa/gui_file_panel.rb +356 -25
  53. data/lib/vimamsa/gui_form_generator.rb +59 -35
  54. data/lib/vimamsa/gui_func_panel.rb +67 -22
  55. data/lib/vimamsa/gui_image.rb +3 -0
  56. data/lib/vimamsa/gui_keylog_panel.rb +246 -0
  57. data/lib/vimamsa/gui_menu.rb +23 -11
  58. data/lib/vimamsa/gui_select_window.rb +19 -48
  59. data/lib/vimamsa/gui_settings.rb +78 -37
  60. data/lib/vimamsa/gui_sourceview.rb +273 -19
  61. data/lib/vimamsa/gui_sourceview_autocomplete.rb +319 -90
  62. data/lib/vimamsa/gui_text.rb +63 -2
  63. data/lib/vimamsa/gui_theme.rb +606 -0
  64. data/lib/vimamsa/hook.rb +3 -0
  65. data/lib/vimamsa/hyper_plain_text.rb +3 -0
  66. data/lib/vimamsa/key_actions.rb +112 -13
  67. data/lib/vimamsa/key_binding_tree.rb +242 -215
  68. data/lib/vimamsa/key_bindings_notepad.rb +43 -0
  69. data/lib/vimamsa/key_bindings_report.rb +261 -0
  70. data/lib/vimamsa/key_bindings_vim.rb +354 -0
  71. data/lib/vimamsa/key_bindings_vimlike.rb +65 -9
  72. data/lib/vimamsa/langservp.rb +271 -54
  73. data/lib/vimamsa/macro.rb +3 -0
  74. data/lib/vimamsa/main.rb +14 -8
  75. data/lib/vimamsa/rbvma.rb +26 -1
  76. data/lib/vimamsa/search.rb +3 -0
  77. data/lib/vimamsa/search_replace.rb +11 -10
  78. data/lib/vimamsa/string_util.rb +120 -40
  79. data/lib/vimamsa/terminal.rb +3 -0
  80. data/lib/vimamsa/test_framework.rb +28 -2
  81. data/lib/vimamsa/tests.rb +3 -0
  82. data/lib/vimamsa/text_objects.rb +353 -0
  83. data/lib/vimamsa/text_transforms.rb +14 -0
  84. data/lib/vimamsa/util.rb +46 -7
  85. data/lib/vimamsa/version.rb +1 -1
  86. data/lib/vimamsa.rb +0 -1
  87. data/modules/color_highlight/color_highlight.rb +118 -0
  88. data/modules/color_highlight/color_highlight_info.rb +3 -0
  89. data/modules/dictation/dictation.rb +1054 -0
  90. data/modules/dictation/dictation_info.rb +3 -0
  91. data/modules/dictation/whisper_worker.py +273 -0
  92. data/modules/ollama/ollama.rb +107 -0
  93. data/modules/ollama/ollama_info.rb +3 -0
  94. data/modules/tts/tts.rb +119 -0
  95. data/modules/tts/tts_info.rb +3 -0
  96. data/run_e2e_vm.sh +28 -0
  97. data/run_tests_vm.sh +130 -0
  98. data/scripts/appimage/AppRun +54 -0
  99. data/scripts/appimage/Dockerfile +18 -0
  100. data/scripts/appimage/build.sh +19 -0
  101. data/scripts/appimage/build_in_container.sh +192 -0
  102. data/scripts/appimage/smoke_test.sh +27 -0
  103. data/scripts/demo/demo_steps.txt +59 -0
  104. data/scripts/demo/record_demo.rb +177 -0
  105. data/scripts/demo/shapes.rb +28 -0
  106. data/styles/134272-molokai.xml +3 -0
  107. data/styles/molokai_cyber.xml +48 -0
  108. data/styles/molokai_edit.xml +1 -0
  109. data/tests/support/virtual_keyboard.rb +254 -0
  110. data/tests/support/virtual_mic.rb +67 -0
  111. data/tests/test_ack.rb +22 -0
  112. data/tests/test_auto_format.rb +122 -0
  113. data/tests/test_autocomplete.rb +211 -0
  114. data/tests/test_autosave.rb +145 -0
  115. data/tests/test_basic_editing.rb +33 -3
  116. data/tests/test_bookmarks.rb +206 -0
  117. data/tests/test_bracket_match.rb +85 -0
  118. data/tests/test_bundling.rb +92 -0
  119. data/tests/test_color_highlight.rb +92 -0
  120. data/tests/test_command_line.rb +79 -0
  121. data/tests/test_command_line_file.rb +27 -0
  122. data/tests/test_context_menu_file.rb +129 -0
  123. data/tests/test_copy_paste.rb +80 -0
  124. data/tests/test_crash_handler.rb +39 -0
  125. data/tests/test_custom_two_phase.rb +92 -0
  126. data/tests/test_dialog_callback_errors.rb +44 -0
  127. data/tests/test_dictation.rb +294 -0
  128. data/tests/test_diff_buffer_name.rb +51 -0
  129. data/tests/test_double_click.rb +41 -0
  130. data/tests/test_drag_selection.rb +125 -0
  131. data/tests/test_e2e_cmdline.rb +116 -0
  132. data/tests/test_e2e_dictation.rb +98 -0
  133. data/tests/test_e2e_replace_char.rb +58 -0
  134. data/tests/test_extract_file_links.rb +55 -0
  135. data/tests/test_file_format.rb +217 -0
  136. data/tests/test_file_manager.rb +72 -0
  137. data/tests/test_file_panel.rb +269 -0
  138. data/tests/test_flash.rb +78 -0
  139. data/tests/test_fold.rb +111 -0
  140. data/tests/test_font_refresh.rb +56 -0
  141. data/tests/test_func_panel.rb +68 -0
  142. data/tests/test_grep_apply.rb +46 -0
  143. data/tests/test_gtk_sync.rb +126 -0
  144. data/tests/test_hpt_highlight_visible.rb +75 -0
  145. data/tests/test_hpt_link_highlight.rb +82 -0
  146. data/tests/test_jump_to_file.rb +41 -0
  147. data/tests/test_key_bindings.rb +208 -0
  148. data/tests/test_keylog_panel.rb +101 -0
  149. data/tests/test_lsp_clangd.rb +281 -0
  150. data/tests/test_lsp_jump.rb +87 -0
  151. data/tests/test_lsp_position_encoding.rb +49 -0
  152. data/tests/test_lsp_symbols.rb +68 -0
  153. data/tests/test_macro.rb +137 -0
  154. data/tests/test_markdown_highlight.rb +57 -0
  155. data/tests/test_mode_badge.rb +41 -0
  156. data/tests/test_notepad_bindings.rb +67 -0
  157. data/tests/test_popup_queue.rb +51 -0
  158. data/tests/test_random_edit.rb +109 -0
  159. data/tests/test_revert.rb +127 -0
  160. data/tests/test_startup_file.rb +58 -0
  161. data/tests/test_status_area.rb +50 -0
  162. data/tests/test_text_objects.rb +163 -0
  163. data/tests/test_text_transforms.rb +329 -0
  164. data/tests/test_tts.rb +68 -0
  165. data/tests/test_vim_bindings.rb +252 -0
  166. data/tests/test_vim_conflicts.rb +63 -0
  167. data/tests/test_window_layout.rb +219 -0
  168. data/vimamsa.gemspec +3 -1
  169. data/vm_guest_run.sh +109 -0
  170. metadata +112 -10
@@ -5,12 +5,14 @@ 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
+ 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
16
 
15
17
  @@num_buffers = 0
16
18
 
@@ -40,6 +42,11 @@ class Buffer < String
40
42
  @t_modified = @last_save
41
43
  @last_autosave = @last_save
42
44
  @autosave_thread = nil
45
+ # Set when a buffer is loaded via session restore: its autosave file is not
46
+ # checked at load time (that path bypasses check_autosave_load), so defer
47
+ # the check until the user first switches to the buffer. See
48
+ # check_session_restore and BufferList#set_current_buffer.
49
+ @needs_autosave_check = false
43
50
 
44
51
  @crypt = nil
45
52
  @update_highlight = true
@@ -80,7 +87,7 @@ class Buffer < String
80
87
  def is_active?
81
88
  for k in vma.gui.windows.keys
82
89
  next if vma.gui.windows[k][:sw].child.nil?
83
- return true if vma.gui.windows[k][:sw].child.bufo == self
90
+ return true if vma.gui.windows[k][:sw].child.bufo.equal?(self)
84
91
  end
85
92
  return false
86
93
  end
@@ -125,12 +132,23 @@ class Buffer < String
125
132
  r = @lsp.get_definition(fpuri, @lpos, @cpos)
126
133
  if !r.nil?
127
134
  jump_to_file(r[0], r[1])
135
+ else
136
+ line = get_current_line
137
+ w = line[0, @cpos + 1].to_s[/\w*\z/].to_s + line[@cpos + 1..].to_s[/\A\w*/].to_s
138
+ w = "" unless line[@cpos].to_s =~ /\w/
139
+ msg = w.empty? ? "No definition found" : "No definition found for `#{w}`"
140
+ hint = @lsp.definition_failure_hint(@fname)
141
+ message(hint ? "#{msg}: #{hint}" : msg)
128
142
  end
129
143
  end
130
144
  end
131
145
 
132
146
  def init_lsp()
133
147
  if cnf.lsp.enabled?
148
+ # LangSrv is loaded lazily here: buffers (e.g. the minibuffer) can be
149
+ # created during startup before editor.rb requires langservp, so require
150
+ # it on demand. require is idempotent, so this is cheap after first load.
151
+ require "vimamsa/langservp"
134
152
  @lsp = LangSrv.get(@lang)
135
153
 
136
154
  if @lang == "php"
@@ -145,7 +163,9 @@ class Buffer < String
145
163
 
146
164
  def detect_file_language
147
165
  @lang = nil
148
- @lang = "c" if @fname.match(/\.(c|h|cpp)$/)
166
+ @lang = "c" if @fname.match(/\.(c|h)$/)
167
+ # GtkSourceView (below) refines these; .hxx/.ipp/.inl it does not know
168
+ @lang = "cpp" if @fname.match(/\.(cpp|cc|cxx|hpp|hh|hxx|ipp|inl|tpp)$/)
149
169
  @lang = "java" if @fname.match(/\.(java)$/)
150
170
  @lang = "ruby" if @fname.match(/\.(rb)$/)
151
171
  @lang = "hyperplaintext" if @fname.match(/\.(txt)$/)
@@ -172,6 +192,11 @@ class Buffer < String
172
192
  return @lang
173
193
  end
174
194
 
195
+ def set_language(lang_id)
196
+ @lang = lang_id
197
+ gui_set_file_lang(@id, @lang)
198
+ end
199
+
175
200
  def view()
176
201
  # Get the VSourceView < GtkSource::View object corresponding to this buffer
177
202
  return vma.gui.buffers[@id]
@@ -202,7 +227,7 @@ class Buffer < String
202
227
  provider = Gtk::CssProvider.new
203
228
  mc.add_css_class("medctr")
204
229
 
205
- provider.load(data: ".medctr { background-color:#353535; }")
230
+ provider.load(data: ".medctr { background-color:#{theme_color(:medctr_bg)}; }")
206
231
  mc.style_context.add_provider(provider)
207
232
 
208
233
  pp mf.set_prepared(true)
@@ -300,6 +325,10 @@ class Buffer < String
300
325
 
301
326
  def unindent
302
327
  debug("unindent", 2)
328
+ if visual_mode?
329
+ unindent_selection
330
+ return
331
+ end
303
332
  cnf.tab.width!.times {
304
333
  p = @pos - 1
305
334
  if p >= 0
@@ -312,6 +341,64 @@ class Buffer < String
312
341
  }
313
342
  end
314
343
 
344
+ # Map every line spanning the visual selection through the block and replace
345
+ # the range with the result, then restore the selection to cover the same
346
+ # lines. The block receives one line (with its trailing "\n") and returns the
347
+ # replacement line.
348
+ def transform_selected_lines
349
+ (startpos, endpos) = get_visual_mode_range2
350
+ first = get_line_start(startpos)
351
+ last = get_line_end(endpos - 1)
352
+ start_lpos = get_line_pos(first)
353
+ end_lpos = get_line_pos(last)
354
+ r = first..last
355
+ mod = self[r].lines.map { |line| yield(line) }.join
356
+ replace_range(r, mod)
357
+ @selection_start = line_range(start_lpos, 1).begin
358
+ set_pos(line_range(end_lpos, 1).begin)
359
+ end
360
+
361
+ def indent_selection
362
+ tw = cnf.tab.width!
363
+ convert = cnf.tab.to_spaces_default?
364
+ convert = true if cnf.tab.to_spaces_languages?.include?(@lang)
365
+ convert = false if cnf.tab.to_spaces_not_languages?.include?(@lang)
366
+ pad = convert ? " " * tw : "\t"
367
+ transform_selected_lines { |line| line == "\n" ? line : pad + line }
368
+ end
369
+
370
+ def unindent_selection
371
+ tw = cnf.tab.width!
372
+ transform_selected_lines { |line| line.sub(/^\t| {1,#{tw}}/, "") }
373
+ end
374
+
375
+ # Remove all leading whitespace from every line spanning the selection, or
376
+ # from the current line when not in visual mode. The cursor stays on the same
377
+ # character (or moves to the line start if it was inside the indentation).
378
+ def remove_indent_selection
379
+ return transform_selected_lines { |line| line.sub(/^[ \t]+/, "") } if visual_mode?
380
+ r = line_range(@lpos, 1, false)
381
+ indent = self[r][/\A[ \t]*/].size
382
+ return if indent == 0
383
+ newpos = [@pos - indent, r.begin].max
384
+ delete_range(r.begin, r.begin + indent - 1)
385
+ set_pos(newpos)
386
+ end
387
+
388
+ # Like remove_indent_selection, but remove only the indentation common to
389
+ # all selected lines: x leading whitespace chars from each line, where x is
390
+ # the smallest indent among the non-blank lines (relative indentation is
391
+ # kept). Blank lines lose at most x chars. On a single line this removes its
392
+ # whole indent, so outside visual mode it acts on the current line like g i.
393
+ def remove_common_indent_selection
394
+ return remove_indent_selection if !visual_mode?
395
+ (startpos, endpos) = get_visual_mode_range2
396
+ lines = self[get_line_start(startpos)..get_line_end(endpos - 1)].lines
397
+ x = lines.reject { |l| l.strip.empty? }.map { |l| l[/\A[ \t]*/].size }.min
398
+ return if x.nil? || x == 0
399
+ transform_selected_lines { |line| line.sub(/\A[ \t]{0,#{x}}/, "") }
400
+ end
401
+
315
402
  def handle_drag_and_drop(fname)
316
403
  debug "[buffer] Dropped file: #{fname}"
317
404
  if is_image_file(fname)
@@ -330,16 +417,264 @@ class Buffer < String
330
417
  return @lang
331
418
  end
332
419
 
420
+ # Encoding and line endings of the file on disk ({ encoding:, crlf: }, see
421
+ # read_file_with_format); nil = UTF-8 with \n. The buffer itself is always
422
+ # UTF-8 with \n; save converts back unless the user chooses to convert.
423
+ attr_reader :file_format
424
+
425
+ def file_format=(fmt)
426
+ @file_format = fmt
427
+ @keep_file_format = nil # ask again on the next save
428
+ end
429
+
430
+ # "ISO-8859-1 with CRLF line endings", or nil for UTF-8 with \n.
431
+ def file_format_desc
432
+ return nil if @file_format.nil?
433
+ enc = @file_format[:encoding]
434
+ parts = []
435
+ parts << enc.name unless [Encoding::UTF_8, Encoding::US_ASCII].include?(enc)
436
+ parts << "CRLF line endings" if @file_format[:crlf]
437
+ return nil if parts.empty?
438
+ parts.join(" with ")
439
+ end
440
+
441
+ # Save in the file's original format? The user's answer for this buffer
442
+ # (true = keep, false = convert to UTF-8 + LF), set when asked on save.
443
+ attr_accessor :keep_file_format
444
+
445
+ # The decision for the next save: the answer given for this buffer, else
446
+ # cnf.file_format.on_save ("keep" / "convert"); nil = ask.
447
+ def keep_file_format_on_save
448
+ return @keep_file_format unless @keep_file_format.nil?
449
+ case cnf.file_format.on_save!
450
+ when "keep" then true
451
+ when "convert" then false
452
+ end
453
+ end
454
+
455
+ # What saving will do with this file's format, for the message shown on load.
456
+ def file_format_save_note
457
+ case keep_file_format_on_save
458
+ when true then "it will be saved in that format"
459
+ when false then "it will be saved as UTF-8 with LF"
460
+ else "you will be asked on first save whether to keep it"
461
+ end
462
+ end
463
+
464
+ def ask_file_format(&after)
465
+ params = {}
466
+ params["title"] = "#{CGI.escapeHTML(File.basename(@fname))} is #{file_format_desc}.\nSave it in that format?"
467
+ params["inputs"] = {}
468
+ params["inputs"]["keep_btn"] = { :label => "Keep #{file_format_desc}", :type => :button, :default_focus => true }
469
+ params["inputs"]["convert_btn"] = { :label => "Convert to UTF-8 with LF", :type => :button }
470
+ params[:callback] = proc { |x|
471
+ @keep_file_format = x["keep_btn"] == "submit"
472
+ after&.call
473
+ }
474
+ PopupFormGenerator.new(params).run
475
+ end
476
+
477
+ # The bytes to write for content in the file's chosen format, or nil when
478
+ # saving as UTF-8 + \n. Falls back to UTF-8 (with a message) if the text has
479
+ # characters the original encoding cannot hold.
480
+ def encode_for_disk(content)
481
+ return nil if file_format_desc.nil? || !keep_file_format_on_save
482
+ s = @file_format[:crlf] ? content.gsub("\n", "\r\n") : content.dup
483
+ enc = @file_format[:encoding]
484
+ begin
485
+ s = s.encode(enc) unless [Encoding::UTF_8, Encoding::US_ASCII].include?(enc)
486
+ rescue Encoding::UndefinedConversionError => ex
487
+ message("Cannot save #{File.basename(@fname)} as #{enc.name} (#{ex.error_char.dump} has no #{enc.name} code); saved as UTF-8")
488
+ @file_format = { encoding: Encoding::UTF_8, crlf: @file_format[:crlf] }
489
+ end
490
+ s.b
491
+ end
492
+
333
493
  def revert()
334
494
  return if !@fname
335
495
  return if !File.exist?(@fname)
336
496
  message("Revert buffer #{@fname}")
337
- str = read_file("", @fname)
338
- self.set_content(str)
497
+ str, fmt = read_file_with_format(@fname)
498
+ @file_format = fmt
499
+ str << "\n" if str[-1] != "\n"
500
+ _fold_state
501
+ if !@folds.empty? || (cnf.fold.start_closed? && str =~ FOLD_START_RE)
502
+ # Folded text is not in the buffer as it is on disk, so a diff would
503
+ # not line up: replace wholesale, keep cursor and view by line number.
504
+ revert_by_replace(str)
505
+ else
506
+ revert_by_diff(str)
507
+ end
339
508
  @last_save = Time.now
340
509
  refresh_title
341
510
  end
342
511
 
512
+ # Reload by applying only the differences as deltas, so that cursor, marks
513
+ # and edit positions move with the text around them (e.g. after the file
514
+ # was edited by an external program). The reload is one undo step.
515
+ def revert_by_diff(str)
516
+ return if str == self.to_s
517
+ v = view
518
+ top = v&.top_visible_pos
519
+ nvis = v&.visible_line_count
520
+ cur = @pos
521
+ new_undo_group
522
+ @reloading = true
523
+ for d in diff_deltas(str)
524
+ top = shift_pos_by_delta(top, d) if top
525
+ cur = shift_pos_by_delta(cur, d)
526
+ add_delta(d, true)
527
+ end
528
+ @reloading = false
529
+ new_undo_group
530
+ set_pos(cur.clamp(0, [self.size - 1, 0].max))
531
+ return if v.nil?
532
+ # Keep the same text at the top of the view, unless that would leave the
533
+ # cursor off screen (many lines added between them).
534
+ top = nil if top && nvis && @pos >= top && get_line_and_col_pos(@pos)[0] - get_line_and_col_pos(top)[0] >= nvis
535
+ top = nil if top && @pos < top
536
+ v.handle_deltas(scroll: top.nil?)
537
+ v.scroll_to_top_pos(top) if top
538
+ end
539
+
540
+ def revert_by_replace(str)
541
+ v = view
542
+ top = v&.top_visible_pos
543
+ toplnum = top ? get_line_and_col_pos(top)[0] : nil
544
+ (lnum, col) = [@lpos, @cpos]
545
+ self.set_content(str)
546
+ lnum = lnum.clamp(0, @line_ends.size - 1)
547
+ set_line_and_column_pos(lnum, col)
548
+ if v && toplnum
549
+ toplnum = toplnum.clamp(0, @line_ends.size - 1)
550
+ v.scroll_to_top_pos(toplnum == 0 ? 0 : @line_ends[toplnum - 1] + 1)
551
+ end
552
+ end
553
+
554
+ # Map position p over delta d. An insert at p moves p only when it is a
555
+ # whole-line insert (ends in "\n"), so text added above a line start pushes
556
+ # it down but text added after the cursor on the same spot does not.
557
+ def shift_pos_by_delta(p, d)
558
+ if d[1] == INSERT
559
+ return p + d[2] if d[0] < p || (d[0] == p && d[3].end_with?("\n"))
560
+ elsif d[1] == DELETE
561
+ return d[0] if p >= d[0] && p < d[0] + d[2]
562
+ return p - d[2] if p >= d[0] + d[2]
563
+ end
564
+ p
565
+ end
566
+
567
+ # Deltas (in application order) that turn the buffer contents into newstr.
568
+ # Diffs by line, then by char inside each changed hunk so positions on
569
+ # lines that were only partly edited map precisely.
570
+ def diff_deltas(newstr)
571
+ deltas = []
572
+ pos = 0 # Position in the partially updated buffer
573
+ for (op, a, b) in myers_diff(self.lines, newstr.lines, 1000)
574
+ if op == :eq
575
+ pos += a.sum(&:size)
576
+ next
577
+ end
578
+ del = a.join
579
+ ins = b.join
580
+ parts = [[:change, del, ins]]
581
+ if !del.empty? && !ins.empty? && del.size + ins.size < 4000
582
+ parts = myers_diff(del.chars, ins.chars, 300).map { |(o, x, y)| [o, x.join, y.join] }
583
+ end
584
+ for (o, x, y) in parts
585
+ if o == :eq
586
+ pos += x.size
587
+ next
588
+ end
589
+ deltas << [pos, DELETE, x.size] if !x.empty?
590
+ if !y.empty?
591
+ deltas << [pos, INSERT, y.size, y]
592
+ pos += y.size
593
+ end
594
+ end
595
+ end
596
+ deltas
597
+ end
598
+
599
+ # Myers diff of arrays a and b. Returns [[:eq, items, items] or
600
+ # [:change, deleted, inserted], ...]. If more than max_d edits are needed,
601
+ # the differing middle is returned as one :change.
602
+ def myers_diff(a, b, max_d)
603
+ # Common prefix/suffix are cheap and usually most of the input
604
+ pre = 0
605
+ pre += 1 while pre < a.size && pre < b.size && a[pre] == b[pre]
606
+ suf = 0
607
+ suf += 1 while suf < a.size - pre && suf < b.size - pre && a[-1 - suf] == b[-1 - suf]
608
+ am = a[pre...(a.size - suf)]
609
+ bm = b[pre...(b.size - suf)]
610
+ ops = [] # [:eq|:del|:ins, item]
611
+ n = am.size
612
+ m = bm.size
613
+ trace = []
614
+ v = { 1 => 0 }
615
+ found = false
616
+ (0..[n + m, max_d].min).each { |d|
617
+ trace << v.dup
618
+ (-d..d).step(2) { |k|
619
+ x = (k == -d || (k != d && v[k - 1] < v[k + 1])) ? v[k + 1] : v[k - 1] + 1
620
+ y = x - k
621
+ while x < n && y < m && am[x] == bm[y]
622
+ x += 1
623
+ y += 1
624
+ end
625
+ v[k] = x
626
+ if x >= n && y >= m
627
+ found = true
628
+ break
629
+ end
630
+ }
631
+ break if found
632
+ }
633
+ if found
634
+ x = n
635
+ y = m
636
+ (trace.size - 1).downto(0) { |d|
637
+ vd = trace[d]
638
+ k = x - y
639
+ prev_k = (k == -d || (k != d && vd[k - 1] < vd[k + 1])) ? k + 1 : k - 1
640
+ prev_x = d == 0 ? 0 : vd[prev_k]
641
+ prev_y = prev_x - prev_k
642
+ while x > prev_x && y > prev_y
643
+ x -= 1
644
+ y -= 1
645
+ ops << [:eq, am[x]]
646
+ end
647
+ break if d == 0
648
+ if x == prev_x
649
+ ops << [:ins, bm[y - 1]]
650
+ else
651
+ ops << [:del, am[x - 1]]
652
+ end
653
+ x = prev_x
654
+ y = prev_y
655
+ }
656
+ ops.reverse!
657
+ else
658
+ am.each { |e| ops << [:del, e] }
659
+ bm.each { |e| ops << [:ins, e] }
660
+ end
661
+
662
+ res = []
663
+ res << [:eq, a[0...pre], a[0...pre]] if pre > 0
664
+ for (op, e) in ops
665
+ if op == :eq
666
+ res << [:eq, [], []] if res.empty? || res[-1][0] != :eq
667
+ res[-1][1] << e
668
+ res[-1][2] << e
669
+ else
670
+ res << [:change, [], []] if res.empty? || res[-1][0] != :change
671
+ res[-1][op == :del ? 1 : 2] << e
672
+ end
673
+ end
674
+ res << [:eq, a[(a.size - suf)..], a[(a.size - suf)..]] if suf > 0
675
+ res
676
+ end
677
+
343
678
  def init_encrypted(crypt:, filename:, encrypted:)
344
679
  @crypt = crypt
345
680
  @encrypted_str = encrypted
@@ -381,10 +716,15 @@ class Buffer < String
381
716
  str << "\n"
382
717
  end
383
718
 
719
+ # Any previously stashed folds refer to the text being replaced (fold.rb);
720
+ # with cnf.fold.start_closed the new content loads with all folds collapsed.
721
+ fold_reset
722
+ str = fold_collapse_all(str) if cnf.fold.start_closed?
723
+
384
724
  self.replace(str)
385
725
  @line_ends = scan_indexes(self, /\n/)
386
726
  words = scan_all_words
387
- Autocomplete.add_words(words)
727
+ Autocomplete.add_words(words, @id)
388
728
 
389
729
  if cnf.btree.experimental?
390
730
  @bt = BufferTree.new(self)
@@ -485,16 +825,20 @@ class Buffer < String
485
825
  @lsp.handle_delta(dc, @fname, @version)
486
826
  end
487
827
  pos = delta[0]
488
- if @edit_pos_history.any? and (@edit_pos_history.last - pos).abs <= 2
489
- @edit_pos_history.pop
490
- end
828
+ # Reloading from disk keeps the user's own edit positions (shifted by
829
+ # update_index) instead of recording the external changes.
830
+ if !@reloading
831
+ if @edit_pos_history.any? and (@edit_pos_history.last - pos).abs <= 2
832
+ @edit_pos_history.pop
833
+ end
491
834
 
492
- lsp = get_line_start(pos)
835
+ lsp = get_line_start(pos)
493
836
 
494
- if @edit_pos_history[-1] != lsp
495
- @edit_pos_history << lsp
837
+ if @edit_pos_history[-1] != lsp
838
+ @edit_pos_history << lsp
839
+ end
840
+ @edit_pos_history_i = 0
496
841
  end
497
- @edit_pos_history_i = 0
498
842
 
499
843
  if delta[1] == DELETE
500
844
  delta[3] = self.slice!(delta[0], delta[2])
@@ -560,6 +904,14 @@ class Buffer < String
560
904
  @marks[k] = @marks[k] + changeamount
561
905
  end
562
906
  end
907
+ # The panel shows each mark's line number and text
908
+ if equal?(vma.buf) && @marks.keys.any? { |k| k.is_a?(String) && k.size == 1 }
909
+ vma.gui&.file_panel_marks_changed
910
+ end
911
+ # Keep closed-fold placeholder anchors (fold.rb) in sync with edits elsewhere.
912
+ @fold_anchors&.each_key do |k|
913
+ @fold_anchors[k] = @fold_anchors[k] + changeamount if @fold_anchors[k] > pos
914
+ end
563
915
  end
564
916
 
565
917
  # Flush @current_group into @edit_history and start a new group.
@@ -608,23 +960,21 @@ class Buffer < String
608
960
  end
609
961
 
610
962
  def get_com_str()
611
- # return nil if @syntax_detect_failed
612
-
613
963
  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
964
 
622
- if !@lang_nfo.nil?
623
- com_str = @lang_nfo.get_metadata("line-comment-start")
965
+ # User config: rules matched against filename in order, first match wins.
966
+ if @fname
967
+ fname_base = File.basename(@fname)
968
+ rules = cnf.comment_chars!
969
+ if rules.is_a?(Array)
970
+ match = rules.find { |r| fname_base.match?(r[:pattern]) }
971
+ com_str = match[:char] if match
972
+ end
624
973
  end
625
974
 
626
- # lang.get_metadata("block-comment-start")
627
- # lang.get_metadata("block-comment-end")
975
+ if com_str.nil? && !@lang_nfo.nil?
976
+ com_str = @lang_nfo.get_metadata("line-comment-start")
977
+ end
628
978
 
629
979
  com_str = "//" if com_str.nil?
630
980
 
@@ -661,11 +1011,8 @@ class Buffer < String
661
1011
 
662
1012
  a = @line_ends[-1] if a == nil
663
1013
  a = 0 if a == nil
664
- if a > 0
665
- a = a - 1
666
- else
667
- a = 0
668
- end
1014
+ return 0 if a == 0 # First line
1015
+ a = a - 1
669
1016
  ls = nil
670
1017
  ls = @line_ends[a] if a != nil
671
1018
  # if a != nil and ls != @line_ends[a]
@@ -749,13 +1096,15 @@ class Buffer < String
749
1096
  return start.._End
750
1097
  end
751
1098
 
752
- def copy(range_id)
1099
+ def copy(range_id, mark = nil)
753
1100
  @paste_lines = false
754
1101
  debug "range_id: #{range_id}"
755
1102
  debug range_id.inspect
756
- range = get_range(range_id)
1103
+ range = get_range(range_id, mark: mark)
1104
+ return if range.nil?
757
1105
  debug range.inspect
758
1106
  vma.clipboard.set(self[range])
1107
+ Gui.flash_range(self, range)
759
1108
  end
760
1109
 
761
1110
  def recalc_line_ends()
@@ -865,6 +1214,17 @@ class Buffer < String
865
1214
  else
866
1215
  return nil
867
1216
  end
1217
+ elsif range_id == :to_char # vim d f <char>: up to and including next <char> on line
1218
+ lend = @line_ends[@lpos]
1219
+ cpos = self.index(mark, @pos + 1)
1220
+ return nil if cpos.nil? or cpos >= lend
1221
+ range = @pos..cpos
1222
+ elsif range_id == :to_char_backward # vim d F <char>: from prev <char> on line, excluding cursor
1223
+ lstart = @lpos == 0 ? 0 : @line_ends[@lpos - 1] + 1
1224
+ return nil if @pos <= lstart
1225
+ cpos = self.rindex(mark, @pos - 1)
1226
+ return nil if cpos.nil? or cpos < lstart
1227
+ range = cpos..(@pos - 1)
868
1228
  elsif range_id == :to_line_end
869
1229
  debug "TO LINE END"
870
1230
  range = @pos..(@line_ends[@lpos] - 1)
@@ -979,6 +1339,13 @@ class Buffer < String
979
1339
 
980
1340
  def mark_current_position(mark_char)
981
1341
  @marks[mark_char] = @pos
1342
+ vma.gui&.file_panel_marks_changed if equal?(vma.buf)
1343
+ end
1344
+
1345
+ # Marks set with m <char>, as { char => pos } sorted by char. @marks also
1346
+ # holds internal entries (e.g. bookmarks' "bm:<id>"), which are excluded.
1347
+ def user_marks
1348
+ @marks.select { |k, _| k.is_a?(String) && k.size == 1 }.sort.to_h
982
1349
  end
983
1350
 
984
1351
  # Get positions of last characters in words
@@ -1021,11 +1388,11 @@ class Buffer < String
1021
1388
  elsif wtype == :linepointer
1022
1389
  jump_to_file(word[0], word[1], word[2])
1023
1390
  elsif wtype == :textfile
1024
- open_existing_file(word)
1391
+ open_new_file(word)
1025
1392
  elsif wtype == :file
1026
1393
  open_with_default_program(word)
1027
1394
  elsif wtype == :hpt_link
1028
- open_existing_file(word)
1395
+ open_new_file(word)
1029
1396
  elsif wtype == :help
1030
1397
  if word == "keybindings"
1031
1398
  call_action(:show_key_bindings)
@@ -1044,6 +1411,7 @@ class Buffer < String
1044
1411
  # m << ["Sort", self.method("convert_selected_text"), :sortlines]
1045
1412
  m << ["Sort", method("call"), :sortlines]
1046
1413
  m << ["Filter: get numbers", method("call"), :getnums_on_lines]
1414
+ m << ["To LaTeX itemize", method("call"), :latex_itemize]
1047
1415
  m << ["Delete selection", method("call"), :delete_selection]
1048
1416
 
1049
1417
  # m << ["Search in dictionary", self.method("handle_word"), nil]
@@ -1071,6 +1439,8 @@ class Buffer < String
1071
1439
 
1072
1440
  # Activated when enter/return pressed
1073
1441
  def handle_line_action()
1442
+ # Enter on a fold-start ({{{) or a closed-fold placeholder toggles the fold.
1443
+ return if fold_toggle_at(lpos)
1074
1444
  if line_action_handler.class == Proc or line_action_handler.class == Method
1075
1445
  # Custom handler
1076
1446
  line_action_handler.call(lpos)
@@ -1150,6 +1520,48 @@ class Buffer < String
1150
1520
  return [word, wtype]
1151
1521
  end
1152
1522
 
1523
+ # Existing file named by the whitespace-delimited word at pos, or nil.
1524
+ # Surrounding quotes, brackets and punctuation are ignored ("(foo.pdf)." ->
1525
+ # foo.pdf). Relative names resolve against this buffer's directory, then the
1526
+ # last used directory, then the working directory.
1527
+ def file_path_at(pos)
1528
+ word, _range = get_word_in_pos(pos, boundary: :space)
1529
+ return nil if word.nil?
1530
+ resolve_file_path(word)
1531
+ end
1532
+
1533
+ # Absolute path of the existing file that word names, or nil. See
1534
+ # file_path_at for the rules.
1535
+ def resolve_file_path(word)
1536
+ word = word.strip.sub(/\A[("'`\[<{]+/, "").sub(/[)"'`\]>},.;:!?]+\z/, "")
1537
+ return nil if word.empty? or is_url(word)
1538
+ if word.start_with?("/", "~")
1539
+ cands = [File.expand_path(word)]
1540
+ else
1541
+ dirs = [@fname && File.dirname(@fname), bufs.last_dir, Dir.pwd].compact.uniq
1542
+ cands = dirs.map { |d| File.expand_path(word, d) }
1543
+ end
1544
+ cands.find { |p| File.file?(p) }
1545
+ end
1546
+
1547
+ # Absolute paths of the existing files named in this buffer, unique, in
1548
+ # order of first appearance: whitespace-separated words (as for
1549
+ # file_path_at) and hyperplaintext links ⟦path⟧ / ⟦img:path⟧ / ⟦audio:path⟧.
1550
+ # Like hpt_check_cur_word, a link may leave out a ".txt" extension. Plain
1551
+ # words are only checked if they contain "." or "/", which skips most text.
1552
+ def file_links
1553
+ found = []
1554
+ to_s.scan(/⟦(?:(?:audio|img):)?([^⟧]+)⟧|(\S+)/).uniq.each do |link, word|
1555
+ if link
1556
+ p = resolve_file_path(link) || resolve_file_path("#{link}.txt")
1557
+ elsif word.include?(".") or word.include?("/")
1558
+ p = resolve_file_path(word)
1559
+ end
1560
+ found << p if p
1561
+ end
1562
+ found.uniq
1563
+ end
1564
+
1153
1565
  def cur_nonwhitespace_word_action()
1154
1566
 
1155
1567
  # (word, wtype) = get_cur_nonwhitespace_word()
@@ -1249,6 +1661,12 @@ class Buffer < String
1249
1661
  #need_redraw!
1250
1662
  #@pos += c.size
1251
1663
  # end_profiler
1664
+
1665
+ # Covers both the key binding path and the Wayland IM insert-text path
1666
+ if vma.kbd&.get_mode == :insert
1667
+ v = (self.view rescue nil)
1668
+ v.autocp_on_insert(c) if v.respond_to?(:autocp_on_insert)
1669
+ end
1252
1670
  end
1253
1671
 
1254
1672
  # Update buffer contents to newstr
@@ -1312,6 +1730,16 @@ class Buffer < String
1312
1730
  @visual_mode = true #TODO: change use of @visual_mode into @selection_active
1313
1731
  end
1314
1732
 
1733
+ # Select the whole buffer (cursor lands on the final char)
1734
+ def select_all()
1735
+ return false if self.size == 0
1736
+ @selection_start = 0
1737
+ @selection_active = true
1738
+ @visual_mode = true # copy/delete of SELECTION are guarded by @visual_mode
1739
+ set_pos(self.size - 1)
1740
+ return true
1741
+ end
1742
+
1315
1743
  # Start selection if not already started
1316
1744
  def continue_selection()
1317
1745
  start_selection if !@selection_active
@@ -1334,19 +1762,60 @@ class Buffer < String
1334
1762
  return true
1335
1763
  end
1336
1764
 
1337
- def transform_selection(op)
1765
+ # Apply a text transform to the current visual selection: yields the selected
1766
+ # text, replaces the range with the block's return value, and ends visual
1767
+ # mode. No-op returning nil when not in visual mode; otherwise returns the
1768
+ # replacement text (truthy), so callers can guard follow-up work on it.
1769
+ def transform_visual_selection
1338
1770
  return if !@visual_mode
1339
1771
  r = get_visual_mode_range
1340
- txt = self[r]
1772
+ txt = yield(self[r])
1773
+ replace_range(r, txt)
1774
+ end_visual_mode
1775
+ txt
1776
+ end
1777
+
1778
+ # Wrap `txt` with hyperplaintext style markers for `op`, or strip all markers
1779
+ # when op == :clear. Shared by style_transform (selection) and set_line_style.
1780
+ def apply_style_markers(txt, op)
1781
+ txt = "⦁" + txt + "⦁" if op == :bold
1782
+ txt = "⟦" + txt + "⟧" if op == :link
1783
+ txt = "❙" + txt + "❙" if op == :title
1784
+ txt = "╱" + txt + "╱" if op == :italic
1785
+ txt.gsub!(/[❙◼⟦⟧⦁╱]/, "") if op == :clear
1786
+ txt
1787
+ end
1788
+
1789
+ def transform_text(txt, op)
1341
1790
  txt.upcase! if op == :upcase
1342
1791
  txt.downcase! if op == :downcase
1343
1792
  txt.gsub!(/\w+/, &:capitalize) if op == :capitalize
1344
1793
  txt.swapcase! if op == :swapcase
1345
1794
  txt.reverse! if op == :reverse
1346
1795
  txt = to_camel_case(txt) if op == :camelcase
1796
+ txt
1797
+ end
1347
1798
 
1348
- replace_range(r, txt)
1349
- end_visual_mode
1799
+ def transform_selection(op)
1800
+ transform_visual_selection { |txt| transform_text(txt, op) }
1801
+ end
1802
+
1803
+ # Apply transform `op` to a motion range, like vim's gU/gu/g~ operators.
1804
+ # range_id :line = current line without its newline (gUU); otherwise a
1805
+ # get_range id, e.g. :to_next_word (gUw). Cursor goes to the range start.
1806
+ def transform_range(range_id, op)
1807
+ if range_id == :line
1808
+ lstart = @lpos == 0 ? 0 : @line_ends[@lpos - 1] + 1
1809
+ lend = @line_ends[@lpos]
1810
+ range = lstart < lend ? lstart..(lend - 1) : nil
1811
+ else
1812
+ range = get_range(range_id)
1813
+ end
1814
+ return if range.nil?
1815
+ old = self[range]
1816
+ txt = transform_text(old.dup, op)
1817
+ replace_range(range, txt) if txt != old
1818
+ set_pos(range.first)
1350
1819
  end
1351
1820
 
1352
1821
  def eval_whole_buf(x = 888)
@@ -1359,40 +1828,35 @@ class Buffer < String
1359
1828
  end
1360
1829
  end
1361
1830
 
1831
+ # Apply converter to the visual selection, or to the current line (without
1832
+ # its newline) when not in visual mode.
1362
1833
  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
1834
  #TODO: Detect if changed?
1368
- replace_range(r, txt)
1369
- end_visual_mode
1835
+ if @visual_mode
1836
+ return if !transform_visual_selection { |txt| $vma.apply_conv(converter_id, txt) }
1837
+ else
1838
+ r = line_range(@lpos, 1, false)
1839
+ r = r.begin..(r.begin - 1) if self[r] == "\n" # empty line
1840
+ # Converters may add a trailing newline; the line already has one
1841
+ txt = $vma.apply_conv(converter_id, self[r]).chomp
1842
+ replace_range(r, txt)
1843
+ end
1844
+ view.after_action
1370
1845
  end
1371
1846
 
1372
1847
  def style_transform(op)
1373
- return if !@visual_mode
1374
- r = get_visual_mode_range
1375
1848
  #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
1849
+ transform_visual_selection { |txt| apply_style_markers(txt, op) }
1384
1850
  end
1385
1851
 
1386
1852
  def set_line_style(op)
1387
1853
  lrange = line_range(@lpos, 1, false)
1388
1854
  txt = self[lrange]
1389
- # txt = "◼ " + txt if op == :heading
1390
- txt = "⦁" + txt + "⦁" if op == :bold
1391
- txt = "❙" + txt + "❙" if op == :title
1392
1855
  txt.gsub!(/◼ /, "") if op == :clear
1393
- txt.gsub!(/[❙◼⟦⟧⦁]/, "") if op == :clear or [:h1, :h2, :h3, :h4].include?(op)
1856
+ txt = apply_style_markers(txt, op)
1394
1857
 
1395
1858
  if [:h1, :h2, :h3, :h4].include?(op)
1859
+ txt.gsub!(/[❙◼⟦⟧⦁╱]/, "")
1396
1860
  txt.strip!
1397
1861
  txt = "◼ " + txt if op == :h1
1398
1862
  txt = "◼◼ " + txt if op == :h2
@@ -1403,12 +1867,7 @@ class Buffer < String
1403
1867
  end
1404
1868
 
1405
1869
  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
1870
+ num_lines = get_repeat_num()
1412
1871
  vma.clipboard.set(self[line_range(@lpos, num_lines)])
1413
1872
  @paste_lines = true
1414
1873
  end
@@ -1528,22 +1987,34 @@ class Buffer < String
1528
1987
 
1529
1988
  set_filename(fpath)
1530
1989
  save()
1990
+ # set_filename re-detects the language and drops the LSP client; attach the
1991
+ # one for the new language (e.g. an untitled buffer saved as foo.cpp).
1992
+ init_lsp if cnf.lsp.enabled?
1531
1993
  gui_set_window_title(@title, @subtitle) #TODO: if not active buffer?
1532
1994
  end
1533
1995
 
1534
- def write_contents_to_file(fpath)
1535
- if @crypt != nil
1996
+ # original_format: write in the file's own encoding / line endings when the
1997
+ # user chose to keep them (save only; backups etc. stay UTF-8).
1998
+ def write_contents_to_file(fpath, original_format: false)
1999
+ # content_for_disk re-inflates any closed folds so the file always holds the
2000
+ # fully expanded text (see fold.rb); equals self.to_s when nothing is folded.
2001
+ disk = content_for_disk
2002
+ raw = original_format && @crypt.nil? ? encode_for_disk(disk) : nil
2003
+ if raw
2004
+ mode = "wb"
2005
+ contents = raw
2006
+ elsif @crypt != nil
1536
2007
  mode = "wb+"
1537
- contents = "VMACRYPT001" + @crypt.encrypt(self.to_s)
2008
+ contents = Encrypt::HEADER_V2 + @crypt.encrypt(disk)
1538
2009
  else
1539
2010
  mode = "w+"
1540
- contents = self.to_s
2011
+ contents = disk
1541
2012
  end
1542
2013
 
1543
2014
  Thread.new {
1544
2015
  begin
1545
2016
  io = File.open(fpath, mode)
1546
- io.set_encoding(self.encoding)
2017
+ io.set_encoding(self.encoding) unless raw # raw: already encoded bytes
1547
2018
  io.write(contents)
1548
2019
  io.close
1549
2020
  rescue Encoding::UndefinedConversionError => ex
@@ -1556,11 +2027,19 @@ class Buffer < String
1556
2027
  io.set_encoding(Encoding::UTF_8)
1557
2028
  io.write(contents)
1558
2029
  rescue Errno::EACCES => ex
1559
- message("File #{fpath} not writeable")
2030
+ GLib::Idle.add { message("File #{fpath} not writeable"); false }
1560
2031
  #TODO: show message box
1561
2032
  end
1562
2033
  @last_save = Time.now
1563
- refresh_title
2034
+ GLib::Idle.add { refresh_title; false }
2035
+ if cnf.auto_chmod_exec? && !@crypt && contents.match?(%r{\A#!\s*/\S})
2036
+ begin
2037
+ FileUtils.chmod("+x", fpath)
2038
+ GLib::Idle.add { message("Set executable: #{fpath}"); false }
2039
+ rescue => e
2040
+ GLib::Idle.add { message("chmod failed: #{e}"); false }
2041
+ end
2042
+ end
1564
2043
  debug "file saved on #{@last_save}"
1565
2044
  sleep 3
1566
2045
  }
@@ -1574,22 +2053,24 @@ class Buffer < String
1574
2053
  end
1575
2054
 
1576
2055
  def unsaved_changes?
1577
- pp [@t_modified, @last_save]
1578
2056
  return true if @t_modified > @last_save
1579
2057
  return false
1580
2058
  end
1581
2059
 
1582
2060
  def refresh_title
1583
2061
  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)
2062
+ mod = unsaved_changes?
2063
+ pfx = mod ? "+ " : ""
2064
+ gui_set_window_title(pfx + title, subtitle, modified: mod)
1587
2065
  end
1588
2066
  end
1589
2067
 
1590
2068
  def check_if_modified_outside
1591
2069
  # Don't check if less than 8 seconds since last checked
1592
2070
  return false if @fname.nil?
2071
+ # Tests write and reload files quickly; the reload prompt would pop up
2072
+ # unasked in the middle of a run and take the keyboard with it.
2073
+ return false if vma_test_mode?
1593
2074
  return false if Time.now - 8 < @file_last_cheked
1594
2075
  @file_last_cheked = Time.now
1595
2076
  return false if !File.exist?(@fname)
@@ -1626,7 +2107,7 @@ class Buffer < String
1626
2107
  return if @fname.nil?
1627
2108
  return if @t_modified <= @last_autosave
1628
2109
  apath = autosave_path
1629
- contents = self.to_s
2110
+ contents = content_for_disk # re-inflate closed folds (fold.rb)
1630
2111
  Thread.new {
1631
2112
  begin
1632
2113
  File.open(apath, "w+") { |io| io.set_encoding(self.encoding); io.write(contents) }
@@ -1655,10 +2136,27 @@ class Buffer < String
1655
2136
  debug "delete autosave failed: #{ex}"
1656
2137
  end
1657
2138
 
2139
+ # Run a deferred autosave check the first time a session-restored buffer is
2140
+ # entered. No-op unless flagged (see @needs_autosave_check). Cleared before
2141
+ # the check so it fires at most once.
2142
+ def check_autosave_load_if_pending
2143
+ return unless @needs_autosave_check
2144
+ @needs_autosave_check = false
2145
+ check_autosave_load
2146
+ end
2147
+
1658
2148
  def check_autosave_load
1659
2149
  apath = autosave_path
1660
2150
  return if apath.nil? || !File.exist?(apath)
1661
- if File.read(apath) == self.to_s
2151
+ if File.read(apath) == content_for_disk # autosave stores the inflated form
2152
+ delete_autosave_file
2153
+ return
2154
+ end
2155
+ # The autosave predates the file on disk: the file has been saved/changed
2156
+ # more recently, so the autosave holds an outdated version. Drop it silently
2157
+ # rather than prompting. (A newer autosave — unsaved changes from a crash —
2158
+ # still prompts below.)
2159
+ if File.exist?(@fname) && File.mtime(apath) < File.mtime(@fname)
1662
2160
  delete_autosave_file
1663
2161
  return
1664
2162
  end
@@ -1666,7 +2164,8 @@ class Buffer < String
1666
2164
  params = {
1667
2165
  "title" => title,
1668
2166
  "inputs" => {
1669
- "yes_btn" => { :label => "Load", :type => :button, :default_focus => true },
2167
+ "yes_btn" => { :label => "Load", :type => :button, :default_focus => true },
2168
+ "diff_btn" => { :label => "Review diff", :type => :button },
1670
2169
  "delete_btn" => { :label => "Delete autosave", :type => :button },
1671
2170
  },
1672
2171
  :callback => proc { |x| load_autosave_callback(x) },
@@ -1681,6 +2180,12 @@ class Buffer < String
1681
2180
  @t_modified = Time.now
1682
2181
  refresh_title
1683
2182
  message("Loaded autosave for #{@fname}")
2183
+ elsif x["diff_btn"] == "submit"
2184
+ apath = autosave_path
2185
+ diff_str = run_cmd("diff -u #{Shellwords.escape(@fname)} #{Shellwords.escape(apath)}")
2186
+ create_new_file(nil, diff_str.empty? ? "(no differences)\n" : diff_str)
2187
+ gui_set_file_lang(vma.buf.id, "diff") unless diff_str.empty?
2188
+ check_autosave_load
1684
2189
  elsif x["delete_btn"] == "submit"
1685
2190
  delete_autosave_file
1686
2191
  message("Deleted autosave for #{@fname}")
@@ -1688,13 +2193,18 @@ class Buffer < String
1688
2193
  end
1689
2194
 
1690
2195
  def save()
2196
+ return if @module.respond_to?(:on_save) and @module.on_save
1691
2197
  check_if_modified_outside #TODO
1692
2198
  if !@fname
1693
2199
  save_as()
1694
2200
  return
1695
2201
  end
2202
+ if file_format_desc && keep_file_format_on_save.nil?
2203
+ ask_file_format { save }
2204
+ return
2205
+ end
1696
2206
  message("Saving file #{@fname}")
1697
- write_contents_to_file(@fname)
2207
+ write_contents_to_file(@fname, original_format: true)
1698
2208
  delete_autosave_file
1699
2209
  hook.call(:file_saved, self)
1700
2210
  end
@@ -1735,3 +2245,4 @@ def backup_all_buffers()
1735
2245
  end
1736
2246
  message("Backup all buffers")
1737
2247
  end
2248
+ end # module Vimamsa