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
@@ -1,3 +1,5 @@
1
+
2
+ module Vimamsa
1
3
  # This file has everyting related to binding key (and other) events
2
4
  # into actions.
3
5
 
@@ -20,6 +22,12 @@
20
22
 
21
23
  class State
22
24
  attr_accessor :key_name, :eval_rule, :children, :action, :label, :major_modes, :level, :cursor_type, :keywords, :root, :parent
25
+ # Order in which the action was bound (KeyBindingTree#bindings lists by it)
26
+ attr_accessor :seq
27
+ # For a binding expanded from a template ("C <op> <motion>"): the values it
28
+ # was expanded from ({ op: :delete, motion: :word_next }), passed to the
29
+ # action, and the template keys
30
+ attr_accessor :bind_args, :template
23
31
  attr_reader :cur_mode, :scope
24
32
 
25
33
  def initialize(key_name, eval_rule = "", ctype = :command, scope: :buffer)
@@ -43,9 +51,40 @@ end
43
51
 
44
52
  class KeyBindingTree
45
53
  attr_accessor :C, :I, :cur_state, :root, :match_state, :last_action, :cur_action, :modifiers, :next_command_count, :method_handles_repeat, :default_mode
46
- attr_reader :mode_root_state, :state_trail, :act_bindings, :default_mode_stack
47
-
48
- def initialize()
54
+ attr_accessor :action_handler, :on_action_error, :logger, :fatal_handler, :error_handler
55
+ attr_reader :mode_root_state, :state_trail, :act_bindings, :default_mode_stack, :actions
56
+ # [mode, keys] of the shared vim bindings bound by bind_vim_bindings (vim_core.rb)
57
+ attr_accessor :vim_added
58
+ # Keywords added to every binding made inside with_keywords
59
+ attr_reader :extra_keywords
60
+ # Key sets ({ name => { keys => value } }) and the templates bound with them
61
+ attr_reader :key_sets, :templates
62
+
63
+ # This class is host-agnostic: it never touches the editor or GUI directly.
64
+ # The host injects collaborators (actions registry, action_handler, logger,
65
+ # fatal_handler, on_action_error) and subscribes to events via #on:
66
+ # :mode_set(label) - set_mode was called explicitly
67
+ # :mode_changed(label) - mode changed (any path)
68
+ # :state_trail_changed(badge, badge_key, trail) - badge/pending-chord display
69
+ # :key_no_match(key, trail) - key did not match any binding
70
+ # :key_pending(trail) - multi-key sequence in progress
71
+ # :key_action(trail, action) - action about to be executed
72
+ # :action_executed(action, ret) - one execution of an action finished
73
+ # :action_handled(trail, action) - key handling for an action completed
74
+ # :key_input(key, event_type) - a key came in (match_key_conf), first
75
+ def initialize(actions: nil)
76
+ @actions = actions
77
+ @extra_keywords = []
78
+ @bind_seq = 0
79
+ @key_sets = {}
80
+ @templates = []
81
+ @listeners = {}
82
+ @action_handler = nil
83
+ @logger = nil
84
+ @fatal_handler = proc { |msg| raise msg }
85
+ # Non-fatal problems the user should see (e.g. a binding to an unknown mode)
86
+ @error_handler = proc { |msg| warn msg }
87
+ @on_action_error = nil
49
88
  @next_command_count = nil
50
89
  @modes = {}
51
90
  @root = State.new("ROOT")
@@ -67,9 +106,31 @@ class KeyBindingTree
67
106
  @act_bindings = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
68
107
  end
69
108
 
109
+ # Subscribe to one of the events listed above initialize
110
+ def on(event, &blk)
111
+ (@listeners[event] ||= []) << blk
112
+ end
113
+
114
+ def emit(event, *args)
115
+ @listeners.fetch(event, []).each { |l| l.call(*args) }
116
+ end
117
+ private :emit
118
+
119
+ def log(msg, level = 1)
120
+ @logger.call(msg, level) if @logger
121
+ end
122
+ private :log
123
+
124
+ # Report a non-fatal problem (bad binding definition etc.) to the host.
125
+ def error(msg)
126
+ log(msg)
127
+ @error_handler.call(msg) if @error_handler
128
+ end
129
+ private :error
130
+
70
131
  def set_mode(label)
71
132
  return if get_mode == :label
72
- vma.buf&.new_undo_group
133
+ emit(:mode_set, label)
73
134
  @match_state = [@modes[label]] # used for matching input
74
135
  @mode_root_state = @modes[label]
75
136
 
@@ -77,9 +138,6 @@ class KeyBindingTree
77
138
  @default_mode_stack << label if label != @default_mode_stack[-1]
78
139
 
79
140
  __set_mode(label)
80
- if !vma.buf.nil?
81
- # vma.buf.mode_stack = @default_mode_stack.clone
82
- end
83
141
  end
84
142
 
85
143
  def set_default_mode(label)
@@ -90,8 +148,7 @@ class KeyBindingTree
90
148
  end
91
149
 
92
150
  def set_mode_stack(ms)
93
- debug "set_mode_stack(#{ms})", 2
94
- show_caller if cnf.debug? # TODO: remove
151
+ log "set_mode_stack(#{ms})", 2
95
152
  @default_mode_stack = ms
96
153
  label = @default_mode_stack[-1]
97
154
  @match_state = [@modes[label]]
@@ -99,10 +156,9 @@ class KeyBindingTree
99
156
  end
100
157
 
101
158
  def dump_state
102
- debug "dump_state", 2
159
+ log "dump_state", 2
103
160
  pp ["@default_mode_stack", @default_mode_stack]
104
161
  pp ["@default_mode", @default_mode]
105
- pp ["vma.buf.mode_stack", vma.buf.mode_stack]
106
162
  pp ["scope", self.get_scope]
107
163
  # pp ["@mode_root_state", @mode_root_state]
108
164
  # pp ["@match_state", @match_state]
@@ -115,16 +171,21 @@ class KeyBindingTree
115
171
  end
116
172
 
117
173
  def to_previous_mode()
118
- debug "to_previous_mode", 2
119
- debug @default_mode_stack
174
+ log "to_previous_mode", 2
175
+ log @default_mode_stack
120
176
  if @default_mode_stack.size > 1
121
177
  @default_mode_stack.pop
122
178
  end
123
- debug @default_mode_stack
179
+ log @default_mode_stack
124
180
  __set_mode(@default_mode_stack[-1])
125
181
  end
126
182
 
127
183
  def add_mode(id, label, cursortype = :command, name: nil, scope: :buffer)
184
+ # Replace any existing mode with the same key id: when a keybinding scheme
185
+ # file is loaded over another one, both binding (which walks @root.children
186
+ # by key name) and matching (which starts from @modes) must resolve to the
187
+ # same, new node.
188
+ @root.children.delete_if { |s| s.key_name == id }
128
189
  mode = State.new(id, "", cursortype, scope: scope)
129
190
  mode.level = 1
130
191
  @modes[label] = mode
@@ -136,11 +197,9 @@ class KeyBindingTree
136
197
 
137
198
  # Add keyboard key binding mode based on another mode
138
199
  def add_minor_mode(id, label, major_mode_label)
200
+ @root.children.delete_if { |s| s.key_name == id }
139
201
  mode = State.new(id)
140
202
  @modes[label] = mode
141
- if @root.nil?
142
- show_caller
143
- end
144
203
  @root.children << mode
145
204
  mode.major_modes << major_mode_label
146
205
  end
@@ -163,6 +222,11 @@ class KeyBindingTree
163
222
  @override_keyhandling_callback = _callback
164
223
  end
165
224
 
225
+ # True while something reads the keys itself (easy jump's labels)
226
+ def keyhandling_override?
227
+ !@override_keyhandling_callback.nil?
228
+ end
229
+
166
230
  def remove_keyhandling_override()
167
231
  @override_keyhandling_callback = nil
168
232
  end
@@ -177,15 +241,15 @@ class KeyBindingTree
177
241
  if c.key_name == key_name and c.eval_rule == ""
178
242
  new_state << c
179
243
  elsif c.key_name == key_name and c.eval_rule != ""
180
- debug "CHECK EVAL: #{c.eval_rule}"
244
+ log "CHECK EVAL: #{c.eval_rule}"
181
245
  if eval(c.eval_rule)
182
246
  # if eval_rule.match(/macro/)
183
247
  debug = true
184
248
  # end
185
249
  new_state << c
186
- debug "EVAL TRUE"
250
+ log "EVAL TRUE"
187
251
  else
188
- debug "EVAL FALSE"
252
+ log "EVAL FALSE"
189
253
  end
190
254
  end
191
255
  }
@@ -206,12 +270,11 @@ class KeyBindingTree
206
270
  end
207
271
 
208
272
  def show_state_trail
209
- (st, children) = get_state_trail_str()
210
- vma.gui.statnfo.markup = "<span weight='ultrabold'>#{st}</span>"
273
+ emit(:state_trail_changed, *get_state_trail_parts())
211
274
  end
212
275
 
213
276
  def __set_mode(label)
214
- debug "__set_mode(#{label})"
277
+ log "__set_mode(#{label})"
215
278
  @mode_history << @mode_root_state
216
279
 
217
280
  # Check if label in form :label
@@ -228,13 +291,7 @@ class KeyBindingTree
228
291
  end
229
292
  @cur_mode = label
230
293
 
231
- if self.get_scope != :editor and !vma.buf.nil?
232
- vma.buf.mode_stack = @default_mode_stack.clone
233
- end
234
-
235
- if !vma.gui.view.nil?
236
- vma.gui.view.draw_cursor() #TODO: handle outside this class
237
- end
294
+ emit(:mode_changed, label)
238
295
  end
239
296
 
240
297
  def get_scope
@@ -278,6 +335,7 @@ class KeyBindingTree
278
335
  end
279
336
 
280
337
  @state_trail = [@mode_root_state]
338
+ @num_digits = nil
281
339
  end
282
340
 
283
341
  # Returns a list of key positions that are free (no action bound) under each
@@ -335,106 +393,70 @@ class KeyBindingTree
335
393
  }.join("\n")
336
394
  end
337
395
 
338
- def get_by_keywords(modes: [], keywords: [])
339
- s = ""
340
- stack = [[@root, ""]]
341
- lines = []
342
-
343
- # Traverse the tree (class State objects) using a stack
344
- while stack.any?
345
- t, p = *stack.pop # t = current state, p = current path
346
- if t.children.any?
347
- t.children.reverse.each { |c|
348
-
349
- # Restrict by modes if specified
350
- if c.level == 1 and !modes.empty?
351
- next if !modes.include?(c.key_name)
352
- end
353
-
354
- if c.eval_rule.size > 0
355
- new_p = "#{p} #{c.key_name}(#{c.eval_rule})"
356
- else
357
- if c.level == 1
358
- new_p = "#{p} [#{c.key_name}]"
359
- else
360
- new_p = "#{p} #{c.key_name}"
361
- end
362
- end
363
- stack << [c, new_p]
364
- }
365
- # stack.concat[t.children]
396
+ # Run the block with kws added to the keywords of every binding it makes,
397
+ # e.g. with_keywords(["module:tts"]) { tts_init }
398
+ def with_keywords(kws)
399
+ old = @extra_keywords
400
+ @extra_keywords = old + kws
401
+ yield
402
+ ensure
403
+ @extra_keywords = old
404
+ end
366
405
 
367
- else
368
- method_desc = t.action
369
- if t.action.class == Symbol
370
- if vma.actions.include?(t.action)
371
- a = vma.actions[t.action].method_name
372
- if !a.nil? and !a.empty?
373
- method_desc = a
374
- end
375
- end
406
+ # Every binding as a record, in definition order:
407
+ # { mode: "C", keys: ["d", "i", "<char>"], action:, keywords: [...], desc:, seq: }
408
+ # seq counts bindkey calls; rebinding keys moves them to the end.
409
+ # A key with a condition is "name(rule)", as in the binding syntax. desc is
410
+ # the action's description, or the action itself (Ruby code, an unknown id).
411
+ def bindings
412
+ out = []
413
+ walk = lambda { |st, mode, path|
414
+ st.children.each { |c|
415
+ p = path + [c.eval_rule.empty? ? c.key_name : "#{c.key_name}(#{c.eval_rule})"]
416
+ if !c.action.nil?
417
+ out << { mode: mode, keys: p, action: c.action, keywords: c.keywords || [], desc: action_desc(c.action), seq: c.seq || 0,
418
+ args: c.bind_args, template: c.template }
376
419
  end
420
+ walk.(c, mode, p) if c.children.any?
421
+ }
422
+ }
423
+ @root.children.each { |m| walk.(m, m.key_name, []) }
424
+ out.each_with_index.sort_by { |b, i| [b[:seq], i] }.map(&:first)
425
+ end
377
426
 
378
- if (keywords - t.keywords).empty? # All keywords are present
379
- kw = ""
380
- # kw = ", [#{t.keywords.join(",")}]" if !t.keywords.empty?
381
- lines << p + " : #{method_desc}#{kw}"
382
- end
383
- end
427
+ # Description of a bound action, or the action as text
428
+ def action_desc(action)
429
+ if action.class == Proc
430
+ f, l = action.source_location
431
+ return "proc (#{File.basename(f.to_s)}:#{l})"
384
432
  end
385
- s = lines.sort.join("\n")
386
- return s
433
+ a = (@actions[action] rescue nil) if action.class == Symbol || action.class == String
434
+ if a && !a.opt&.[](:code) && !a.method_name.to_s.empty? && a.method_name.to_s != action.to_s
435
+ return a.method_name.to_s
436
+ end
437
+ action.to_s
438
+ end
439
+
440
+ # Lines "[C] keys : description" of the bindings in modes (all if empty)
441
+ # that have all of keywords, sorted
442
+ def get_by_keywords(modes: [], keywords: [])
443
+ bindings.select { |b|
444
+ (modes.empty? || modes.include?(b[:mode])) && (keywords - b[:keywords]).empty?
445
+ }.map { |b| " [#{b[:mode]}] #{b[:keys].join(" ")} : #{b[:desc]}" }.sort.join("\n")
387
446
  end
388
447
 
389
- # Print key bindings to show as documentation or for debugging
390
448
  def to_s()
391
449
  return self.class.to_s
392
- s = ""
393
- # @cur_state = @root
394
- stack = [[@root, ""]]
395
- lines = []
396
-
397
- # Traverse the tree (class State objects) using a stack
398
- while stack.any?
399
- t, p = *stack.pop # t = current state, p = current path
400
- if t.children.any?
401
- t.children.reverse.each { |c|
402
- if c.eval_rule.size > 0
403
- new_p = "#{p} #{c.key_name}(#{c.eval_rule})"
404
- else
405
- if c.level == 1
406
- new_p = "#{p} [#{c.key_name}]"
407
- else
408
- new_p = "#{p} #{c.key_name}"
409
- end
410
- end
411
- stack << [c, new_p]
412
- }
413
- # stack.concat[t.children]
414
- else
415
- method_desc = t.action
416
- if t.action.class == Symbol
417
- if vma.actions.include?(t.action)
418
- a = vma.actions[t.action].method_name
419
- if !a.nil? and !a.empty?
420
- method_desc = a
421
- end
422
- end
423
- end
424
-
425
- kw = ""
426
- # kw = ", " + t.keywords.join(",") if !t.keywords.empty?
427
- lines << p + " : #{method_desc}#{kw}"
428
- end
429
- end
430
- s = lines.sort.join("\n")
431
- return s
432
450
  end
433
451
 
434
- def get_state_trail_str
435
- s_trail = ""
436
- last_state = @state_trail.last
437
- last_state = last_state[0] if last_state.class == Array
452
+ # Returns [badge_str, badge_key, trail_str]:
453
+ # badge_str = human readable mode ("COMMAND", "C>fexp", ...), no brackets
454
+ # badge_key = key_name of the mode state ("C", "I", "fexp", ...)
455
+ # trail_str = pending key chord states + repeat count
456
+ def get_state_trail_parts
457
+ badge_str = ""
458
+ badge_key = nil
459
+ trail_str = ""
438
460
  first = true
439
461
  for st in @state_trail
440
462
  st = st[0] if st.class == Array
@@ -450,39 +472,90 @@ class KeyBindingTree
450
472
  mode_str = "VISUAL" if mode_str == "V"
451
473
  mode_str = "BROWSE" if mode_str == "B"
452
474
 
453
- s_trail << "[#{trailpfx}#{mode_str}]"
475
+ badge_key = st.key_name
476
+ badge_str = "#{trailpfx}#{mode_str}"
477
+ elsif st.key_name == "<num>" and @num_digits
478
+ trail_str << " #{@num_digits}"
454
479
  else
455
- s_trail << " #{st.to_s}"
480
+ trail_str << " #{st.to_s}"
456
481
  end
457
482
  first = false
458
483
  end
484
+ if !@next_command_count.nil?
485
+ trail_str << " #{@next_command_count}"
486
+ end
487
+ trail_str.strip!
488
+ return [badge_str, badge_key, trail_str]
489
+ end
490
+
491
+ def get_state_trail_str
492
+ (badge, _key, trail) = get_state_trail_parts()
493
+ s_trail = "[#{badge}]"
494
+ s_trail << " #{trail}" if !trail.empty?
495
+ last_state = @state_trail.last
496
+ last_state = last_state[0] if last_state.class == Array
459
497
  children = ""
460
498
  for cstate in last_state.children
461
499
  act_s = "..."
462
500
  act_s = cstate.action.to_s if cstate.action != nil
463
501
  children << " #{cstate.to_s} #{act_s}\n"
464
502
  end
465
- if !@next_command_count.nil?
466
- s_trail << " #{@next_command_count}"
467
- end
468
503
  return [s_trail, children]
469
504
  end
470
505
 
506
+ # True for a bare modifier key event ("ctrl", "shift!", ...)
507
+ def modifier_key?(c)
508
+ %w[ctrl alt shift meta super caps].include?(c.to_s.delete_suffix("!"))
509
+ end
510
+
471
511
  def set_next_command_count(num)
472
512
  if @next_command_count != nil
473
513
  @next_command_count = @next_command_count * 10 + num.to_i
474
514
  else
475
515
  @next_command_count = num.to_i
476
516
  end
477
- debug("NEXT COMMAND COUNT: #{@next_command_count}")
517
+ log("NEXT COMMAND COUNT: #{@next_command_count}")
478
518
  end
479
519
 
480
520
  # Modifies state of key binding tree (move to new state) based on received event
521
+ # A count typed inside a key sequence, for bindings like "C d <num> e"
522
+ # (d 3 e = delete to the end of the third word). The digits go to
523
+ # @num_digits; when the next key matches, they become the repeat count,
524
+ # multiplied by a count typed before the sequence (2 d 3 e = 6), as in vim.
525
+ # Exact bindings win: "C d 0" is still matched before this is tried.
526
+ def match_num_key(c, event_type)
527
+ return false unless event_type == :key_press and c.match?(/\A[0-9]\z/)
528
+ if @num_digits and @match_state.all? { |s| s.key_name == "<num>" }
529
+ @num_digits << c
530
+ else
531
+ return false if c == "0"
532
+ nums = @match_state.flat_map { |s| s.children.select { |x| x.key_name == "<num>" } }
533
+ return false if nums.empty?
534
+ @match_state = nums
535
+ @state_trail << nums
536
+ @num_digits = c.dup
537
+ end
538
+ emit(:key_pending, get_state_trail_str[0])
539
+ show_state_trail
540
+ true
541
+ end
542
+
543
+ def finish_num_count
544
+ return if @num_digits.nil?
545
+ @next_command_count = (@next_command_count || 1) * @num_digits.to_i
546
+ @num_digits = nil
547
+ end
548
+
481
549
  # Checks child nodes of current state if they match received event
482
550
  # if yes, change state to child
483
551
  # if no, go back to root
484
552
  def match_key_conf(c, translated_c, event_type)
485
- debug "MATCH KEY CONF: #{[c, translated_c]}"
553
+ log "MATCH KEY CONF: #{[c, translated_c]}"
554
+ # Every key as it comes in, before anything handles it (demo recorder)
555
+ emit(:key_input, c, event_type)
556
+ # A delete still flashing from the previous key must land before this
557
+ # key's action runs.
558
+ Gui.flush_flash
486
559
 
487
560
  if !@override_keyhandling_callback.nil?
488
561
  ret = @override_keyhandling_callback.call(c, event_type)
@@ -492,6 +565,8 @@ class KeyBindingTree
492
565
  eval_s = nil
493
566
 
494
567
  new_state = match(c)
568
+ return true if new_state.nil? and match_num_key(c, event_type)
569
+ finish_num_count if new_state
495
570
  # #TODO:
496
571
  # new_state = match(translated_c)
497
572
  # if new_state == nil and translated_c.index("shift") == 0
@@ -540,11 +615,20 @@ class KeyBindingTree
540
615
  end
541
616
 
542
617
  if new_state == nil
543
- debug("NO MATCH")
618
+ log("NO MATCH")
619
+ if event_type == :key_press and !modifier_key?(c)
620
+ emit(:key_no_match, c, get_state_trail_str[0])
621
+ # A key that leads nowhere (e.g. esc) also aborts a count that is being
622
+ # typed: "2 0 0 esc" must not leave 200 pending for the next command.
623
+ # Modifier keys are excluded: they arrive as separate press events and
624
+ # must not break e.g. "2 0 ctrl-d".
625
+ @next_command_count = nil
626
+ @num_digits = nil
627
+ end
544
628
  if event_type == :key_press and c != "shift"
545
629
  # TODO:include other modifiers in addition to shift?
546
630
  set_state_to_root
547
- printf(", BACK TO ROOT") if cnf.debug?
631
+ log("BACK TO ROOT", 2)
548
632
  end
549
633
 
550
634
  if event_type == :key_release and c == "shift!"
@@ -552,10 +636,8 @@ class KeyBindingTree
552
636
  # only on key release when no other key has been pressed
553
637
  # after said modifier key (shift).
554
638
  set_state_to_root
555
- printf(", BACK TO ROOT") if cnf.debug?
639
+ log("BACK TO ROOT", 2)
556
640
  end
557
-
558
- printf("\n") if cnf.debug?
559
641
  else
560
642
 
561
643
  # Don't execute action if one of the states has children
@@ -588,20 +670,35 @@ class KeyBindingTree
588
670
  end
589
671
 
590
672
  if s_act.any? and !state_with_children.any?
673
+ wildcard = !eval_s.nil? # matched a "<char>" or /regexp/ key
591
674
  eval_s = s_act.first.action if eval_s == nil
592
675
  # if eval_s.to_s.match(/end_recording/)
593
676
  # require "pry"; binding.pry
594
677
  # end
595
- debug "FOUND MATCH:#{eval_s}"
596
- debug "CHAR: #{c}"
678
+ log "FOUND MATCH:#{eval_s}"
679
+ log "CHAR: #{c}"
597
680
  c.gsub!("\\", %q{\\\\} * 4) # Escape \ -chars
598
681
  c.gsub!("'", "#{'\\' * 4}'") # Escape ' -chars
599
682
 
683
+ node = s_act.first
684
+ if node.bind_args && eval_s.class == String
685
+ # A template expansion gets its values (and the typed character)
686
+ vals = "{" + node.bind_args.map { |k, v| "#{k}: #{v.inspect}" }.join(", ") + "}"
687
+ eval_s = wildcard ? "a.#{eval_s}!(#{vals}, <char>)" : "a.#{eval_s}!(#{vals})"
688
+ elsif wildcard && eval_s.class == String && (r = @actions&.[](eval_s)) && !r.opt&.[](:code)
689
+ # A named action gets the typed character as its argument. As a
690
+ # string, so macros and the key log can replay it like Ruby code.
691
+ # (the gsub! below fills in the escaped character)
692
+ eval_s = "a.#{eval_s}!(<char>)"
693
+ end
600
694
  eval_s.gsub!("<char>", "'#{c}'") if eval_s.class == String
601
- debug eval_s
602
- debug c
695
+ log eval_s
696
+ log c
603
697
  handle_key_bindigs_action(eval_s, c)
604
698
  set_state_to_root
699
+ else
700
+ # Multi-key sequence still in progress
701
+ emit(:key_pending, get_state_trail_str[0])
605
702
  end
606
703
  end
607
704
 
@@ -610,7 +707,10 @@ class KeyBindingTree
610
707
  return true
611
708
  end
612
709
 
613
- def bindkey(key, action, keywords: "")
710
+ # A key using a key set ("C <op> <motion>") is a template, see
711
+ # bind_template. filter: for templates, a proc (mode, keys, action) that
712
+ # says whether to bind one expansion.
713
+ def bindkey(key, action, keywords: "", args: nil, template: nil, filter: nil)
614
714
  # puts "keywords #{keywords}" if !keywords.empty?
615
715
  if keywords.class == String
616
716
  keywords = keywords.split(" ")
@@ -621,27 +721,188 @@ class KeyBindingTree
621
721
  # "X esc || X ctrl!" => "vma.kbd.to_previous_mode",
622
722
  key = key.split("||")
623
723
  end
724
+ keywords = keywords + @extra_keywords
624
725
 
625
726
  a = action
626
727
  if action.class == Array
627
- label = a[0]
728
+ label = @actions.resolve(a[0])
628
729
  a = label
629
730
  proc = action[1]
630
731
  msg = action[2]
631
- reg_act(label, proc, msg)
732
+ @actions.register(label, Action.new(label, msg, proc))
733
+ elsif ActionRef === a
734
+ # a.move.word.next: the action must exist (catches typos)
735
+ if !@actions.include?(a)
736
+ error("bindkey: unknown action #{a.to_s}#{@actions.did_you_mean(a.to_s)} for #{key.inspect}. Binding skipped.")
737
+ return
738
+ end
739
+ a = @actions.resolve(a)
740
+ elsif a.class == Symbol
741
+ a = @actions.resolve(a) # old id => new id (ACTION_ALIASES)
742
+ end
743
+ key.each { |k|
744
+ if template_key?(k)
745
+ bind_template(k.strip, a, keywords, filter)
746
+ else
747
+ _bindkey(k, a, keywords: keywords, args: args, template: template)
748
+ end
749
+ }
750
+ end
751
+
752
+ # ── Key sets and templates (doc/vim_compatibility_plan.md, step 1) ──
753
+ #
754
+ # A key set maps keys to values, e.g. the Vim operators and motions:
755
+ # define_key_set :op, { "d" => :delete, "g U" => :upcase }
756
+ # define_key_set :motion, { "w" => :word_next, "f <char>" => :find_char,
757
+ # "f space" => { id: :find_char, char: " " } }
758
+ # A binding whose keys name a key set is a template:
759
+ # bindkey "C <op> <motion>", "op.motion"
760
+ # It is expanded into one binding per combination (C d w, C g U f <char>,
761
+ # ...), each passing its values to the action: a.op.motion!({ op: :delete,
762
+ # motion: :word_next }). A Hash value adds its other fields to the values.
763
+ # "<same>" repeats the last key of the placeholder before it (d d, g U U).
764
+ # A count may be typed before every placeholder but the first (d 3 w): the
765
+ # expansion also gets a "<num>" variant there.
766
+
767
+ def define_key_set(name, entries)
768
+ @key_sets[name.to_sym] = entries.dup
769
+ end
770
+
771
+ # Add entries to a key set; the templates already bound with it get the
772
+ # new combinations too
773
+ def key_set_add(name, entries)
774
+ name = name.to_sym
775
+ (@key_sets[name] ||= {}).merge!(entries)
776
+ @templates.each { |t|
777
+ next if !t[:key].split.include?("<#{name}>")
778
+ bind_template(t[:key], t[:action], t[:keywords], t[:filter], only: { name => entries.keys }, record: false)
779
+ }
780
+ end
781
+
782
+ def key_set(name)
783
+ @key_sets[name.to_sym]
784
+ end
785
+
786
+ def template_key?(key)
787
+ key.split.any? { |t|
788
+ t == "<same>" || ((m = t.match(/\A<([a-z_]+)>\z/)) && @key_sets.key?(m[1].to_sym))
789
+ }
790
+ end
791
+
792
+ # The expansions of the key part of a template ("<op> <motion>") as
793
+ # [[keys, values], ...]. only: { set name => [keys] } limits that set to
794
+ # those entries.
795
+ def expand_template(keydef, only: nil)
796
+ out = [[[], {}, nil]] # keys, values, last key of the previous placeholder
797
+ first = true
798
+ keydef.split.each { |tok|
799
+ m = tok.match(/\A<([a-z_]+)>\z/)
800
+ name = m && m[1].to_sym
801
+ if tok == "<same>" || (name && @key_sets.key?(name))
802
+ nums = first ? [false] : [false, true]
803
+ out = out.flat_map { |ks, vals, last|
804
+ if tok == "<same>"
805
+ next [] if last.nil?
806
+ entries = { last => nil }
807
+ else
808
+ entries = @key_sets[name]
809
+ entries = entries.select { |k, _| only[name].include?(k) } if only && only[name]
810
+ end
811
+ nums.flat_map { |num|
812
+ entries.map { |ek, ev|
813
+ v = vals.dup
814
+ if ev.is_a?(Hash)
815
+ v[name] = ev[:id]
816
+ v.merge!(ev.reject { |k, _| k == :id })
817
+ elsif tok != "<same>"
818
+ v[name] = ev
819
+ end
820
+ eks = ek.split
821
+ [ks + (num ? ["<num>"] : []) + eks, v, eks.last]
822
+ }
823
+ }
824
+ }
825
+ first = false
826
+ else
827
+ out = out.map { |ks, vals, last| [ks + [tok], vals, last] }
828
+ end
829
+ }
830
+ out.map { |ks, vals, _| [ks, vals] }
831
+ end
832
+
833
+ # Bind every expansion of a template, e.g. "C <op> <motion>"
834
+ def bind_template(key, action, keywords, filter = nil, only: nil, record: true)
835
+ m = key.match(/\A(\S+)\s(\S.*)\z/)
836
+ if m.nil?
837
+ error("bindkey: invalid template #{key.inspect}. Binding skipped.")
838
+ return
632
839
  end
633
- key.each { |k| _bindkey(k, a, keywords: keywords) }
840
+ mstr, keydef = m[1], m[2]
841
+ modes = mstr.match?(/\A\p{Lu}+\z/) ? mstr.chars : [mstr]
842
+ @templates << { key: key, action: action, keywords: keywords, filter: filter } if record
843
+ modes.each { |mode|
844
+ expand_template(keydef, only: only).each { |keys, vals|
845
+ next if filter && !filter.call(mode, keys, action)
846
+ _bindkey("#{mode} #{keys.join(" ")}", action, keywords: keywords, args: vals, template: "#{mode} #{keydef}")
847
+ }
848
+ }
634
849
  end
635
850
 
636
- def unbindkey(key)
851
+ # Unbind one or more key definitions (split on "||").
852
+ #
853
+ # Normally each key addresses a single binding to remove, e.g.
854
+ # unbindkey "C , k"
855
+ #
856
+ # To tear down every binding under a node without listing each key, pass
857
+ # include_child_nodes: true (or address a bare mode with no chord, which has
858
+ # no leaf of its own to delete and so implies the same). Both of these clear
859
+ # all child bindings of the addressed node while leaving the node itself:
860
+ # unbindkey "dictation" # whole minor mode
861
+ # unbindkey "dictation", include_child_nodes: true
862
+ # unbindkey "C ,", include_child_nodes: true # every "C , x" chord
863
+ def unbindkey(key, include_child_nodes: false)
637
864
  if key.class != Array
638
865
  key = key.split("||")
639
866
  end
640
- #TODO: test
641
- key.each { |k| _bindkey(k.strip, :delete_state) }
867
+ key.each { |k|
868
+ k = k.strip
869
+ if include_child_nodes || k.split(/\s+/).size == 1
870
+ unbind_child_nodes(k)
871
+ else
872
+ _bindkey(k, :delete_state)
873
+ end
874
+ }
875
+ end
876
+
877
+ # Remove every child binding under the node addressed by `key`, leaving the
878
+ # node itself in place. No-op if the node doesn't exist.
879
+ def unbind_child_nodes(key)
880
+ tokens = key.strip.split(/\s+/)
881
+ node = find_state_by_path(tokens)
882
+ return if node.nil?
883
+ node.children.clear
884
+ # Drop the action->keydef map for a whole mode so menus/help stop listing
885
+ # its bindings (only meaningful when addressing a bare mode root).
886
+ @act_bindings.delete(tokens[0]) if tokens.size == 1 && @act_bindings.key?(tokens[0])
887
+ end
888
+
889
+ # Resolve the State addressed by a key path: the first token is a mode id (a
890
+ # direct child of @root), any remaining tokens are chord keys walked down from
891
+ # there. Accepts a string or a pre-split token array. Returns nil if unfound.
892
+ def find_state_by_path(key)
893
+ tokens = key.class == Array ? key.dup : key.strip.split(/\s+/)
894
+ mode_id = tokens.shift
895
+ node = @root.children.find { |s| s.key_name == mode_id }
896
+ tokens.each { |k|
897
+ return nil if node.nil?
898
+ m = /(.+)\((.*)\)/.match(k) # strip an (eval_rule) suffix, as binding does
899
+ key_name = m ? m[1] : k
900
+ node = node.children.find { |s| s.key_name == key_name }
901
+ }
902
+ node
642
903
  end
643
904
 
644
- def _bindkey(key, action, keywords: [])
905
+ def _bindkey(key, action, keywords: [], args: nil, template: nil)
645
906
  key.strip!
646
907
  key.gsub!(/\s+/, " ")
647
908
 
@@ -650,17 +911,20 @@ class KeyBindingTree
650
911
  # return
651
912
  # end
652
913
  # $action_list << { :action => action, :key => key }
653
- if !vma.actions.include?(action)
914
+ if !@actions.include?(action)
654
915
  if action.class == String
655
- reg_act(action, proc { eval(action) }, action)
916
+ # Ruby code, run by exec_action (code: true keeps it apart from
917
+ # dotted action ids, which are strings too)
918
+ @actions.register(action, Action.new(action, action, proc { eval(action) }, { code: true }))
656
919
  end
657
920
  end
658
921
 
659
922
  m = key.match(/^(\S+)\s(\S.*)$/)
660
923
  # Match/split e.g. "VC , , s" to "VC" and ", , s"
924
+ modes = nil
661
925
  if m
662
926
  modetmp = m[1]
663
- debug [key, modetmp, m].inspect
927
+ log [key, modetmp, m].inspect
664
928
 
665
929
  # If all of first word are uppercase, e.g. in
666
930
  # "VCIX left" => "buf.move(BACKWARD_CHAR)",
@@ -668,33 +932,54 @@ class KeyBindingTree
668
932
  modes = modetmp.split("") if modetmp.match(/^\p{Lu}+$/) # Uppercase
669
933
 
670
934
  # If all of first word is down case, like in:
671
- # bindkey "audio space", :audio_stop
935
+ # bindkey "audio space", "audio.stop"
672
936
  # interpret as whole word representing a mode.
673
937
  modes = [modetmp] if modetmp.match(/^\p{Ll}+$/) # Lowercase
674
938
  keydef = m[2]
675
939
  else
676
- fatal_error("Error in keydef #{key.inspect}")
940
+ @fatal_handler.call("Error in keydef #{key.inspect}")
941
+ end
942
+
943
+ # Mode part is neither all uppercase nor all lowercase, e.g. "Fexp , x"
944
+ if modes.nil?
945
+ error("bindkey: invalid mode #{modetmp.inspect} in #{key.inspect}: " \
946
+ "mode must be all uppercase (major modes, e.g. \"C\") or all " \
947
+ "lowercase (minor modes, e.g. \"fexp\"). Binding skipped.")
948
+ return
677
949
  end
678
950
 
679
951
  # puts "keywords #{keywords}"
680
952
  modes.each { |mode_id|
681
- mode_bind_key(mode_id, keydef, action, keywords: keywords)
953
+ next if !mode_bind_key(mode_id, keydef, action, keywords: keywords, args: args, template: template)
682
954
 
683
- # Map froma actions to keybindings (e.g. to show bindings in menu)
684
- @act_bindings[mode_id][action] = keydef
955
+ # Map froma actions to keybindings (e.g. to show bindings in menu).
956
+ # Not for template expansions: the action has hundreds of them.
957
+ @act_bindings[mode_id][action] = keydef if template.nil?
685
958
  }
686
959
  end
687
960
 
688
961
  # Binds a keyboard key combination to an action,
689
962
  # for a given keyboard mode like insert ("I") or command ("C")
690
- def mode_bind_key(mode_id, keydef, action, keywords: [])
963
+ # Returns true if the binding was created, false if the mode is unknown.
964
+ def mode_bind_key(mode_id, keydef, action, keywords: [], args: nil, template: nil)
691
965
  # debug "mode_bind_key #{mode_id.inspect}, #{keydef.inspect}, #{action.inspect}", 2
692
966
  # Example:
693
- # bindkey "C , f", :gui_file_finder
967
+ # bindkey "C , f", "file.finder"
694
968
  # mode_id = "C", keydef = ", f"
695
- # and action = :gui_file_finder
696
-
697
- set_state(mode_id, "") # TODO: check is ok?
969
+ # and action = "file.finder"
970
+
971
+ # Bind only to a mode that exists. Without this check the binding would
972
+ # silently end up in the current default mode (see set_state), e.g. a
973
+ # 'bindkey "fexp , x"' in custom.rb (loaded before FileManager.init creates
974
+ # the fexp mode) would become "C , x" and fire in every buffer.
975
+ mode_state = @root.children.find { |s| s.key_name == mode_id }
976
+ if mode_state.nil?
977
+ error("bindkey: unknown mode #{mode_id.inspect} for #{keydef.inspect} => " \
978
+ "#{action.inspect}. Binding skipped. If the mode is created by a " \
979
+ "module, bind it in hook_custom_after_init.")
980
+ return false
981
+ end
982
+ @cur_state = mode_state
698
983
  start_state = @cur_state
699
984
 
700
985
  k_arr = keydef.split #e.g. definition: "C y e" = > ["C", "y", "e"]
@@ -739,29 +1024,33 @@ class KeyBindingTree
739
1024
  prev_state.children.delete(cur_state)
740
1025
  else
741
1026
  @cur_state.action = action
1027
+ @cur_state.seq = (@bind_seq += 1)
1028
+ @cur_state.bind_args = args
1029
+ @cur_state.template = template
742
1030
  end
743
1031
  @cur_state.keywords = keywords
744
1032
  @cur_state = @root
1033
+ return true
745
1034
  end
746
1035
 
747
1036
  def handle_key_bindigs_action(action, c)
748
1037
  trail_str = get_state_trail_str[0]
1038
+ # Emitted before execution so key logs show the entry even if the action raises
1039
+ emit(:key_action, trail_str, action)
749
1040
  # $acth << action #TODO:needed here?
750
1041
  @method_handles_repeat = false #TODO:??
751
1042
  n = 1
752
- if @next_command_count and !(action.class == String and action.include?("set_next_command_count"))
1043
+ counting = action.class == String && (action.include?("set_next_command_count") || action.include?("kbd.count.digit"))
1044
+ if @next_command_count and !counting
753
1045
  n = @next_command_count
754
- debug("COUNT command #{n} times")
1046
+ log("COUNT command #{n} times")
755
1047
  end
756
1048
 
757
1049
  begin
758
1050
  n.times do
759
- ret = exec_action(action)
1051
+ ret = @action_handler.call(action)
760
1052
 
761
- if vma.macro.is_recording and ret != false
762
- debug "RECORD ACTION:#{action}", 2
763
- vma.macro.record_action(action)
764
- end
1053
+ emit(:action_executed, action, ret)
765
1054
  break if @method_handles_repeat
766
1055
  # Some methods have specific implementation for repeat,
767
1056
  # like '5yy' => copy next five lines. (copy_line())
@@ -769,52 +1058,25 @@ class KeyBindingTree
769
1058
  # like '20j' => go to next line 20 times.
770
1059
  # But methods can also handle the number input themselves if vma.kbd.method_handles_repeat=true is set,
771
1060
  end
772
- # run_as_idle proc { vma.buf.refresh_cursor; vma.buf.refresh_cursor }, delay: 0.05
773
- rescue SyntaxError
774
- message("SYNTAX ERROR with eval cmd #{action}: " + $!.to_s)
775
- # rescue NoMethodError
776
- # debug("NoMethodError with eval cmd #{action}: " + $!.to_s)
777
- # rescue NameError
778
- # debug("NameError with eval cmd #{action}: " + $!.to_s)
779
- # raise
780
1061
  rescue Exception => e
781
- puts "BACKTRACE"
782
- puts e.backtrace
783
- puts e.inspect
784
- puts "BACKTRACE END"
785
- if $!.class == SystemExit
786
- exit
787
- else
788
- crash("Error with action: #{action}: ", e)
789
- end
1062
+ raise if @on_action_error.nil?
1063
+ @on_action_error.call(action, e)
790
1064
  end
791
1065
 
792
- if !(action.class == String and action.include?("set_next_command_count"))
1066
+ if !counting
793
1067
  @next_command_count = nil
794
1068
  end
795
1069
 
796
- if cnf.kbd.show_prev_action? and trail_str.class == String
797
- len_limit = 35
798
- action_desc = "UNK"
799
- if action.class == String && (m = action.match(/\Abuf\.insert_txt\((.+)\)\z/))
800
- char_part = m[1].gsub("&", "&amp;").gsub("<", "&lt;").gsub(">", "&gt;")
801
- action_desc = "insert #{char_part}"
802
- else
803
- action_desc = vma.actions[action]&.method_name || action.to_s
804
- action_desc = action_desc[0..len_limit] if action_desc.size > len_limit
805
- end
806
- trail_str = trail_str.gsub("&", "&amp;").gsub("<", "&lt;").gsub(">", "&gt;")
807
- vma.gui.action_trail_label.markup = "<span weight='bold'>#{action_desc}|#{trail_str}</span>"
808
- end
1070
+ emit(:action_handled, trail_str, action)
809
1071
  end
810
1072
  end
811
1073
 
812
- def bindkey(key, action, keywords: "")
813
- vma.kbd.bindkey(key, action, keywords: keywords)
1074
+ def bindkey(key, action, keywords: "", filter: nil)
1075
+ vma.kbd.bindkey(key, action, keywords: keywords, filter: filter)
814
1076
  end
815
1077
 
816
- def unbindkey(key)
817
- vma.kbd.unbindkey(key)
1078
+ def unbindkey(key, include_child_nodes: false)
1079
+ vma.kbd.unbindkey(key, include_child_nodes: include_child_nodes)
818
1080
  end
819
1081
 
820
1082
  def add_keys(keywords, to_add)
@@ -826,10 +1088,15 @@ end
826
1088
  def exec_action(action)
827
1089
  vma.kbd.last_action = vma.kbd.cur_action
828
1090
  vma.kbd.cur_action = action
1091
+ action = action.to_s if ActionRef === action
829
1092
  if action.class == Symbol
830
1093
  return call_action(action)
831
1094
  elsif action.class == Proc
832
1095
  return action.call
1096
+ elsif action.class == String && (r = vma.actions[action]) && !r.opt&.[](:code)
1097
+ # A dotted action id ("move.word.next"). Registered actions win over
1098
+ # running the string as Ruby, even where the id is valid Ruby too.
1099
+ return call_action(action)
833
1100
  elsif action.class == String && vma.actions.include?(action.to_sym)
834
1101
  # Symbols serialised through JSON become plain strings; dispatch them as actions.
835
1102
  return call_action(action.to_sym)
@@ -838,80 +1105,6 @@ def exec_action(action)
838
1105
  end
839
1106
  end
840
1107
 
841
- def show_free_key_bindings()
842
- kbd_s = "❙Free key binding slots❙\n"
843
- kbd_s << "\n⦁[Mode] <prefix> : <free keys>⦁\n"
844
- kbd_s << "[B]=Browse, [C]=Command, [I]=Insert, [V]=Visual\n"
845
- kbd_s << "Free = not yet bound under that prefix\n"
846
- kbd_s << "===============================================\n"
847
- kbd_s << vma.kbd.get_free_bindings
848
- kbd_s << "\n"
849
- b = create_new_buffer(kbd_s, "free-key-bindings")
850
- gui_set_file_lang(b.id, "hyperplaintext")
851
- end
852
-
853
- def show_key_bindings()
854
- kbd_s = "❙Key bindings❙\n"
855
- kbd_s << "\n⦁[Mode] <keys> : <action>⦁\n"
856
- done = []
857
-
858
- kbd_s << "[B]=Browse, [C]=Command, [I]=Insert, [V]=Visual\n"
859
- kbd_s << "<key>!: Press <key> once, release before pressing any other keys\n"
860
- kbd_s << "===============================================\n"
861
- kbd_s << "◼ Basic\n"
862
- kbd_s << "◼◼ Command mode\n"
863
-
864
- x = vma.kbd.get_by_keywords(modes: ["C"], keywords: ["intro"])
865
- done.concat(x.lines); kbd_s << x
866
-
867
- kbd_s << "\n"
868
- kbd_s << "◼◼ Insert mode\n"
869
- x = vma.kbd.get_by_keywords(modes: ["I"], keywords: ["intro"])
870
- done.concat(x.lines); kbd_s << x
871
- kbd_s << "\n"
872
- kbd_s << "◼◼ Visual mode\n"
873
- x = vma.kbd.get_by_keywords(modes: ["V"], keywords: ["intro"])
874
- done.concat(x.lines); kbd_s << x
875
- kbd_s << "\n"
876
-
877
- kbd_s << "◼ Hyper Plaintext\n"
878
- x = vma.kbd.get_by_keywords(modes: ["C"], keywords: ["hyperplaintext"])
879
- x2 = vma.kbd.get_by_keywords(modes: ["V"], keywords: ["hyperplaintext"])
880
- done.concat(x.lines); kbd_s << x << "\n" << x2
881
- kbd_s << "\n"
882
-
883
- kbd_s << "◼ Core\n"
884
- x = vma.kbd.get_by_keywords(modes: [], keywords: ["core"])
885
- x << vma.kbd.get_by_keywords(modes: ["X"], keywords: ["intro"])
886
-
887
- done.concat(x.lines); kbd_s << x
888
- kbd_s << "\n"
889
-
890
- kbd_s << "◼ Debug / Experimental\n"
891
- x = vma.kbd.get_by_keywords(modes: [], keywords: ["experimental"])
892
- done.concat(x.lines); kbd_s << x
893
- kbd_s << "\n"
894
-
895
- kbd_s << "◼ Others\n"
896
- # x = vma.kbd.get_by_keywords(modes: [], keywords:["experimental"])
897
- # x = vma.kbd.to_s
898
- x = vma.kbd.get_by_keywords(modes: [], keywords: [])
899
- done << x.lines - done
900
- kbd_s << (x.lines - done).join
901
- kbd_s << "\n"
902
-
903
- kbd_s << "===============================================\n"
904
- # x = vma.kbd.to_s
905
- # # require "pry"; binding.pry
906
- # done << x.lines - done
907
- # kbd_s << (x.lines - done).join
908
- # kbd_s << "\n"
909
- # kbd_s << "===============================================\n"
910
- b = create_new_buffer(kbd_s, "key-bindings")
911
- gui_set_file_lang(b.id, "hyperplaintext")
912
- #
913
- end
914
-
915
1108
  # Try to clear modifiers when program loses focus
916
1109
  # e.g. after alt-tab
917
1110
  # TODO
@@ -923,3 +1116,4 @@ end
923
1116
  # def handle_key_event(event)
924
1117
  # vma.kbd.handle_key_event(event)
925
1118
  # end
1119
+ end # module Vimamsa