Class: Rvim::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/rvim/command.rb

Defined Under Namespace

Classes: Parsed, UserCommand

Constant Summary collapse

SET_TOKEN_RE =
/\A(no)?(\w+)(?:=(\S+))?\??\z/
SUBSTITUTE_RE =
%r{
  \A
  (?<range>%|\d+(?:,\d+)?|'<,'>)?
  s/
  (?<pat>(?:\\.|[^/])*)
  /
  (?<rep>(?:\\.|[^/])*)
  /?
  (?<flags>[gi]*)?
  \z
}x
FILTER_RE =
/\A(?<range>%|\d+(?:,\d+)?|'<,'>)?!(?<cmd>.*)\z/.freeze
SORT_RE =
/\A
  (?<range>%|\d+(?:,\d+)?|'<,'>)?
  \s*sort
  (?<bang>!)?
  (?:\s+(?<flags>[uni]+))?
  \z
/x.freeze
MAP_MODIFIER_RE =
/\A<(silent|unique|buffer|expr|nowait|script)>\s+/i.freeze
MODE_TAGS =
{
  normal: 'n',
  visual: 'v',
  insert: 'i',
  op_pending: 'o',
  cmdline: 'c',
}.freeze
VIMGREP_RE =
%r{\A/(?<pat>(?:\\.|[^/])*)/\s+(?<files>.+)\z}.freeze
LET_RE =
/\A(?<name>\w+)\s*=\s*(?<value>.*)\z/.freeze
ABBREV_MODES =
{
  abbrev: %i[insert cmdline],
  iabbrev: %i[insert],
  cabbrev: %i[cmdline],
  noreabbrev: %i[insert cmdline],
  inoreabbrev: %i[insert],
  cnoreabbrev: %i[cmdline],
  unabbrev: %i[insert cmdline],
  iunabbrev: %i[insert],
  cunabbrev: %i[cmdline],
  abclear: %i[insert cmdline],
  iabclear: %i[insert],
  cabclear: %i[cmdline],
}.freeze
USER_COMMAND_RE =
/\A(?:-nargs=(?<nargs>[01*+?])\s+)?(?<name>[A-Z][A-Za-z0-9_]*)\s+(?<body>.+)\z/m.freeze
ABBREV_MODE_TAGS =
{ insert: 'i', cmdline: 'c' }.freeze
KIND_TAGS =
{ char: 'c', line: 'l', block: 'b' }.freeze

Class Method Summary collapse

Class Method Details

.any_modified?(editor) ⇒ Boolean

Returns:

  • (Boolean)


2050
2051
2052
2053
2054
2055
# File 'lib/rvim/command.rb', line 2050

def self.any_modified?(editor)
  editor.send(:save_current_buffer) if editor.current_buffer
  return true if editor.modified

  editor.buffers.values.any?(&:modified)
end

.build_session_script(editor) ⇒ Object



1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
# File 'lib/rvim/command.rb', line 1773

def self.build_session_script(editor)
  out = []
  out << '" rvim session script — re-source with :source <file>'
  out << "cd #{Dir.pwd}"

  # Buffers — :badd adds them without switching.
  editor.buffers.each_value do |buf|
    next unless buf.filepath

    out << "badd #{buf.filepath}"
  end

  # Current file gets focused via :edit.
  if editor.filepath
    out << "edit #{editor.filepath}"
  end

  out
end

.colorscheme_search_paths(name) ⇒ Object



1033
1034
1035
1036
1037
1038
# File 'lib/rvim/command.rb', line 1033

def self.colorscheme_search_paths(name)
  [
    File.expand_path("~/.config/rvim/colors/#{name}.vim"),
    File.expand_path("~/.rvim/colors/#{name}.vim"),
  ]
end

.compile_sub_pattern(str, ignorecase: false) ⇒ Object



2096
2097
2098
2099
2100
# File 'lib/rvim/command.rb', line 2096

def self.compile_sub_pattern(str, ignorecase: false)
  Regexp.new(str, ignorecase ? Regexp::IGNORECASE : 0)
rescue RegexpError
  nil
end

.confirm_destructive_quit(editor) ⇒ Object



1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
# File 'lib/rvim/command.rb', line 1901

def self.confirm_destructive_quit(editor)
  editor.confirm_prompt('Save changes before closing?', %w[y n c]) do |choice|
    case choice
    when 'y'
      save_all_modified(editor)
      editor.quit! unless any_modified?(editor)
    when 'n'
      editor.quit!
    when 'c'
      editor.status_message = 'Cancelled'
    end
  end
end

.current_location_list(editor) ⇒ Object



1155
1156
1157
1158
1159
1160
1161
1162
1163
# File 'lib/rvim/command.rb', line 1155

def self.current_location_list(editor)
  win = editor.current_window
  unless win
    editor.status_message = 'E776: no location list (no current window)'
    return nil
  end

  win.location_list
end

.effective_sub_ignorecase(editor, pattern_str) ⇒ Object



2102
2103
2104
2105
2106
2107
2108
# File 'lib/rvim/command.rb', line 2102

def self.effective_sub_ignorecase(editor, pattern_str)
  Rvim::Search.effective_ignorecase(
    pattern_str,
    ignorecase: editor.settings.get(:ignorecase),
    smartcase: editor.settings.get(:smartcase),
  )
end

.ensure_buffer_nonempty(editor) ⇒ Object



750
751
752
753
754
755
756
# File 'lib/rvim/command.rb', line 750

def self.ensure_buffer_nonempty(editor)
  if editor.buffer_of_lines.empty?
    editor.buffer_of_lines << String.new('', encoding: editor.encoding)
    editor.instance_variable_set(:@line_index, 0)
    editor.instance_variable_set(:@byte_pointer, 0)
  end
end

.execute(editor, parsed) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# File 'lib/rvim/command.rb', line 272

def self.execute(editor, parsed)
  return unless parsed

  case parsed.verb
  when :w
    execute_write(editor, parsed)
  when :q
    execute_quit(editor, parsed)
  when :qa
    execute_quit_all(editor, parsed)
  when :wq
    execute_write(editor, parsed)
    execute_quit(editor, parsed)
  when :cq
    editor.quit!(exit_code: 1)
  when :e
    if parsed.arg.nil? || parsed.arg.empty?
      editor.status_message = 'E32: No file name'
    else
      editor.open(parsed.arg)
    end
  when :bn
    editor.next_buffer
  when :bp
    editor.prev_buffer
  when :b
    if parsed.arg.nil? || parsed.arg.empty?
      editor.status_message = 'E32: No buffer specified'
    else
      editor.switch_buffer_by(parsed.arg)
    end
  when :bd
    editor.delete_current_buffer(force: parsed.bang)
  when :set
    execute_set(editor, parsed, local: false)
  when :setlocal
    execute_set(editor, parsed, local: true)
  when :ls
    editor.show_list(format_buffers(editor))
  when :marks
    editor.show_list(format_marks(editor))
  when :jumps
    editor.show_list(format_jumps(editor))
  when :registers
    filter_chars = parsed.arg.to_s.scan(/\S/).reject { |c| c == '"' }
    editor.show_list(format_registers(editor, filter: filter_chars))
  when :tabnext
    editor.tab_advance
  when :tabprev
    editor.tab_retreat
  when :tabnew
    editor.tab_new(parsed.arg)
  when :tabclose
    editor.tab_close
  when :tabonly
    editor.tab_only
  when :tabmove
    execute_tabmove(editor, parsed)
  when :resize
    execute_resize(editor, parsed, vertical: false)
  when :vertical
    # :vertical resize N — parsed.arg should start with "resize"
    if parsed.arg.to_s.strip.start_with?('resize', 'res')
      inner = parsed.arg.to_s.sub(/\A(resize|res)\s*/, '')
      execute_resize(editor, Parsed.new(verb: :resize, arg: inner, bang: false, line_number: nil), vertical: true)
    end
  when :sp
    if parsed.arg && !parsed.arg.empty?
      editor.open(parsed.arg)
    end
    editor.split_horizontal
  when :vsp
    if parsed.arg && !parsed.arg.empty?
      editor.open(parsed.arg)
    end
    editor.split_vertical
  when :goto
    last = editor.buffer_of_lines.size - 1
    target = (parsed.line_number - 1).clamp(0, last)
    editor.push_jump
    editor.instance_variable_set(:@line_index, target)
    editor.send(:snap_to_visible)
    editor.instance_variable_set(:@byte_pointer, 0)
  when :sub
    execute_substitute(editor, parsed)
  when :source
    if parsed.arg.nil? || parsed.arg.empty?
      editor.status_message = 'E471: Argument required'
    else
      editor.source(parsed.arg)
    end
  when :runtime
    execute_runtime(editor, parsed)
  when :packadd
    execute_packadd(editor, parsed)
  when :messages
    editor.show_list(['Messages:'] + (editor.messages || []))
  when :execute_cmd
    execute_execute(editor, parsed)
  when :silent
    execute_silent(editor, parsed)
  when :verbose
    execute_verbose(editor, parsed)
  when :redir
    execute_redir(editor, parsed)
  when :user_command_def
    execute_user_command_def(editor, parsed)
  when :user_command_del
    execute_user_command_del(editor, parsed)
  when :help
    execute_help(editor, parsed)
  when :helpclose
    editor.close_help_buffer
  when :earlier
    execute_earlier(editor, parsed)
  when :later
    execute_later(editor, parsed)
  when :undolist
    editor.show_list(format_undo_list(editor))
  when :mksession
    execute_mksession(editor, parsed)
  when :badd
    if parsed.arg && !parsed.arg.empty?
      editor.add_buffer(parsed.arg.strip)
    end
  when :terminal
    execute_terminal(editor, parsed)
  when :lua_chunk
    editor.lua.eval(parsed.arg.to_s)
  when :luafile
    if parsed.arg.nil? || parsed.arg.empty?
      editor.status_message = 'E471: Argument required'
    else
      editor.lua.load_file(File.expand_path(parsed.arg.to_s.strip))
    end
  when :history
    editor.show_list(format_history(editor))
  when :map, :nmap, :vmap, :imap, :omap, :cmap,
       :noremap, :nnoremap, :vnoremap, :inoremap, :onoremap, :cnoremap
    execute_map(editor, parsed)
  when :unmap, :nunmap, :vunmap, :iunmap, :ounmap, :cunmap
    execute_unmap(editor, parsed)
  when :mapclear, :nmapclear, :vmapclear, :imapclear, :omapclear, :cmapclear
    execute_mapclear(editor, parsed)
  when :abbrev, :iabbrev, :cabbrev, :noreabbrev, :inoreabbrev, :cnoreabbrev
    execute_abbrev(editor, parsed)
  when :unabbrev, :iunabbrev, :cunabbrev
    execute_unabbrev(editor, parsed)
  when :abclear, :iabclear, :cabclear
    execute_abclear(editor, parsed)
  when :let
    execute_let(editor, parsed)
  when :fold
    execute_fold(editor, parsed)
  when :bang
    execute_bang(editor, parsed)
  when :filter
    execute_filter(editor, parsed)
  when :r
    execute_read(editor, parsed)
  when :autocmd
    execute_autocmd(editor, parsed)
  when :augroup
    execute_augroup(editor, parsed)
  when :sort
    execute_sort(editor, parsed)
  when :delete
    execute_delete(editor, parsed)
  when :yank
    execute_yank(editor, parsed)
  when :put
    execute_put(editor, parsed)
  when :move
    execute_move(editor, parsed)
  when :copy
    execute_copy(editor, parsed)
  when :join
    execute_join(editor, parsed)
  when :nohlsearch
    execute_nohlsearch(editor, parsed)
  when :retab
    execute_retab(editor, parsed)
  when :cd
    execute_cd(editor, parsed)
  when :pwd
    execute_pwd(editor, parsed)
  when :vimgrep
    execute_vimgrep(editor, parsed)
  when :cnext
    execute_cnext(editor, parsed)
  when :cprev
    execute_cprev(editor, parsed)
  when :cc
    execute_cc(editor, parsed)
  when :clist, :copen
    editor.show_list(format_quickfix(editor))
  when :cclose
    editor.dismiss_list
  when :lvimgrep
    execute_lvimgrep(editor, parsed)
  when :lnext
    execute_lnext(editor, parsed)
  when :lprev
    execute_lprev(editor, parsed)
  when :ll
    execute_ll(editor, parsed)
  when :llist, :lopen
    editor.show_list(format_location_list(editor))
  when :lclose
    editor.dismiss_list
  when :lmake
    execute_lmake(editor, parsed)
  when :lgrep
    execute_lgrep(editor, parsed)
  when :diffthis
    execute_diffthis(editor, parsed)
  when :diffoff
    execute_diffoff(editor, parsed)
  when :diffupdate
    editor.recompute_diff_status
  when :diffsplit
    execute_diffsplit(editor, parsed)
  when :hi
    execute_hi(editor, parsed)
  when :colorscheme
    execute_colorscheme(editor, parsed)
  when :digraphs
    execute_digraphs(editor, parsed)
  when :tag
    execute_tag(editor, parsed)
  when :tags_list
    editor.show_list(format_tag_stack(editor))
  when :tnext
    editor.tag_next
  when :tprev
    editor.tag_prev
  when :bufdo
    execute_bufdo(editor, parsed)
  when :tabdo
    execute_tabdo(editor, parsed)
  when :windo
    execute_windo(editor, parsed)
  when :argdo
    execute_argdo(editor, parsed)
  when :args
    execute_args(editor, parsed)
  when :argadd
    execute_argadd(editor, parsed)
  when :make
    execute_make(editor, parsed)
  when :grep
    execute_grep(editor, parsed)
  else
    if (uc = editor.user_commands[parsed.verb.to_s])
      execute_user_command(editor, uc, parsed)
    else
      editor.status_message = "E492: Not an editor command: #{parsed.verb}"
    end
  end
end

.execute_abbrev(editor, parsed) ⇒ Object



1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
# File 'lib/rvim/command.rb', line 1511

def self.execute_abbrev(editor, parsed)
  arg = parsed.arg.to_s.strip
  modes = ABBREV_MODES[parsed.verb] || %i[insert cmdline]

  if arg.empty?
    editor.show_list(format_abbreviations(editor, modes))
    return
  end

  lhs, rhs = arg.split(/\s+/, 2)
  if rhs.nil? || rhs.empty?
    editor.show_list(format_abbreviations(editor, modes, lhs_filter: lhs))
    return
  end

  recursive = !%i[noreabbrev inoreabbrev cnoreabbrev].include?(parsed.verb)
  editor.abbreviations.add(modes, lhs, rhs, recursive: recursive)
end

.execute_abclear(editor, parsed) ⇒ Object



1541
1542
1543
1544
# File 'lib/rvim/command.rb', line 1541

def self.execute_abclear(editor, parsed)
  modes = ABBREV_MODES[parsed.verb] || %i[insert cmdline]
  editor.abbreviations.clear(modes)
end

.execute_argadd(editor, parsed) ⇒ Object



893
894
895
896
897
898
# File 'lib/rvim/command.rb', line 893

def self.execute_argadd(editor, parsed)
  arg = parsed.arg.to_s.strip
  return if arg.empty?

  arg.split(/\s+/).each { |p| editor.add_arg(p) }
end

.execute_argdo(editor, parsed) ⇒ Object



867
868
869
870
871
872
873
874
875
# File 'lib/rvim/command.rb', line 867

def self.execute_argdo(editor, parsed)
  cmd = parsed.arg.to_s
  return if cmd.empty?

  editor.arg_list.each do |path|
    editor.open(path)
    execute(editor, parse(cmd))
  end
end

.execute_args(editor, parsed) ⇒ Object



877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
# File 'lib/rvim/command.rb', line 877

def self.execute_args(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    list = editor.arg_list
    if list.empty?
      editor.status_message = 'E163: there is no argument list'
    else
      editor.show_list(['Argument list', *list.each_with_index.map { |p, i| format('   %2d  %s', i + 1, p) }])
    end
    return
  end

  paths = arg.split(/\s+/).flat_map { |p| Dir.glob(p).empty? ? [p] : Dir.glob(p) }
  editor.set_arg_list(paths)
end

.execute_augroup(editor, parsed) ⇒ Object



1359
1360
1361
1362
1363
1364
1365
1366
# File 'lib/rvim/command.rb', line 1359

def self.execute_augroup(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty? || arg.casecmp?('END')
    editor.autocommands.current_group = nil
  else
    editor.autocommands.current_group = arg
  end
end

.execute_autocmd(editor, parsed) ⇒ Object



1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
# File 'lib/rvim/command.rb', line 1324

def self.execute_autocmd(editor, parsed)
  arg = parsed.arg.to_s.strip

  if parsed.bang
    if arg.empty?
      editor.autocommands.clear_group(editor.autocommands.current_group)
      return
    end

    parts = arg.split(/\s+/, 3)
    events = parts[0].split(',')
    pattern = parts[1]
    events.each do |ev|
      editor.autocommands.remove(event: ev, pattern: pattern)
    end
    return
  end

  if arg.empty?
    editor.show_list(format_autocommands(editor))
    return
  end

  parts = arg.split(/\s+/, 3)
  if parts.size < 3
    editor.status_message = 'E471: Argument required: :autocmd events pattern command'
    return
  end

  events_token, patterns_token, command = parts
  events = events_token.split(',')
  patterns = patterns_token.split(',')
  editor.autocommands.add(events, patterns, command)
end

.execute_bang(editor, parsed) ⇒ Object



1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
# File 'lib/rvim/command.rb', line 1383

def self.execute_bang(editor, parsed)
  cmd = parsed.arg.to_s
  if cmd.start_with?('!')
    if editor.last_bang_cmd
      cmd = editor.last_bang_cmd + cmd[1..]
    else
      editor.status_message = 'E34: no previous command'
      return
    end
  end
  cmd = expand_filenames(editor, cmd)
  editor.last_bang_cmd = cmd

  result = Rvim::Filter.run(cmd, shell: editor.settings.get(:shell), shellcmdflag: editor.settings.get(:shellcmdflag))
  if result.success?
    lines = result.stdout.chomp("\n").split("\n", -1)
    lines = ['(no output)'] if lines.empty? || lines == ['']
    editor.show_list(lines)
  else
    editor.status_message = filter_error_status(result)
  end
end

.execute_bufdo(editor, parsed) ⇒ Object



828
829
830
831
832
833
834
835
836
837
838
839
840
841
# File 'lib/rvim/command.rb', line 828

def self.execute_bufdo(editor, parsed)
  cmd = parsed.arg.to_s
  return if cmd.empty?

  saved = editor.current_buffer
  editor.buffer_order.each do |id|
    buf = editor.buffers[id]
    next unless buf

    editor.swap_to_buffer(buf)
    execute(editor, parse(cmd))
  end
  editor.swap_to_buffer(saved) if saved && editor.buffers.values.include?(saved)
end

.execute_cc(editor, parsed) ⇒ Object



1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
# File 'lib/rvim/command.rb', line 1255

def self.execute_cc(editor, parsed)
  qf = editor.quickfix
  if qf.empty?
    editor.status_message = 'E42: No Errors'
    return
  end

  n = parsed.arg.to_s.strip
  idx = n.empty? ? qf.index : n.to_i - 1
  entry = qf.at(idx)
  if entry
    jump_to_quickfix_entry(editor, entry)
    editor.status_message = "(#{qf.index + 1} of #{qf.size}) #{format_quickfix_summary(entry)}"
  else
    editor.status_message = "E553: No more items"
  end
end

.execute_cd(editor, parsed) ⇒ Object



721
722
723
724
725
726
727
728
# File 'lib/rvim/command.rb', line 721

def self.execute_cd(editor, parsed)
  path = parsed.arg.to_s.strip
  target = path.empty? ? Dir.home : File.expand_path(path)
  Dir.chdir(target)
  editor.status_message = Dir.pwd
rescue => e
  editor.status_message = "E: cd: #{e.message}"
end

.execute_cnext(editor, _parsed) ⇒ Object



1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
# File 'lib/rvim/command.rb', line 1231

def self.execute_cnext(editor, _parsed)
  qf = editor.quickfix
  if qf.empty?
    editor.status_message = 'E42: No Errors'
    return
  end

  entry = qf.advance(+1)
  jump_to_quickfix_entry(editor, entry)
  editor.status_message = "(#{qf.index + 1} of #{qf.size}) #{format_quickfix_summary(entry)}"
end

.execute_colorscheme(editor, parsed) ⇒ Object



1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
# File 'lib/rvim/command.rb', line 1012

def self.execute_colorscheme(editor, parsed)
  name = parsed.arg.to_s.strip
  if name.empty?
    editor.status_message = 'colorscheme name required'
    return
  end

  if name == 'default'
    Rvim::Highlights.reset_to_defaults!
    return
  end

  paths = colorscheme_search_paths(name)
  target = paths.find { |p| File.exist?(p) }
  if target
    editor.source(target)
  else
    editor.status_message = "E185: Cannot find color scheme '#{name}'"
  end
end

.execute_copy(editor, parsed) ⇒ Object



674
675
676
677
678
679
680
681
682
683
684
685
# File 'lib/rvim/command.rb', line 674

def self.execute_copy(editor, parsed)
  start_line, end_line = resolve_range_default_current(editor, parsed)
  target = parsed.arg.to_i
  last = editor.buffer_of_lines.size - 1
  target = target.clamp(0, last + 1)

  copied = editor.buffer_of_lines[start_line..end_line].map(&:dup)
  editor.buffer_of_lines.insert(target, *copied)
  editor.instance_variable_set(:@line_index, target)
  editor.instance_variable_set(:@byte_pointer, 0)
  editor.modified = true
end

.execute_cprev(editor, _parsed) ⇒ Object



1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
# File 'lib/rvim/command.rb', line 1243

def self.execute_cprev(editor, _parsed)
  qf = editor.quickfix
  if qf.empty?
    editor.status_message = 'E42: No Errors'
    return
  end

  entry = qf.advance(-1)
  jump_to_quickfix_entry(editor, entry)
  editor.status_message = "(#{qf.index + 1} of #{qf.size}) #{format_quickfix_summary(entry)}"
end

.execute_delete(editor, parsed) ⇒ Object



604
605
606
607
608
609
610
611
612
613
614
615
616
617
# File 'lib/rvim/command.rb', line 604

def self.execute_delete(editor, parsed)
  start_line, end_line = resolve_range_default_current(editor, parsed)
  register = parsed.arg.to_s.strip
  lines = editor.buffer_of_lines[start_line..end_line]
  text = lines.map(&:to_s).join("\n")
  kind = :line
  if register.empty?
    editor.send(:write_register, text, kind, register: nil)
  else
    editor.send(:write_register, text, kind, register: register)
  end
  editor.replace_line_range(start_line, end_line, [])
  ensure_buffer_nonempty(editor)
end

.execute_diffoff(editor, parsed) ⇒ Object



1048
1049
1050
1051
1052
1053
1054
# File 'lib/rvim/command.rb', line 1048

def self.execute_diffoff(editor, parsed)
  bufs = parsed.bang ? editor.buffers.values : [editor.current_buffer].compact
  bufs.each do |b|
    b.diff_active = false
    b.diff_status = nil
  end
end

.execute_diffsplit(editor, parsed) ⇒ Object



1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
# File 'lib/rvim/command.rb', line 1056

def self.execute_diffsplit(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.status_message = 'E32: No file name'
    return
  end

  current = editor.current_buffer
  current.diff_active = true if current
  editor.split_vertical
  editor.open(arg)
  editor.current_buffer.diff_active = true if editor.current_buffer
  editor.recompute_diff_status
end

.execute_diffthis(editor, _parsed) ⇒ Object



1040
1041
1042
1043
1044
1045
1046
# File 'lib/rvim/command.rb', line 1040

def self.execute_diffthis(editor, _parsed)
  buf = editor.current_buffer
  return unless buf

  buf.diff_active = true
  editor.recompute_diff_status
end

.execute_digraphs(editor, parsed) ⇒ Object



918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
# File 'lib/rvim/command.rb', line 918

def self.execute_digraphs(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.show_list(format_digraphs)
    return
  end

  tokens = arg.split(/\s+/)
  pair, code_token = tokens
  if pair.nil? || pair.length != 2 || code_token.nil?
    editor.status_message = 'E471: usage: :digraph d1d2 N'
    return
  end

  code = code_token.to_i
  if code <= 0
    editor.status_message = 'E471: codepoint must be positive integer'
    return
  end

  Rvim::Digraphs.define(pair, code)
end

.execute_earlier(editor, parsed) ⇒ Object



1702
1703
1704
1705
1706
1707
1708
1709
# File 'lib/rvim/command.rb', line 1702

def self.execute_earlier(editor, parsed)
  count, unit = parse_undo_arg(parsed.arg)
  if unit == :count
    count.times { editor.send(:undo, nil) }
  elsif unit == :seconds
    editor.travel_undo_seconds(-count)
  end
end

.execute_execute(editor, parsed) ⇒ Object



1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
# File 'lib/rvim/command.rb', line 1607

def self.execute_execute(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.status_message = 'E471: Argument required'
    return
  end

  # Strip a single pair of surrounding quotes; vim's :execute concatenates
  # quoted strings. For v1 we accept a single-quoted form.
  cmd = if (arg.start_with?("'") && arg.end_with?("'") && arg.length >= 2) ||
           (arg.start_with?('"') && arg.end_with?('"') && arg.length >= 2)
          arg[1..-2]
        else
          arg
        end

  cmd = cmd.start_with?(':') ? cmd : ":#{cmd}"
  sub = parse(cmd)
  execute(editor, sub) if sub
end

.execute_filter(editor, parsed) ⇒ Object



1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
# File 'lib/rvim/command.rb', line 1406

def self.execute_filter(editor, parsed)
  start_line, end_line = resolve_sub_range(editor, parsed.range)
  input = editor.buffer_of_lines[start_line..end_line].join("\n")
  cmd = expand_filenames(editor, parsed.arg.to_s)
  result = Rvim::Filter.run(cmd, input: input, shell: editor.settings.get(:shell), shellcmdflag: editor.settings.get(:shellcmdflag))
  unless result.success?
    editor.status_message = filter_error_status(result)
    return
  end

  out_lines = result.stdout.chomp("\n").split("\n", -1)
  out_lines = [''] if out_lines.empty?
  editor.replace_line_range(start_line, end_line, out_lines)
end

.execute_fold(editor, parsed) ⇒ Object



1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
# File 'lib/rvim/command.rb', line 1455

def self.execute_fold(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.create_fold_at_cursor(1)
    return
  end

  a, b = arg.split(/[,\s]+/, 2).map { |t| t.to_i }
  if a && b && a >= 1 && b >= 1
    editor.create_fold_over(a - 1, b - 1)
  else
    editor.status_message = 'E471: Argument required: :fold N,M'
  end
end

.execute_grep(editor, parsed) ⇒ Object



800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
# File 'lib/rvim/command.rb', line 800

def self.execute_grep(editor, parsed)
  args = parsed.arg.to_s.strip
  if args.empty?
    editor.status_message = 'E471: usage: :grep PATTERN [FILES]'
    return
  end

  prg = editor.settings.get(:grepprg).to_s
  prg = 'grep -n' if prg.empty?
  cmd = if prg.include?('$*')
          prg.sub('$*', args)
        else
          "#{prg} #{args}"
        end
  result = Rvim::Filter.run(cmd, shell: editor.settings.get(:shell), shellcmdflag: editor.settings.get(:shellcmdflag))
  output = result.stdout.to_s
  gfm = editor.settings.get(:grepformat).to_s
  gfm = editor.settings.get(:errorformat).to_s if gfm.empty?
  entries = Rvim::Errorformat.parse(output, gfm)
  editor.quickfix.set(entries)
  if entries.empty?
    editor.status_message = "E480: No match: #{args}"
  else
    editor.status_message = "(1 of #{entries.size}) #{format_quickfix_summary(entries.first)}"
    jump_to_quickfix_entry(editor, entries.first) unless parsed.bang
  end
end

.execute_help(editor, parsed) ⇒ Object



1697
1698
1699
1700
# File 'lib/rvim/command.rb', line 1697

def self.execute_help(editor, parsed)
  topic = parsed.arg.to_s.strip
  editor.open_help_buffer(topic.empty? ? nil : topic)
end

.execute_hi(editor, parsed) ⇒ Object



950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
# File 'lib/rvim/command.rb', line 950

def self.execute_hi(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.show_list(format_highlights)
    return
  end

  tokens = arg.split(/\s+/)
  group = tokens.shift

  if group&.casecmp?('clear')
    if tokens.empty?
      Rvim::Highlights.reset_to_defaults!
    else
      Rvim::Highlights.clear(tokens.first)
    end
    return
  end

  attrs = {}
  tokens.each do |t|
    next unless t.include?('=')

    key, val = t.split('=', 2)
    case key.downcase
    when 'ctermfg' then attrs[:fg] = val
    when 'ctermbg' then attrs[:bg] = val
    when 'cterm', 'gui'
      val.to_s.split(',').each do |a|
        case a.downcase
        when 'bold' then attrs[:bold] = true
        when 'italic' then attrs[:italic] = true
        when 'underline' then attrs[:underline] = true
        when 'reverse', 'inverse' then attrs[:reverse] = true
        when 'none' then attrs.merge!(bold: false, italic: false, underline: false, reverse: false)
        end
      end
    end
  end

  Rvim::Highlights.set(group, **attrs)
end

.execute_join(editor, parsed) ⇒ Object



687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
# File 'lib/rvim/command.rb', line 687

def self.execute_join(editor, parsed)
  start_line, end_line = if parsed.range
                           resolve_sub_range(editor, parsed.range)
                         else
                           cur = editor.line_index
                           last = [cur + 1, editor.buffer_of_lines.size - 1].min
                           [cur, last]
                         end
  return if start_line >= end_line

  sep = parsed.bang ? '' : ' '
  lines = editor.buffer_of_lines[start_line..end_line]
  first = lines.first.to_s
  rest = lines[1..-1].map { |l| l.to_s.lstrip }
  joined = parsed.bang ? (first + rest.join) : ([first.rstrip, *rest.reject(&:empty?)].join(sep))
  editor.replace_line_range(start_line, end_line, [joined])
end

.execute_later(editor, parsed) ⇒ Object



1711
1712
1713
1714
1715
1716
1717
1718
# File 'lib/rvim/command.rb', line 1711

def self.execute_later(editor, parsed)
  count, unit = parse_undo_arg(parsed.arg)
  if unit == :count
    count.times { editor.send(:redo, nil) }
  elsif unit == :seconds
    editor.travel_undo_seconds(count)
  end
end

.execute_let(editor, parsed) ⇒ Object



1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
# File 'lib/rvim/command.rb', line 1472

def self.execute_let(editor, parsed)
  arg = parsed.arg.to_s.strip
  m = LET_RE.match(arg)
  unless m
    editor.status_message = 'E121: Undefined variable: usage :let name = value'
    return
  end

  raw = m[:value].strip
  value = if raw.start_with?("'") && raw.end_with?("'") && raw.length >= 2
            raw[1..-2]
          elsif raw.start_with?('"') && raw.end_with?('"') && raw.length >= 2
            raw[1..-2]
          else
            raw
          end
  editor.let_vars[m[:name]] = value
end

.execute_lgrep(editor, parsed) ⇒ Object



1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
# File 'lib/rvim/command.rb', line 1134

def self.execute_lgrep(editor, parsed)
  list = current_location_list(editor)
  return unless list

  args = parsed.arg.to_s.strip
  if args.empty?
    editor.status_message = 'E471: usage: :lgrep PATTERN [FILES]'
    return
  end

  prg = editor.settings.get(:grepprg).to_s
  prg = 'grep -n $* /dev/null' if prg.empty?
  cmd = prg.include?('$*') ? prg.sub('$*', args) : "#{prg} #{args}"
  result = Rvim::Filter.run(cmd, shell: editor.settings.get(:shell), shellcmdflag: editor.settings.get(:shellcmdflag))
  gfm = editor.settings.get(:grepformat).to_s
  gfm = editor.settings.get(:errorformat).to_s if gfm.empty?
  entries = Rvim::Errorformat.parse(result.stdout.to_s, gfm)
  list.set(entries)
  report_list_status(editor, entries, parsed.bang, "E480: No match: #{args}")
end

.execute_ll(editor, parsed) ⇒ Object



1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
# File 'lib/rvim/command.rb', line 1102

def self.execute_ll(editor, parsed)
  list = current_location_list(editor)
  if list.nil? || list.empty?
    editor.status_message = 'E776: no location list'
    return
  end

  n = parsed.arg.to_s.strip
  idx = n.empty? ? list.index : n.to_i - 1
  entry = list.at(idx)
  if entry
    jump_to_quickfix_entry(editor, entry)
  else
    editor.status_message = 'E553: No more items'
  end
end

.execute_lmake(editor, parsed) ⇒ Object



1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
# File 'lib/rvim/command.rb', line 1119

def self.execute_lmake(editor, parsed)
  list = current_location_list(editor)
  return unless list

  args = parsed.arg.to_s
  prg = editor.settings.get(:makeprg).to_s
  prg = 'make' if prg.empty?
  cmd = args.empty? ? prg : "#{prg} #{args}"
  result = Rvim::Filter.run(cmd, shell: editor.settings.get(:shell), shellcmdflag: editor.settings.get(:shellcmdflag))
  output = result.stdout.to_s + result.stderr.to_s
  entries = Rvim::Errorformat.parse(output, editor.settings.get(:errorformat))
  list.set(entries)
  report_list_status(editor, entries, parsed.bang, '(No errors)')
end

.execute_lnext(editor, _parsed) ⇒ Object



1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
# File 'lib/rvim/command.rb', line 1078

def self.execute_lnext(editor, _parsed)
  list = current_location_list(editor)
  if list.nil? || list.empty?
    editor.status_message = 'E776: no location list'
    return
  end

  entry = list.advance(+1)
  jump_to_quickfix_entry(editor, entry)
  editor.status_message = "(#{list.index + 1} of #{list.size}) #{format_quickfix_summary(entry)}"
end

.execute_lprev(editor, _parsed) ⇒ Object



1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
# File 'lib/rvim/command.rb', line 1090

def self.execute_lprev(editor, _parsed)
  list = current_location_list(editor)
  if list.nil? || list.empty?
    editor.status_message = 'E776: no location list'
    return
  end

  entry = list.advance(-1)
  jump_to_quickfix_entry(editor, entry)
  editor.status_message = "(#{list.index + 1} of #{list.size}) #{format_quickfix_summary(entry)}"
end

.execute_lvimgrep(editor, parsed) ⇒ Object



1071
1072
1073
1074
1075
1076
# File 'lib/rvim/command.rb', line 1071

def self.execute_lvimgrep(editor, parsed)
  list = current_location_list(editor)
  return unless list

  run_vimgrep(editor, parsed, list, label: 'location list')
end

.execute_make(editor, parsed) ⇒ Object



783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
# File 'lib/rvim/command.rb', line 783

def self.execute_make(editor, parsed)
  args = parsed.arg.to_s
  prg = editor.settings.get(:makeprg).to_s
  prg = 'make' if prg.empty?
  cmd = args.empty? ? prg : "#{prg} #{args}"
  result = Rvim::Filter.run(cmd, shell: editor.settings.get(:shell), shellcmdflag: editor.settings.get(:shellcmdflag))
  output = result.stdout.to_s + result.stderr.to_s
  entries = Rvim::Errorformat.parse(output, editor.settings.get(:errorformat))
  editor.quickfix.set(entries)
  if entries.empty?
    editor.status_message = '(No errors)'
  else
    editor.status_message = "(1 of #{entries.size}) #{format_quickfix_summary(entries.first)}"
    jump_to_quickfix_entry(editor, entries.first) unless parsed.bang
  end
end

.execute_map(editor, parsed) ⇒ Object



535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'lib/rvim/command.rb', line 535

def self.execute_map(editor, parsed)
  arg = parsed.arg.to_s.strip
  modes = Rvim::Keymap.modes_for(parsed.verb, bang: parsed.bang)

  if arg.empty?
    editor.show_list(format_mappings(editor, modes))
    return
  end

  silent = false
  while (m = MAP_MODIFIER_RE.match(arg))
    silent = true if m[1].downcase == 'silent'
    arg = arg[m[0].length..-1]
  end

  lhs_raw, rhs_raw = arg.split(/\s+/, 2)
  if rhs_raw.nil? || rhs_raw.empty?
    lhs = Rvim::Keymap.expand(lhs_raw, leader: editor.mapleader)
    editor.show_list(format_mappings(editor, modes, lhs_filter: lhs))
    return
  end

  lhs = Rvim::Keymap.expand(lhs_raw, leader: editor.mapleader)
  rhs = Rvim::Keymap.expand(rhs_raw, leader: editor.mapleader)
  recursive = !Rvim::Keymap.noremap?(parsed.verb)
  editor.keymap.add(modes, lhs, rhs, recursive: recursive, silent: silent)
end

.execute_mapclear(editor, parsed) ⇒ Object



1491
1492
1493
1494
# File 'lib/rvim/command.rb', line 1491

def self.execute_mapclear(editor, parsed)
  modes = Rvim::Keymap.modes_for(parsed.verb, bang: parsed.bang)
  editor.keymap.clear(modes)
end

.execute_mksession(editor, parsed) ⇒ Object



1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
# File 'lib/rvim/command.rb', line 1756

def self.execute_mksession(editor, parsed)
  arg = parsed.arg.to_s.strip
  target = arg.empty? ? 'Session.vim' : arg
  target = File.expand_path(target)

  if File.exist?(target) && !parsed.bang
    editor.status_message = "E189: \"#{File.basename(target)}\" exists (add ! to override)"
    return
  end

  lines = build_session_script(editor)
  File.write(target, lines.join("\n") + "\n")
  editor.status_message = "Session written to #{target}"
rescue => e
  editor.status_message = "E: mksession: #{e.message}"
end

.execute_move(editor, parsed) ⇒ Object



656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
# File 'lib/rvim/command.rb', line 656

def self.execute_move(editor, parsed)
  start_line, end_line = resolve_range_default_current(editor, parsed)
  target = parsed.arg.to_i
  last = editor.buffer_of_lines.size - 1
  target = target.clamp(0, last + 1)

  moving = editor.buffer_of_lines[start_line..end_line].map(&:dup)
  # Remove from original position
  editor.buffer_of_lines.slice!(start_line, end_line - start_line + 1)
  # Adjust target if it was AFTER the cut
  target -= (end_line - start_line + 1) if target > end_line
  target = target.clamp(0, editor.buffer_of_lines.size)
  editor.buffer_of_lines.insert(target, *moving)
  editor.instance_variable_set(:@line_index, target.clamp(0, [editor.buffer_of_lines.size - 1, 0].max))
  editor.instance_variable_set(:@byte_pointer, 0)
  editor.modified = true
end

.execute_nohlsearch(editor, _parsed) ⇒ Object



705
706
707
708
# File 'lib/rvim/command.rb', line 705

def self.execute_nohlsearch(editor, _parsed)
  editor.instance_variable_set(:@search_matches, [])
  editor.instance_variable_set(:@search_pattern, nil)
end

.execute_packadd(editor, parsed) ⇒ Object



1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
# File 'lib/rvim/command.rb', line 1571

def self.execute_packadd(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.status_message = 'E471: Argument required'
    return
  end

  bang = parsed.bang
  home = File.expand_path('~/.vim')
  candidates = []
  candidates += Dir.glob(File.join(home, 'pack', '*', 'start', arg))
  candidates += Dir.glob(File.join(home, 'pack', '*', 'opt', arg))

  if candidates.empty?
    editor.status_message = "E919: Directory not found in 'packpath': #{arg}"
    return
  end

  pkg_dir = candidates.first
  # Append to runtimepath if not already present.
  rtp = editor.settings.get(:runtimepath).to_s
  unless rtp.split(',').include?(pkg_dir)
    editor.settings.set(:runtimepath, rtp.empty? ? pkg_dir : "#{rtp},#{pkg_dir}")
  end

  # Source plugin/*.vim files unless !bang (which loads structure only).
  return if bang

  Dir.glob(File.join(pkg_dir, 'plugin', '*.vim')).sort.each { |p| editor.source(p) }
end

.execute_put(editor, parsed) ⇒ Object



632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# File 'lib/rvim/command.rb', line 632

def self.execute_put(editor, parsed)
  register = parsed.arg.to_s.strip
  register = nil if register.empty?
  entry = editor.read_register(register)
  return unless entry

  lines = entry.text.to_s.split("\n", -1)
  lines.pop if lines.last == ''

  target = if parsed.range
             _, end_line = resolve_sub_range(editor, parsed.range)
             end_line
           else
             editor.line_index
           end
  target = -1 if parsed.bang # ":put!" puts above current/range start
  if parsed.bang && parsed.range
    start_line, _ = resolve_sub_range(editor, parsed.range)
    target = start_line - 1
  end

  editor.insert_lines_after(target, lines)
end

.execute_pwd(editor, _parsed) ⇒ Object



730
731
732
# File 'lib/rvim/command.rb', line 730

def self.execute_pwd(editor, _parsed)
  editor.status_message = Dir.pwd
end

.execute_quit(editor, parsed) ⇒ Object



1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
# File 'lib/rvim/command.rb', line 1866

def self.execute_quit(editor, parsed)
  if editor.windows.size > 1
    editor.close_current_window
    return
  end

  # Last window in the current tab. If more tabs exist, close the tab.
  if editor.tabs.size > 1
    editor.tab_close
    return
  end

  if any_modified?(editor) && !parsed.bang
    if editor.settings.get(:confirm)
      confirm_destructive_quit(editor)
    else
      editor.status_message = 'E37: No write since last change (add ! to override)'
    end
  else
    editor.quit!
  end
end

.execute_quit_all(editor, parsed) ⇒ Object



1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
# File 'lib/rvim/command.rb', line 1889

def self.execute_quit_all(editor, parsed)
  if any_modified?(editor) && !parsed.bang
    if editor.settings.get(:confirm)
      confirm_destructive_quit(editor)
    else
      editor.status_message = 'E37: No write since last change (add ! to override)'
    end
  else
    editor.quit!
  end
end

.execute_read(editor, parsed) ⇒ Object



1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
# File 'lib/rvim/command.rb', line 1421

def self.execute_read(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.status_message = 'E32: No file name'
    return
  end

  if arg.start_with?('!')
    cmd = arg.sub(/\A!\s*/, '')
    result = Rvim::Filter.run(cmd, shell: editor.settings.get(:shell), shellcmdflag: editor.settings.get(:shellcmdflag))
    unless result.success?
      editor.status_message = filter_error_status(result)
      return
    end

    out_lines = result.stdout.chomp("\n").split("\n", -1)
    editor.insert_lines_after(editor.line_index, out_lines)
  else
    unless File.exist?(arg)
      editor.status_message = "E484: Can't open file #{arg}"
      return
    end

    out_lines = File.readlines(arg, chomp: true)
    editor.insert_lines_after(editor.line_index, out_lines)
  end
end

.execute_redir(editor, parsed) ⇒ Object



1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
# File 'lib/rvim/command.rb', line 1813

def self.execute_redir(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg == 'END' || arg.upcase == 'END'
    editor.close_redir
    return
  end

  m = arg.match(/\A(>>?)\s*(.+)\z/)
  if m
    path = File.expand_path(m[2].strip)
    mode = m[1] == '>>' ? 'a' : 'w'
    editor.open_redir_file(path, mode)
    return
  end

  m = arg.match(/\A@([A-Za-z*"+])\z/)
  if m
    editor.open_redir_register(m[1])
    return
  end

  editor.status_message = 'E474: Invalid argument: usage: :redir > file'
end

.execute_resize(editor, parsed, vertical: false) ⇒ Object



1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
# File 'lib/rvim/command.rb', line 1999

def self.execute_resize(editor, parsed, vertical: false)
  arg = parsed.arg.to_s.strip
  return if arg.empty?

  axis = vertical ? :width : :height
  if arg.start_with?('+', '-')
    editor.resize_current(axis, arg.to_i)
  else
    editor.resize_to(axis, arg.to_i)
  end
end

.execute_retab(editor, parsed) ⇒ Object



710
711
712
713
714
715
716
717
718
719
# File 'lib/rvim/command.rb', line 710

def self.execute_retab(editor, parsed)
  width = parsed.arg.to_s.strip
  n = width.empty? ? editor.settings.get(:shiftwidth) : width.to_i
  n = 1 if n.nil? || n <= 0
  spaces = ' ' * n
  editor.buffer_of_lines.each_with_index do |line, i|
    editor.buffer_of_lines[i] = line.gsub("\t", spaces)
  end
  editor.modified = true
end

.execute_runtime(editor, parsed) ⇒ Object



1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
# File 'lib/rvim/command.rb', line 1546

def self.execute_runtime(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.status_message = 'E471: Argument required'
    return
  end

  bang = parsed.bang
  pattern = arg
  paths = runtime_paths(editor).flat_map do |dir|
    Dir.glob(File.expand_path(File.join(dir, pattern)))
  end.uniq

  if paths.empty?
    editor.status_message = "E484: Can't find file in 'runtimepath': #{pattern}"
    return
  end

  if bang
    paths.each { |p| editor.source(p) }
  else
    editor.source(paths.first)
  end
end

.execute_set(editor, parsed, local: false) ⇒ Object



2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
# File 'lib/rvim/command.rb', line 2031

def self.execute_set(editor, parsed, local: false)
  messages = []
  target_buffer = local ? editor.current_buffer : nil
  Array(parsed.set_options).each do |name, value|
    if editor.settings.known?(name)
      editor.settings.set(name, value, buffer: target_buffer)
      normalized = editor.settings.normalize(name)
      if normalized == :foldmethod
        editor.rebuild_folds_for_method
      elsif normalized == :foldlevel
        editor.apply_fold_level
      end
    else
      messages << "E518: Unknown option: #{name}"
    end
  end
  editor.status_message = messages.join('; ') unless messages.empty?
end

.execute_silent(editor, parsed) ⇒ Object



1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
# File 'lib/rvim/command.rb', line 1628

def self.execute_silent(editor, parsed)
  arg = parsed.arg.to_s.strip
  return if arg.empty?

  cmd = arg.start_with?(':') ? arg : ":#{arg}"
  sub = parse(cmd)
  execute(editor, sub) if sub
  # Suppress whatever status_message the inner command set.
  editor.status_message = nil
end

.execute_sort(editor, parsed) ⇒ Object



1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
# File 'lib/rvim/command.rb', line 1299

def self.execute_sort(editor, parsed)
  flags = parsed.arg.to_s
  numeric = flags.include?('n')
  ignorecase = flags.include?('i')
  uniq = flags.include?('u')

  range = parsed.range || :whole
  start_line, end_line = resolve_sub_range(editor, range)
  lines = editor.buffer_of_lines[start_line..end_line].dup

  sort_key = if numeric
               ->(line) { line.to_s[/-?\d+/].to_i }
             elsif ignorecase
               ->(line) { line.to_s.downcase }
             else
               ->(line) { line.to_s }
             end

  sorted = lines.sort_by(&sort_key)
  sorted.reverse! if parsed.bang
  sorted = sorted.uniq if uniq

  editor.replace_line_range(start_line, end_line, sorted)
end

.execute_substitute(editor, parsed) ⇒ Object



2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
# File 'lib/rvim/command.rb', line 2057

def self.execute_substitute(editor, parsed)
  sub = parsed.sub
  pattern_ic = sub[:ignorecase] || effective_sub_ignorecase(editor, sub[:pattern])
  pattern = compile_sub_pattern(sub[:pattern], ignorecase: pattern_ic)
  unless pattern
    editor.status_message = "E383: Invalid search string: #{sub[:pattern]}"
    return
  end

  replacement = sub[:replacement].to_s.gsub(/\\\//, '/')
  global = sub[:global]
  start_line, end_line = resolve_sub_range(editor, parsed.range)

  count = 0
  lines = 0
  (start_line..end_line).each do |i|
    line = editor.buffer_of_lines[i]
    new_line, n = if global
                    gsub = line.gsub(pattern) { count += 1; replacement }
                    [gsub, count]
                  else
                    replaced = false
                    s = line.sub(pattern) do
                      replaced = true
                      count += 1
                      replacement
                    end
                    [s, replaced ? 1 : 0]
                  end
    if new_line != line
      editor.buffer_of_lines[i] = new_line
      lines += 1
      editor.modified = true
    end
    _ = n
  end
  editor.status_message = "#{count} substitution#{count == 1 ? '' : 's'} on #{lines} line#{lines == 1 ? '' : 's'}"
end

.execute_tabdo(editor, parsed) ⇒ Object



843
844
845
846
847
848
849
850
851
852
853
# File 'lib/rvim/command.rb', line 843

def self.execute_tabdo(editor, parsed)
  cmd = parsed.arg.to_s
  return if cmd.empty?

  saved_idx = editor.current_tab_index
  editor.tabs.size.times do |i|
    editor.swap_to_tab(i)
    execute(editor, parse(cmd))
  end
  editor.swap_to_tab(saved_idx) if saved_idx && saved_idx < editor.tabs.size
end

.execute_tabmove(editor, parsed) ⇒ Object



1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
# File 'lib/rvim/command.rb', line 1984

def self.execute_tabmove(editor, parsed)
  arg = parsed.arg.to_s.strip
  return if editor.tabs.size <= 1

  src = editor.current_tab_index
  dst = if arg.empty?
          editor.tabs.size - 1
        elsif arg.start_with?('+', '-')
          src + arg.to_i
        else
          arg.to_i
        end
  editor.tab_move(dst)
end

.execute_tag(editor, parsed) ⇒ Object



900
901
902
903
904
905
906
907
908
# File 'lib/rvim/command.rb', line 900

def self.execute_tag(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.status_message = 'E471: usage: :tag NAME'
    return
  end

  editor.tag_jump(arg)
end

.execute_terminal(editor, parsed) ⇒ Object



1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
# File 'lib/rvim/command.rb', line 1737

def self.execute_terminal(editor, parsed)
  cmd = parsed.arg.to_s.strip
  cmd = editor.settings.get(:shell).to_s if cmd.empty?
  cmd = '/bin/sh' if cmd.empty?

  result = Rvim::Filter.run(
    cmd,
    shell: editor.settings.get(:shell).to_s,
    shellcmdflag: editor.settings.get(:shellcmdflag).to_s,
  )

  output = result.stdout.to_s
  output += result.stderr.to_s if result.stderr && !result.stderr.empty?
  lines = output.lines.map { |l| l.chomp }
  lines = [''] if lines.empty?

  editor.open_terminal_buffer("term://#{cmd}", lines, status: result.status.exitstatus)
end

.execute_unabbrev(editor, parsed) ⇒ Object



1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
# File 'lib/rvim/command.rb', line 1530

def self.execute_unabbrev(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.status_message = 'E474: Argument required'
    return
  end

  modes = ABBREV_MODES[parsed.verb] || %i[insert cmdline]
  editor.abbreviations.remove(modes, arg)
end

.execute_unmap(editor, parsed) ⇒ Object



563
564
565
566
567
568
569
570
571
572
573
# File 'lib/rvim/command.rb', line 563

def self.execute_unmap(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.status_message = 'E474: Invalid argument: usage: :unmap lhs'
    return
  end

  lhs = Rvim::Keymap.expand(arg, leader: editor.mapleader)
  modes = Rvim::Keymap.modes_for(parsed.verb, bang: parsed.bang)
  editor.keymap.remove(modes, lhs)
end

.execute_user_command(editor, uc, parsed) ⇒ Object



1805
1806
1807
1808
1809
1810
1811
# File 'lib/rvim/command.rb', line 1805

def self.execute_user_command(editor, uc, parsed)
  args = parsed.arg.to_s
  body = uc.body.gsub('<args>', args).gsub('<bang>', parsed.bang ? '!' : '')
  cmd = body.start_with?(':') ? body : ":#{body}"
  sub = parse(cmd)
  execute(editor, sub) if sub
end

.execute_user_command_def(editor, parsed) ⇒ Object



1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
# File 'lib/rvim/command.rb', line 1663

def self.execute_user_command_def(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    rows = ['user commands:'] + editor.user_commands.values.map { |uc| "  #{uc.name}    #{uc.body}" }
    editor.show_list(rows)
    return
  end

  m = USER_COMMAND_RE.match(arg)
  unless m
    editor.status_message = 'E182: Invalid command name'
    return
  end

  name = m[:name]
  if !parsed.bang && editor.user_commands.key?(name)
    editor.status_message = "E174: Command already exists: add ! to replace it: #{name}"
    return
  end

  editor.user_commands[name] = UserCommand.new(name: name, nargs: m[:nargs] || '0', body: m[:body])
end

.execute_user_command_del(editor, parsed) ⇒ Object



1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
# File 'lib/rvim/command.rb', line 1686

def self.execute_user_command_del(editor, parsed)
  arg = parsed.arg.to_s.strip
  if arg.empty?
    editor.status_message = 'E471: Argument required'
    return
  end
  unless editor.user_commands.delete(arg)
    editor.status_message = "E184: No such user-defined command: #{arg}"
  end
end

.execute_verbose(editor, parsed) ⇒ Object



1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
# File 'lib/rvim/command.rb', line 1639

def self.execute_verbose(editor, parsed)
  arg = parsed.arg.to_s.strip
  return if arg.empty?

  # Optional level prefix: :verbose 9 cmd. Default 1.
  level = 1
  m = arg.match(/\A(\d+)\s+(.*)\z/)
  if m
    level = m[1].to_i
    arg = m[2]
  end
  saved = editor.settings.get(:verbose)
  editor.settings.set(:verbose, level)
  cmd = arg.start_with?(':') ? arg : ":#{arg}"
  sub = parse(cmd)
  execute(editor, sub) if sub
ensure
  editor.settings.set(:verbose, saved) if saved
end

.execute_vimgrep(editor, parsed) ⇒ Object



1227
1228
1229
# File 'lib/rvim/command.rb', line 1227

def self.execute_vimgrep(editor, parsed)
  run_vimgrep(editor, parsed, editor.quickfix, label: 'quickfix')
end

.execute_windo(editor, parsed) ⇒ Object



855
856
857
858
859
860
861
862
863
864
865
# File 'lib/rvim/command.rb', line 855

def self.execute_windo(editor, parsed)
  cmd = parsed.arg.to_s
  return if cmd.empty?

  saved = editor.current_window
  editor.windows.dup.each do |win|
    editor.send(:activate_window, win)
    execute(editor, parse(cmd))
  end
  editor.send(:activate_window, saved) if saved && editor.windows.include?(saved)
end

.execute_write(editor, parsed) ⇒ Object



1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
# File 'lib/rvim/command.rb', line 1854

def self.execute_write(editor, parsed)
  target = parsed.arg && !parsed.arg.empty? ? parsed.arg : editor.filepath
  if target.nil?
    editor.status_message = 'E32: No file name'
    return
  end
  editor.save(target)
  editor.status_message = "\"#{target}\" written"
rescue => e
  editor.status_message = "E: #{e.message}"
end

.execute_yank(editor, parsed) ⇒ Object



619
620
621
622
623
624
625
626
627
628
629
630
# File 'lib/rvim/command.rb', line 619

def self.execute_yank(editor, parsed)
  start_line, end_line = resolve_range_default_current(editor, parsed)
  register = parsed.arg.to_s.strip
  lines = editor.buffer_of_lines[start_line..end_line]
  text = lines.map(&:to_s).join("\n")
  kind = :line
  if register.empty?
    editor.send(:write_register, text, kind, register: nil)
  else
    editor.send(:write_register, text, kind, register: register)
  end
end

.expand_filenames(editor, str) ⇒ Object

Replace standalone % with current filepath and # with alternate. Use % / # to escape.



760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
# File 'lib/rvim/command.rb', line 760

def self.expand_filenames(editor, str)
  out = +''
  i = 0
  bytes = str.to_s
  while i < bytes.length
    c = bytes[i]
    if c == '\\' && (bytes[i + 1] == '%' || bytes[i + 1] == '#')
      out << bytes[i + 1]
      i += 2
    elsif c == '%' && editor.filepath
      out << editor.filepath
      i += 1
    elsif c == '#' && editor.alternate_filepath
      out << editor.alternate_filepath
      i += 1
    else
      out << c
      i += 1
    end
  end
  out
end

.filter_error_status(result) ⇒ Object



1449
1450
1451
1452
1453
# File 'lib/rvim/command.rb', line 1449

def self.filter_error_status(result)
  msg = result.stderr.lines.first&.chomp
  msg = "exit #{result.status.exitstatus}" if msg.nil? || msg.empty?
  "E: filter: #{msg[0, 60]}"
end

.format_abbreviations(editor, modes, lhs_filter: nil) ⇒ Object



1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
# File 'lib/rvim/command.rb', line 1839

def self.format_abbreviations(editor, modes, lhs_filter: nil)
  header = '   mode  lhs                rhs'
  rows = []
  modes.each do |mode|
    editor.abbreviations.each(mode) do |lhs, entry|
      next if lhs_filter && lhs != lhs_filter

      tag = ABBREV_MODE_TAGS[mode] || ' '
      marker = entry.recursive ? ' ' : '*'
      rows << format('   %s%s    %-18s %s', tag, marker, lhs, entry.rhs)
    end
  end
  [header] + rows
end

.format_autocommands(editor) ⇒ Object



1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
# File 'lib/rvim/command.rb', line 1368

def self.format_autocommands(editor)
  header = '   group     event           pattern         command'
  rows = []
  editor.autocommands.each do |e|
    rows << format(
      '   %-9s %-15s %-15s %s',
      (e.group || '').to_s[0, 9],
      e.event.to_s[0, 15],
      e.pattern.to_s[0, 15],
      e.command.to_s,
    )
  end
  ['Autocommands', header, *rows]
end

.format_buffers(editor) ⇒ Object



2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
# File 'lib/rvim/command.rb', line 2020

def self.format_buffers(editor)
  header = '  N  flags  Name'
  rows = editor.buffer_order.map do |id|
    b = editor.buffers[id]
    cur = (id == editor.current_buffer&.id) ? '%' : ' '
    mod = b.modified ? '+' : ' '
    format('%s %2d  %s     %s', cur, id, mod, b.display_name)
  end
  [header, *rows]
end

.format_digraphsObject



941
942
943
944
945
946
947
948
# File 'lib/rvim/command.rb', line 941

def self.format_digraphs
  header = '   pair  char  codepoint'
  rows = []
  Rvim::Digraphs.each do |pair, ch|
    rows << format('   %-4s  %-4s  U+%04X', pair, ch, ch.codepoints.first || 0)
  end
  ['Digraphs', header, *rows]
end

.format_highlightsObject



993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
# File 'lib/rvim/command.rb', line 993

def self.format_highlights
  header = '   group         fg              bg              attrs'
  rows = Rvim::Highlights.groups.map do |name, attr|
    attrs = []
    attrs << 'bold' if attr.bold
    attrs << 'italic' if attr.italic
    attrs << 'underline' if attr.underline
    attrs << 'reverse' if attr.reverse
    format(
      '   %-13s %-15s %-15s %s',
      name[0, 13],
      (attr.fg || '').to_s[0, 15],
      (attr.bg || '').to_s[0, 15],
      attrs.join(','),
    )
  end
  ['Highlight groups', header, *rows]
end

.format_history(editor) ⇒ Object



2011
2012
2013
2014
2015
2016
2017
2018
# File 'lib/rvim/command.rb', line 2011

def self.format_history(editor)
  header = '      #  cmd'
  hist = editor.ex_history
  rows = hist.each_with_index.map do |line, i|
    format('%7d  %s', i + 1, line)
  end
  ['Command Line History', header, *rows]
end

.format_jumps(editor) ⇒ Object



1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
# File 'lib/rvim/command.rb', line 1953

def self.format_jumps(editor)
  header = ' jump line  col  text'
  jumps = editor.jump_list || []
  idx = editor.jump_index || 0
  rows = jumps.each_with_index.map do |(line, col), i|
    marker = (i == idx) ? '>' : ' '
    text = (editor.buffer_of_lines[line] || '').lstrip[0, 60]
    format('%s %4d  %4d  %4d  %s', marker, jumps.size - i, line + 1, col, text)
  end
  [header, *rows]
end

.format_location_list(editor) ⇒ Object



1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
# File 'lib/rvim/command.rb', line 1174

def self.format_location_list(editor)
  win = editor.current_window
  return ['No window'] unless win

  list = win.location_list
  header = '   #  file:line:col  text'
  rows = list.entries.each_with_index.map do |e, i|
    marker = i == list.index ? '>' : ' '
    format('%s %3d  %s:%d:%d  %s', marker, i + 1, e.file, e.line, e.col, e.text.to_s[0, 80])
  end
  ['Location list', header, *rows]
end

.format_mappings(editor, modes, lhs_filter: nil) ⇒ Object



583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/rvim/command.rb', line 583

def self.format_mappings(editor, modes, lhs_filter: nil)
  header = '   mode  lhs                rhs'
  rows = []
  modes.each do |mode|
    editor.keymap.each(mode) do |lhs, mapping|
      next if lhs_filter && lhs != lhs_filter

      tag = MODE_TAGS[mode] || ' '
      marker = mapping.recursive ? ' ' : '*'
      rows << format(
        '   %s%s    %-18s %s',
        tag,
        marker,
        Rvim::Keymap.render(lhs),
        Rvim::Keymap.render(mapping.rhs),
      )
    end
  end
  ['Mappings', header, *rows]
end

.format_marks(editor) ⇒ Object



1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
# File 'lib/rvim/command.rb', line 1965

def self.format_marks(editor)
  header = 'mark  line  col  file/text'
  rows = []
  # Local marks (a-z) — fetch from current buffer
  local = editor.instance_variable_get(:@marks).instance_variable_get(:@table)
  local.sort.each do |name, (line, col)|
    text = editor.buffer_of_lines[line].to_s.lstrip[0, 60]
    rows << format(' %s   %4d  %4d  %s', name, line + 1, col, text)
  end
  # Global marks (A-Z)
  global = editor.instance_variable_get(:@global_marks).instance_variable_get(:@table)
  global.sort.each do |name, (buf_id, line, col)|
    buf = editor.buffers[buf_id]
    info = buf ? buf.display_name : "(buffer #{buf_id})"
    rows << format(' %s   %4d  %4d  %s', name, line + 1, col, info)
  end
  [header, *rows]
end

.format_quickfix(editor) ⇒ Object



1285
1286
1287
1288
1289
1290
1291
1292
1293
# File 'lib/rvim/command.rb', line 1285

def self.format_quickfix(editor)
  header = '   #  file:line:col  text'
  rows = []
  editor.quickfix.entries.each_with_index do |e, i|
    marker = i == editor.quickfix.index ? '>' : ' '
    rows << format('%s %3d  %s:%d:%d  %s', marker, i + 1, e.file, e.line, e.col, e.text.to_s[0, 80])
  end
  ['Quickfix', header, *rows]
end

.format_quickfix_summary(entry) ⇒ Object



1295
1296
1297
# File 'lib/rvim/command.rb', line 1295

def self.format_quickfix_summary(entry)
  "#{entry.file}:#{entry.line}:#{entry.col} #{entry.text.to_s[0, 60]}"
end

.format_registers(editor, filter: nil) ⇒ Object



1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
# File 'lib/rvim/command.rb', line 1930

def self.format_registers(editor, filter: nil)
  header = 'type  name  content'
  table = editor.instance_variable_get(:@registers).instance_variable_get(:@table) || {}
  rows = []
  # Order: " (unnamed), "0-"9 (numbered), "a-"z (named)
  ordered_keys = ['"', *('0'..'9'), *('a'..'z')].select { |k| table[k] }
  ordered_keys = ordered_keys & filter if filter && !filter.empty?
  ordered_keys.each do |name|
    entry = table[name]
    next unless entry

    kind = KIND_TAGS[entry.kind] || '?'
    text = entry.text.is_a?(Array) ? entry.text.join("\\n") : entry.text.to_s
    preview = text.gsub("\n", '\\n')[0, 60]
    rows << format('   %s   "%s   %s', kind, name, preview)
  end
  # Add "% if filepath set and not filtered out
  if editor.filepath && (filter.nil? || filter.empty? || filter.include?('%'))
    rows << format('   c   "%%   %s', editor.filepath[0, 60])
  end
  [header, *rows]
end

.format_tag_stack(editor) ⇒ Object



910
911
912
913
914
915
916
# File 'lib/rvim/command.rb', line 910

def self.format_tag_stack(editor)
  header = '   #  name              file:line'
  rows = editor.tag_stack.each_with_index.map do |e, i|
    format('   %2d  %-16s  %s:%d', i + 1, e[:name].to_s[0, 16], (e[:file] || '').to_s, e[:line_index] + 1)
  end
  ['Tag stack', header, *rows]
end

.format_undo_list(editor) ⇒ Object



1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
# File 'lib/rvim/command.rb', line 1793

def self.format_undo_list(editor)
  rows = ['number changes  when']
  stamps = editor.undo_timestamps || []
  hist = editor.instance_variable_get(:@undo_redo_history) || []
  hist.each_with_index do |_, i|
    when_ago = stamps[i] ? "#{(Time.now - stamps[i]).to_i}s ago" : '?'
    marker = i == editor.instance_variable_get(:@undo_redo_index) ? '>' : ' '
    rows << format(' %s%5d %7d  %s', marker, i, i, when_ago)
  end
  rows
end

.jump_to_quickfix_entry(editor, entry) ⇒ Object



1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
# File 'lib/rvim/command.rb', line 1273

def self.jump_to_quickfix_entry(editor, entry)
  return unless entry

  if entry.file && entry.file != editor.filepath
    editor.open(entry.file)
  end
  editor.push_jump
  editor.instance_variable_set(:@line_index, [entry.line - 1, 0].max)
  target_line = editor.buffer_of_lines[editor.line_index] || ''
  editor.instance_variable_set(:@byte_pointer, (entry.col - 1).clamp(0, target_line.bytesize))
end

.parse(input) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/rvim/command.rb', line 31

def self.parse(input)
  str = input.to_s.dup
  str = str[1..] if str.start_with?(':')
  str.strip!
  return nil if str.empty?

  if (m = SUBSTITUTE_RE.match(str))
    return Parsed.new(
      verb: :sub,
      range: parse_range(m[:range]),
      sub: {
        pattern: m[:pat],
        replacement: m[:rep],
        global: m[:flags].to_s.include?('g'),
        ignorecase: m[:flags].to_s.include?('i'),
      },
      arg: nil,
      bang: false,
      line_number: nil,
    )
  end

  if (m = FILTER_RE.match(str))
    if m[:range]
      return Parsed.new(verb: :filter, range: parse_range(m[:range]), arg: m[:cmd], bang: false, line_number: nil)
    else
      return Parsed.new(verb: :bang, arg: m[:cmd], bang: false, line_number: nil)
    end
  end

  if (m = SORT_RE.match(str))
    return Parsed.new(
      verb: :sort,
      range: m[:range] ? parse_range(m[:range]) : nil,
      arg: m[:flags].to_s,
      bang: !m[:bang].nil?,
      line_number: nil,
    )
  end

  if str.match?(/\A\d+\z/)
    return Parsed.new(verb: :goto, arg: nil, bang: false, line_number: str.to_i)
  end

  # Generic range prefix: strip a leading range like 5,10 or % or '<,'>
  # if it's followed by an alphabetic verb. Substitute/filter/sort have
  # their own range parsing above, so they never reach this path.
  generic_range = nil
  if (m = /\A(?<r>%|\d+(?:,\d+)?|'<,'>)\s*(?<rest>[a-zA-Z].*)\z/.match(str))
    generic_range = parse_range(m[:r])
    str = m[:rest]
  end

  tokens = str.split(/\s+/, 2)
  head = tokens[0]
  arg = tokens[1]
  # Allow short verbs with an immediate numeric argument (e.g. :1t2, :5d3).
  # Split the leading letters off the head when the rest is digits.
  if (m = /\A(?<verb>[a-zA-Z]+!?)(?<rest>\d.*)\z/.match(head))
    head = m[:verb]
    arg = arg ? "#{m[:rest]} #{arg}" : m[:rest]
  end
  bang = head.end_with?('!')
  verb_str = bang ? head.chomp('!') : head

  verb = case verb_str
         when 'w', 'write' then :w
         when 'q', 'quit' then :q
         when 'qa', 'qall', 'quitall' then :qa
         when 'wq' then :wq
         when 'x' then :wq
         when 'cq', 'cquit' then :cq
         when 'e', 'edit' then :e
         when 'r', 'read' then :r
         when 'bn', 'bnext' then :bn
         when 'bp', 'bprev', 'bprevious' then :bp
         when 'b', 'buffer' then :b
         when 'bd', 'bdelete' then :bd
         when 'sp', 'split' then :sp
         when 'vsp', 'vsplit' then :vsp
         when 'set', 'se' then :set
         when 'setlocal', 'setl' then :setlocal
         when 'ls', 'buffers', 'files' then :ls
         when 'marks' then :marks
         when 'jumps' then :jumps
         when 'registers', 'reg', 'display' then :registers
         when 'tabnext', 'tabn' then :tabnext
         when 'tabprev', 'tabp', 'tabprevious', 'tabNext' then :tabprev
         when 'tabnew', 'tabe', 'tabedit' then :tabnew
         when 'tabclose', 'tabc' then :tabclose
         when 'tabonly', 'tabo' then :tabonly
         when 'tabmove', 'tabm' then :tabmove
         when 'resize', 'res' then :resize
         when 'vertical' then :vertical
         when 'source', 'so' then :source
         when 'runtime', 'runt' then :runtime
         when 'packadd' then :packadd
         when 'messages', 'mes', 'mess' then :messages
         when 'execute', 'exe' then :execute_cmd
         when 'silent', 'sil' then :silent
         when 'verbose', 'verb' then :verbose
         when 'redir', 'red' then :redir
         when 'command', 'com' then :user_command_def
         when 'delcommand', 'delc' then :user_command_del
         when 'help', 'h' then :help
         when 'helpclose', 'helpc' then :helpclose
         when 'earlier', 'ear' then :earlier
         when 'later', 'lat' then :later
         when 'undolist', 'undol' then :undolist
         when 'mksession', 'mks' then :mksession
         when 'badd', 'bad' then :badd
         when 'terminal', 'term' then :terminal
         when 'lua' then :lua_chunk
         when 'luafile' then :luafile
         when 'history', 'his' then :history
         when 'map' then :map
         when 'nmap' then :nmap
         when 'vmap' then :vmap
         when 'imap' then :imap
         when 'omap' then :omap
         when 'noremap', 'no' then :noremap
         when 'nnoremap', 'nn' then :nnoremap
         when 'vnoremap', 'vn' then :vnoremap
         when 'inoremap', 'ino' then :inoremap
         when 'onoremap', 'ono' then :onoremap
         when 'unmap', 'unm' then :unmap
         when 'nunmap', 'nun' then :nunmap
         when 'vunmap', 'vu' then :vunmap
         when 'iunmap', 'iu' then :iunmap
         when 'ounmap', 'ou' then :ounmap
         when 'mapclear', 'mapc' then :mapclear
         when 'nmapclear', 'nmapc' then :nmapclear
         when 'vmapclear', 'vmapc' then :vmapclear
         when 'imapclear', 'imapc' then :imapclear
         when 'omapclear', 'omapc' then :omapclear
         when 'cmap', 'cm' then :cmap
         when 'cnoremap', 'cno' then :cnoremap
         when 'cunmap', 'cun' then :cunmap
         when 'cmapclear', 'cmapc' then :cmapclear
         when 'abbreviate', 'abbrev', 'ab' then :abbrev
         when 'iabbrev', 'iab' then :iabbrev
         when 'cabbrev', 'ca' then :cabbrev
         when 'noreabbrev', 'norea' then :noreabbrev
         when 'inoreabbrev', 'inoreab' then :inoreabbrev
         when 'cnoreabbrev', 'cnorea' then :cnoreabbrev
         when 'unabbreviate', 'una' then :unabbrev
         when 'iunabbrev', 'iuna' then :iunabbrev
         when 'cunabbrev', 'cuna' then :cunabbrev
         when 'abclear', 'abc' then :abclear
         when 'iabclear', 'iabc' then :iabclear
         when 'cabclear', 'cabc' then :cabclear
         when 'let' then :let
         when 'fold', 'fo' then :fold
         when 'autocmd', 'au' then :autocmd
         when 'augroup', 'aug' then :augroup
         when 'd', 'delete' then :delete
         when 'y', 'yank' then :yank
         when 'p', 'put' then :put
         when 'm', 'move' then :move
         when 'co', 'copy', 't' then :copy
         when 'j', 'join' then :join
         when 'noh', 'nohlsearch' then :nohlsearch
         when 'retab' then :retab
         when 'cd', 'chdir' then :cd
         when 'pwd' then :pwd
         when 'vimgrep', 'vim' then :vimgrep
         when 'cnext', 'cn' then :cnext
         when 'cprev', 'cp', 'cprevious' then :cprev
         when 'cc' then :cc
         when 'clist', 'cl' then :clist
         when 'copen', 'cope' then :copen
         when 'cclose', 'cclo' then :cclose
         when 'lvimgrep', 'lvim' then :lvimgrep
         when 'lnext', 'lne' then :lnext
         when 'lprev', 'lp', 'lprevious' then :lprev
         when 'll' then :ll
         when 'llist', 'll!' then :llist
         when 'lopen', 'lop' then :lopen
         when 'lclose', 'lcl' then :lclose
         when 'lmake' then :lmake
         when 'lgrep' then :lgrep
         when 'diffthis', 'difft' then :diffthis
         when 'diffoff' then :diffoff
         when 'diffupdate', 'diffu' then :diffupdate
         when 'diffsplit', 'diffs' then :diffsplit
         when 'hi', 'highlight' then :hi
         when 'colorscheme', 'colo' then :colorscheme
         when 'digraph', 'digraphs', 'dig' then :digraphs
         when 'tag', 'ta' then :tag
         when 'tags' then :tags_list
         when 'tnext', 'tn' then :tnext
         when 'tprev', 'tp', 'tprevious' then :tprev
         when 'bufdo' then :bufdo
         when 'tabdo' then :tabdo
         when 'windo' then :windo
         when 'argdo' then :argdo
         when 'args', 'ar' then :args
         when 'argadd', 'arga' then :argadd
         when 'make' then :make
         when 'grep' then :grep
         else verb_str.to_sym
         end

  if verb == :set || verb == :setlocal
    set_options = parse_set(arg)
    return Parsed.new(verb: verb, arg: arg, bang: bang, line_number: nil, set_options: set_options)
  end

  Parsed.new(verb: verb, arg: arg, bang: bang, line_number: nil, range: generic_range)
end

.parse_range(token) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/rvim/command.rb', line 259

def self.parse_range(token)
  return :current if token.nil? || token.empty?
  return :whole if token == '%'
  return :visual if token == "'<,'>"

  if token.include?(',')
    a, b = token.split(',').map(&:to_i)
    [a, b]
  else
    [token.to_i, token.to_i]
  end
end

.parse_set(args) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/rvim/command.rb', line 242

def self.parse_set(args)
  args.to_s.split(/\s+/).map do |tok|
    m = tok.match(SET_TOKEN_RE)
    next unless m

    name = m[2]
    if m[1] == 'no'
      [name, false]
    elsif m[3]
      val = m[3].match?(/\A\d+\z/) ? m[3].to_i : m[3]
      [name, val]
    else
      [name, true]
    end
  end.compact
end

.parse_undo_arg(arg) ⇒ Object



1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
# File 'lib/rvim/command.rb', line 1720

def self.parse_undo_arg(arg)
  a = arg.to_s.strip
  return [1, :count] if a.empty?

  m = a.match(/\A(\d+)([smhd])?\z/)
  return [1, :count] unless m

  n = m[1].to_i
  case m[2]
  when nil then [n, :count]
  when 's' then [n, :seconds]
  when 'm' then [n * 60, :seconds]
  when 'h' then [n * 3600, :seconds]
  when 'd' then [n * 86_400, :seconds]
  end
end

.report_list_status(editor, entries, bang, empty_message) ⇒ Object



1165
1166
1167
1168
1169
1170
1171
1172
# File 'lib/rvim/command.rb', line 1165

def self.report_list_status(editor, entries, bang, empty_message)
  if entries.empty?
    editor.status_message = empty_message
  else
    editor.status_message = "(1 of #{entries.size}) #{format_quickfix_summary(entries.first)}"
    jump_to_quickfix_entry(editor, entries.first) unless bang
  end
end

.resolve_range_default_current(editor, parsed) ⇒ Object



734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
# File 'lib/rvim/command.rb', line 734

def self.resolve_range_default_current(editor, parsed)
  if parsed.range
    resolve_sub_range(editor, parsed.range)
  else
    # No range — ":delete N" treats arg as a count when arg looks like a number.
    count = parsed.arg.to_s.strip
    if count =~ /\A\d+\z/
      start_line = editor.line_index
      end_line = [start_line + count.to_i - 1, editor.buffer_of_lines.size - 1].min
      [start_line, end_line]
    else
      [editor.line_index, editor.line_index]
    end
  end
end

.resolve_sub_range(editor, range) ⇒ Object



2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
# File 'lib/rvim/command.rb', line 2110

def self.resolve_sub_range(editor, range)
  last = editor.buffer_of_lines.size - 1
  case range
  when :current
    [editor.line_index, editor.line_index]
  when :whole
    [0, last]
  when :visual
    last_visual = editor.instance_variable_get(:@last_visual)
    if last_visual
      al = last_visual[:anchor][0]
      el = last_visual[:last_end][0]
      [[al, el].min, [al, el].max].map { |v| v.clamp(0, last) }
    else
      [editor.line_index, editor.line_index]
    end
  when Array
    a, b = range
    [(a - 1).clamp(0, last), (b - 1).clamp(0, last)]
  else
    [editor.line_index, editor.line_index]
  end
end

.run_vimgrep(editor, parsed, target_list, label:) ⇒ Object



1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
# File 'lib/rvim/command.rb', line 1187

def self.run_vimgrep(editor, parsed, target_list, label:)
  arg = parsed.arg.to_s.strip
  m = VIMGREP_RE.match(arg)
  unless m
    editor.status_message = "E682: usage: :#{label.start_with?('loc') ? 'lvimgrep' : 'vimgrep'} /pattern/ {files}"
    return
  end

  begin
    pattern = Regexp.new(m[:pat])
  rescue RegexpError => e
    editor.status_message = "E383: Invalid pattern: #{e.message}"
    return
  end

  entries = []
  m[:files].split(/\s+/).each do |g|
    Dir.glob(g).each do |path|
      next unless File.file?(path)

      File.foreach(path).with_index do |line, i|
        md = pattern.match(line)
        next unless md

        entries << Rvim::Quickfix::Entry.new(
          file: path,
          line: i + 1,
          col: md.begin(0) + 1,
          text: line.chomp,
        )
      end
    end
  end

  target_list.set(entries)
  report_list_status(editor, entries, parsed.bang, "E480: No match: #{m[:pat]}")
end

.runtime_paths(editor) ⇒ Object



1602
1603
1604
1605
# File 'lib/rvim/command.rb', line 1602

def self.runtime_paths(editor)
  rtp = editor.settings.get(:runtimepath).to_s
  rtp.split(',').map { |p| File.expand_path(p.strip) }.reject(&:empty?)
end

.save_all_modified(editor) ⇒ Object



1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
# File 'lib/rvim/command.rb', line 1915

def self.save_all_modified(editor)
  editor.send(:save_current_buffer) if editor.current_buffer
  editor.buffers.values.each do |b|
    next unless b.modified
    next unless b.filepath

    previous = editor.current_buffer
    editor.swap_to_buffer(b)
    editor.save
    editor.swap_to_buffer(previous) if previous && previous != b
  end
end