-
Notifications
You must be signed in to change notification settings - Fork 715
/
commands.cc
2725 lines (2452 loc) · 105 KB
/
commands.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
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
532
533
534
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
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
992
993
994
995
996
997
998
999
1000
#include "commands.hh"
#include "buffer.hh"
#include "buffer_manager.hh"
#include "buffer_utils.hh"
#include "client.hh"
#include "client_manager.hh"
#include "command_manager.hh"
#include "completion.hh"
#include "context.hh"
#include "event_manager.hh"
#include "face_registry.hh"
#include "file.hh"
#include "hash_map.hh"
#include "highlighter.hh"
#include "highlighters.hh"
#include "insert_completer.hh"
#include "normal.hh"
#include "option_manager.hh"
#include "option_types.hh"
#include "parameters_parser.hh"
#include "ranges.hh"
#include "ranked_match.hh"
#include "regex.hh"
#include "register_manager.hh"
#include "remote.hh"
#include "shell_manager.hh"
#include "string.hh"
#include "user_interface.hh"
#include "window.hh"
#include <functional>
#include <utility>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#if defined(__GLIBC__) || defined(__CYGWIN__)
#include <malloc.h>
#endif
namespace Kakoune
{
extern const char* version;
namespace
{
Buffer* open_fifo(StringView name, StringView filename, Buffer::Flags flags, bool scroll)
{
int fd = open(parse_filename(filename).c_str(), O_RDONLY | O_NONBLOCK);
fcntl(fd, F_SETFD, FD_CLOEXEC);
if (fd < 0)
throw runtime_error(format("unable to open '{}'", filename));
return create_fifo_buffer(name.str(), fd, flags, scroll);
}
template<typename... Completers> struct PerArgumentCommandCompleter;
template<> struct PerArgumentCommandCompleter<>
{
Completions operator()(const Context&, CompletionFlags, CommandParameters,
size_t, ByteCount) const { return {}; }
};
template<typename Completer, typename... Rest>
struct PerArgumentCommandCompleter<Completer, Rest...> : PerArgumentCommandCompleter<Rest...>
{
template<typename C, typename... R,
typename = std::enable_if_t<not std::is_base_of<PerArgumentCommandCompleter<>,
std::remove_reference_t<C>>::value>>
PerArgumentCommandCompleter(C&& completer, R&&... rest)
: PerArgumentCommandCompleter<Rest...>(std::forward<R>(rest)...),
m_completer(std::forward<C>(completer)) {}
Completions operator()(const Context& context, CompletionFlags flags,
CommandParameters params, size_t token_to_complete,
ByteCount pos_in_token) const
{
if (token_to_complete == 0)
{
const String& arg = token_to_complete < params.size() ?
params[token_to_complete] : String();
return m_completer(context, flags, arg, pos_in_token);
}
return PerArgumentCommandCompleter<Rest...>::operator()(
context, flags, params.subrange(1),
token_to_complete-1, pos_in_token);
}
Completer m_completer;
};
template<typename... Completers>
PerArgumentCommandCompleter<std::decay_t<Completers>...>
make_completer(Completers&&... completers)
{
return {std::forward<Completers>(completers)...};
}
template<typename Completer>
auto add_flags(Completer completer, Completions::Flags completions_flags)
{
return [completer=std::move(completer), completions_flags]
(const Context& context, CompletionFlags flags, const String& prefix, ByteCount cursor_pos) {
Completions res = completer(context, flags, prefix, cursor_pos);
res.flags |= completions_flags;
return res;
};
}
template<typename Completer>
auto menu(Completer completer)
{
return add_flags(std::move(completer), Completions::Flags::Menu);
}
template<bool menu>
auto filename_completer = make_completer(
[](const Context& context, CompletionFlags flags, const String& prefix, ByteCount cursor_pos)
{ return Completions{ 0_byte, cursor_pos,
complete_filename(prefix,
context.options()["ignored_files"].get<Regex>(),
cursor_pos, FilenameFlags::Expand),
menu ? Completions::Flags::Menu : Completions::Flags::None}; });
template<bool ignore_current = false>
static Completions complete_buffer_name(const Context& context, CompletionFlags flags,
StringView prefix, ByteCount cursor_pos)
{
struct RankedMatchAndBuffer : RankedMatch
{
RankedMatchAndBuffer(RankedMatch m, const Buffer* b)
: RankedMatch{std::move(m)}, buffer{b} {}
using RankedMatch::operator==;
using RankedMatch::operator<;
const Buffer* buffer;
};
StringView query = prefix.substr(0, cursor_pos);
Vector<RankedMatchAndBuffer> filename_matches;
Vector<RankedMatchAndBuffer> matches;
for (const auto& buffer : BufferManager::instance())
{
if (ignore_current and buffer.get() == &context.buffer())
continue;
StringView bufname = buffer->display_name();
if (buffer->flags() & Buffer::Flags::File)
{
if (RankedMatch match{split_path(bufname).second, query})
{
filename_matches.emplace_back(match, buffer.get());
continue;
}
}
if (RankedMatch match{bufname, query})
matches.emplace_back(match, buffer.get());
}
std::sort(filename_matches.begin(), filename_matches.end());
std::sort(matches.begin(), matches.end());
CandidateList res;
for (auto& match : filename_matches)
res.push_back(match.buffer->display_name());
for (auto& match : matches)
res.push_back(match.buffer->display_name());
return { 0, cursor_pos, res };
}
template<typename Func>
auto make_single_word_completer(Func&& func)
{
return make_completer(
[func = std::move(func)](const Context& context, CompletionFlags flags,
const String& prefix, ByteCount cursor_pos) -> Completions {
auto candidate = { func(context) };
return { 0_byte, cursor_pos, complete(prefix, cursor_pos, candidate) }; });
}
const ParameterDesc no_params{ {}, ParameterDesc::Flags::None, 0, 0 };
const ParameterDesc single_param{ {}, ParameterDesc::Flags::None, 1, 1 };
const ParameterDesc single_optional_param{ {}, ParameterDesc::Flags::None, 0, 1 };
const ParameterDesc double_params{ {}, ParameterDesc::Flags::None, 2, 2 };
static constexpr auto scopes = { "global", "buffer", "window" };
static Completions complete_scope(const Context&, CompletionFlags,
const String& prefix, ByteCount cursor_pos)
{
return { 0_byte, cursor_pos, complete(prefix, cursor_pos, scopes) };
}
static Completions complete_command_name(const Context& context, CompletionFlags,
const String& prefix, ByteCount cursor_pos)
{
return CommandManager::instance().complete_command_name(
context, prefix.substr(0, cursor_pos));
}
struct ShellScriptCompleter
{
ShellScriptCompleter(String shell_script,
Completions::Flags flags = Completions::Flags::None)
: m_shell_script{std::move(shell_script)}, m_flags(flags) {}
Completions operator()(const Context& context, CompletionFlags flags,
CommandParameters params, size_t token_to_complete,
ByteCount pos_in_token)
{
if (flags & CompletionFlags::Fast) // no shell on fast completion
return Completions{};
ShellContext shell_context{
params,
{ { "token_to_complete", to_string(token_to_complete) },
{ "pos_in_token", to_string(pos_in_token) } }
};
String output = ShellManager::instance().eval(m_shell_script, context, {},
ShellManager::Flags::WaitForStdout,
shell_context).first;
CandidateList candidates;
for (auto&& candidate : output | split<StringView>('\n'))
candidates.push_back(candidate.str());
return {0_byte, pos_in_token, std::move(candidates), m_flags};
}
private:
String m_shell_script;
Completions::Flags m_flags;
};
struct ShellCandidatesCompleter
{
ShellCandidatesCompleter(String shell_script,
Completions::Flags flags = Completions::Flags::None)
: m_shell_script{std::move(shell_script)}, m_flags(flags) {}
Completions operator()(const Context& context, CompletionFlags flags,
CommandParameters params, size_t token_to_complete,
ByteCount pos_in_token)
{
if (flags & CompletionFlags::Start)
m_token = -1;
if (m_token != token_to_complete)
{
ShellContext shell_context{
params,
{ { "token_to_complete", to_string(token_to_complete) } }
};
String output = ShellManager::instance().eval(m_shell_script, context, {},
ShellManager::Flags::WaitForStdout,
shell_context).first;
m_candidates.clear();
for (auto c : output | split<StringView>('\n'))
m_candidates.emplace_back(c.str(), used_letters(c));
m_token = token_to_complete;
}
StringView query = params[token_to_complete].substr(0, pos_in_token);
UsedLetters query_letters = used_letters(query);
Vector<RankedMatch> matches;
for (const auto& candidate : m_candidates)
{
if (RankedMatch match{candidate.first, candidate.second, query, query_letters})
matches.push_back(match);
}
constexpr size_t max_count = 100;
CandidateList res;
// Gather best max_count matches
for_n_best(matches, max_count, [](auto& lhs, auto& rhs) { return rhs < lhs; },
[&] (const RankedMatch& m) {
if (not res.empty() and res.back() == m.candidate())
return false;
res.push_back(m.candidate().str());
return true;
});
return Completions{0_byte, pos_in_token, std::move(res), m_flags};
}
private:
String m_shell_script;
Vector<std::pair<String, UsedLetters>, MemoryDomain::Completion> m_candidates;
int m_token = -1;
Completions::Flags m_flags;
};
template<typename Completer>
struct PromptCompleterAdapter
{
PromptCompleterAdapter(Completer completer) : m_completer{completer} {}
Completions operator()(const Context& context, CompletionFlags flags,
StringView prefix, ByteCount cursor_pos)
{
return m_completer(context, flags, {String{String::NoCopy{}, prefix}}, 0, cursor_pos);
}
private:
Completer m_completer;
};
Scope* get_scope_ifp(StringView scope, const Context& context)
{
if (prefix_match("global", scope))
return &GlobalScope::instance();
else if (prefix_match("buffer", scope))
return &context.buffer();
else if (prefix_match("window", scope))
return &context.window();
else if (prefix_match(scope, "buffer="))
return &BufferManager::instance().get_buffer(scope.substr(7_byte));
return nullptr;
}
Scope& get_scope(StringView scope, const Context& context)
{
if (auto s = get_scope_ifp(scope, context))
return *s;
throw runtime_error(format("no such scope: '{}'", scope));
}
struct CommandDesc
{
const char* name;
const char* alias;
const char* docstring;
ParameterDesc params;
CommandFlags flags;
CommandHelper helper;
CommandCompleter completer;
void (*func)(const ParametersParser&, Context&, const ShellContext&);
};
template<bool force_reload>
void edit(const ParametersParser& parser, Context& context, const ShellContext&)
{
const bool scratch = (bool)parser.get_switch("scratch");
if (parser.positional_count() == 0 and not force_reload and not scratch)
throw wrong_argument_count();
const bool no_hooks = context.hooks_disabled();
const auto flags = (no_hooks ? Buffer::Flags::NoHooks : Buffer::Flags::None) |
(parser.get_switch("debug") ? Buffer::Flags::Debug : Buffer::Flags::None);
auto& buffer_manager = BufferManager::instance();
const auto& name = parser.positional_count() > 0 ?
parser[0] : (scratch ? generate_buffer_name("*scratch-{}*") : context.buffer().name());
Buffer* buffer = buffer_manager.get_buffer_ifp(name);
if (scratch)
{
if (parser.get_switch("readonly") or parser.get_switch("fifo") or parser.get_switch("scroll"))
throw runtime_error("scratch is not compatible with readonly, fifo or scroll");
if (buffer == nullptr or force_reload)
{
if (buffer != nullptr and force_reload)
buffer_manager.delete_buffer(*buffer);
buffer = create_buffer_from_string(std::move(name), flags, {});
}
else if (buffer->flags() & Buffer::Flags::File)
throw runtime_error(format("buffer '{}' exists but is not a scratch buffer", name));
}
else if (force_reload and buffer and buffer->flags() & Buffer::Flags::File)
{
reload_file_buffer(*buffer);
}
else
{
if (auto fifo = parser.get_switch("fifo"))
buffer = open_fifo(name, *fifo, flags, (bool)parser.get_switch("scroll"));
else if (not buffer)
{
buffer = parser.get_switch("existing") ? open_file_buffer(name, flags)
: open_or_create_file_buffer(name, flags);
if (buffer->flags() & Buffer::Flags::New)
context.print_status({ format("new file '{}'", name),
context.faces()["StatusLine"] });
}
buffer->flags() &= ~Buffer::Flags::NoHooks;
if (parser.get_switch("readonly"))
{
buffer->flags() |= Buffer::Flags::ReadOnly;
buffer->options()["readonly"].set(true);
}
}
Buffer* current_buffer = context.has_buffer() ? &context.buffer() : nullptr;
const size_t param_count = parser.positional_count();
if (current_buffer and (buffer != current_buffer or param_count > 1))
context.push_jump();
if (buffer != current_buffer)
context.change_buffer(*buffer);
buffer = &context.buffer(); // change_buffer hooks might change the buffer again
if (parser.get_switch("fifo") and not parser.get_switch("scroll"))
context.selections_write_only() = { *buffer, Selection{} };
else if (param_count > 1 and not parser[1].empty())
{
int line = std::max(0, str_to_int(parser[1]) - 1);
int column = param_count > 2 and not parser[2].empty() ?
std::max(0, str_to_int(parser[2]) - 1) : 0;
auto& buffer = context.buffer();
context.selections_write_only() = { buffer, buffer.clamp({ line, column }) };
if (context.has_window())
context.window().center_line(context.selections().main().cursor().line);
}
}
ParameterDesc edit_params{
{ { "existing", { false, "fail if the file does not exist, do not open a new file" } },
{ "scratch", { false, "create a scratch buffer, not linked to a file" } },
{ "debug", { false, "create buffer as debug output" } },
{ "fifo", { true, "create a buffer reading its content from a named fifo" } },
{ "readonly", { false, "create a buffer in readonly mode" } },
{ "scroll", { false, "place the initial cursor so that the fifo will scroll to show new data" } } },
ParameterDesc::Flags::None, 0, 3
};
const CommandDesc edit_cmd = {
"edit",
"e",
"edit [<switches>] <filename> [<line> [<column>]]: open the given filename in a buffer",
edit_params,
CommandFlags::None,
CommandHelper{},
filename_completer<false>,
edit<false>
};
const CommandDesc force_edit_cmd = {
"edit!",
"e!",
"edit! [<switches>] <filename> [<line> [<column>]]: open the given filename in a buffer, "
"force reload if needed",
edit_params,
CommandFlags::None,
CommandHelper{},
filename_completer<false>,
edit<true>
};
const ParameterDesc write_params{
{
{ "sync", { false, "force the synchronization of the file onto the filesystem" } },
{ "method", { true, "explicit writemethod (replace|overwrite)" } },
},
ParameterDesc::Flags::SwitchesOnlyAtStart, 0, 1
};
auto parse_write_method(StringView str)
{
constexpr auto desc = enum_desc(Meta::Type<WriteMethod>{});
auto it = find_if(desc, [str](const EnumDesc<WriteMethod>& d) { return d.name == str; });
if (it == desc.end())
throw runtime_error(format("invalid writemethod '{}'", str));
return it->value;
}
void do_write_buffer(Context& context, Optional<String> filename, WriteFlags flags, Optional<WriteMethod> write_method = {})
{
Buffer& buffer = context.buffer();
const bool is_file = (bool)(buffer.flags() & Buffer::Flags::File);
if (not filename and !is_file)
throw runtime_error("cannot write a non file buffer without a filename");
const bool is_readonly = (bool)(context.buffer().flags() & Buffer::Flags::ReadOnly);
// if the buffer is in read-only mode and we try to save it directly
// or we try to write to it indirectly using e.g. a symlink, throw an error
if (is_file and is_readonly and
(not filename or real_path(*filename) == buffer.name()))
throw runtime_error("cannot overwrite the buffer when in readonly mode");
auto effective_filename = not filename ? buffer.name() : parse_filename(*filename);
auto method = write_method.value_or_compute([&] { return context.options()["writemethod"].get<WriteMethod>(); });
context.hooks().run_hook(Hook::BufWritePre, effective_filename, context);
write_buffer_to_file(buffer, effective_filename, method, flags);
context.hooks().run_hook(Hook::BufWritePost, effective_filename, context);
}
template<bool force = false>
void write_buffer(const ParametersParser& parser, Context& context, const ShellContext&)
{
return do_write_buffer(context,
parser.positional_count() > 0 ? parser[0] : Optional<String>{},
(parser.get_switch("sync") ? WriteFlags::Sync : WriteFlags::None) |
(force ? WriteFlags::Force : WriteFlags::None),
parser.get_switch("method").map(parse_write_method));
}
const CommandDesc write_cmd = {
"write",
"w",
"write [<switches>] [<filename>]: write the current buffer to its file "
"or to <filename> if specified",
write_params,
CommandFlags::None,
CommandHelper{},
filename_completer<false>,
write_buffer,
};
const CommandDesc force_write_cmd = {
"write!",
"w!",
"write! [<switches>] [<filename>]: write the current buffer to its file "
"or to <filename> if specified, even when the file is write protected",
write_params,
CommandFlags::None,
CommandHelper{},
filename_completer<false>,
write_buffer<true>,
};
void write_all_buffers(const Context& context, bool sync = false, Optional<WriteMethod> write_method = {})
{
// Copy buffer list because hooks might be creating/deleting buffers
Vector<SafePtr<Buffer>> buffers;
for (auto& buffer : BufferManager::instance())
buffers.emplace_back(buffer.get());
for (auto& buffer : buffers)
{
if ((buffer->flags() & Buffer::Flags::File) and
((buffer->flags() & Buffer::Flags::New) or
buffer->is_modified())
and !(buffer->flags() & Buffer::Flags::ReadOnly))
{
auto method = write_method.value_or_compute([&] { return context.options()["writemethod"].get<WriteMethod>(); });
auto flags = sync ? WriteFlags::Sync : WriteFlags::None;
buffer->run_hook_in_own_context(Hook::BufWritePre, buffer->name(), context.name());
write_buffer_to_file(*buffer, buffer->name(), method, flags);
buffer->run_hook_in_own_context(Hook::BufWritePost, buffer->name(), context.name());
}
}
}
const CommandDesc write_all_cmd = {
"write-all",
"wa",
"write-all [<switches>]: write all changed buffers that are associated to a file",
ParameterDesc{
write_params.switches,
ParameterDesc::Flags::None, 0, 0
},
CommandFlags::None,
CommandHelper{},
CommandCompleter{},
[](const ParametersParser& parser, Context& context, const ShellContext&){
write_all_buffers(context,
(bool)parser.get_switch("sync"),
parser.get_switch("method").map(parse_write_method));
}
};
static void ensure_all_buffers_are_saved()
{
auto is_modified = [](const std::unique_ptr<Buffer>& buf) {
return (buf->flags() & Buffer::Flags::File) and buf->is_modified();
};
auto it = find_if(BufferManager::instance(), is_modified);
const auto end = BufferManager::instance().end();
if (it == end)
return;
String message = format("{} modified buffers remaining: [",
std::count_if(it, end, is_modified));
while (it != end)
{
message += (*it)->name();
it = std::find_if(it+1, end, is_modified);
message += (it != end) ? ", " : "]";
}
throw runtime_error(message);
}
template<bool force>
void kill(const ParametersParser& parser, Context& context, const ShellContext&)
{
auto& client_manager = ClientManager::instance();
if (not force)
ensure_all_buffers_are_saved();
const int status = parser.positional_count() > 0 ? str_to_int(parser[0]) : 0;
while (not client_manager.empty())
client_manager.remove_client(**client_manager.begin(), true, status);
throw kill_session{status};
}
const CommandDesc kill_cmd = {
"kill",
nullptr,
"kill [<exit status>]: terminate the current session, the server and all clients connected. "
"An optional integer parameter can set the server and client processes exit status",
{ {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },
CommandFlags::None,
CommandHelper{},
CommandCompleter{},
kill<false>
};
const CommandDesc force_kill_cmd = {
"kill!",
nullptr,
"kill! [<exit status>]: force the termination of the current session, the server and all clients connected. "
"An optional integer parameter can set the server and client processes exit status",
{ {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },
CommandFlags::None,
CommandHelper{},
CommandCompleter{},
kill<true>
};
template<bool force>
void quit(const ParametersParser& parser, Context& context, const ShellContext&)
{
if (not force and ClientManager::instance().count() == 1 and not Server::instance().is_daemon())
ensure_all_buffers_are_saved();
const int status = parser.positional_count() > 0 ? str_to_int(parser[0]) : 0;
ClientManager::instance().remove_client(context.client(), true, status);
}
const CommandDesc quit_cmd = {
"quit",
"q",
"quit [<exit status>]: quit current client, and the kakoune session if the client is the last "
"(if not running in daemon mode). "
"An optional integer parameter can set the client exit status",
{ {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },
CommandFlags::None,
CommandHelper{},
CommandCompleter{},
quit<false>
};
const CommandDesc force_quit_cmd = {
"quit!",
"q!",
"quit! [<exit status>]: quit current client, and the kakoune session if the client is the last "
"(if not running in daemon mode). Force quit even if the client is the "
"last and some buffers are not saved. "
"An optional integer parameter can set the client exit status",
{ {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },
CommandFlags::None,
CommandHelper{},
CommandCompleter{},
quit<true>
};
template<bool force>
void write_quit(const ParametersParser& parser, Context& context,
const ShellContext& shell_context)
{
do_write_buffer(context, {},
parser.get_switch("sync") ? WriteFlags::Sync : WriteFlags::None,
parser.get_switch("method").map(parse_write_method));
quit<force>(parser, context, shell_context);
}
const CommandDesc write_quit_cmd = {
"write-quit",
"wq",
"write-quit [-sync] [<exit status>]: write current buffer and quit current client. "
"An optional integer parameter can set the client exit status",
write_params,
CommandFlags::None,
CommandHelper{},
CommandCompleter{},
write_quit<false>
};
const CommandDesc force_write_quit_cmd = {
"write-quit!",
"wq!",
"write-quit! [-sync] [<exit status>] write: current buffer and quit current client, even if other buffers are not saved. "
"An optional integer parameter can set the client exit status",
write_params,
CommandFlags::None,
CommandHelper{},
CommandCompleter{},
write_quit<true>
};
const CommandDesc write_all_quit_cmd = {
"write-all-quit",
"waq",
"write-all-quit [-sync] [<exit status>]: write all buffers associated to a file and quit current client. "
"An optional integer parameter can set the client exit status.",
write_params,
CommandFlags::None,
CommandHelper{},
CommandCompleter{},
[](const ParametersParser& parser, Context& context, const ShellContext& shell_context)
{
write_all_buffers(context,
(bool)parser.get_switch("sync"),
parser.get_switch("method").map(parse_write_method));
quit<false>(parser, context, shell_context);
}
};
const CommandDesc buffer_cmd = {
"buffer",
"b",
"buffer <name>: set buffer to edit in current client",
single_param,
CommandFlags::None,
CommandHelper{},
make_completer(menu(complete_buffer_name<true>)),
[](const ParametersParser& parser, Context& context, const ShellContext&)
{
Buffer& buffer = BufferManager::instance().get_buffer(parser[0]);
if (&buffer != &context.buffer())
{
context.push_jump();
context.change_buffer(buffer);
}
}
};
template<bool next>
void cycle_buffer(const ParametersParser& parser, Context& context, const ShellContext&)
{
Buffer* oldbuf = &context.buffer();
auto it = find_if(BufferManager::instance(),
[oldbuf](const std::unique_ptr<Buffer>& lhs)
{ return lhs.get() == oldbuf; });
kak_assert(it != BufferManager::instance().end());
Buffer* newbuf = nullptr;
auto cycle = [&] {
if (not next)
{
if (it == BufferManager::instance().begin())
it = BufferManager::instance().end();
--it;
}
else
{
if (++it == BufferManager::instance().end())
it = BufferManager::instance().begin();
}
newbuf = it->get();
};
cycle();
while (newbuf != oldbuf and newbuf->flags() & Buffer::Flags::Debug)
cycle();
if (newbuf != oldbuf)
{
context.push_jump();
context.change_buffer(*newbuf);
}
}
const CommandDesc buffer_next_cmd = {
"buffer-next",
"bn",
"buffer-next: move to the next buffer in the list",
no_params,
CommandFlags::None,
CommandHelper{},
CommandCompleter{},
cycle_buffer<true>
};
const CommandDesc buffer_previous_cmd = {
"buffer-previous",
"bp",
"buffer-previous: move to the previous buffer in the list",
no_params,
CommandFlags::None,
CommandHelper{},
CommandCompleter{},
cycle_buffer<false>
};
template<bool force>
void delete_buffer(const ParametersParser& parser, Context& context, const ShellContext&)
{
BufferManager& manager = BufferManager::instance();
Buffer& buffer = parser.positional_count() == 0 ? context.buffer() : manager.get_buffer(parser[0]);
if (not force and (buffer.flags() & Buffer::Flags::File) and buffer.is_modified())
throw runtime_error(format("buffer '{}' is modified", buffer.name()));
manager.delete_buffer(buffer);
context.forget_buffer(buffer);
}
const CommandDesc delete_buffer_cmd = {
"delete-buffer",
"db",
"delete-buffer [name]: delete current buffer or the buffer named <name> if given",
single_optional_param,
CommandFlags::None,
CommandHelper{},
make_completer(menu(complete_buffer_name<false>)),
delete_buffer<false>
};
const CommandDesc force_delete_buffer_cmd = {
"delete-buffer!",
"db!",
"delete-buffer! [name]: delete current buffer or the buffer named <name> if "
"given, even if the buffer is unsaved",
single_optional_param,
CommandFlags::None,
CommandHelper{},
make_completer(menu(complete_buffer_name<false>)),
delete_buffer<true>
};
const CommandDesc rename_buffer_cmd = {
"rename-buffer",
nullptr,
"rename-buffer <name>: change current buffer name",
ParameterDesc{
{
{ "scratch", { false, "convert a file buffer to a scratch buffer" } },
{ "file", { false, "convert a scratch buffer to a file buffer" } }
},
ParameterDesc::Flags::None, 1, 1
},
CommandFlags::None,
CommandHelper{},
filename_completer<false>,
[](const ParametersParser& parser, Context& context, const ShellContext&)
{
if (parser.get_switch("scratch") and parser.get_switch("file"))
throw runtime_error("scratch and file are incompatible switches");
auto& buffer = context.buffer();
if (parser.get_switch("scratch"))
buffer.flags() &= ~(Buffer::Flags::File | Buffer::Flags::New);
if (parser.get_switch("file"))
buffer.flags() |= Buffer::Flags::File;
if (not buffer.set_name(parser[0]))
throw runtime_error(format("unable to change buffer name to '{}': a buffer with this name already exists", parser[0]));
}
};
static constexpr auto highlighter_scopes = { "global/", "buffer/", "window/", "shared/" };
template<bool add>
Completions highlighter_cmd_completer(
const Context& context, CompletionFlags flags, CommandParameters params,
size_t token_to_complete, ByteCount pos_in_token)
{
if (token_to_complete == 0)
{
StringView path = params[0];
auto sep_it = find(path, '/');
if (sep_it == path.end())
return { 0_byte, pos_in_token, complete(path, pos_in_token, highlighter_scopes) };
StringView scope{path.begin(), sep_it};
HighlighterGroup* root = nullptr;
if (scope == "shared")
root = &SharedHighlighters::instance();
else if (auto* s = get_scope_ifp(scope, context))
root = &s->highlighters().group();
else
return {};
auto offset = scope.length() + 1;
return offset_pos(root->complete_child(StringView{sep_it+1, path.end()}, pos_in_token - offset, add), offset);
}
else if (add and token_to_complete == 1)
{
StringView name = params[1];
return { 0_byte, name.length(), complete(name, pos_in_token, HighlighterRegistry::instance() | transform(&HighlighterRegistry::Item::key)) };
}
else
return {};
}
Highlighter& get_highlighter(const Context& context, StringView path)
{
if (not path.empty() and path.back() == '/')
path = path.substr(0_byte, path.length() - 1);
auto sep_it = find(path, '/');
StringView scope{path.begin(), sep_it};
auto* root = (scope == "shared") ? static_cast<HighlighterGroup*>(&SharedHighlighters::instance())
: static_cast<HighlighterGroup*>(&get_scope(scope, context).highlighters().group());
if (sep_it != path.end())
return root->get_child(StringView{sep_it+1, path.end()});
return *root;
}
static void redraw_relevant_clients(Context& context, StringView highlighter_path)
{
StringView scope{highlighter_path.begin(), find(highlighter_path, '/')};
if (scope == "window")
context.window().force_redraw();
else if (scope == "buffer" or prefix_match(scope, "buffer="))
{
auto& buffer = scope == "buffer" ? context.buffer() : BufferManager::instance().get_buffer(scope.substr(7_byte));
for (auto&& client : ClientManager::instance())
{
if (&client->context().buffer() == &buffer)
client->context().window().force_redraw();
}
}
else
{
for (auto&& client : ClientManager::instance())
client->context().window().force_redraw();
}
}
const CommandDesc arrange_buffers_cmd = {
"arrange-buffers",
nullptr,
"arrange-buffers <buffer>...: reorder the buffers in the buffers list\n"
" the named buffers will be moved to the front of the buffer list, in the order given\n"
" buffers that do not appear in the parameters will remain at the end of the list, keeping their current order",
ParameterDesc{{}, ParameterDesc::Flags::None, 1},
CommandFlags::None,
CommandHelper{},
[](const Context& context, CompletionFlags flags, CommandParameters params, size_t, ByteCount cursor_pos)
{
return complete_buffer_name<false>(context, flags, params.back(), cursor_pos);
},
[](const ParametersParser& parser, Context&, const ShellContext&)
{
BufferManager::instance().arrange_buffers(parser.positionals_from(0));
}
};
const CommandDesc add_highlighter_cmd = {
"add-highlighter",
"addhl",
"add-highlighter <path>/<name> <type> <type params>...: add an highlighter to the group identified by <path>\n"
" <path> is a '/' delimited path or the parent highlighter, starting with either\n"
" 'global', 'buffer', 'window' or 'shared', if <name> is empty, it will be autogenerated",
ParameterDesc{
{ { "override", { false, "replace existing highlighter with same path if it exists" } }, },
ParameterDesc::Flags::SwitchesOnlyAtStart, 2
},
CommandFlags::None,
[](const Context& context, CommandParameters params) -> String
{
if (params.size() > 1)
{
HighlighterRegistry& registry = HighlighterRegistry::instance();
auto it = registry.find(params[1]);
if (it != registry.end())
return format("{}:\n{}", params[1], indent(it->value.docstring));
}
return "";
},
highlighter_cmd_completer<true>,
[](const ParametersParser& parser, Context& context, const ShellContext&)
{
HighlighterRegistry& registry = HighlighterRegistry::instance();
auto begin = parser.begin();
StringView path = *begin++;
StringView type = *begin++;
Vector<String> highlighter_params;
for (; begin != parser.end(); ++begin)
highlighter_params.push_back(*begin);
auto it = registry.find(type);
if (it == registry.end())
throw runtime_error(format("no such highlighter type: '{}'", type));
auto slash = find(path | reverse(), '/');
if (slash == path.rend())
throw runtime_error("no parent in path");
auto auto_name = [](ConstArrayView<String> params) {
return join(params | transform([](StringView s) { return replace(s, "/", "<slash>"); }), "_");
};