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
@@ -1,9 +1,13 @@
1
1
  require "pty"
2
2
 
3
+ module Vimamsa
4
+
3
5
 
4
6
  class Editor
5
7
  attr_reader :file_content_search_paths, :file_name_search_paths, :gui, :hook, :macro, :actions
6
- attr_accessor :converters, :fh, :paint_stack, :kbd, :langsrv, :register, :cur_register, :clipboard
8
+ # @!attribute [rw] kbd
9
+ # @return [KeyBindingTree]
10
+ attr_accessor :converters, :fh, :bookmarks, :paint_stack, :kbd, :langsrv, :register, :cur_register, :clipboard
7
11
  #attr_writer :call_func, :update_highlight
8
12
 
9
13
  def initialize()
@@ -43,16 +47,86 @@ class Editor
43
47
  File.delete(fp)
44
48
  for f in x.lines
45
49
  f.gsub!("\n", "")
46
- if File.exist?(f)
47
- if file_is_text_file(f)
48
- jump_to_file(f)
50
+ fpath = f.dup
51
+ if !File.exist?(fpath)
52
+ GLib::Idle.add do
53
+ Gui.confirm("File does not exist. Create new file?\r #{fpath}",
54
+ proc {
55
+ FileUtils.mkdir_p(File.dirname(fpath))
56
+ IO.write(fpath, "")
57
+ jump_to_file(fpath)
58
+ })
59
+ false
49
60
  end
61
+ else
62
+ # open_new_file reports files it cannot open (e.g. not text)
63
+ GLib::Idle.add { jump_to_file(fpath); false }
50
64
  end
51
65
  end
52
66
  end
53
67
  end
54
68
  end
55
69
 
70
+ # Connect the host-agnostic KeyBindingTree to this editor: action dispatch,
71
+ # logging, and the side effects of mode/state changes (undo grouping,
72
+ # autocomplete dismissal, mode stack sync, cursor redraw, GUI badge/keylog).
73
+ def setup_kbd_handlers
74
+ @kbd.action_handler = method(:exec_action)
75
+ @kbd.logger = method(:debug)
76
+ @kbd.fatal_handler = method(:fatal_error)
77
+ # Non-fatal binding problems (e.g. custom.rb binding to an unknown mode).
78
+ # message() can fire before the minibuffer exists (custom.rb is loaded
79
+ # during start), so it must not be allowed to break startup.
80
+ @kbd.error_handler = proc { |msg|
81
+ warn msg
82
+ begin
83
+ message(msg)
84
+ rescue Exception
85
+ end
86
+ }
87
+ @kbd.on_action_error = proc { |action, e|
88
+ if e.is_a?(SyntaxError)
89
+ message("SYNTAX ERROR with eval cmd #{action}: " + e.to_s)
90
+ else
91
+ puts "BACKTRACE"
92
+ puts e.backtrace
93
+ puts e.inspect
94
+ puts "BACKTRACE END"
95
+ if e.is_a?(SystemExit)
96
+ exit
97
+ else
98
+ crash("Error with action: #{action}: ", e)
99
+ end
100
+ end
101
+ }
102
+
103
+ @kbd.on(:mode_set) { |label| vma.buf&.new_undo_group }
104
+ @kbd.on(:mode_changed) { |label|
105
+ if label != :insert
106
+ # Dismiss the autocomplete popup when leaving insert mode
107
+ v = (vma.buf&.view rescue nil)
108
+ v.hide_completions if v.respond_to?(:hide_completions)
109
+ end
110
+ if @kbd.get_scope != :editor and !vma.buf.nil?
111
+ vma.buf.mode_stack = @kbd.default_mode_stack.clone
112
+ end
113
+ vma.gui.view.draw_cursor() if !vma.gui.view.nil?
114
+ }
115
+ @kbd.on(:state_trail_changed) { |badge, badge_key, trail|
116
+ vma.gui.update_mode_badge(badge, badge_key, trail)
117
+ }
118
+ @kbd.on(:key_no_match) { |c, trail| vma.gui.keylog_panel&.log_nomatch(c, trail) }
119
+ @kbd.on(:key_pending) { |trail| vma.gui.keylog_panel&.log_pending(trail) }
120
+ @kbd.on(:key_action) { |trail, action| vma.gui.keylog_panel&.log_action(trail, action) }
121
+ @kbd.on(:action_executed) { |action, ret|
122
+ if vma.macro.is_recording and ret != false
123
+ debug "RECORD ACTION:#{action}", 2
124
+ vma.macro.record_action(action)
125
+ end
126
+ }
127
+ @kbd.on(:action_handled) { |trail, action| vma.gui.show_action_trail(trail, action) }
128
+ end
129
+
56
130
  def start
57
131
  @gui = $vmag #TODO
58
132
 
@@ -69,9 +143,32 @@ class Editor
69
143
  register_plugin(:Search, $search)
70
144
 
71
145
  # build_key_bindings_tree
72
- @kbd = KeyBindingTree.new()
73
- $kbd = @kbd #TODO: remove global
74
- require "vimamsa/key_bindings_vimlike"
146
+ @kbd = KeyBindingTree.new(actions: @actions)
147
+ setup_kbd_handlers
148
+
149
+ # Load user settings early so the keybinding scheme choice is available
150
+ # before the binding tree is populated. custom.rb still loads later.
151
+ settings_path = get_dot_path("settings.rb")
152
+ if File.exist?(settings_path)
153
+ begin
154
+ eval(IO.read(settings_path))
155
+ rescue Exception => e
156
+ message("Error in settings.rb: #{e}")
157
+ end
158
+ end
159
+
160
+ scheme = cnf.keybindings.scheme! || "vimlike"
161
+ # Tests assume the default scheme regardless of user settings;
162
+ # test files load scheme overrides themselves when needed.
163
+ scheme = "vimlike" if ARGV.include?("--test")
164
+ case scheme
165
+ when "notepad"
166
+ require "vimamsa/key_bindings_notepad"
167
+ when "vim"
168
+ require "vimamsa/key_bindings_vim"
169
+ else
170
+ require "vimamsa/key_bindings_vimlike"
171
+ end
75
172
 
76
173
  $buffers = BufferList.new
77
174
  $minibuffer = Buffer.new(">", "")
@@ -84,12 +181,12 @@ class Editor
84
181
  sleep(0.03)
85
182
 
86
183
  BufferManager.init
184
+ Bookmarks.init
87
185
 
88
186
  @gui.init_menu
89
187
 
90
188
  mkdir_if_not_exists(get_dot_path(""))
91
189
  mkdir_if_not_exists(get_dot_path("backup"))
92
- mkdir_if_not_exists(get_dot_path("testfoobar")) #TODO
93
190
  listen_dir = get_dot_path("listen")
94
191
  mkdir_if_not_exists(listen_dir)
95
192
  listener = Listen.to(listen_dir) do |modified, added, removed|
@@ -104,11 +201,13 @@ class Editor
104
201
  IO.write(custom_fn, example_custom)
105
202
  end
106
203
 
107
- settings_path = get_dot_path("settings.rb")
108
- if File.exist?(settings_path)
109
- eval(IO.read(settings_path))
110
- end
204
+ # Install desktop launcher + icon into ~/.local/share on first run.
205
+ install_desktop_integration
111
206
 
207
+ # Phase 1 of custom.rb: the body of the file. Runs before the inits below so
208
+ # that cnf.* set there is visible to them. Anything that needs modes/actions
209
+ # they register goes in phase 2 (hook_custom_after_init, called at the end of
210
+ # start; see call_custom_after_init).
112
211
  custom_script = read_file("", custom_fn)
113
212
  eval(custom_script) if custom_script
114
213
 
@@ -148,11 +247,12 @@ class Editor
148
247
  fname_ = File.expand_path(cnf.startup_file!)
149
248
  if File.exist?(fname_)
150
249
  fname = fname_
250
+ @startup_fname = fname_
151
251
  end
152
252
  else
153
253
  # fname = ppath("demo.txt")
154
254
  end
155
- fname = ARGV[0] if ARGV.size >= 1 and File.file?(File.expand_path(ARGV[0]))
255
+ fname = ARGV[0] if ARGV.size >= 1 and File.file?(File.expand_path(ARGV[0])) and !ARGV.include?("--test")
156
256
  # vma.add_content_search_path(Dir.pwd)
157
257
  for fn in ARGV
158
258
  fn = File.expand_path(fn)
@@ -162,7 +262,7 @@ class Editor
162
262
  end
163
263
  end
164
264
 
165
- argv_has_files = ARGV.any? { |a| File.file?(File.expand_path(a)) }
265
+ argv_has_files = !ARGV.include?("--test") && ARGV.any? { |a| File.file?(File.expand_path(a)) }
166
266
 
167
267
  if fname
168
268
  open_new_file(fname)
@@ -170,25 +270,56 @@ class Editor
170
270
  create_new_buffer(file_contents = "\n")
171
271
  end
172
272
 
273
+ gui.restore_view_layout
274
+
173
275
  #Load plugins
174
276
  require "vimamsa/file_history.rb"
175
277
  @fh = FileHistory.new
176
278
  @_plugins[:FileHistory] = @fh
279
+ @bookmarks = Bookmarks.new
177
280
 
178
281
  register_plugin(:FileHistory, @fh)
179
282
  register_plugin(:FileFinder, FileFinder.new)
180
283
  # To access via vma.FileFinder
181
284
  # self.define_singleton_method(:FileFinder) { @_plugins[:FileFinder] }
182
285
 
183
- check_session_restore unless argv_has_files
286
+ # Not in test mode: the dialog grabs focus from the editor window, which
287
+ # breaks (and is never the subject of) an automated run.
288
+ check_session_restore unless argv_has_files || vma_test_mode?
184
289
 
185
290
  @hook.call(:after_init)
186
291
 
292
+ # Phase 2 of custom.rb: everything (modules, plugins, buffers) now exists.
293
+ call_custom_after_init
294
+
295
+ # Paint the initial mode badge (e.g. COMMAND). show_state_trail is otherwise
296
+ # only called from key handling, so without this the badge stays blank until
297
+ # the first keypress. set_state_to_root populates @state_trail the same way
298
+ # the key handler does before rendering.
299
+ @kbd.set_state_to_root
300
+ @kbd.show_state_trail
301
+
302
+ # AppImage: from here on, started programs get the user's environment
303
+ restore_host_env
304
+
187
305
  if ARGV.include?("--test")
188
306
  test_files = ARGV.select { |a| a.end_with?(".rb") && File.file?(a) }
189
307
  run_as_idle proc {
190
308
  test_files.each { |f| load f }
191
- success = run_vma_tests
309
+ classes = if $vma_test_class_filter
310
+ $vma_test_class_filter.filter_map { |name|
311
+ begin
312
+ Object.const_get(name)
313
+ rescue NameError
314
+ puts "Unknown test class: #{name}"
315
+ nil
316
+ end
317
+ }
318
+ else
319
+ []
320
+ end
321
+ success = run_vma_tests(*classes)
322
+ $vma_tests_ok = success # exe/run_tests.rb turns this into the exit code
192
323
  # Defer shutdown so GTK can drain all pending idle callbacks from test
193
324
  # teardown before widget destruction begins (avoids heap corruption).
194
325
  GLib::Timeout.add(300) { shutdown(); false }
@@ -258,7 +389,9 @@ class Editor
258
389
  @gui.quit
259
390
  end
260
391
 
392
+ # Window size and view layout (see VMAgui#save_window_layout)
261
393
  def save_state
394
+ @gui.save_window_layout
262
395
  end
263
396
 
264
397
  def save_session
@@ -280,6 +413,13 @@ class Editor
280
413
  fnames.reject! { |f| vma.buffers.get_buffer_by_filename(f) }
281
414
  return if fnames.empty?
282
415
 
416
+ # After a restart (restart_editor) reopen the previous files silently.
417
+ if ENV["VIMAMSA_RESTORE_SESSION"]
418
+ restore_session_files(fnames)
419
+ message("Session restored: #{fnames.size} file(s)")
420
+ return
421
+ end
422
+
283
423
  n = fnames.size
284
424
  label = n == 1 ? "1 file" : "#{n} files"
285
425
  params = {
@@ -290,9 +430,7 @@ class Editor
290
430
  },
291
431
  :callback => proc { |x|
292
432
  if x["yes_btn"] == "submit"
293
- initial = vma.buffers.list.find { |b| b.fname.nil? }
294
- fnames.each { |f| load_buffer(f) }
295
- initial&.close
433
+ restore_session_files(fnames)
296
434
  message("Session restored: #{label}")
297
435
  end
298
436
  },
@@ -300,6 +438,18 @@ class Editor
300
438
  PopupFormGenerator.new(params).run
301
439
  end
302
440
 
441
+ def restore_session_files(fnames)
442
+ initial = vma.buffers.list.find { |b| b.fname.nil? }
443
+ fnames.each { |f| b = load_buffer(f); b&.needs_autosave_check = true }
444
+ initial&.close
445
+ # Loading the session switches to its last file; cnf.startup_file stays
446
+ # the buffer shown on startup.
447
+ if @startup_fname and (id = vma.buffers.get_buffer_by_filename(@startup_fname))
448
+ vma.buffers.set_current_buffer(id)
449
+ end
450
+ gui.restore_column2_buffer
451
+ end
452
+
303
453
  def add_content_search_path(pathstr)
304
454
  p = File.expand_path(pathstr)
305
455
  if !@file_content_search_paths.include?(p)
@@ -368,30 +518,6 @@ def open_file_dialog()
368
518
  gui_open_file_dialog(File.dirname(path))
369
519
  end
370
520
 
371
- class Clipboard
372
- def initialize
373
- @clipboard = []
374
- end
375
-
376
- def set(s)
377
- if !(s.class <= String) or s.size == 0
378
- debug s.inspect
379
- debug [s, s.class, s.size]
380
- log_error("s.class != String or s.size == 0")
381
- return
382
- end
383
- @clipboard << s
384
- set_system_clipboard(s)
385
- vma.register[vma.cur_register] = s
386
- debug "SET CLIPBOARD: [#{s}]"
387
- debug "REGISTER: #{vma.cur_register}:#{vma.register[vma.cur_register]}"
388
- end
389
-
390
- def get()
391
- return @clipboard[-1]
392
- end
393
- end
394
-
395
521
  def set_cursor_pos(new_pos)
396
522
  buf.set_pos(new_pos)
397
523
  #render_buffer(vma.buf)
@@ -530,7 +656,12 @@ def load_buffer(fname)
530
656
  return nil
531
657
  end
532
658
  debug("LOAD BUFFER: #{fname}")
533
- buffer = Buffer.new(read_file("", fname), fname)
659
+ content, fmt = read_file_with_format(fname)
660
+ buffer = Buffer.new(content, fname)
661
+ buffer.file_format = fmt
662
+ if buffer.file_format_desc
663
+ message("#{File.basename(fname)} is #{buffer.file_format_desc}; #{buffer.file_format_save_note}")
664
+ end
534
665
  # gui_set_current_buffer(buffer.id)
535
666
  buffer.set_active
536
667
  debug("DONE LOAD: #{fname}")
@@ -562,9 +693,14 @@ def jump_to_file(filename, tnum = nil, charn = nil)
562
693
  end
563
694
  end
564
695
 
565
- #TODO: needed?
566
- def open_existing_file(filename)
567
- open_new_file(filename)
696
+ def do_open_file(filename)
697
+ message "New file opened: #{filename}"
698
+ bu = load_buffer(filename)
699
+ vma.buffers.set_current_buffer_by_id(bu.id)
700
+ # The repo/working dir is full of *_vma_autosave files; prompting about them
701
+ # mid-test steals the keyboard. tests/test_autosave.rb calls
702
+ # check_autosave_load directly, so the prompt itself stays covered.
703
+ bu.check_autosave_load unless vma_test_mode?
568
704
  end
569
705
 
570
706
  def open_new_file(filename, file_contents = "")
@@ -576,25 +712,28 @@ def open_new_file(filename, file_contents = "")
576
712
  message "Switching to: #{filename}"
577
713
  bu = vma.buffers.set_current_buffer(b)
578
714
  else
579
- if !is_path_writable(filename)
580
- message("Path #{filename} cannot be written to")
581
- return false
582
- elsif !File.exist?(filename)
715
+ if !File.exist?(filename)
583
716
  message("File #{filename} does not exist")
584
717
  return false
585
718
  elsif !file_is_text_file(filename)
586
719
  message("File #{filename} does not contain text")
587
720
  return false
588
721
  end
722
+ message("Note: #{filename} is read-only") unless is_path_writable(filename)
589
723
  if Encrypt.is_encrypted?(filename)
590
724
  decrypt_dialog(filename: filename)
591
725
  return nil
592
726
  end
593
- message "New file opened: #{filename}"
594
- fname = filename
595
- bu = load_buffer(fname)
596
- vma.buffers.set_current_buffer_by_id(bu.id)
597
- bu.check_autosave_load
727
+ if File.size(filename) > 1_000_000
728
+ size_mb = File.size(filename) / 1_000_000.0
729
+ Gui.confirm("Warning: #{filename}\nis large (#{format("%.1f", size_mb)} MB).\nOpen anyway?",
730
+ proc { do_open_file(filename) })
731
+ return nil
732
+ end
733
+ do_open_file(filename)
734
+ # get_buffer_by_filename returns a buffer id, not the Buffer; resolve it so
735
+ # callers (e.g. jump_to_file) get a Buffer to act on.
736
+ bu = vma.buffers.get_buffer_by_id(vma.buffers.get_buffer_by_filename(filename))
598
737
  end
599
738
  return bu
600
739
  end
@@ -605,13 +744,43 @@ def scan_word_start_marks(search_str)
605
744
  return wsmarks
606
745
  end
607
746
 
747
+ # Base directory for user config/data (settings.rb, custom.rb, backups,
748
+ # session, listen dir, crash reports, ...). Defaults to ~/.config/vimamsa but
749
+ # can be overridden with the --user-dir switch or by setting $vma_user_dir
750
+ # before startup. Tests point this at an isolated directory so they never read
751
+ # or write the real user config.
752
+ def vma_user_dir
753
+ $vma_user_dir ||= File.expand_path("~/.config/vimamsa")
754
+ end
755
+
608
756
  def get_dot_path(sfx)
609
- dot_dir = File.expand_path("~/.config/vimamsa")
757
+ dot_dir = vma_user_dir
610
758
  FileUtils.mkdir_p(dot_dir) unless File.exist?(dot_dir)
611
759
  dpath = "#{dot_dir}/#{sfx}"
612
760
  return dpath
613
761
  end
614
762
 
763
+ # Base directory for files the program generates (window layout, ...), as
764
+ # opposed to user-edited config: $XDG_DATA_HOME/vimamsa, by default
765
+ # ~/.local/share/vimamsa. When the user dir was moved (--user-dir, tests),
766
+ # data goes there too, so those runs stay isolated. See doc/TODO.md (XDG item).
767
+ def vma_data_dir
768
+ $vma_data_dir ||= begin
769
+ if File.expand_path(vma_user_dir) != File.expand_path("~/.config/vimamsa")
770
+ vma_user_dir
771
+ else
772
+ base = ENV["XDG_DATA_HOME"].to_s
773
+ base = File.expand_path("~/.local/share") if base.empty?
774
+ File.join(base, "vimamsa")
775
+ end
776
+ end
777
+ end
778
+
779
+ def get_data_path(sfx)
780
+ FileUtils.mkdir_p(vma_data_dir) unless File.exist?(vma_data_dir)
781
+ "#{vma_data_dir}/#{sfx}"
782
+ end
783
+
615
784
  def get_file_line_pointer(s)
616
785
  #"/code/vimamsa/lib/vimamsa/buffer_select.rb:31:def"
617
786
  # m = s.match(/(~[a-z]*)?\/.*\//)
@@ -671,13 +840,49 @@ def find_project_dir_of_cur_buffer()
671
840
  return pdir
672
841
  end
673
842
 
843
+ # Quit and relaunch the editor: reloads settings.rb/custom.rb and reopens the
844
+ # files that were open (via the saved session), all automatically. Replaces the
845
+ # current process with exec, so the same window is torn down as the new one comes up.
846
+ def restart_editor
847
+ vma.save_session
848
+ vma.gui.save_window_layout
849
+ vma.hook.call(:shutdown)
850
+ ruby = RbConfig.ruby
851
+ script = $PROGRAM_NAME
852
+ message("Restarting...")
853
+ # Signal the new instance to restore the session without prompting.
854
+ exec({ "VIMAMSA_RESTORE_SESSION" => "1" }, ruby, script)
855
+ rescue => ex
856
+ message("Restart failed: #{ex}")
857
+ end
858
+
674
859
  def reload_customrb
675
860
  custom_fn = get_dot_path("custom.rb")
676
861
  custom_script = read_file("", custom_fn)
677
862
  eval(custom_script) if custom_script
863
+ call_custom_after_init # everything is loaded already: run phase 2 right away
864
+ gui_refresh_colors # apply any cnf.theme.colors/cyber overrides live
678
865
  message("Reloaded #{custom_fn}")
679
866
  end
680
867
 
868
+ # Phase 2 of custom.rb. The body of custom.rb is evaluated early during
869
+ # Editor#start, before the modes and actions of Grep/FileManager/Autocomplete
870
+ # and of the modules are registered — so that cnf.* from custom.rb is visible to
871
+ # them (e.g. cnf.fexp.experimental). Anything that depends on those, above all
872
+ # key bindings for their modes ("fexp ...", "grep ...", module minor modes),
873
+ # belongs in an optional hook_custom_after_init function, which is called from
874
+ # here once everything is loaded.
875
+ def call_custom_after_init
876
+ return if !respond_to?(:hook_custom_after_init, true)
877
+ begin
878
+ send(:hook_custom_after_init)
879
+ rescue Exception => e
880
+ warn e.inspect
881
+ warn e.backtrace
882
+ message("Error in hook_custom_after_init: #{e}")
883
+ end
884
+ end
885
+
681
886
  def save_settings_to_file
682
887
  settings_path = get_dot_path("settings.rb")
683
888
  lines = all_settings_defs.flat_map { |section| section[:settings] }.map do |s|
@@ -716,3 +921,4 @@ def install_demo_files_callback(x)
716
921
  message("Demo files installed to #{dest_dir}")
717
922
  end
718
923
 
924
+ end # module Vimamsa
@@ -1,4 +1,7 @@
1
1
  require "openssl"
2
+ require "securerandom"
3
+
4
+ module Vimamsa
2
5
 
3
6
  def decrypt_dialog(filename:, wrong_pass: false)
4
7
  callback = proc { |x| Encrypt.open(filename, x) }
@@ -8,64 +11,109 @@ def decrypt_dialog(filename:, wrong_pass: false)
8
11
  end
9
12
 
10
13
  class Encrypt
14
+ HEADER_V1 = "VMACRYPT001"
15
+ HEADER_V2 = "VMACRYPT002"
16
+
17
+ PBKDF2_ITERATIONS = 600_000
18
+ PBKDF2_KEY_LEN = 32 # 256-bit key for AES-256
19
+ SALT_LEN = 16
20
+ NONCE_LEN = 12
21
+ TAG_LEN = 16
22
+
11
23
  def self.is_encrypted?(fn)
12
24
  debug "self.is_encrypted?(fn)", 2
13
25
  begin
14
26
  file = File.open(fn, "r")
15
- first_11_characters = file.read(11)
16
- return true if first_11_characters == "VMACRYPT001"
27
+ header = file.read(11)
28
+ return true if header == HEADER_V1 || header == HEADER_V2
17
29
  rescue Errno::ENOENT
18
- puts "File not found: #{file_path}"
30
+ puts "File not found: #{fn}"
19
31
  rescue => e
20
32
  puts "An error occurred: #{e.message}"
21
33
  ensure
22
34
  file&.close
23
35
  end
24
- return false
36
+ false
25
37
  end
26
38
 
27
39
  def self.open(fn, password)
28
40
  debug "open_encrypted(filename,password)", 2
29
- encrypted = read_file("", fn)[11..-1]
41
+ content = read_file("", fn)
42
+ header = content[0..10]
43
+ payload = content[11..-1]
30
44
  begin
31
45
  crypt = Encrypt.new(password)
32
- str = crypt.decrypt(encrypted)
33
- # debug "PASS OK!", 2
46
+ str = (header == HEADER_V1) ? crypt.decrypt_v1(payload) : crypt.decrypt_v2(payload)
34
47
  bu = create_new_buffer(str)
35
- bu.init_encrypted(crypt: crypt, filename: fn, encrypted: encrypted)
48
+ bu.init_encrypted(crypt: crypt, filename: fn, encrypted: payload)
36
49
  rescue OpenSSL::Cipher::CipherError => e
37
- # Wrong password
38
50
  decrypt_dialog(filename: fn, wrong_pass: true)
39
51
  end
40
52
  end
41
53
 
42
54
  def initialize(pass_phrase)
43
- salt = "uvgixEtU"
44
- @enc = OpenSSL::Cipher.new "AES-128-CBC"
45
- @enc.encrypt
46
- @enc.pkcs5_keyivgen pass_phrase, salt
47
- @dec = OpenSSL::Cipher.new "AES-128-CBC"
48
- @dec.decrypt
49
- @dec.pkcs5_keyivgen pass_phrase, salt
55
+ @pass_phrase = pass_phrase
56
+ # Lazy-init legacy cipher only when needed for V1 decryption
57
+ @dec_v1 = nil
50
58
  end
51
59
 
60
+ # Always produces V2 (AES-256-GCM) output. Returns uppercase hex payload.
52
61
  def encrypt(text)
53
- cipher = @enc
54
- encrypted = cipher.update text
55
- encrypted << cipher.final
56
- encrypted = encrypted.unpack("H*")[0].upcase
57
- @enc.reset
58
- return encrypted
62
+ salt = SecureRandom.random_bytes(SALT_LEN)
63
+ nonce = SecureRandom.random_bytes(NONCE_LEN)
64
+ key = derive_key(salt)
65
+
66
+ cipher = OpenSSL::Cipher.new("AES-256-GCM")
67
+ cipher.encrypt
68
+ cipher.key = key
69
+ cipher.iv = nonce
70
+
71
+ ciphertext = cipher.update(text.b) + cipher.final
72
+ tag = cipher.auth_tag(TAG_LEN)
73
+
74
+ (salt + nonce + tag + ciphertext).unpack1("H*").upcase
75
+ end
76
+
77
+ # Decrypt a V1 (AES-128-CBC, pkcs5_keyivgen) hex payload.
78
+ def decrypt_v1(hex_payload)
79
+ @dec_v1 ||= begin
80
+ c = OpenSSL::Cipher.new("AES-128-CBC")
81
+ c.decrypt
82
+ c.pkcs5_keyivgen(@pass_phrase, "uvgixEtU")
83
+ c
84
+ end
85
+ raw = [hex_payload.strip].pack("H*")
86
+ plain = @dec_v1.update(raw) + @dec_v1.final
87
+ @dec_v1.reset
88
+ plain.force_encoding("utf-8")
59
89
  end
60
90
 
61
- def decrypt(encrypted)
62
- cipher = @dec
63
- encrypted = [encrypted].pack("H*").unpack("C*").pack("c*")
64
- plain = cipher.update encrypted
65
- plain << cipher.final
91
+ # Decrypt a V2 (AES-256-GCM, PBKDF2) hex payload.
92
+ # Raises OpenSSL::Cipher::CipherError on wrong password or tampered data.
93
+ def decrypt_v2(hex_payload)
94
+ raw = [hex_payload.strip].pack("H*")
95
+
96
+ offset = 0
97
+ salt = raw[offset, SALT_LEN]; offset += SALT_LEN
98
+ nonce = raw[offset, NONCE_LEN]; offset += NONCE_LEN
99
+ tag = raw[offset, TAG_LEN]; offset += TAG_LEN
100
+ ciphertext = raw[offset..-1]
101
+
102
+ key = derive_key(salt)
103
+ cipher = OpenSSL::Cipher.new("AES-256-GCM")
104
+ cipher.decrypt
105
+ cipher.key = key
106
+ cipher.iv = nonce
107
+ cipher.auth_tag = tag
108
+
109
+ plain = cipher.update(ciphertext) + cipher.final
66
110
  plain.force_encoding("utf-8")
67
- @dec.reset
68
- return plain
111
+ end
112
+
113
+ private
114
+
115
+ def derive_key(salt)
116
+ OpenSSL::PKCS5.pbkdf2_hmac(@pass_phrase, salt, PBKDF2_ITERATIONS, PBKDF2_KEY_LEN, "SHA256")
69
117
  end
70
118
  end
71
119
 
@@ -77,3 +125,4 @@ end
77
125
  def encrypt_cur_buffer_callback(password, b = nil)
78
126
  vma.buf.set_encrypted(password)
79
127
  end
128
+ end # module Vimamsa
@@ -1,6 +1,8 @@
1
1
  require "parallel"
2
2
  require "stridx"
3
3
 
4
+ module Vimamsa
5
+
4
6
  # Limit file search to these extensions:
5
7
  cnf.find_extensions = [".txt", ".h", ".c", ".cpp", ".hpp", ".rb", ".java", ".js", ".py"]
6
8
  cnf.search_dirs = []
@@ -67,7 +69,7 @@ class FileFinder
67
69
  @@idx.add(x, i)
68
70
  end
69
71
  @@idx_updating = false
70
- message("Finish updating file index")
72
+ GLib::Idle.add { message("Finish updating file index"); false }
71
73
  }
72
74
  end
73
75
 
@@ -149,8 +151,6 @@ class FileFinder
149
151
 
150
152
  def filter_files(search_str)
151
153
  puts "search list: #{@@dir_list.size}"
152
- dir_hash = {}
153
-
154
154
  res = @@idx.find(search_str)
155
155
  resultarr = []
156
156
  for (idx, score) in res
@@ -159,21 +159,6 @@ class FileFinder
159
159
  resultarr << [fn, score]
160
160
  end
161
161
  return resultarr
162
-
163
- # Ripl.start :binding => binding
164
-
165
- scores = Parallel.map(@@dir_list, in_threads: 8) do |file|
166
- [file, srn_dst(search_str, file)]
167
- end
168
- for s in scores
169
- dir_hash[s[0]] = s[1] if s[1] > 0
170
- end
171
- # debug scores
172
- dir_hash = dir_hash.sort_by { |k, v| -v }
173
- dir_hash = dir_hash[0..20]
174
- dir_hash.map do |file, d|
175
- debug "D:#{d} #{file}"
176
- end
177
- return dir_hash
178
162
  end
179
163
  end
164
+ end # module Vimamsa