kakoune

Fork of kakoune, an acceptable text editor
git clone git://git.laack.co/kakoune.git
Log | Files | Refs

commands.cc (113955B)


      1 #include "commands.hh"
      2 
      3 #include "alias_registry.hh"
      4 #include "buffer.hh"
      5 #include "buffer_manager.hh"
      6 #include "buffer_utils.hh"
      7 #include "client.hh"
      8 #include "client_manager.hh"
      9 #include "command_manager.hh"
     10 #include "completion.hh"
     11 #include "context.hh"
     12 #include "debug.hh"
     13 #include "event_manager.hh"
     14 #include "face_registry.hh"
     15 #include "file.hh"
     16 #include "hash_map.hh"
     17 #include "hook_manager.hh"
     18 #include "highlighter.hh"
     19 #include "highlighters.hh"
     20 #include "input_handler.hh"
     21 #include "insert_completer.hh"
     22 #include "keymap_manager.hh"
     23 #include "local_scope.hh"
     24 #include "normal.hh"
     25 #include "option_manager.hh"
     26 #include "option_types.hh"
     27 #include "parameters_parser.hh"
     28 #include "profile.hh"
     29 #include "ranges.hh"
     30 #include "ranked_match.hh"
     31 #include "regex.hh"
     32 #include "register_manager.hh"
     33 #include "remote.hh"
     34 #include "shell_manager.hh"
     35 #include "string.hh"
     36 #include "user_interface.hh"
     37 #include "window.hh"
     38 
     39 #include <utility>
     40 
     41 #include <sys/types.h>
     42 #include <sys/stat.h>
     43 #include <fcntl.h>
     44 #include <unistd.h>
     45 
     46 #if defined(__GLIBC__) || defined(__CYGWIN__)
     47 #include <malloc.h>
     48 #endif
     49 
     50 namespace Kakoune
     51 {
     52 
     53 extern const char* version;
     54 
     55 namespace
     56 {
     57 
     58 Buffer* open_fifo(StringView name, StringView filename, Buffer::Flags flags, bool scroll)
     59 {
     60     int fd = open(parse_filename(filename).c_str(), O_RDONLY | O_NONBLOCK);
     61     fcntl(fd, F_SETFD, FD_CLOEXEC);
     62     if (fd < 0)
     63        throw runtime_error(format("unable to open '{}'", filename));
     64 
     65     return create_fifo_buffer(name.str(), fd, flags, scroll ? AutoScroll::Yes : AutoScroll::No);
     66 }
     67 
     68 template<typename... Completers> struct PerArgumentCommandCompleter;
     69 
     70 template<> struct PerArgumentCommandCompleter<>
     71 {
     72     Completions operator()(const Context&, CommandParameters,
     73                            size_t, ByteCount) const { return {}; }
     74 };
     75 
     76 template<typename Completer, typename... Rest>
     77 struct PerArgumentCommandCompleter<Completer, Rest...> : PerArgumentCommandCompleter<Rest...>
     78 {
     79     template<typename C, typename... R>
     80         requires (not std::is_base_of_v<PerArgumentCommandCompleter<>, std::remove_reference_t<C>>)
     81     PerArgumentCommandCompleter(C&& completer, R&&... rest)
     82       : PerArgumentCommandCompleter<Rest...>(std::forward<R>(rest)...),
     83         m_completer(std::forward<C>(completer)) {}
     84 
     85     Completions operator()(const Context& context,
     86                            CommandParameters params, size_t token_to_complete,
     87                            ByteCount pos_in_token)
     88     {
     89         if (token_to_complete == 0)
     90         {
     91             const String& arg = token_to_complete < params.size() ?
     92                                 params[token_to_complete] : String();
     93             return m_completer(context, arg, pos_in_token);
     94         }
     95         return PerArgumentCommandCompleter<Rest...>::operator()(
     96             context, params.subrange(1),
     97             token_to_complete-1, pos_in_token);
     98     }
     99 
    100     Completer m_completer;
    101 };
    102 
    103 template<typename... Completers>
    104 PerArgumentCommandCompleter<std::decay_t<Completers>...>
    105 make_completer(Completers&&... completers)
    106 {
    107     return {std::forward<Completers>(completers)...};
    108 }
    109 
    110 template<typename Completer>
    111 auto add_flags(Completer completer, Completions::Flags completions_flags)
    112 {
    113     return [completer=std::move(completer), completions_flags]
    114            (const Context& context, StringView prefix, ByteCount cursor_pos) {
    115         Completions res = completer(context, prefix, cursor_pos);
    116         res.flags |= completions_flags;
    117         return res;
    118     };
    119 }
    120 
    121 template<typename Completer>
    122 auto menu(Completer completer)
    123 {
    124     return add_flags(std::move(completer), Completions::Flags::Menu);
    125 }
    126 
    127 template<bool menu>
    128 auto filename_completer = make_completer(
    129     [](const Context& context, StringView prefix, ByteCount cursor_pos)
    130     { return Completions{ 0_byte, cursor_pos,
    131                           complete_filename(prefix,
    132                                             context.options()["ignored_files"].get<Regex>(),
    133                                             cursor_pos, FilenameFlags::Expand),
    134                                             menu ? Completions::Flags::Menu : Completions::Flags::None}; });
    135 
    136 template<bool menu>
    137 auto filename_arg_completer =
    138     [](const Context& context, StringView prefix, ByteCount cursor_pos) -> Completions
    139     { return { 0_byte, cursor_pos,
    140                complete_filename(prefix,
    141                                  context.options()["ignored_files"].get<Regex>(),
    142                                  cursor_pos, FilenameFlags::OnlyDirectories),
    143                menu ? Completions::Flags::Menu : Completions::Flags::None }; };
    144 
    145 auto client_arg_completer =
    146     [](const Context& context, StringView prefix, ByteCount cursor_pos) -> Completions
    147     { return { 0_byte, cursor_pos,
    148                ClientManager::instance().complete_client_name(prefix, cursor_pos),
    149                Completions::Flags::Menu }; };
    150 
    151 auto arg_completer = [](auto candidates) -> PromptCompleter {
    152     return [=](const Context& context, StringView prefix, ByteCount cursor_pos) -> Completions {
    153         return Completions{ 0_byte, cursor_pos, complete(prefix, cursor_pos, candidates), Completions::Flags::Menu };
    154     };
    155 };
    156 
    157 template<bool ignore_current = false>
    158 static Completions complete_buffer_name(const Context& context, StringView prefix, ByteCount cursor_pos)
    159 {
    160     struct RankedMatchAndBuffer : RankedMatch
    161     {
    162         RankedMatchAndBuffer(RankedMatch m, const Buffer* b)
    163             : RankedMatch{std::move(m)}, buffer{b} {}
    164 
    165         using RankedMatch::operator==;
    166         using RankedMatch::operator<;
    167 
    168         const Buffer* buffer;
    169     };
    170 
    171     StringView query = prefix.substr(0, cursor_pos);
    172     Vector<RankedMatchAndBuffer> filename_matches;
    173     Vector<RankedMatchAndBuffer> matches;
    174     for (const auto& buffer : BufferManager::instance())
    175     {
    176         if (ignore_current and buffer.get() == &context.buffer())
    177             continue;
    178 
    179         StringView bufname = buffer->display_name();
    180         if (buffer->flags() & Buffer::Flags::File)
    181         {
    182             if (RankedMatch match{split_path(bufname).second, query})
    183             {
    184                 filename_matches.emplace_back(match, buffer.get());
    185                 continue;
    186             }
    187         }
    188         if (RankedMatch match{bufname, query})
    189             matches.emplace_back(match, buffer.get());
    190     }
    191     std::sort(filename_matches.begin(), filename_matches.end());
    192     std::sort(matches.begin(), matches.end());
    193 
    194     CandidateList res;
    195     for (auto& match : filename_matches)
    196         res.push_back(match.buffer->display_name());
    197     for (auto& match : matches)
    198         res.push_back(match.buffer->display_name());
    199 
    200     return { 0, cursor_pos, res };
    201 }
    202 
    203 template<typename Func>
    204 auto make_single_word_completer(Func&& func)
    205 {
    206     return make_completer(
    207         [func = std::move(func)](const Context& context,
    208                StringView prefix, ByteCount cursor_pos) -> Completions {
    209             auto candidate = { func(context) };
    210             return { 0_byte, cursor_pos, complete(prefix, cursor_pos, candidate) }; });
    211 }
    212 
    213 const ParameterDesc no_params{ {}, ParameterDesc::Flags::None, 0, 0 };
    214 const ParameterDesc single_param{ {}, ParameterDesc::Flags::None, 1, 1 };
    215 const ParameterDesc single_optional_param{ {}, ParameterDesc::Flags::None, 0, 1 };
    216 const ParameterDesc double_params{ {}, ParameterDesc::Flags::None, 2, 2 };
    217 
    218 static Completions complete_scope(const Context&,
    219                                   StringView prefix, ByteCount cursor_pos)
    220 {
    221    static constexpr StringView scopes[] = { "global", "buffer", "window", "local"};
    222    return { 0_byte, cursor_pos, complete(prefix, cursor_pos, scopes) };
    223 }
    224 
    225 static Completions complete_scope_including_current(const Context&,
    226                                   StringView prefix, ByteCount cursor_pos)
    227 {
    228    static constexpr StringView scopes[] = { "global", "buffer", "window", "local", "current" };
    229    return { 0_byte, cursor_pos, complete(prefix, cursor_pos, scopes) };
    230 }
    231 
    232 static Completions complete_scope_no_global(const Context&,
    233                                             StringView prefix, ByteCount cursor_pos)
    234 {
    235    static constexpr StringView scopes[] = { "buffer", "window", "local", "current" };
    236    return { 0_byte, cursor_pos, complete(prefix, cursor_pos, scopes) };
    237 }
    238 
    239 
    240 static Completions complete_command_name(const Context& context,
    241                                          StringView prefix, ByteCount cursor_pos)
    242 {
    243    return CommandManager::instance().complete_command_name(
    244        context, prefix.substr(0, cursor_pos));
    245 }
    246 
    247 struct AsyncShellScript
    248 {
    249     AsyncShellScript(String shell_script,
    250                      Completions::Flags flags = Completions::Flags::None)
    251       : m_shell_script{std::move(shell_script)}, m_flags(flags) {}
    252 
    253     AsyncShellScript(const AsyncShellScript& other) : m_shell_script{other.m_shell_script}, m_flags(other.m_flags) {}
    254     AsyncShellScript& operator=(const AsyncShellScript& other) {  m_shell_script = other.m_shell_script; m_flags = other.m_flags; return *this; }
    255 
    256 protected:
    257     void spawn_script(const Context& context, const ShellContext& shell_context, auto&& handle_line)
    258     {
    259         m_handle_line = handle_line;
    260         m_running_script.emplace(ShellManager::instance().spawn(m_shell_script, context, false, shell_context));
    261         m_watcher.emplace((int)m_running_script->out, FdEvents::Read, EventMode::Urgent,
    262                           [this, &input_handler=context.input_handler()](auto&&... args) { read_stdout(input_handler); });
    263     }
    264 
    265     void read_stdout(InputHandler& input_handler)
    266     {
    267         char buffer[2048];
    268         bool closed = false;
    269         int fd = (int)m_running_script->out;
    270         while (fd_readable(fd))
    271         {
    272             int size = read(fd, buffer, sizeof(buffer));
    273             if (size == 0)
    274             {
    275                 closed = true;
    276                 break;
    277             }
    278             m_stdout_buffer.insert(m_stdout_buffer.end(), buffer, buffer + size);
    279         }
    280         auto end = closed ? m_stdout_buffer.end() : find(m_stdout_buffer | reverse(), '\n').base();
    281         for (auto c : ArrayView(m_stdout_buffer.begin(), end) | split<StringView>('\n')
    282                                                               | filter([](auto s) { return not s.empty(); }))
    283             m_handle_line(c);
    284 
    285         m_stdout_buffer.erase(m_stdout_buffer.begin(), end);
    286 
    287         input_handler.refresh_ifn();
    288         if (closed)
    289         {
    290             m_running_script.reset();
    291             m_watcher.reset();
    292             m_handle_line = {};
    293         }
    294     }
    295 
    296     String m_shell_script;
    297     Optional<Shell> m_running_script;
    298     Optional<FDWatcher> m_watcher;
    299     Vector<char, MemoryDomain::Completion> m_stdout_buffer;
    300     Function<void (StringView)> m_handle_line;
    301     Completions::Flags m_flags;
    302 };
    303 
    304 struct ShellScriptCompleter : AsyncShellScript
    305 {
    306     using AsyncShellScript::AsyncShellScript;
    307 
    308     Completions operator()(const Context& context,
    309                            CommandParameters params, size_t token_to_complete,
    310                            ByteCount pos_in_token)
    311     {
    312         CandidateList candidates;
    313         if (m_last_token != token_to_complete or pos_in_token != m_last_pos_in_token)
    314         {
    315             ShellContext shell_context{
    316                 params,
    317                 { { "token_to_complete", to_string(token_to_complete) },
    318                   { "pos_in_token",      to_string(pos_in_token) } }
    319             };
    320             spawn_script(context, shell_context, [this](StringView line) { m_candidates.push_back(line.str()); });
    321 
    322             candidates = std::move(m_candidates); // avoid completion menu flicker by keeping the previous result visible
    323             m_candidates.clear();
    324             m_last_token = token_to_complete;
    325             m_last_pos_in_token = pos_in_token;
    326         }
    327         else
    328             candidates = m_candidates;
    329 
    330         return {0_byte, pos_in_token, std::move(candidates), m_flags};
    331     }
    332 
    333 private:
    334     CandidateList m_candidates;
    335     int m_last_token = -1;
    336     ByteCount m_last_pos_in_token = -1;
    337 };
    338 
    339 struct ShellCandidatesCompleter : AsyncShellScript
    340 {
    341     using AsyncShellScript::AsyncShellScript;
    342 
    343     Completions operator()(const Context& context,
    344                            CommandParameters params, size_t token_to_complete,
    345                            ByteCount pos_in_token)
    346     {
    347         if (m_last_token != token_to_complete)
    348         {
    349             ShellContext shell_context{
    350                 params,
    351                 { { "token_to_complete", to_string(token_to_complete) } }
    352             };
    353             spawn_script(context, shell_context, [this](StringView line) { m_candidates.emplace_back(line.str(), used_letters(line)); });
    354             m_candidates.clear();
    355             m_last_token = token_to_complete;
    356         }
    357         return rank_candidates(params[token_to_complete].substr(0, pos_in_token));
    358     }
    359 
    360 private:
    361     Completions rank_candidates(StringView query)
    362     {
    363         UsedLetters query_letters = used_letters(query);
    364         Vector<RankedMatch> matches;
    365         for (auto&& [i, candidate] : m_candidates | enumerate())
    366         {
    367             if (RankedMatch m{candidate.first, candidate.second, query, query_letters})
    368             {
    369                 m.set_input_sequence_number(i);
    370                 matches.push_back(m);
    371             }
    372         }
    373 
    374         constexpr size_t max_count = 100;
    375         CandidateList res;
    376         // Gather best max_count matches
    377         for_n_best(matches, max_count, [](auto& lhs, auto& rhs) { return rhs < lhs; }, [&] (const RankedMatch& m) {
    378             if (not res.empty() and res.back() == m.candidate())
    379                 return false;
    380             res.push_back(m.candidate().str());
    381             return true;
    382         });
    383 
    384         return Completions{0_byte, query.length(), std::move(res), m_flags};
    385     }
    386 
    387     Vector<std::pair<String, UsedLetters>, MemoryDomain::Completion> m_candidates;
    388     int m_last_token = -1;
    389 };
    390 
    391 template<typename Completer>
    392 struct PromptCompleterAdapter
    393 {
    394     PromptCompleterAdapter(Completer completer) : m_completer{std::move(completer)} {}
    395 
    396     operator PromptCompleter() &&
    397     {
    398         if (not m_completer)
    399             return {};
    400         return [completer=std::move(m_completer)](const Context& context,
    401                                                   StringView prefix, ByteCount cursor_pos) {
    402             return completer(context, {String{String::NoCopy{}, prefix}}, 0, cursor_pos);
    403         };
    404     }
    405 
    406 private:
    407     Completer m_completer;
    408 };
    409 
    410 Scope* get_scope_ifp(StringView scope, const Context& context)
    411 {
    412     if (prefix_match("global", scope))
    413         return &GlobalScope::instance();
    414     else if (prefix_match("buffer", scope))
    415         return &context.buffer();
    416     else if (prefix_match("window", scope))
    417         return &context.window();
    418     else if (prefix_match("local", scope))
    419         return context.local_scope();
    420     else if (prefix_match(scope, "buffer="))
    421         return &BufferManager::instance().get_buffer(scope.substr(7_byte));
    422     return nullptr;
    423 }
    424 
    425 Scope& get_scope(StringView scope, const Context& context)
    426 {
    427     if (auto s = get_scope_ifp(scope, context))
    428         return *s;
    429     throw runtime_error(format("no such scope: '{}'", scope));
    430 }
    431 
    432 struct CommandDesc
    433 {
    434     const char* name;
    435     const char* alias;
    436     const char* docstring;
    437     ParameterDesc params;
    438     CommandFlags flags;
    439     CommandHelper helper;
    440     CommandCompleter completer;
    441     void (*func)(const ParametersParser&, Context&, const ShellContext&);
    442 };
    443 
    444 template<bool force_reload>
    445 void edit(const ParametersParser& parser, Context& context, const ShellContext&)
    446 {
    447     const bool scratch = (bool)parser.get_switch("scratch");
    448 
    449     if (parser.positional_count() == 0 and not force_reload and not scratch)
    450         throw wrong_argument_count();
    451 
    452     const bool no_hooks = context.hooks_disabled();
    453     const auto flags = (no_hooks ? Buffer::Flags::NoHooks : Buffer::Flags::None) |
    454        (parser.get_switch("debug") ? Buffer::Flags::Debug : Buffer::Flags::None);
    455 
    456     auto& buffer_manager = BufferManager::instance();
    457     const auto& name = parser.positional_count() > 0 ?
    458         parser[0] : (scratch ? generate_buffer_name("*scratch-{}*") : context.buffer().name());
    459 
    460     Buffer* buffer = buffer_manager.get_buffer_ifp(name);
    461     if (scratch)
    462     {
    463         if (parser.get_switch("readonly") or parser.get_switch("fifo") or parser.get_switch("scroll"))
    464             throw runtime_error("scratch is not compatible with readonly, fifo or scroll");
    465 
    466         if (buffer == nullptr or force_reload)
    467         {
    468             if (buffer != nullptr and force_reload)
    469                 buffer_manager.delete_buffer(*buffer);
    470             buffer = create_buffer_from_string(name, flags, {});
    471         }
    472         else if (buffer->flags() & Buffer::Flags::File)
    473             throw runtime_error(format("buffer '{}' exists but is not a scratch buffer", name));
    474     }
    475     else if (force_reload and buffer and buffer->flags() & Buffer::Flags::File)
    476     {
    477         reload_file_buffer(*buffer);
    478     }
    479     else
    480     {
    481         if (auto fifo = parser.get_switch("fifo"))
    482             buffer = open_fifo(name, *fifo, flags, (bool)parser.get_switch("scroll"));
    483         else if (not buffer)
    484         {
    485             buffer = parser.get_switch("existing") ? open_file_buffer(name, flags)
    486                                                    : open_or_create_file_buffer(name, flags);
    487             if (buffer->flags() & Buffer::Flags::New)
    488                 context.print_status({format("new file '{}'", name), context.faces()["StatusLine"]});
    489         }
    490 
    491         buffer->flags() &= ~Buffer::Flags::NoHooks;
    492         if (parser.get_switch("readonly"))
    493         {
    494             buffer->flags() |= Buffer::Flags::ReadOnly;
    495             buffer->options().get_local_option("readonly").set(true);
    496         }
    497     }
    498 
    499     Buffer* current_buffer = context.has_buffer() ? &context.buffer() : nullptr;
    500 
    501     const size_t param_count = parser.positional_count();
    502     if (current_buffer and (buffer != current_buffer or param_count > 1))
    503         context.push_jump();
    504 
    505     if (buffer != current_buffer)
    506         context.change_buffer(*buffer);
    507     buffer = &context.buffer(); // change_buffer hooks might change the buffer again
    508 
    509     if (parser.get_switch("fifo") and not parser.get_switch("scroll"))
    510         context.selections_write_only() = { *buffer, Selection{} };
    511     else if (param_count > 1 and not parser[1].empty())
    512     {
    513         int line = std::max(0, str_to_int(parser[1]) - 1);
    514         int column = param_count > 2 and not parser[2].empty() ?
    515                      std::max(0, str_to_int(parser[2]) - 1) : 0;
    516 
    517         auto& buffer = context.buffer();
    518         context.selections_write_only() = { buffer, buffer.clamp({ line,  column }) };
    519         if (context.has_window())
    520             context.window().center_line(context.selections().main().cursor().line);
    521     }
    522 }
    523 
    524 ParameterDesc edit_params{
    525     { { "existing", { {}, "fail if the file does not exist, do not open a new file" } },
    526       { "scratch",  { {}, "create a scratch buffer, not linked to a file" } },
    527       { "debug",    { {}, "create buffer as debug output" } },
    528       { "fifo",     { {filename_arg_completer<true>},  "create a buffer reading its content from a named fifo" } },
    529       { "readonly", { {}, "create a buffer in readonly mode" } },
    530       { "scroll",   { {}, "place the initial cursor so that the fifo will scroll to show new data" } } },
    531       ParameterDesc::Flags::None, 0, 3
    532 };
    533 const CommandDesc edit_cmd = {
    534     "edit",
    535     "e",
    536     "edit [<switches>] <filename> [<line> [<column>]]: open the given filename in a buffer",
    537     edit_params,
    538     CommandFlags::None,
    539     CommandHelper{},
    540     filename_completer<false>,
    541     edit<false>
    542 };
    543 
    544 const CommandDesc force_edit_cmd = {
    545     "edit!",
    546     "e!",
    547     "edit! [<switches>] <filename> [<line> [<column>]]: open the given filename in a buffer, "
    548     "force reload if needed",
    549     edit_params,
    550     CommandFlags::None,
    551     CommandHelper{},
    552     filename_completer<false>,
    553     edit<true>
    554 };
    555 
    556 const ParameterDesc write_params = {
    557     {
    558         { "sync", { {}, "force the synchronization of the file onto the filesystem" } },
    559         { "method", { {arg_completer(Array{"replace", "overwrite"})}, "explicit writemethod (replace|overwrite)" } },
    560         { "force", { {}, "Allow overwriting existing file with explicit filename" } }
    561     },
    562     ParameterDesc::Flags::None, 0, 1
    563 };
    564 
    565 const ParameterDesc write_params_except_force = {
    566     {
    567         { "sync", { {}, "force the synchronization of the file onto the filesystem" } },
    568         { "method", { {arg_completer(Array{"replace", "overwrite"})}, "explicit writemethod (replace|overwrite)" } },
    569     },
    570     ParameterDesc::Flags::None, 0, 1
    571 };
    572 
    573 auto parse_write_method(StringView str)
    574 {
    575     constexpr auto desc = enum_desc(Meta::Type<WriteMethod>{});
    576     auto it = find_if(desc, [str](const EnumDesc<WriteMethod>& d) { return d.name == str; });
    577     if (it == desc.end())
    578         throw runtime_error(format("invalid writemethod '{}'", str));
    579     return it->value;
    580 }
    581 
    582 void do_write_buffer(Context& context, Optional<String> filename, WriteFlags flags, Optional<WriteMethod> write_method = {})
    583 {
    584     Buffer& buffer = context.buffer();
    585     const bool is_file = (bool)(buffer.flags() & Buffer::Flags::File);
    586 
    587     if (not filename and not is_file)
    588         throw runtime_error("cannot write a non file buffer without a filename");
    589 
    590     const bool is_readonly = (bool)(context.buffer().flags() & Buffer::Flags::ReadOnly);
    591     // if the buffer is in read-only mode and we try to save it directly
    592     // or we try to write to it indirectly using e.g. a symlink, throw an error
    593     if (is_file and is_readonly and
    594         (not filename or real_path(*filename) == buffer.filename()))
    595         throw runtime_error("cannot overwrite the buffer when in readonly mode");
    596 
    597     auto effective_filename = filename ? parse_filename(*filename) : buffer.filename();
    598     if (filename and not (flags & WriteFlags::Force) and
    599         real_path(effective_filename) != buffer.filename() and
    600         regular_file_exists(effective_filename))
    601         throw runtime_error("cannot overwrite existing file without -force");
    602 
    603     auto method = write_method.value_or_compute([&] { return context.options()["writemethod"].get<WriteMethod>(); });
    604 
    605     context.hooks().run_hook(Hook::BufWritePre, effective_filename, context);
    606     BusyIndicator busy_indicator{context, [&](std::chrono::seconds elapsed) {
    607         return DisplayLine{format("waiting while writing buffer '{}' ({}s)", buffer.filename(), elapsed.count()),
    608                            context.faces()["Information"]};
    609     }};
    610     FinalEol finaleol = context.options()["finaleol"].get<FinalEol>();
    611     write_buffer_to_file(buffer, effective_filename, method, flags, finaleol);
    612     context.hooks().run_hook(Hook::BufWritePost, effective_filename, context);
    613 }
    614 
    615 template<bool force = false>
    616 void write_buffer(const ParametersParser& parser, Context& context, const ShellContext&)
    617 {
    618     return do_write_buffer(context,
    619                            parser.positional_count() > 0 ? parser[0] : Optional<String>{},
    620                            (parser.get_switch("sync") ? WriteFlags::Sync : WriteFlags::None) |
    621                            (parser.get_switch("force") or force ? WriteFlags::Force : WriteFlags::None),
    622                            parser.get_switch("method").map(parse_write_method));
    623 }
    624 
    625 const CommandDesc write_cmd = {
    626     "write",
    627     "w",
    628     "write [<switches>] [<filename>]: write the current buffer to its file "
    629     "or to <filename> if specified",
    630     write_params,
    631     CommandFlags::None,
    632     CommandHelper{},
    633     filename_completer<false>,
    634     write_buffer,
    635 };
    636 
    637 const CommandDesc force_write_cmd = {
    638     "write!",
    639     "w!",
    640     "write! [<switches>] [<filename>]: write the current buffer to its file "
    641     "or to <filename> if specified, even when the file is write protected",
    642     write_params_except_force,
    643     CommandFlags::None,
    644     CommandHelper{},
    645     filename_completer<false>,
    646     write_buffer<true>,
    647 };
    648 
    649 void write_all_buffers(const Context& context, bool sync = false, Optional<WriteMethod> write_method = {})
    650 {
    651     // Copy buffer list because hooks might be creating/deleting buffers
    652     Vector<SafePtr<Buffer>> buffers;
    653     for (auto& buffer : BufferManager::instance())
    654         buffers.emplace_back(buffer.get());
    655 
    656     for (auto& buffer : buffers)
    657     {
    658         if ((buffer->flags() & Buffer::Flags::File) and
    659             ((buffer->flags() & Buffer::Flags::New) or
    660              buffer->is_modified())
    661             and not (buffer->flags() & Buffer::Flags::ReadOnly))
    662         {
    663             auto method = write_method.value_or_compute([&] { return context.options()["writemethod"].get<WriteMethod>(); });
    664             auto flags = sync ? WriteFlags::Sync : WriteFlags::None;
    665             buffer->run_hook_in_own_context(Hook::BufWritePre, buffer->name(), context.name());
    666             BusyIndicator busy_indicator{context, [&](std::chrono::seconds elapsed) {
    667                 return DisplayLine{format("waiting while writing buffer ({}s)", elapsed.count()),
    668                                    context.faces()["Information"]};
    669             }};
    670             write_buffer_to_file(*buffer, buffer->name(), method, flags);
    671             buffer->run_hook_in_own_context(Hook::BufWritePost, buffer->name(), context.name());
    672         }
    673     }
    674 }
    675 
    676 const CommandDesc write_all_cmd = {
    677     "write-all",
    678     "wa",
    679     "write-all [<switches>]: write all changed buffers that are associated to a file",
    680     ParameterDesc{
    681         write_params_except_force.switches,
    682         ParameterDesc::Flags::None, 0, 0
    683     },
    684     CommandFlags::None,
    685     CommandHelper{},
    686     CommandCompleter{},
    687     [](const ParametersParser& parser, Context& context, const ShellContext&){
    688         write_all_buffers(context,
    689                           (bool)parser.get_switch("sync"),
    690                           parser.get_switch("method").map(parse_write_method));
    691     }
    692 };
    693 
    694 static void ensure_all_buffers_are_saved(Context& context)
    695 {
    696     auto is_modified = [](const UniquePtr<Buffer>& buf) {
    697         return (buf->flags() & Buffer::Flags::File) and buf->is_modified();
    698     };
    699 
    700     auto it = find_if(BufferManager::instance(), is_modified);
    701     const auto end = BufferManager::instance().end();
    702     if (it == end)
    703         return;
    704 
    705     if (not context.buffer().is_modified())
    706     {
    707         context.push_jump();
    708         context.change_buffer(**it);
    709     }
    710 
    711     String message = format("{} modified buffers remaining: [",
    712                             std::count_if(it, end, is_modified));
    713     while (it != end)
    714     {
    715         message += (*it)->display_name();
    716         it = std::find_if(it+1, end, is_modified);
    717         message += (it != end) ? ", " : "]";
    718     }
    719     throw runtime_error(message);
    720 }
    721 
    722 template<bool force>
    723 void kill(const ParametersParser& parser, Context& context, const ShellContext&)
    724 {
    725     auto& client_manager = ClientManager::instance();
    726 
    727     if (not force)
    728         ensure_all_buffers_are_saved(context);
    729 
    730     const int status = parser.positional_count() > 0 ? str_to_int(parser[0]) : 0;
    731     while (not client_manager.empty())
    732         client_manager.remove_client(**client_manager.begin(), true, status);
    733 
    734     throw kill_session{status};
    735 }
    736 
    737 const CommandDesc kill_cmd = {
    738     "kill",
    739     nullptr,
    740     "kill [<exit status>]: terminate the current session, the server and all clients connected. "
    741     "An optional integer parameter can set the server and client processes exit status",
    742     { {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },
    743     CommandFlags::None,
    744     CommandHelper{},
    745     CommandCompleter{},
    746     kill<false>
    747 };
    748 
    749 
    750 const CommandDesc force_kill_cmd = {
    751     "kill!",
    752     nullptr,
    753     "kill! [<exit status>]: force the termination of the current session, the server and all clients connected. "
    754     "An optional integer parameter can set the server and client processes exit status",
    755     { {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },
    756     CommandFlags::None,
    757     CommandHelper{},
    758     CommandCompleter{},
    759     kill<true>
    760 };
    761 
    762 const CommandDesc daemonize_session_cmd = {
    763     "daemonize-session",
    764     nullptr,
    765     "daemonize-session: set the session server not to quit on last client exit",
    766     { {} },
    767     CommandFlags::None,
    768     CommandHelper{},
    769     CommandCompleter{},
    770     [](const ParametersParser&, Context&, const ShellContext&) { Server::instance().daemonize(); }
    771 };
    772 
    773 template<bool force>
    774 void quit(const ParametersParser& parser, Context& context, const ShellContext&)
    775 {
    776     if (not force and ClientManager::instance().count() == 1 and not Server::instance().is_daemon())
    777         ensure_all_buffers_are_saved(context);
    778 
    779     const int status = parser.positional_count() > 0 ? str_to_int(parser[0]) : 0;
    780     ClientManager::instance().remove_client(context.client(), true, status);
    781 }
    782 
    783 const CommandDesc quit_cmd = {
    784     "quit",
    785     "q",
    786     "quit [<exit status>]: quit current client, and the kakoune session if the client is the last "
    787     "(if not running in daemon mode). "
    788     "An optional integer parameter can set the client exit status",
    789     { {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },
    790     CommandFlags::None,
    791     CommandHelper{},
    792     CommandCompleter{},
    793     quit<false>
    794 };
    795 
    796 const CommandDesc force_quit_cmd = {
    797     "quit!",
    798     "q!",
    799     "quit! [<exit status>]: quit current client, and the kakoune session if the client is the last "
    800     "(if not running in daemon mode). Force quit even if the client is the "
    801     "last and some buffers are not saved. "
    802     "An optional integer parameter can set the client exit status",
    803     { {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 1 },
    804     CommandFlags::None,
    805     CommandHelper{},
    806     CommandCompleter{},
    807     quit<true>
    808 };
    809 
    810 template<bool force>
    811 void write_quit(const ParametersParser& parser, Context& context,
    812                 const ShellContext& shell_context)
    813 {
    814     do_write_buffer(context, {},
    815                     parser.get_switch("sync") ? WriteFlags::Sync : WriteFlags::None,
    816                     parser.get_switch("method").map(parse_write_method));
    817     quit<force>(parser, context, shell_context);
    818 }
    819 
    820 const CommandDesc write_quit_cmd = {
    821     "write-quit",
    822     "wq",
    823     "write-quit [<switches>] [<exit status>]: write current buffer and quit current client. "
    824     "An optional integer parameter can set the client exit status",
    825     write_params_except_force,
    826     CommandFlags::None,
    827     CommandHelper{},
    828     CommandCompleter{},
    829     write_quit<false>
    830 };
    831 
    832 const CommandDesc force_write_quit_cmd = {
    833     "write-quit!",
    834     "wq!",
    835     "write-quit! [<switches>] [<exit status>] write: current buffer and quit current client, even if other buffers are not saved. "
    836     "An optional integer parameter can set the client exit status",
    837     write_params_except_force,
    838     CommandFlags::None,
    839     CommandHelper{},
    840     CommandCompleter{},
    841     write_quit<true>
    842 };
    843 
    844 const CommandDesc write_all_quit_cmd = {
    845     "write-all-quit",
    846     "waq",
    847     "write-all-quit [<switches>] [<exit status>]: write all buffers associated to a file and quit current client. "
    848     "An optional integer parameter can set the client exit status.",
    849     write_params_except_force,
    850     CommandFlags::None,
    851     CommandHelper{},
    852     CommandCompleter{},
    853     [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)
    854     {
    855         write_all_buffers(context,
    856                           (bool)parser.get_switch("sync"),
    857                           parser.get_switch("method").map(parse_write_method));
    858         quit<false>(parser, context, shell_context);
    859     }
    860 };
    861 
    862 const CommandDesc buffer_cmd = {
    863     "buffer",
    864     "b",
    865     "buffer <name>: set buffer to edit in current client",
    866     {
    867         { { "matching", { {}, "treat the argument as a regex" } } },
    868         ParameterDesc::Flags::None, 1, 1
    869     },
    870     CommandFlags::None,
    871     CommandHelper{},
    872     make_completer(menu(complete_buffer_name<true>)),
    873     [](const ParametersParser& parser, Context& context, const ShellContext&)
    874     {
    875         Buffer& buffer = parser.get_switch("matching") ? BufferManager::instance().get_buffer_matching(
    876                                                              [re=Regex{parser[0]}](Buffer& buffer) {
    877                                                                 auto name = buffer.name();
    878                                                                 return regex_match(name.begin(), name.end(), re);
    879                                                              })
    880                                                        : BufferManager::instance().get_buffer(parser[0]);
    881         if (&buffer != &context.buffer())
    882         {
    883             context.push_jump();
    884             context.change_buffer(buffer);
    885         }
    886     }
    887 };
    888 
    889 template<bool next>
    890 void cycle_buffer(const ParametersParser& parser, Context& context, const ShellContext&)
    891 {
    892     Buffer* oldbuf = &context.buffer();
    893     auto it = find_if(BufferManager::instance(),
    894                       [oldbuf](const UniquePtr<Buffer>& lhs)
    895                       { return lhs.get() == oldbuf; });
    896     kak_assert(it != BufferManager::instance().end());
    897 
    898     Buffer* newbuf = nullptr;
    899     auto cycle = [&] {
    900         if (not next)
    901         {
    902             if (it == BufferManager::instance().begin())
    903                 it = BufferManager::instance().end();
    904             --it;
    905         }
    906         else
    907         {
    908             if (++it == BufferManager::instance().end())
    909                 it = BufferManager::instance().begin();
    910         }
    911         newbuf = it->get();
    912     };
    913     cycle();
    914     while (newbuf != oldbuf and newbuf->flags() & Buffer::Flags::Debug)
    915         cycle();
    916 
    917     if (newbuf != oldbuf)
    918     {
    919         context.push_jump();
    920         context.change_buffer(*newbuf);
    921     }
    922 }
    923 
    924 const CommandDesc buffer_next_cmd = {
    925     "buffer-next",
    926     "bn",
    927     "buffer-next: move to the next buffer in the list",
    928     no_params,
    929     CommandFlags::None,
    930     CommandHelper{},
    931     CommandCompleter{},
    932     cycle_buffer<true>
    933 };
    934 
    935 const CommandDesc buffer_previous_cmd = {
    936     "buffer-previous",
    937     "bp",
    938     "buffer-previous: move to the previous buffer in the list",
    939     no_params,
    940     CommandFlags::None,
    941     CommandHelper{},
    942     CommandCompleter{},
    943     cycle_buffer<false>
    944 };
    945 
    946 template<bool force>
    947 void delete_buffer(const ParametersParser& parser, Context& context, const ShellContext&)
    948 {
    949     BufferManager& manager = BufferManager::instance();
    950     Buffer& buffer = parser.positional_count() == 0 ? context.buffer() : manager.get_buffer(parser[0]);
    951     if (not force and (buffer.flags() & Buffer::Flags::File) and buffer.is_modified())
    952         throw runtime_error(format("buffer '{}' is modified", buffer.display_name()));
    953 
    954     manager.delete_buffer(buffer);
    955     context.forget_buffer(buffer);
    956 }
    957 
    958 const CommandDesc delete_buffer_cmd = {
    959     "delete-buffer",
    960     "db",
    961     "delete-buffer [name]: delete current buffer or the buffer named <name> if given",
    962     single_optional_param,
    963     CommandFlags::None,
    964     CommandHelper{},
    965     make_completer(menu(complete_buffer_name<false>)),
    966     delete_buffer<false>
    967 };
    968 
    969 const CommandDesc force_delete_buffer_cmd = {
    970     "delete-buffer!",
    971     "db!",
    972     "delete-buffer! [name]: delete current buffer or the buffer named <name> if "
    973     "given, even if the buffer is unsaved",
    974     single_optional_param,
    975     CommandFlags::None,
    976     CommandHelper{},
    977     make_completer(menu(complete_buffer_name<false>)),
    978     delete_buffer<true>
    979 };
    980 
    981 const CommandDesc rename_buffer_cmd = {
    982     "rename-buffer",
    983     nullptr,
    984     "rename-buffer <name>: change current buffer name",
    985     ParameterDesc{
    986         {
    987             { "scratch",  { {}, "convert a file buffer to a scratch buffer" } },
    988             { "file",  { {}, "convert a scratch buffer to a file buffer" } }
    989         },
    990         ParameterDesc::Flags::None, 1, 1
    991     },
    992     CommandFlags::None,
    993     CommandHelper{},
    994     filename_completer<false>,
    995     [](const ParametersParser& parser, Context& context, const ShellContext&)
    996     {
    997         if (parser.get_switch("scratch") and parser.get_switch("file"))
    998             throw runtime_error("scratch and file are incompatible switches");
    999 
   1000         auto& buffer = context.buffer();
   1001         if (parser.get_switch("scratch"))
   1002             buffer.flags() &= ~(Buffer::Flags::File | Buffer::Flags::New);
   1003         if (parser.get_switch("file"))
   1004             buffer.flags() |= Buffer::Flags::File;
   1005 
   1006         const bool is_file = (buffer.flags() & Buffer::Flags::File);
   1007 
   1008         if (not buffer.set_name(is_file ? parse_filename(parser[0]) : parser[0]))
   1009             throw runtime_error(format("unable to change buffer name to '{}': a buffer with this name already exists", parser[0]));
   1010     }
   1011 };
   1012 
   1013 static constexpr auto highlighter_scopes = { "global/", "buffer/", "window/", "shared/" };
   1014 
   1015 template<bool add>
   1016 Completions highlighter_cmd_completer(
   1017     const Context& context, CommandParameters params,
   1018     size_t token_to_complete, ByteCount pos_in_token)
   1019 {
   1020     if (token_to_complete == 0)
   1021     {
   1022 
   1023         StringView path = params[0];
   1024         auto sep_it = find(path, '/');
   1025         if (sep_it == path.end())
   1026            return { 0_byte, pos_in_token, complete(path, pos_in_token, highlighter_scopes),
   1027                     Completions::Flags::Menu };
   1028 
   1029         StringView scope{path.begin(), sep_it};
   1030         HighlighterGroup* root = nullptr;
   1031         if (scope == "shared")
   1032             root = &SharedHighlighters::instance();
   1033         else if (auto* s = get_scope_ifp(scope, context))
   1034             root = &s->highlighters().group();
   1035         else
   1036             return {};
   1037 
   1038         auto offset = scope.length() + 1;
   1039         return offset_pos(root->complete_child(StringView{sep_it+1, path.end()}, pos_in_token - offset, add), offset);
   1040     }
   1041     else if (add and token_to_complete == 1)
   1042     {
   1043         StringView name = params[1];
   1044         return { 0_byte, name.length(), complete(name, pos_in_token, HighlighterRegistry::instance() | transform(&HighlighterRegistry::Item::key)),
   1045                  Completions::Flags::Menu };
   1046     }
   1047     else
   1048         return {};
   1049 }
   1050 
   1051 static std::pair<HighlighterGroup&, Highlighter&> get_highlighter(const Context& context, StringView path)
   1052 {
   1053     if (not path.empty() and path.back() == '/')
   1054         path = path.substr(0_byte, path.length() - 1);
   1055 
   1056     auto sep_it = find(path, '/');
   1057     if (path.starts_with("buffer="))
   1058     {
   1059         auto& buffer_manager = BufferManager::instance();
   1060         while (sep_it != path.end() and not buffer_manager.get_buffer_ifp({path.begin()+7, sep_it}))
   1061             sep_it = std::find(sep_it+1, path.end(), '/');
   1062     }
   1063 
   1064     StringView scope{path.begin(), sep_it};
   1065     auto* root = (scope == "shared") ? static_cast<HighlighterGroup*>(&SharedHighlighters::instance())
   1066                                      : static_cast<HighlighterGroup*>(&get_scope(scope, context).highlighters().group());
   1067     if (sep_it != path.end())
   1068         return {*root, root->get_child(StringView{sep_it+1, path.end()})};
   1069     return {*root, *root};
   1070 }
   1071 
   1072 static void redraw_relevant_clients(Context& context, HighlighterGroup& root)
   1073 {
   1074     for (auto&& client : ClientManager::instance())
   1075     {
   1076         if (&root == &SharedHighlighters::instance() or
   1077             &root == &GlobalScope::instance().highlighters().group() or
   1078             &root == &client->context().buffer().highlighters().group() or
   1079             &root == &client->context().window().highlighters().group())
   1080             client->force_redraw();
   1081     }
   1082 }
   1083 
   1084 const CommandDesc arrange_buffers_cmd = {
   1085     "arrange-buffers",
   1086     nullptr,
   1087     "arrange-buffers <buffer>...: reorder the buffers in the buffers list\n"
   1088     "    the named buffers will be moved to the front of the buffer list, in the order given\n"
   1089     "    buffers that do not appear in the parameters will remain at the end of the list, keeping their current order",
   1090     ParameterDesc{
   1091         { { "back", { {}, "place the named buffers at the back, rather than the front, of the buffer list" } }, },
   1092         ParameterDesc::Flags::None, 1
   1093     },
   1094     CommandFlags::None,
   1095     CommandHelper{},
   1096     [](const Context& context, CommandParameters params, size_t, ByteCount cursor_pos)
   1097     {
   1098         return menu(complete_buffer_name<false>)(context, params.back(), cursor_pos);
   1099     },
   1100     [](const ParametersParser& parser, Context&, const ShellContext&)
   1101     {
   1102         const auto to_back = (bool)parser.get_switch("back");
   1103         BufferManager::instance().arrange_buffers(parser.positionals_from(0), to_back);
   1104     }
   1105 };
   1106 
   1107 const CommandDesc add_highlighter_cmd = {
   1108     "add-highlighter",
   1109     "addhl",
   1110     "add-highlighter [-override] <path>/<name> <type> <type params>...: add a highlighter to the group identified by <path>\n"
   1111     "    <path> is a '/' delimited path or the parent highlighter, starting with either\n"
   1112     "   'global', 'buffer', 'window' or 'shared', if <name> is empty, it will be autogenerated",
   1113     ParameterDesc{
   1114         { { "override", { {}, "replace existing highlighter with same path if it exists" } }, },
   1115         ParameterDesc::Flags::SwitchesOnlyAtStart, 2
   1116     },
   1117     CommandFlags::None,
   1118     [](const Context& context, CommandParameters params) -> String
   1119     {
   1120         if (params.size() > 1)
   1121         {
   1122             HighlighterRegistry& registry = HighlighterRegistry::instance();
   1123             auto it = registry.find(params[1]);
   1124             if (it != registry.end())
   1125             {
   1126                 auto docstring = it->value.description->docstring;
   1127                 auto desc_params = generate_switches_doc(it->value.description->params.switches);
   1128 
   1129                 if (desc_params.empty())
   1130                     return format("{}:\n{}", params[1], indent(docstring));
   1131                 else
   1132                 {
   1133                     auto desc_indent = Vector<String>{docstring, "Switches:", indent(desc_params)}
   1134                                            | transform([](auto& s) { return indent(s); });
   1135                     return format("{}:\n{}", params[1], join(desc_indent, "\n"));
   1136                 }
   1137             }
   1138         }
   1139         return "";
   1140     },
   1141     highlighter_cmd_completer<true>,
   1142     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1143     {
   1144         HighlighterRegistry& registry = HighlighterRegistry::instance();
   1145 
   1146         auto begin = parser.begin();
   1147         StringView path = *begin++;
   1148         StringView type = *begin++;
   1149         Vector<String> highlighter_params;
   1150         for (; begin != parser.end(); ++begin)
   1151             highlighter_params.push_back(*begin);
   1152 
   1153         auto it = registry.find(type);
   1154         if (it == registry.end())
   1155             throw runtime_error(format("no such highlighter type: '{}'", type));
   1156 
   1157         auto slash = find(path | reverse(), '/');
   1158         if (slash == path.rend())
   1159             throw runtime_error("no parent in path");
   1160 
   1161         auto auto_name = [](ConstArrayView<String> params) {
   1162             return join(params | transform([](StringView s) { return replace(s, "/", "<slash>"); }), "_");
   1163         };
   1164 
   1165         String name{slash.base(), path.end()};
   1166         auto [root, parent] = get_highlighter(context, {path.begin(), slash.base() - 1});
   1167         parent.add_child(name.empty() ? auto_name(parser.positionals_from(1)) : std::move(name),
   1168                          it->value.factory(highlighter_params, &parent), (bool)parser.get_switch("override"));
   1169 
   1170         redraw_relevant_clients(context, root);
   1171     }
   1172 };
   1173 
   1174 const CommandDesc remove_highlighter_cmd = {
   1175     "remove-highlighter",
   1176     "rmhl",
   1177     "remove-highlighter <path>: remove highlighter identified by <path>",
   1178     single_param,
   1179     CommandFlags::None,
   1180     CommandHelper{},
   1181     highlighter_cmd_completer<false>,
   1182     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1183     {
   1184         StringView path = parser[0];
   1185         if (not path.empty() and path.back() == '/') // ignore trailing /
   1186             path = path.substr(0_byte, path.length() - 1_byte);
   1187 
   1188         auto rev_path = path | reverse();
   1189         auto sep_it = find(rev_path, '/');
   1190         if (sep_it == rev_path.end())
   1191             return;
   1192         auto [root, parent] = get_highlighter(context, {path.begin(), sep_it.base()});
   1193         parent.remove_child({sep_it.base(), path.end()});
   1194         redraw_relevant_clients(context, root);
   1195     }
   1196 };
   1197 
   1198 static Completions complete_hooks(const Context&, StringView prefix, ByteCount cursor_pos)
   1199 {
   1200     return { 0_byte, cursor_pos, complete(prefix, cursor_pos, enum_desc(Meta::Type<Hook>{}) | transform(&EnumDesc<Hook>::name)) };
   1201 }
   1202 
   1203 const CommandDesc add_hook_cmd = {
   1204     "hook",
   1205     nullptr,
   1206     "hook [<switches>] <scope> <hook_name> <filter> <command>: add <command> in <scope> "
   1207     "to be executed on hook <hook_name> when its parameter matches the <filter> regex\n"
   1208     "<scope> can be:\n"
   1209     "  * global: hook is executed for any buffer or window\n"
   1210     "  * buffer: hook is executed only for the current buffer\n"
   1211     "            (and any window for that buffer)\n"
   1212     "  * window: hook is executed only for the current window\n",
   1213     ParameterDesc{
   1214         { { "group", { ArgCompleter{}, "set hook group, see remove-hooks" } },
   1215           { "always", { {}, "run hook even if hooks are disabled" } },
   1216           { "once", { {}, "run the hook only once" } } },
   1217         ParameterDesc::Flags::None, 4, 4
   1218     },
   1219     CommandFlags::None,
   1220     CommandHelper{},
   1221     make_completer(menu(complete_scope), menu(complete_hooks), complete_nothing, CommandManager::Completer{}),
   1222     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1223     {
   1224         auto descs = enum_desc(Meta::Type<Hook>{});
   1225         auto it = find_if(descs, [&](const EnumDesc<Hook>& desc) { return desc.name == parser[1]; });
   1226         if (it == descs.end())
   1227             throw runtime_error{format("no such hook: '{}'", parser[1])};
   1228 
   1229         Regex regex{parser[2], RegexCompileFlags::Optimize};
   1230         const String& command = parser[3];
   1231         auto group = parser.get_switch("group").value_or(StringView{});
   1232 
   1233         if (any_of(group, [](char c) { return not is_word(c, { '-' }); }) or
   1234             (not group.empty() and not is_word(group[0])))
   1235             throw runtime_error{format("invalid group name '{}'", group)};
   1236 
   1237         const auto flags = (parser.get_switch("always") ? HookFlags::Always : HookFlags::None) |
   1238                            (parser.get_switch("once")   ? HookFlags::Once   : HookFlags::None);
   1239         get_scope(parser[0], context).hooks().add_hook(it->value, group.str(), flags,
   1240                                                        std::move(regex), command, context);
   1241     }
   1242 };
   1243 
   1244 const CommandDesc remove_hook_cmd = {
   1245     "remove-hooks",
   1246     "rmhooks",
   1247     "remove-hooks <scope> <group>: remove all hooks whose group matches the regex <group>",
   1248     double_params,
   1249     CommandFlags::None,
   1250     CommandHelper{},
   1251     [](const Context& context,
   1252        CommandParameters params, size_t token_to_complete,
   1253        ByteCount pos_in_token) -> Completions
   1254     {
   1255         if (token_to_complete == 0)
   1256             return menu(complete_scope)(context, params[0], pos_in_token);
   1257         else if (token_to_complete == 1)
   1258         {
   1259             if (auto scope = get_scope_ifp(params[0], context))
   1260                 return { 0_byte, params[0].length(),
   1261                          scope->hooks().complete_hook_group(params[1], pos_in_token),
   1262                          Completions::Flags::Menu };
   1263         }
   1264         return {};
   1265     },
   1266     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1267     {
   1268         get_scope(parser[0], context).hooks().remove_hooks(Regex{parser[1]});
   1269     }
   1270 };
   1271 
   1272 const CommandDesc trigger_user_hook_cmd = {
   1273     "trigger-user-hook",
   1274     nullptr,
   1275     "trigger-user-hook <param>: run 'User' hook with <param> as filter string",
   1276     single_param,
   1277     CommandFlags::None,
   1278     CommandHelper{},
   1279     CommandCompleter{},
   1280     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1281     {
   1282         context.hooks().run_hook(Hook::User, parser[0], context);
   1283     }
   1284 };
   1285 
   1286 Vector<String> params_to_shell(const ParametersParser& parser)
   1287 {
   1288     Vector<String> vars;
   1289     for (size_t i = 0; i < parser.positional_count(); ++i)
   1290         vars.push_back(parser[i]);
   1291     return vars;
   1292 }
   1293 
   1294 Completions complete_completer_type(const Context&, StringView prefix, ByteCount cursor_pos)
   1295 {
   1296    static constexpr StringView completers[] = {"file", "client", "buffer", "shell-script", "shell-script-candidates", "command", "shell"};
   1297    return { 0_byte, cursor_pos, complete(prefix, cursor_pos, completers) };
   1298 }
   1299 
   1300 
   1301 CommandCompleter make_command_completer(StringView type, StringView param, Completions::Flags completions_flags)
   1302 {
   1303     if (type == "file")
   1304     {
   1305         return [=](const Context& context, CommandParameters params,
   1306                    size_t token_to_complete, ByteCount pos_in_token) {
   1307              const String& prefix = params[token_to_complete];
   1308              const auto& ignored_files = context.options()["ignored_files"].get<Regex>();
   1309              return Completions{0_byte, pos_in_token,
   1310                                 complete_filename(prefix, ignored_files,
   1311                                                   pos_in_token, FilenameFlags::Expand),
   1312                                 completions_flags};
   1313         };
   1314     }
   1315     else if (type == "client")
   1316     {
   1317         return [=](const Context& context, CommandParameters params,
   1318                    size_t token_to_complete, ByteCount pos_in_token)
   1319         {
   1320              const String& prefix = params[token_to_complete];
   1321              auto& cm = ClientManager::instance();
   1322              return Completions{0_byte, pos_in_token,
   1323                                 cm.complete_client_name(prefix, pos_in_token),
   1324                                 completions_flags};
   1325         };
   1326     }
   1327     else if (type == "buffer")
   1328     {
   1329         return [=](const Context& context, CommandParameters params,
   1330                    size_t token_to_complete, ByteCount pos_in_token)
   1331         {
   1332              return add_flags(complete_buffer_name<false>, completions_flags)(
   1333                  context, params[token_to_complete], pos_in_token);
   1334         };
   1335     }
   1336     else if (type == "shell-script")
   1337     {
   1338         if (param.empty())
   1339             throw runtime_error("shell-script requires a shell script parameter");
   1340 
   1341         return ShellScriptCompleter{param.str(), completions_flags};
   1342     }
   1343     else if (type == "shell-script-candidates")
   1344     {
   1345         if (param.empty())
   1346             throw runtime_error("shell-script-candidates requires a shell script parameter");
   1347 
   1348         return ShellCandidatesCompleter{param.str(), completions_flags};
   1349     }
   1350     else if (type == "command")
   1351         return CommandManager::NestedCompleter{};
   1352     else if (type == "shell")
   1353     {
   1354         return [=](const Context& context, CommandParameters params,
   1355                    size_t token_to_complete, ByteCount pos_in_token)
   1356         {
   1357             return add_flags(shell_complete, completions_flags)(
   1358                 context, params[token_to_complete], pos_in_token);
   1359         };
   1360     }
   1361     else
   1362         throw runtime_error(format("invalid command completion type '{}'", type));
   1363 }
   1364 
   1365 static CommandCompleter parse_completion_switch(const ParametersParser& parser, Completions::Flags completions_flags) {
   1366     for (StringView completion_switch : {"file-completion", "client-completion", "buffer-completion",
   1367                                          "shell-script-completion", "shell-script-candidates",
   1368                                          "command-completion", "shell-completion"})
   1369     {
   1370         if (auto param = parser.get_switch(completion_switch))
   1371         {
   1372             constexpr StringView suffix = "-completion";
   1373             if (completion_switch.ends_with(suffix))
   1374                 completion_switch = completion_switch.substr(0, completion_switch.length() - suffix.length());
   1375             return make_command_completer(completion_switch, *param, completions_flags);
   1376         }
   1377     }
   1378     return {};
   1379 }
   1380 
   1381 void define_command(const ParametersParser& parser, Context& context, const ShellContext&)
   1382 {
   1383     const String& cmd_name = parser[0];
   1384     auto& cm = CommandManager::instance();
   1385 
   1386     if (not all_of(cmd_name, is_identifier))
   1387         throw runtime_error(format("invalid command name: '{}'", cmd_name));
   1388 
   1389     if (cm.command_defined(cmd_name) and not parser.get_switch("override"))
   1390         throw runtime_error(format("command '{}' already defined", cmd_name));
   1391 
   1392     CommandFlags flags = CommandFlags::None;
   1393     if (parser.get_switch("hidden"))
   1394         flags = CommandFlags::Hidden;
   1395 
   1396     const bool menu = (bool)parser.get_switch("menu");
   1397     const Completions::Flags completions_flags = menu ?
   1398         Completions::Flags::Menu : Completions::Flags::None;
   1399 
   1400     const String& commands = parser[1];
   1401     CommandFunc cmd;
   1402     ParameterDesc desc;
   1403     if (auto params = parser.get_switch("params"))
   1404     {
   1405         size_t min = 0, max = -1;
   1406         StringView counts = *params;
   1407         static const Regex re{R"((\d+)?..(\d+)?)"};
   1408         MatchResults<const char*> res;
   1409         if (regex_match(counts.begin(), counts.end(), res, re))
   1410         {
   1411             if (res[1].matched)
   1412                 min = (size_t)str_to_int({res[1].first, res[1].second});
   1413             if (res[2].matched)
   1414                 max = (size_t)str_to_int({res[2].first, res[2].second});
   1415         }
   1416         else
   1417             min = max = (size_t)str_to_int(counts);
   1418 
   1419         desc = ParameterDesc{ {}, ParameterDesc::Flags::SwitchesAsPositional, min, max };
   1420         cmd = [=](const ParametersParser& parser, Context& context, const ShellContext& sc) {
   1421             LocalScope local_scope{context};
   1422             CommandManager::instance().execute(commands, context,
   1423                                                { params_to_shell(parser), sc.env_vars });
   1424         };
   1425     }
   1426     else
   1427     {
   1428         desc = ParameterDesc{ {}, ParameterDesc::Flags::SwitchesAsPositional, 0, 0 };
   1429         cmd = [=](const ParametersParser& parser, Context& context, const ShellContext& sc) {
   1430             LocalScope local_scope{context};
   1431             CommandManager::instance().execute(commands, context, { {}, sc.env_vars });
   1432         };
   1433     }
   1434 
   1435     CommandCompleter completer = parse_completion_switch(parser, completions_flags);
   1436     if (menu and not completer)
   1437         throw runtime_error("menu switch requires a completion switch");
   1438     auto docstring = trim_indent(parser.get_switch("docstring").value_or(StringView{}));
   1439 
   1440     cm.register_command(cmd_name, cmd, docstring, desc, flags, CommandHelper{}, std::move(completer));
   1441 }
   1442 
   1443 const CommandDesc define_command_cmd = {
   1444     "define-command",
   1445     "def",
   1446     "define-command [<switches>] <name> <cmds>: define a command <name> executing <cmds>",
   1447     ParameterDesc{
   1448         { { "params",                   { ArgCompleter{},  "take parameters, accessible to each shell escape as $0..$N\n"
   1449                                                  "parameter should take the form <count> or <min>..<max> (both omittable)" } },
   1450           { "override",                 { {}, "allow overriding an existing command" } },
   1451           { "hidden",                   { {}, "do not display the command in completion candidates" } },
   1452           { "docstring",                { ArgCompleter{},  "define the documentation string for command" } },
   1453           { "menu",                     { {}, "treat completions as the only valid inputs" } },
   1454           { "file-completion",          { {}, "complete parameters using filename completion" } },
   1455           { "client-completion",        { {}, "complete parameters using client name completion" } },
   1456           { "buffer-completion",        { {}, "complete parameters using buffer name completion" } },
   1457           { "command-completion",       { {}, "complete parameters using kakoune command completion" } },
   1458           { "shell-completion",         { {}, "complete parameters using shell command completion" } },
   1459           { "shell-script-completion",  { ArgCompleter{},  "complete parameters using the given shell-script" } },
   1460           { "shell-script-candidates",  { ArgCompleter{},  "get the parameter candidates using the given shell-script" } } },
   1461         ParameterDesc::Flags::None,
   1462         2, 2
   1463     },
   1464     CommandFlags::None,
   1465     CommandHelper{},
   1466     CommandCompleter{},
   1467     define_command
   1468 };
   1469 
   1470 static Completions complete_alias_name(const Context& context, StringView prefix, ByteCount cursor_pos)
   1471 {
   1472    return { 0_byte, cursor_pos, complete(prefix, cursor_pos,
   1473                                            context.aliases().flatten_aliases()
   1474                                          | transform(&HashItem<String, String>::key))};
   1475 }
   1476 
   1477 const CommandDesc alias_cmd = {
   1478     "alias",
   1479     nullptr,
   1480     "alias <scope> <alias> <command>: alias <alias> to <command> in <scope>",
   1481     ParameterDesc{{}, ParameterDesc::Flags::None, 3, 3},
   1482     CommandFlags::None,
   1483     CommandHelper{},
   1484     make_completer(menu(complete_scope), complete_alias_name, complete_command_name),
   1485     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1486     {
   1487         if (not CommandManager::instance().command_defined(parser[2]))
   1488             throw runtime_error(format("no such command: '{}'", parser[2]));
   1489 
   1490         AliasRegistry& aliases = get_scope(parser[0], context).aliases();
   1491         aliases.add_alias(parser[1], parser[2]);
   1492     }
   1493 };
   1494 
   1495 const CommandDesc unalias_cmd = {
   1496     "unalias",
   1497     nullptr,
   1498     "unalias <scope> <alias> [<expected>]: remove <alias> from <scope>\n"
   1499     "If <expected> is specified, remove <alias> only if its value is <expected>",
   1500     ParameterDesc{{}, ParameterDesc::Flags::None, 2, 3},
   1501     CommandFlags::None,
   1502     CommandHelper{},
   1503     make_completer(menu(complete_scope), complete_alias_name, complete_command_name),
   1504     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1505     {
   1506         AliasRegistry& aliases = get_scope(parser[0], context).aliases();
   1507         if (parser.positional_count() == 3 and
   1508             aliases[parser[1]] != parser[2])
   1509             return;
   1510         aliases.remove_alias(parser[1]);
   1511     }
   1512 };
   1513 
   1514 const CommandDesc complete_command_cmd = {
   1515     "complete-command",
   1516     "compl",
   1517     "complete-command [<switches>] <name> <type> [<param>]\n"
   1518     "define command completion",
   1519     ParameterDesc{
   1520         { { "menu",                     { {}, "treat completions as the only valid inputs" } }, },
   1521         ParameterDesc::Flags::None, 2, 3},
   1522     CommandFlags::None,
   1523     CommandHelper{},
   1524     make_completer(complete_command_name, complete_completer_type),
   1525     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1526     {
   1527         const Completions::Flags flags = parser.get_switch("menu") ? Completions::Flags::Menu : Completions::Flags::None;
   1528         CommandCompleter completer = make_command_completer(parser[1], parser.positional_count() >= 3 ? parser[2] : StringView{}, flags);
   1529         CommandManager::instance().set_command_completer(parser[0], std::move(completer));
   1530     }
   1531 };
   1532 
   1533 const CommandDesc echo_cmd = {
   1534     "echo",
   1535     nullptr,
   1536     "echo <params>...: display given parameters in the status line",
   1537     ParameterDesc{
   1538         { { "markup", { {}, "parse markup" } },
   1539           { "quoting", { {arg_completer(Array{"raw", "kakoune", "shell"})}, "quote each argument separately using the given style (raw|kakoune|shell)" } },
   1540           { "end-of-line", { {}, "add trailing end-of-line" } },
   1541           { "to-file", { {filename_arg_completer<false>}, "echo contents to given filename" } },
   1542           { "to-shell-script", { ArgCompleter{}, "pipe contents to given shell script" } },
   1543           { "debug", { {}, "write to debug buffer instead of status line" } } },
   1544         ParameterDesc::Flags::SwitchesOnlyAtStart
   1545     },
   1546     CommandFlags::None,
   1547     CommandHelper{},
   1548     CommandCompleter{},
   1549     [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)
   1550     {
   1551         String message;
   1552         if (auto quoting = parser.get_switch("quoting"))
   1553             message = join(parser | transform(quoter(option_from_string(Meta::Type<Quoting>{}, *quoting))),
   1554                            ' ', false);
   1555         else
   1556             message = join(parser, ' ', false);
   1557 
   1558         if (parser.get_switch("end-of-line"))
   1559             message.push_back('\n');
   1560 
   1561         if (auto filename = parser.get_switch("to-file"))
   1562         {
   1563             BusyIndicator busy_indicator{context, [&](std::chrono::seconds elapsed) {
   1564                 return DisplayLine{format("waiting while writing to '{}' ({}s)", *filename, elapsed.count()),
   1565                                    context.faces()["Information"]};
   1566             }};
   1567             write_to_file(*filename, message);
   1568         }
   1569         else if (auto command = parser.get_switch("to-shell-script"))
   1570             ShellManager::instance().eval(*command, context, message, ShellManager::Flags::None, shell_context);
   1571         else if (parser.get_switch("debug"))
   1572             write_to_debug_buffer(message);
   1573         else if (parser.get_switch("markup"))
   1574             context.print_status(parse_display_line(message, context.faces()));
   1575         else
   1576             context.print_status({message, context.faces()["StatusLine"]});
   1577     }
   1578 };
   1579 
   1580 KeymapMode parse_keymap_mode(StringView str, const KeymapManager::UserModeList& user_modes)
   1581 {
   1582     if (prefix_match("normal", str))  return KeymapMode::Normal;
   1583     if (prefix_match("insert", str))  return KeymapMode::Insert;
   1584     if (prefix_match("menu", str))    return KeymapMode::Menu;
   1585     if (prefix_match("prompt", str))  return KeymapMode::Prompt;
   1586     if (prefix_match("goto", str))    return KeymapMode::Goto;
   1587     if (prefix_match("view", str))    return KeymapMode::View;
   1588     if (prefix_match("user", str))    return KeymapMode::User;
   1589     if (prefix_match("object", str))  return KeymapMode::Object;
   1590     if (prefix_match("combine", str)) return KeymapMode::Combine;
   1591 
   1592     auto it = find(user_modes, str);
   1593     if (it == user_modes.end())
   1594         throw runtime_error(format("no such keymap mode: '{}'", str));
   1595 
   1596     char offset = static_cast<char>(KeymapMode::FirstUserMode);
   1597     return (KeymapMode)(std::distance(user_modes.begin(), it) + offset);
   1598 }
   1599 
   1600 static constexpr auto modes = make_array<StringView>({ "normal", "insert", "menu", "prompt", "goto", "view", "user", "object", "combine" });
   1601 
   1602 const CommandDesc debug_cmd = {
   1603     "debug",
   1604     nullptr,
   1605     "debug <command>: write some debug information to the *debug* buffer",
   1606     ParameterDesc{{}, ParameterDesc::Flags::SwitchesOnlyAtStart, 1},
   1607     CommandFlags::None,
   1608     CommandHelper{},
   1609     make_completer(
   1610         [](const Context& context, StringView prefix, ByteCount cursor_pos) -> Completions {
   1611                auto c = {"info", "buffers", "options", "memory", "shared-strings",
   1612                          "profile-hash-maps", "faces", "mappings", "regex", "registers"};
   1613                return { 0_byte, cursor_pos, complete(prefix, cursor_pos, c), Completions::Flags::Menu };
   1614     }),
   1615     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1616     {
   1617         if (parser[0] == "info")
   1618         {
   1619             write_to_debug_buffer(format("version: {}", version));
   1620             write_to_debug_buffer(format("pid: {}", getpid()));
   1621             write_to_debug_buffer(format("session: {}", Server::instance().session()));
   1622             #ifdef KAK_DEBUG
   1623             write_to_debug_buffer("build: debug");
   1624             #else
   1625             write_to_debug_buffer("build: release");
   1626             #endif
   1627         }
   1628         else if (parser[0] == "buffers")
   1629         {
   1630             write_to_debug_buffer("Buffers:");
   1631             for (auto& buffer : BufferManager::instance())
   1632                 write_to_debug_buffer(buffer->debug_description());
   1633         }
   1634         else if (parser[0] == "options")
   1635         {
   1636             write_to_debug_buffer("Options:");
   1637             for (auto& option : context.options().flatten_options())
   1638                 write_to_debug_buffer(format(" * {} \"{}\"{}: {}", option->name(), option->docstring(),
   1639                                              option->flags() & OptionFlags::Hidden ? " (hidden)" : "",
   1640                                              option->get_as_string(Quoting::Kakoune)));
   1641         }
   1642         else if (parser[0] == "memory")
   1643         {
   1644             size_t total = 0;
   1645             write_to_debug_buffer("Memory usage:");
   1646             const ColumnCount column_size = 17;
   1647             write_to_debug_buffer(format("{:17} │{:17} │{:17} │{:17} ",
   1648                                          "domain",
   1649                                          "bytes",
   1650                                          "active allocs",
   1651                                          "total allocs"));
   1652             write_to_debug_buffer(format("{0}┼{0}┼{0}┼{0}", String(Codepoint{0x2500}, column_size + 1)));
   1653 
   1654             for (int domain = 0; domain < (int)MemoryDomain::Count; ++domain)
   1655             {
   1656                 auto& stats = memory_stats[domain];
   1657                 total += stats.allocated_bytes;
   1658                 write_to_debug_buffer(format("{:17} │{:17} │{:17} │{:17} ",
   1659                                              domain_name((MemoryDomain)domain),
   1660                                              grouped(stats.allocated_bytes),
   1661                                              grouped(stats.allocation_count),
   1662                                              grouped(stats.total_allocation_count)));
   1663             }
   1664             write_to_debug_buffer({});
   1665             write_to_debug_buffer(format("  Total: {}", grouped(total)));
   1666             #if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 33))
   1667             write_to_debug_buffer(format("  Malloced: {}", grouped(mallinfo2().uordblks)));
   1668             #elif defined(__GLIBC__) || defined(__CYGWIN__)
   1669             write_to_debug_buffer(format("  Malloced: {}", grouped(mallinfo().uordblks)));
   1670             #endif
   1671         }
   1672         else if (parser[0] == "shared-strings")
   1673         {
   1674             StringRegistry::instance().debug_stats();
   1675         }
   1676         else if (parser[0] == "profile-hash-maps")
   1677         {
   1678             profile_hash_maps();
   1679         }
   1680         else if (parser[0] == "faces")
   1681         {
   1682             write_to_debug_buffer("Faces:");
   1683             for (auto& face : context.faces().flatten_faces())
   1684                 write_to_debug_buffer(format(" * {}: {}", face.key, face.value.face));
   1685         }
   1686         else if (parser[0] == "mappings")
   1687         {
   1688             auto& keymaps = context.keymaps();
   1689             auto user_modes = keymaps.user_modes();
   1690             write_to_debug_buffer("Mappings:");
   1691             for (auto mode : concatenated(modes, user_modes))
   1692             {
   1693                 KeymapMode m = parse_keymap_mode(mode, user_modes);
   1694                 for (auto& key : keymaps.get_mapped_keys(m)) {
   1695                     auto* mapping = keymaps.get_mapping(key, m);
   1696                     const KeyList& kl = mapping->keys;
   1697                     String keys;
   1698                     for (const auto& k : kl)
   1699                         keys += to_string(k);
   1700                     write_to_debug_buffer(
   1701                         format(" * {} {}: '{}' {} {}", mode, key, keys,
   1702                                mapping->atomic ? "(atomic)" : "", mapping->docstring));
   1703                 }
   1704             }
   1705         }
   1706         else if (parser[0] == "regex")
   1707         {
   1708             if (parser.positional_count() != 2)
   1709                 throw runtime_error("expected a regex");
   1710 
   1711             write_to_debug_buffer(format(" * {}:\n{}",
   1712                                   parser[1], dump_regex(compile_regex(parser[1], RegexCompileFlags::Optimize))));
   1713         }
   1714         else if (parser[0] == "registers")
   1715         {
   1716             write_to_debug_buffer("Register info:");
   1717             for (auto&& [name, reg] : RegisterManager::instance())
   1718             {
   1719                 auto content = reg->get(context);
   1720 
   1721                 if (content.size() == 1 and content[0] == "")
   1722                     continue;
   1723 
   1724                 write_to_debug_buffer(format(" * {} = {}\n", name,
   1725                     join(content | transform(quote), "\n     = ")));
   1726             }
   1727         }
   1728         else
   1729             throw runtime_error(format("no such debug command: '{}'", parser[0]));
   1730     }
   1731 };
   1732 
   1733 const CommandDesc source_cmd = {
   1734     "source",
   1735     nullptr,
   1736     "source <filename> <params>...: execute commands contained in <filename>\n"
   1737     "parameters are available in the sourced script as %arg{0}, %arg{1}, …",
   1738     ParameterDesc{ {}, ParameterDesc::Flags::None, 1, (size_t)-1 },
   1739     CommandFlags::None,
   1740     CommandHelper{},
   1741     filename_completer<true>,
   1742     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1743     {
   1744         ProfileScope profile{context.options()["debug"].get<DebugFlags>(), [&](std::chrono::microseconds duration) {
   1745             write_to_debug_buffer(format("sourcing '{}' took {} us", parser[0], (size_t)duration.count()));
   1746         }};
   1747 
   1748         String path = real_path(parse_filename(parser[0]));
   1749         MappedFile file_content{path};
   1750         try
   1751         {
   1752             auto params = parser | skip(1) | gather<Vector<String>>();
   1753             CommandManager::instance().execute(file_content, context,
   1754                                                {params, {{"source", path}}});
   1755         }
   1756         catch (Kakoune::runtime_error& err)
   1757         {
   1758             write_to_debug_buffer(format("{}:{}", parser[0], err.what()));
   1759             throw;
   1760         }
   1761     }
   1762 };
   1763 
   1764 static String option_doc_helper(const Context& context, CommandParameters params)
   1765 {
   1766     const bool is_switch = params.size() > 1 and (params[0] == "-add" or params[0] == "-remove");
   1767     if (params.size() < 2 + (is_switch ? 1 : 0))
   1768         return "";
   1769 
   1770     auto desc = GlobalScope::instance().option_registry().option_desc(params[1 + (is_switch ? 1 : 0)]);
   1771     if (not desc or desc->docstring().empty())
   1772         return "";
   1773 
   1774     return format("{}:\n{}", desc->name(), indent(desc->docstring()));
   1775 }
   1776 
   1777 static OptionManager& get_options(StringView scope, const Context& context, StringView option_name)
   1778 {
   1779     if (scope == "current")
   1780         return context.options()[option_name].manager();
   1781     return get_scope(scope, context).options();
   1782 }
   1783 
   1784 const CommandDesc set_option_cmd = {
   1785     "set-option",
   1786     "set",
   1787     "set-option [<switches>] <scope> <name> <value>: set option <name> in <scope> to <value>\n"
   1788     "<scope> can be global, buffer, window, or current which refers to the narrowest "
   1789     "scope the option is set in",
   1790     ParameterDesc{
   1791         { { "add",    { {}, "add to option rather than replacing it" } },
   1792           { "remove", { {}, "remove from option rather than replacing it" } } },
   1793         ParameterDesc::Flags::SwitchesOnlyAtStart, 2, (size_t)-1
   1794     },
   1795     CommandFlags::None,
   1796     option_doc_helper,
   1797     [](const Context& context, CommandParameters params,
   1798        size_t token_to_complete, ByteCount pos_in_token) -> Completions
   1799     {
   1800         if (token_to_complete == 0)
   1801             return menu(complete_scope_including_current)(context, params[0], pos_in_token);
   1802         else if (token_to_complete == 1)
   1803             return { 0_byte, params[1].length(),
   1804                      GlobalScope::instance().option_registry().complete_option_name(params[1], pos_in_token),
   1805                      Completions::Flags::Menu };
   1806         else if (token_to_complete == 2 and params[2].empty() and
   1807                  GlobalScope::instance().option_registry().option_exists(params[1]))
   1808         {
   1809             OptionManager& options = get_scope(params[0], context).options();
   1810             return {0_byte, params[2].length(),
   1811                     {options[params[1]].get_as_string(Quoting::Kakoune)},
   1812                     Completions::Flags::Quoted};
   1813         }
   1814         return Completions{};
   1815     },
   1816     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1817     {
   1818         bool add = (bool)parser.get_switch("add");
   1819         bool remove = (bool)parser.get_switch("remove");
   1820         if (add and remove)
   1821             throw runtime_error("cannot add and remove at the same time");
   1822 
   1823         Option& opt = get_options(parser[0], context, parser[1]).get_local_option(parser[1]);
   1824         if (add)
   1825             opt.add_from_strings(parser.positionals_from(2));
   1826         else if (remove)
   1827             opt.remove_from_strings(parser.positionals_from(2));
   1828         else
   1829             opt.set_from_strings(parser.positionals_from(2));
   1830     }
   1831 };
   1832 
   1833 Completions complete_option(const Context& context, CommandParameters params,
   1834                             size_t token_to_complete, ByteCount pos_in_token)
   1835 {
   1836     if (token_to_complete == 0)
   1837         return menu(complete_scope_no_global)(context, params[0], pos_in_token);
   1838     else if (token_to_complete == 1)
   1839         return { 0_byte, params[1].length(),
   1840                  GlobalScope::instance().option_registry().complete_option_name(params[1], pos_in_token),
   1841                  Completions::Flags::Menu };
   1842     return Completions{};
   1843 }
   1844 
   1845 const CommandDesc unset_option_cmd = {
   1846     "unset-option",
   1847     "unset",
   1848     "unset-option <scope> <name>: remove <name> option from scope, falling back on parent scope value\n"
   1849     "<scope> can be buffer, window, or current which refers to the narrowest "
   1850     "scope the option is set in",
   1851     double_params,
   1852     CommandFlags::None,
   1853     option_doc_helper,
   1854     complete_option,
   1855     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1856     {
   1857         auto& options = get_options(parser[0], context, parser[1]);
   1858         if (&options == &GlobalScope::instance().options())
   1859             throw runtime_error("cannot unset options in global scope");
   1860         options.unset_option(parser[1]);
   1861     }
   1862 };
   1863 
   1864 const CommandDesc update_option_cmd = {
   1865     "update-option",
   1866     nullptr,
   1867     "update-option <scope> <name>: update <name> option from scope\n"
   1868     "some option types, such as line-specs or range-specs can be updated to latest buffer timestamp\n"
   1869     "<scope> can be buffer, window, or current which refers to the narrowest "
   1870     "scope the option is set in",
   1871     double_params,
   1872     CommandFlags::None,
   1873     option_doc_helper,
   1874     complete_option,
   1875     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1876     {
   1877         Option& opt = get_options(parser[0], context, parser[1]).get_local_option(parser[1]);
   1878         opt.update(context);
   1879     }
   1880 };
   1881 
   1882 const CommandDesc declare_option_cmd = {
   1883     "declare-option",
   1884     "decl",
   1885     "declare-option [<switches>] <type> <name> [value]: declare option <name> of type <type>.\n"
   1886     "set its initial value to <value> if given and the option did not exist\n"
   1887     "Available types:\n"
   1888     "    int: integer\n"
   1889     "    bool: boolean (true/false or yes/no)\n"
   1890     "    str: character string\n"
   1891     "    regex: regular expression\n"
   1892     "    int-list: list of integers\n"
   1893     "    str-list: list of character strings\n"
   1894     "    completions: list of completion candidates\n"
   1895     "    line-specs: list of line specs\n"
   1896     "    range-specs: list of range specs\n"
   1897     "    str-to-str-map: map from strings to strings\n",
   1898     ParameterDesc{
   1899         { { "hidden",    { {}, "do not display option name when completing" } },
   1900           { "docstring", { ArgCompleter{},  "specify option description" } } },
   1901         ParameterDesc::Flags::SwitchesOnlyAtStart, 2, (size_t)-1
   1902     },
   1903     CommandFlags::None,
   1904     CommandHelper{},
   1905     make_completer(
   1906         [](const Context& context,
   1907            StringView prefix, ByteCount cursor_pos) -> Completions {
   1908                auto c = {"int", "bool", "str", "regex", "int-list", "str-list", "completions", "line-specs", "range-specs", "str-to-str-map"};
   1909                return { 0_byte, cursor_pos, complete(prefix, cursor_pos, c), Completions::Flags::Menu };
   1910     }),
   1911     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1912     {
   1913         Option* opt = nullptr;
   1914 
   1915         OptionFlags flags = OptionFlags::None;
   1916         if (parser.get_switch("hidden"))
   1917             flags = OptionFlags::Hidden;
   1918 
   1919         auto docstring = trim_indent(parser.get_switch("docstring").value_or(StringView{}));
   1920         OptionsRegistry& reg = GlobalScope::instance().option_registry();
   1921 
   1922 
   1923         if (parser[0] == "int")
   1924             opt = &reg.declare_option<int>(parser[1], docstring, 0, flags);
   1925         else if (parser[0] == "bool")
   1926             opt = &reg.declare_option<bool>(parser[1], docstring, false, flags);
   1927         else if (parser[0] == "str")
   1928             opt = &reg.declare_option<String>(parser[1], docstring, "", flags);
   1929         else if (parser[0] == "regex")
   1930             opt = &reg.declare_option<Regex>(parser[1], docstring, Regex{}, flags);
   1931         else if (parser[0] == "int-list")
   1932             opt = &reg.declare_option<Vector<int, MemoryDomain::Options>>(parser[1], docstring, {}, flags);
   1933         else if (parser[0] == "str-list")
   1934             opt = &reg.declare_option<Vector<String, MemoryDomain::Options>>(parser[1], docstring, {}, flags);
   1935         else if (parser[0] == "completions")
   1936             opt = &reg.declare_option<CompletionList>(parser[1], docstring, {}, flags);
   1937         else if (parser[0] == "line-specs")
   1938             opt = &reg.declare_option<TimestampedList<LineAndSpec>>(parser[1], docstring, {}, flags);
   1939         else if (parser[0] == "range-specs")
   1940             opt = &reg.declare_option<TimestampedList<RangeAndString>>(parser[1], docstring, {}, flags);
   1941         else if (parser[0] == "str-to-str-map")
   1942             opt = &reg.declare_option<HashMap<String, String, MemoryDomain::Options>>(parser[1], docstring, {}, flags);
   1943         else
   1944             throw runtime_error(format("no such option type: '{}'", parser[0]));
   1945 
   1946         if (parser.positional_count() > 2)
   1947             opt->set_from_strings(parser.positionals_from(2));
   1948     }
   1949 };
   1950 
   1951 template<bool unmap>
   1952 static Completions map_key_completer(const Context& context, CommandParameters params,
   1953                                      size_t token_to_complete, ByteCount pos_in_token)
   1954 {
   1955     if (token_to_complete == 0)
   1956         return menu(complete_scope)(context, params[0], pos_in_token);
   1957     if (token_to_complete == 1)
   1958     {
   1959         auto& user_modes = get_scope(params[0], context).keymaps().user_modes();
   1960         return { 0_byte, params[1].length(),
   1961                  complete(params[1], pos_in_token, concatenated(modes, user_modes)),
   1962                  Completions::Flags::Menu };
   1963     }
   1964     if (unmap and token_to_complete == 2)
   1965     {
   1966         KeymapManager& keymaps = get_scope(params[0], context).keymaps();
   1967         KeymapMode keymap_mode = parse_keymap_mode(params[1], keymaps.user_modes());
   1968         KeyList keys = keymaps.get_mapped_keys(keymap_mode);
   1969 
   1970         return { 0_byte, params[2].length(),
   1971                  complete(params[2], pos_in_token,
   1972                           keys | transform([](Key k) { return to_string(k); })
   1973                                | gather<Vector<String>>()),
   1974                  Completions::Flags::Menu };
   1975     }
   1976     return {};
   1977 }
   1978 
   1979 const CommandDesc map_key_cmd = {
   1980     "map",
   1981     nullptr,
   1982     "map [<switches>] <scope> <mode> <key> <keys>: map <key> to <keys> in given <mode> in <scope>",
   1983     ParameterDesc{
   1984         { { "atomic", { {}, "repeat whole mapping if count given" } },
   1985           { "docstring", { ArgCompleter{}, "specify mapping description" } } },
   1986         ParameterDesc::Flags::None, 4, 4
   1987     },
   1988     CommandFlags::None,
   1989     CommandHelper{},
   1990     map_key_completer<false>,
   1991     [](const ParametersParser& parser, Context& context, const ShellContext&)
   1992     {
   1993         KeymapManager& keymaps = get_scope(parser[0], context).keymaps();
   1994         KeymapMode keymap_mode = parse_keymap_mode(parser[1], keymaps.user_modes());
   1995 
   1996         KeyList key = parse_keys(parser[2]);
   1997         if (key.size() != 1)
   1998             throw runtime_error("only a single key can be mapped");
   1999 
   2000         KeyList mapping = parse_keys(parser[3]);
   2001         keymaps.map_key(key[0], keymap_mode, std::move(mapping),
   2002                         trim_indent(parser.get_switch("docstring").value_or("")),
   2003                         (bool) parser.get_switch("atomic"));
   2004     }
   2005 };
   2006 
   2007 const CommandDesc unmap_key_cmd = {
   2008     "unmap",
   2009     nullptr,
   2010     "unmap <scope> <mode> [<key> [<expected-keys>]]: unmap <key> from given <mode> in <scope>.\n"
   2011     "If <expected-keys> is specified, remove the mapping only if its value is <expected-keys>.\n"
   2012     "If only <scope> and <mode> are specified remove all mappings",
   2013     ParameterDesc{{}, ParameterDesc::Flags::None, 2, 4},
   2014     CommandFlags::None,
   2015     CommandHelper{},
   2016     map_key_completer<true>,
   2017     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2018     {
   2019         KeymapManager& keymaps = get_scope(parser[0], context).keymaps();
   2020         KeymapMode keymap_mode = parse_keymap_mode(parser[1], keymaps.user_modes());
   2021 
   2022         if (parser.positional_count() == 2)
   2023         {
   2024             keymaps.unmap_keys(keymap_mode);
   2025             return;
   2026         }
   2027 
   2028         KeyList key = parse_keys(parser[2]);
   2029         if (key.size() != 1)
   2030             throw runtime_error("only a single key can be unmapped");
   2031 
   2032         if (auto* mapping = keymaps.get_mapping(key[0], keymap_mode);
   2033             mapping and (parser.positional_count() < 4 or
   2034                          mapping->keys == parse_keys(parser[3])))
   2035             keymaps.unmap_key(key[0], keymap_mode);
   2036     }
   2037 };
   2038 
   2039 template<size_t... P>
   2040 ParameterDesc make_context_wrap_params_impl(Array<HashItem<String, SwitchDesc>, sizeof...(P)>&& additional_params,
   2041                                             std::index_sequence<P...>)
   2042 {
   2043     return { { { "client",     { {client_arg_completer},  "run in the client context for each client in the given comma separated list" } },
   2044                { "try-client", { {client_arg_completer},  "run in given client context if it exists, or else in the current one" } },
   2045                { "buffer",     { {complete_buffer_name<false>},  "run in a disposable context for each given buffer in the comma separated list argument" } },
   2046                { "draft",      { {}, "run in a disposable context" } },
   2047                { "itersel",    { {}, "run once for each selection with that selection as the only one" } },
   2048                std::move(additional_params[P])...},
   2049         ParameterDesc::Flags::SwitchesOnlyAtStart, 1
   2050     };
   2051 }
   2052 
   2053 template<size_t N>
   2054 ParameterDesc make_context_wrap_params(Array<HashItem<String, SwitchDesc>, N>&& additional_params)
   2055 {
   2056     return make_context_wrap_params_impl(std::move(additional_params), std::make_index_sequence<N>());
   2057 }
   2058 
   2059 template<typename Func>
   2060 void context_wrap(const ParametersParser& parser, Context& context, StringView default_saved_regs, Func func)
   2061 {
   2062     if ((int)(bool)parser.get_switch("buffer") +
   2063         (int)(bool)parser.get_switch("client") +
   2064         (int)(bool)parser.get_switch("try-client") > 1)
   2065         throw runtime_error{"only one of -buffer, -client or -try-client can be specified"};
   2066 
   2067     const auto& register_manager = RegisterManager::instance();
   2068     auto make_register_restorer = [&](char c) {
   2069         auto& reg = register_manager[c];
   2070         return OnScopeEnd([&, c, save=reg.save(context), d=ScopedSetBool{reg.modified_hook_disabled()}] {
   2071             try
   2072             {
   2073                 reg.restore(context, save);
   2074             }
   2075             catch (runtime_error& err)
   2076             {
   2077                 write_to_debug_buffer(format("failed to restore register '{}': {}", c, err.what()));
   2078             }
   2079         });
   2080     };
   2081     Vector<decltype(make_register_restorer(0))> saved_registers;
   2082     for (auto c : parser.get_switch("save-regs").value_or(default_saved_regs))
   2083         saved_registers.push_back(make_register_restorer(c));
   2084 
   2085     if (auto bufnames = parser.get_switch("buffer"))
   2086     {
   2087         auto context_wrap_for_buffer = [&](Buffer& buffer) {
   2088             InputHandler input_handler{{buffer, Selection{}}, Context::Flags::Draft};
   2089             func(parser, input_handler.context());
   2090         };
   2091         if (*bufnames == "*")
   2092         {
   2093             for (auto&& buffer : BufferManager::instance()
   2094                                | transform(&UniquePtr<Buffer>::get)
   2095                                | filter([](Buffer* buf) { return not (buf->flags() & Buffer::Flags::Debug); })
   2096                                | gather<Vector<SafePtr<Buffer>>>()) // gather as we might be mutating the buffer list in the loop.
   2097                 context_wrap_for_buffer(*buffer);
   2098         }
   2099         else
   2100             for (auto&& name : *bufnames
   2101                              | split<StringView>(',', '\\')
   2102                              | transform(unescape<',', '\\'>))
   2103                 context_wrap_for_buffer(BufferManager::instance().get_buffer(name));
   2104         return;
   2105     }
   2106 
   2107     auto context_wrap_for_context = [&parser, &func](Context& base_context) {
   2108         Optional<InputHandler> input_handler;
   2109 
   2110         const bool draft = (bool)parser.get_switch("draft");
   2111         if (draft)
   2112         {
   2113             input_handler.emplace(base_context.selections(),
   2114                                   Context::Flags::Draft,
   2115                                   base_context.name());
   2116 
   2117             // Preserve window so that window scope is available
   2118             if (base_context.has_window())
   2119                 input_handler->context().set_window(base_context.window());
   2120 
   2121             // We do not want this draft context to commit undo groups if the real one is
   2122             // going to commit the whole thing later
   2123             if (base_context.is_editing())
   2124                 input_handler->context().disable_undo_handling();
   2125         }
   2126 
   2127         Context& c = input_handler ? input_handler->context() : base_context;
   2128 
   2129         ScopedEdition edition{c};
   2130         ScopedSelectionEdition selection_edition{c};
   2131 
   2132         if (parser.get_switch("itersel"))
   2133         {
   2134             SelectionList sels{base_context.selections()};
   2135             Vector<Selection> new_sels;
   2136             size_t main = 0;
   2137             size_t timestamp = c.buffer().timestamp();
   2138             bool one_selection_succeeded = false;
   2139             for (auto& sel : sels)
   2140             {
   2141                 c.selections_write_only() = SelectionList{sels.buffer(), sel, sels.timestamp()};
   2142                 c.selections().update();
   2143 
   2144                 try
   2145                 {
   2146                     func(parser, c);
   2147                     one_selection_succeeded = true;
   2148 
   2149                     if (&sels.buffer() != &c.buffer())
   2150                         throw runtime_error("buffer has changed while iterating on selections");
   2151 
   2152                     if (not draft)
   2153                     {
   2154                         update_selections(new_sels, main, c.buffer(), timestamp);
   2155                         timestamp = c.buffer().timestamp();
   2156                         if (&sel == &sels.main())
   2157                             main = new_sels.size() + c.selections().main_index();
   2158 
   2159                         const auto middle = new_sels.insert(new_sels.end(), c.selections().begin(), c.selections().end());
   2160                         std::inplace_merge(new_sels.begin(), middle, new_sels.end(), compare_selections);
   2161                     }
   2162                 }
   2163                 catch (no_selections_remaining&) {}
   2164             }
   2165 
   2166             if (not one_selection_succeeded)
   2167             {
   2168                 c.selections_write_only() = std::move(sels);
   2169                 throw no_selections_remaining{};
   2170             }
   2171 
   2172             if (not draft)
   2173                 c.selections_write_only().set(std::move(new_sels), main);
   2174         }
   2175         else
   2176         {
   2177             const bool collapse_jumps = not (c.flags() & Context::Flags::Draft) and c.has_buffer();
   2178             auto& jump_list = c.jump_list();
   2179             const size_t prev_index = jump_list.current_index();
   2180             auto jump = collapse_jumps ? c.selections() : Optional<SelectionList>{};
   2181 
   2182             func(parser, c);
   2183 
   2184             // If the jump list got mutated, collapse all jumps into a single one from original selections
   2185             if (auto index = jump_list.current_index();
   2186                 collapse_jumps and index > prev_index and
   2187                 contains(BufferManager::instance(), &jump->buffer()))
   2188                 jump_list.push(std::move(*jump), prev_index);
   2189         }
   2190     };
   2191 
   2192     ClientManager& cm = ClientManager::instance();
   2193     if (auto client_names = parser.get_switch("client"))
   2194     {
   2195         if (*client_names == "*")
   2196         {
   2197             for (auto&& client : ClientManager::instance()
   2198                                | transform(&UniquePtr<Client>::get)
   2199                                | gather<Vector<SafePtr<Client>>>()) // gather as we might be mutating the client list in the loop.
   2200                 context_wrap_for_context(client->context());
   2201         }
   2202         else
   2203             for (auto&& name : *client_names
   2204                              | split<StringView>(',', '\\')
   2205                              | transform(unescape<',', '\\'>))
   2206                 context_wrap_for_context(ClientManager::instance().get_client(name).context());
   2207     }
   2208     else if (auto client_name = parser.get_switch("try-client"))
   2209     {
   2210         Client* client = cm.get_client_ifp(*client_name);
   2211         context_wrap_for_context(client ? client->context() : context);
   2212     }
   2213     else
   2214         context_wrap_for_context(context);
   2215 }
   2216 
   2217 const CommandDesc execute_keys_cmd = {
   2218     "execute-keys",
   2219     "exec",
   2220     "execute-keys [<switches>] <keys>: execute given keys as if entered by user",
   2221     make_context_wrap_params<3>({{
   2222         {"save-regs",  {ArgCompleter{}, "restore all given registers after execution (default: '/\"|^@:')"}},
   2223         {"with-maps",  {{}, "use user defined key mapping when executing keys"}},
   2224         {"with-hooks", {{}, "trigger hooks while executing keys"}}
   2225     }}),
   2226     CommandFlags::None,
   2227     CommandHelper{},
   2228     CommandCompleter{},
   2229     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2230     {
   2231         context_wrap(parser, context, "/\"|^@:", [](const ParametersParser& parser, Context& context) {
   2232             ScopedSetBool disable_keymaps(context.keymaps_disabled(), not parser.get_switch("with-maps"));
   2233             ScopedSetBool disable_hooks(context.hooks_disabled(), not parser.get_switch("with-hooks"));
   2234 
   2235             for (auto& key : parser | transform(parse_keys) | flatten())
   2236                 context.input_handler().handle_key(key);
   2237         });
   2238     }
   2239 };
   2240 
   2241 
   2242 const CommandDesc evaluate_commands_cmd = {
   2243     "evaluate-commands",
   2244     "eval",
   2245     "evaluate-commands [<switches>] <commands>...: execute commands as if entered by user",
   2246     make_context_wrap_params<3>({{
   2247         {"save-regs",  {ArgCompleter{}, "restore all given registers after execution (default: '')"}},
   2248         {"no-hooks", { {}, "disable hooks while executing commands" }},
   2249         {"verbatim", { {}, "do not reparse argument" }}
   2250     }}),
   2251     CommandFlags::None,
   2252     CommandHelper{},
   2253     CommandManager::NestedCompleter{},
   2254     [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)
   2255     {
   2256         context_wrap(parser, context, {}, [&](const ParametersParser& parser, Context& context) {
   2257             const bool no_hooks = context.hooks_disabled() or parser.get_switch("no-hooks");
   2258             ScopedSetBool disable_hooks(context.hooks_disabled(), no_hooks);
   2259 
   2260             LocalScope local_scope{context};
   2261             if (parser.get_switch("verbatim"))
   2262                 CommandManager::instance().execute_single_command(parser | gather<Vector<String>>(), context, shell_context);
   2263             else
   2264                 CommandManager::instance().execute(join(parser, ' ', false), context, shell_context);
   2265         });
   2266     }
   2267 };
   2268 
   2269 struct CapturedShellContext
   2270 {
   2271     explicit CapturedShellContext(const ShellContext& sc)
   2272       : params{sc.params.begin(), sc.params.end()}, env_vars{sc.env_vars} {}
   2273 
   2274     Vector<String> params;
   2275     EnvVarMap env_vars;
   2276 
   2277     operator ShellContext() const { return { params, env_vars }; }
   2278 };
   2279 
   2280 const CommandDesc prompt_cmd = {
   2281     "prompt",
   2282     nullptr,
   2283     "prompt [<switches>] <prompt> <command>: prompt the user to enter a text string "
   2284     "and then executes <command>, entered text is available in the 'text' value",
   2285     ParameterDesc{
   2286         { { "init", { ArgCompleter{}, "set initial prompt content" } },
   2287           { "password", { {}, "Do not display entered text and clear reg after command" } },
   2288           { "menu", { {}, "treat completions as the only valid inputs" } },
   2289           { "file-completion", { {}, "use file completion for prompt" } },
   2290           { "client-completion", { {}, "use client completion for prompt" } },
   2291           { "buffer-completion", { {}, "use buffer completion for prompt" } },
   2292           { "command-completion", { {}, "use command completion for prompt" } },
   2293           { "shell-completion", { {}, "use shell command completion for prompt" } },
   2294           { "shell-script-completion", { ArgCompleter{}, "use shell command completion for prompt" } },
   2295           { "shell-script-candidates", { ArgCompleter{}, "use shell command completion for prompt" } },
   2296           { "on-change", { ArgCompleter{}, "command to execute whenever the prompt changes" } },
   2297           { "on-abort", { ArgCompleter{}, "command to execute whenever the prompt is canceled" } } },
   2298         ParameterDesc::Flags::None, 2, 2
   2299     },
   2300     CommandFlags::None,
   2301     CommandHelper{},
   2302     CommandCompleter{},
   2303     [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)
   2304     {
   2305         const String& command = parser[1];
   2306         auto initstr = parser.get_switch("init").value_or(StringView{});
   2307 
   2308         const Completions::Flags completions_flags = parser.get_switch("menu") ?
   2309             Completions::Flags::Menu : Completions::Flags::None;
   2310         PromptCompleterAdapter completer = parse_completion_switch(parser, completions_flags);
   2311 
   2312         const auto flags = parser.get_switch("password") ?
   2313             PromptFlags::Password : PromptFlags::None;
   2314 
   2315         context.input_handler().prompt(
   2316             parser[0], initstr.str(), {}, context.faces()["Prompt"],
   2317             flags, '_', std::move(completer),
   2318             [command,
   2319              on_change = parser.get_switch("on-change").value_or("").str(),
   2320              on_abort = parser.get_switch("on-abort").value_or("").str(),
   2321              sc = CapturedShellContext{shell_context}]
   2322             (StringView str, PromptEvent event, Context& context) mutable
   2323             {
   2324                 if ((event == PromptEvent::Abort and on_abort.empty()) or
   2325                     (event == PromptEvent::Change and on_change.empty()))
   2326                     return;
   2327 
   2328                 sc.env_vars["text"_sv] = String{String::NoCopy{}, str};
   2329                 auto remove_text = OnScopeEnd([&] {
   2330                     sc.env_vars.erase("text"_sv);
   2331                 });
   2332 
   2333                 StringView cmd;
   2334                 switch (event)
   2335                 {
   2336                     case PromptEvent::Validate: cmd = command; break;
   2337                     case PromptEvent::Change: cmd = on_change; break;
   2338                     case PromptEvent::Abort: cmd = on_abort; break;
   2339                 }
   2340                 try
   2341                 {
   2342                     CommandManager::instance().execute(cmd, context, sc);
   2343                 }
   2344                 catch (Kakoune::runtime_error& error)
   2345                 {
   2346                     context.print_status({error.what().str(), context.faces()["Error"]});
   2347                     context.hooks().run_hook(Hook::RuntimeError, error.what(), context);
   2348                 }
   2349             });
   2350     }
   2351 };
   2352 
   2353 const CommandDesc on_key_cmd = {
   2354     "on-key",
   2355     nullptr,
   2356     "on-key [<switches>] <command>: wait for next user key and then execute <command>, "
   2357     "with key available in the `key` value",
   2358     ParameterDesc{
   2359         { { "mode-name", { ArgCompleter{}, "set mode name to use" } } },
   2360         ParameterDesc::Flags::None, 1, 1
   2361     },
   2362     CommandFlags::None,
   2363     CommandHelper{},
   2364     CommandCompleter{},
   2365     [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)
   2366     {
   2367         String command = parser[0];
   2368 
   2369         CapturedShellContext sc{shell_context};
   2370         context.input_handler().on_next_key(
   2371             parser.get_switch("mode-name").value_or("on-key"),
   2372             KeymapMode::None, [=](Key key, Context& context) mutable {
   2373             sc.env_vars["key"_sv] = to_string(key);
   2374 
   2375             CommandManager::instance().execute(command, context, sc);
   2376         });
   2377     }
   2378 };
   2379 
   2380 const CommandDesc info_cmd = {
   2381     "info",
   2382     nullptr,
   2383     "info [<switches>] <text>: display an info box containing <text>",
   2384     ParameterDesc{
   2385         { { "anchor", { ArgCompleter{}, "set info anchoring <line>.<column>" } },
   2386           { "style", { {arg_completer(Array{"above", "below", "menu", "modal"})}, "set info style (above, below, menu, modal)" } },
   2387           { "markup", { {}, "parse markup" } },
   2388           { "title", { ArgCompleter{}, "set info title" } } },
   2389         ParameterDesc::Flags::None, 0, 1
   2390     },
   2391     CommandFlags::None,
   2392     CommandHelper{},
   2393     CommandCompleter{},
   2394     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2395     {
   2396         if (not context.has_client())
   2397             return;
   2398 
   2399         const InfoStyle style = parser.get_switch("style").map(
   2400             [](StringView style) -> Optional<InfoStyle> {
   2401                 if (style == "above") return InfoStyle::InlineAbove;
   2402                 if (style == "below") return InfoStyle::InlineBelow;
   2403                 if (style == "menu") return InfoStyle::MenuDoc;
   2404                 if (style == "modal") return InfoStyle::Modal;
   2405                 throw runtime_error(format("invalid style: '{}'", style));
   2406             }).value_or(parser.get_switch("anchor") ? InfoStyle::Inline : InfoStyle::Prompt);
   2407 
   2408         context.client().info_hide(style == InfoStyle::Modal);
   2409         if (parser.positional_count() == 0)
   2410             return;
   2411 
   2412         const BufferCoord pos = parser.get_switch("anchor").map(
   2413             [](StringView anchor) {
   2414                 auto dot = find(anchor, '.');
   2415                 if (dot == anchor.end())
   2416                     throw runtime_error("expected <line>.<column> for anchor");
   2417 
   2418                 return BufferCoord{str_to_int({anchor.begin(), dot})-1,
   2419                                    str_to_int({dot+1, anchor.end()})-1};
   2420             }).value_or(BufferCoord{});
   2421 
   2422         auto title = parser.get_switch("title").value_or(StringView{});
   2423         if (parser.get_switch("markup"))
   2424             context.client().info_show(parse_display_line(title, context.faces()),
   2425                                        parse_display_line_list(parser[0], context.faces()),
   2426                                        pos, style);
   2427         else
   2428             context.client().info_show(title.str(), parser[0], pos, style);
   2429     }
   2430 };
   2431 
   2432 const CommandDesc try_catch_cmd = {
   2433     "try",
   2434     nullptr,
   2435     "try <cmds> [catch <error_cmds>]...: execute <cmds> in current context.\n"
   2436     "if an error is raised and <error_cmds> is specified, execute it and do\n"
   2437     "not propagate that error. If <error_cmds> raises an error and another\n"
   2438     "<error_cmds> is provided, execute this one and so-on\n",
   2439     ParameterDesc{{}, ParameterDesc::Flags::None, 1},
   2440     CommandFlags::None,
   2441     CommandHelper{},
   2442     CommandCompleter{},
   2443     [](const ParametersParser& parser, Context& context, const ShellContext& shell_context)
   2444     {
   2445         if ((parser.positional_count() % 2) != 1)
   2446             throw wrong_argument_count();
   2447 
   2448         for (size_t i = 1; i < parser.positional_count(); i += 2)
   2449         {
   2450             if (parser[i] != "catch")
   2451                 throw runtime_error("usage: try <commands> [catch <on error commands>]...");
   2452         }
   2453 
   2454         CommandManager& command_manager = CommandManager::instance();
   2455         Optional<ShellContext> shell_context_with_error;
   2456         for (size_t i = 0; i < parser.positional_count(); i += 2)
   2457         {
   2458             if (i == 0 or i < parser.positional_count() - 1)
   2459             {
   2460                 try
   2461                 {
   2462                     command_manager.execute(parser[i], context,
   2463                                             shell_context_with_error.value_or(shell_context));
   2464                     return;
   2465                 }
   2466                 catch (const runtime_error& error)
   2467                 {
   2468                     shell_context_with_error.emplace(shell_context);
   2469                     shell_context_with_error->env_vars[StringView{"error"}] = error.what().str();
   2470                 }
   2471             }
   2472             else
   2473                 command_manager.execute(parser[i], context,
   2474                                         shell_context_with_error.value_or(shell_context));
   2475         }
   2476     }
   2477 };
   2478 
   2479 static Completions complete_face(const Context& context,
   2480                                  StringView prefix, ByteCount cursor_pos)
   2481 {
   2482     return {0_byte, cursor_pos,
   2483             complete(prefix, cursor_pos, context.faces().flatten_faces() |
   2484                      transform([](auto& entry) -> const String& { return entry.key; }))};
   2485 }
   2486 
   2487 static String face_doc_helper(const Context& context, CommandParameters params)
   2488 {
   2489     if (params.size() < 2)
   2490         return {};
   2491     try
   2492     {
   2493         auto face = context.faces()[params[1]];
   2494         return format("{}:\n{}", params[1], indent(to_string(face)));
   2495     }
   2496     catch (runtime_error&)
   2497     {
   2498         return {};
   2499     }
   2500 }
   2501 
   2502 const CommandDesc set_face_cmd = {
   2503     "set-face",
   2504     "face",
   2505     "set-face <scope> <name> <facespec>: set face <name> to <facespec> in <scope>\n"
   2506     "\n"
   2507     "facespec format is:\n"
   2508     "    <fg color>[,<bg color>[,<underline color>]][+<attributes>][@<base>]\n"
   2509     "colors are either a color name, rgb:######, or rgba:######## values.\n"
   2510     "attributes is a combination of:\n"
   2511     "    u: underline, c: curly underline, U: double underline,\n"
   2512     "    i: italic,            b: bold,            r: reverse,\n"
   2513     "    s: strikethrough,     B: blink,           d: dim,\n"
   2514     "    f: final foreground,              g: final background,\n"
   2515     "    a: final attributes,              F: same as +fga\n"
   2516     "facespec can as well just be the name of another face.\n"
   2517     "if a base face is specified, colors and attributes are applied on top of it",
   2518     ParameterDesc{{}, ParameterDesc::Flags::None, 3, 3},
   2519     CommandFlags::None,
   2520     face_doc_helper,
   2521     make_completer(menu(complete_scope), complete_face, complete_face),
   2522     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2523     {
   2524         get_scope(parser[0], context).faces().add_face(parser[1], parser[2], true);
   2525 
   2526         for (auto& client : ClientManager::instance())
   2527             client->force_redraw();
   2528     }
   2529 };
   2530 
   2531 const CommandDesc unset_face_cmd = {
   2532     "unset-face",
   2533     nullptr,
   2534     "unset-face <scope> <name>: remove <face> from <scope>",
   2535     double_params,
   2536     CommandFlags::None,
   2537     face_doc_helper,
   2538     make_completer(menu(complete_scope), menu(complete_face)),
   2539     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2540     {
   2541        get_scope(parser[0], context).faces().remove_face(parser[1]);
   2542     }
   2543 };
   2544 
   2545 const CommandDesc rename_client_cmd = {
   2546     "rename-client",
   2547     nullptr,
   2548     "rename-client <name>: set current client name to <name>",
   2549     single_param,
   2550     CommandFlags::None,
   2551     CommandHelper{},
   2552     make_single_word_completer([](const Context& context){ return context.name(); }),
   2553     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2554     {
   2555         const String& name = parser[0];
   2556         if (not all_of(name, is_identifier))
   2557             throw runtime_error{format("invalid client name: '{}'", name)};
   2558         else if (ClientManager::instance().client_name_exists(name) and
   2559                  context.name() != name)
   2560             throw runtime_error{format("client name '{}' is not unique", name)};
   2561         else
   2562             context.set_name(name);
   2563     }
   2564 };
   2565 
   2566 const CommandDesc set_register_cmd = {
   2567     "set-register",
   2568     "reg",
   2569     "set-register <name> <values>...: set register <name> to <values>",
   2570     ParameterDesc{{}, ParameterDesc::Flags::SwitchesAsPositional, 1},
   2571     CommandFlags::None,
   2572     CommandHelper{},
   2573     make_completer(
   2574          [](const Context& context,
   2575             StringView prefix, ByteCount cursor_pos) -> Completions {
   2576              return { 0_byte, cursor_pos,
   2577                       RegisterManager::instance().complete_register_name(prefix, cursor_pos) };
   2578         }),
   2579     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2580     {
   2581         RegisterManager::instance()[parser[0]].set(context, parser.positionals_from(1));
   2582     }
   2583 };
   2584 
   2585 const CommandDesc select_cmd = {
   2586     "select",
   2587     nullptr,
   2588     "select <selection_desc>...: select given selections\n"
   2589     "\n"
   2590     "selection_desc format is <anchor_line>.<anchor_column>,<cursor_line>.<cursor_column>",
   2591     ParameterDesc{{
   2592             {"timestamp", {ArgCompleter{}, "specify buffer timestamp at which those selections are valid"}},
   2593             {"codepoint", {{}, "columns are specified in codepoints, not bytes"}},
   2594             {"display-column", {{}, "columns are specified in display columns, not bytes"}}
   2595         },
   2596         ParameterDesc::Flags::SwitchesOnlyAtStart, 1
   2597     },
   2598     CommandFlags::None,
   2599     CommandHelper{},
   2600     CommandCompleter{},
   2601     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2602     {
   2603         auto& buffer = context.buffer();
   2604         const size_t timestamp = parser.get_switch("timestamp").map(str_to_int_ifp).cast<size_t>().value_or(buffer.timestamp());
   2605         ColumnType column_type = ColumnType::Byte;
   2606         if (parser.get_switch("codepoint"))
   2607             column_type = ColumnType::Codepoint;
   2608         else if (parser.get_switch("display-column"))
   2609             column_type = ColumnType::DisplayColumn;
   2610         ColumnCount tabstop = context.options()["tabstop"].get<int>();
   2611         ScopedSelectionEdition selection_edition{context};
   2612         context.selections_write_only() = selection_list_from_strings(buffer, column_type, parser.positionals_from(0), timestamp, 0, tabstop);
   2613     }
   2614 };
   2615 
   2616 const CommandDesc change_directory_cmd = {
   2617     "change-directory",
   2618     "cd",
   2619     "change-directory [<directory>]: change the server's working directory to <directory>, or the home directory if unspecified",
   2620     single_optional_param,
   2621     CommandFlags::None,
   2622     CommandHelper{},
   2623     make_completer(filename_arg_completer<true>),
   2624     [](const ParametersParser& parser, Context& ctx, const ShellContext&)
   2625     {
   2626         StringView target = parser.positional_count() == 1 ? StringView{parser[0]} : "~";
   2627         auto path = real_path(parse_filename(target));
   2628         if (chdir(path.c_str()) != 0)
   2629             throw runtime_error(format("unable to change to directory: '{}'", target));
   2630         for (auto& buffer : BufferManager::instance())
   2631             buffer->update_display_name();
   2632         ctx.hooks().run_hook(Hook::EnterDirectory, path, ctx);
   2633     }
   2634 };
   2635 
   2636 const CommandDesc rename_session_cmd = {
   2637     "rename-session",
   2638     nullptr,
   2639     "rename-session <name>: change remote session name",
   2640     single_param,
   2641     CommandFlags::None,
   2642     CommandHelper{},
   2643     make_single_word_completer([](const Context&){ return Server::instance().session(); }),
   2644     [](const ParametersParser& parser, Context& ctx, const ShellContext&)
   2645     {
   2646         String old_name = Server::instance().session();
   2647         if (not Server::instance().rename_session(parser[0]))
   2648             throw runtime_error(format("unable to rename current session: '{}' may be already in use", parser[0]));
   2649         ctx.hooks().run_hook(Hook::SessionRenamed, format("{}:{}", old_name, Server::instance().session()), ctx);
   2650     }
   2651 };
   2652 
   2653 const CommandDesc fail_cmd = {
   2654     "fail",
   2655     nullptr,
   2656     "fail [<message>]: raise an error with the given message",
   2657     ParameterDesc{},
   2658     CommandFlags::None,
   2659     CommandHelper{},
   2660     CommandCompleter{},
   2661     [](const ParametersParser& parser, Context&, const ShellContext&)
   2662     {
   2663         throw failure{join(parser, " ")};
   2664     }
   2665 };
   2666 
   2667 const CommandDesc declare_user_mode_cmd = {
   2668     "declare-user-mode",
   2669     nullptr,
   2670     "declare-user-mode <name>: add a new user keymap mode",
   2671     single_param,
   2672     CommandFlags::None,
   2673     CommandHelper{},
   2674     CommandCompleter{},
   2675     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2676     {
   2677         context.keymaps().add_user_mode(parser[0]);
   2678     }
   2679 };
   2680 
   2681 // We need ownership of the mode_name in the lock case
   2682 void enter_user_mode(Context& context, NormalParams params, String mode_name, KeymapMode mode, bool lock)
   2683 {
   2684     on_next_key_with_autoinfo(context, format("user.{}", mode_name), KeymapMode::None,
   2685                              [params, mode_name, mode, lock](Key key, Context& context) mutable {
   2686         if (key == Key::Escape)
   2687             return;
   2688 
   2689         if (auto* mapping = context.keymaps().get_mapping(key, mode))
   2690         {
   2691             ScopedSetBool disable_keymaps(context.keymaps_disabled());
   2692 
   2693             InputHandler::ScopedForceNormal force_normal{context.input_handler(), params};
   2694 
   2695             ScopedEdition edition(context);
   2696             for (auto& key : auto(mapping->keys)) // copy to allow reentrant unmap
   2697                 context.input_handler().handle_key(key);
   2698         }
   2699 
   2700         if (lock)
   2701             enter_user_mode(context, params, std::move(mode_name), mode, true);
   2702     }, lock ? format("{} (lock)", mode_name) : mode_name,
   2703     build_autoinfo_for_mapping(context, mode, {}));
   2704 }
   2705 
   2706 const CommandDesc enter_user_mode_cmd = {
   2707     "enter-user-mode",
   2708     nullptr,
   2709     "enter-user-mode [<switches>] <name> [<count>] [<register>]: enable <name> keymap mode for next key",
   2710     ParameterDesc{
   2711         { { "lock", { {}, "stay in mode until <esc> is pressed" } },
   2712           { "count", { ArgCompleter{}, "count to forward to normal mode parameters" } },
   2713           { "register", { ArgCompleter{}, "register to forward to normal mode parameters" } } },
   2714         ParameterDesc::Flags::None, 1, 1
   2715     },
   2716     CommandFlags::None,
   2717     CommandHelper{},
   2718     [](const Context& context,
   2719        CommandParameters params, size_t token_to_complete,
   2720        ByteCount pos_in_token) -> Completions
   2721     {
   2722         if (token_to_complete == 0)
   2723         {
   2724             return { 0_byte, params[0].length(),
   2725                      complete(params[0], pos_in_token, context.keymaps().user_modes()),
   2726                      Completions::Flags::Menu };
   2727         }
   2728         return {};
   2729     },
   2730     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2731     {
   2732         auto lock = (bool)parser.get_switch("lock");
   2733         KeymapMode mode = parse_keymap_mode(parser[0], context.keymaps().user_modes());
   2734         NormalParams params{
   2735             parser.get_switch("count").map(str_to_int_ifp).value_or(0),
   2736             parser.get_switch("register").map([](auto&& s) { return s.empty() ? '\0' : s[0]; }).value_or('\0')
   2737         };
   2738         enter_user_mode(context, params, parser[0], mode, lock);
   2739     }
   2740 };
   2741 
   2742 const CommandDesc provide_module_cmd = {
   2743     "provide-module",
   2744     nullptr,
   2745     "provide-module [<switches>] <name> <cmds>: declares a module <name> provided by <cmds>",
   2746     ParameterDesc{
   2747         { { "override", { {}, "allow overriding an existing module" } } },
   2748         ParameterDesc::Flags::None,
   2749         2, 2
   2750     },
   2751     CommandFlags::None,
   2752     CommandHelper{},
   2753     CommandCompleter{},
   2754     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2755     {
   2756         const String& module_name = parser[0];
   2757         auto& cm = CommandManager::instance();
   2758 
   2759         if (not all_of(module_name, is_identifier))
   2760             throw runtime_error(format("invalid module name: '{}'", module_name));
   2761 
   2762         if (cm.module_defined(module_name) and not parser.get_switch("override"))
   2763             throw runtime_error(format("module '{}' already defined", module_name));
   2764         cm.register_module(module_name, parser[1]);
   2765     }
   2766 };
   2767 
   2768 const CommandDesc require_module_cmd = {
   2769     "require-module",
   2770     nullptr,
   2771     "require-module <name>: ensures that <name> module has been loaded",
   2772     single_param,
   2773     CommandFlags::None,
   2774     CommandHelper{},
   2775     make_completer(menu(
   2776          [](const Context&, StringView prefix, ByteCount cursor_pos) {
   2777             return CommandManager::instance().complete_module_name(prefix.substr(0, cursor_pos));
   2778         })),
   2779     [](const ParametersParser& parser, Context& context, const ShellContext&)
   2780     {
   2781         CommandManager::instance().load_module(parser[0], context);
   2782     }
   2783 };
   2784 
   2785 }
   2786 
   2787 void register_commands()
   2788 {
   2789     CommandManager& cm = CommandManager::instance();
   2790     cm.register_command("nop", [](const ParametersParser&, Context&, const ShellContext&){}, "do nothing",
   2791         {{}, ParameterDesc::Flags::IgnoreUnknownSwitches});
   2792 
   2793     auto register_command = [&](const CommandDesc& c)
   2794     {
   2795         cm.register_command(c.name, c.func, c.docstring, c.params, c.flags, c.helper, c.completer);
   2796         if (c.alias)
   2797             GlobalScope::instance().aliases().add_alias(c.alias, c.name);
   2798     };
   2799 
   2800     register_command(edit_cmd);
   2801     register_command(force_edit_cmd);
   2802     register_command(write_cmd);
   2803     register_command(force_write_cmd);
   2804     register_command(write_all_cmd);
   2805     register_command(write_all_quit_cmd);
   2806     register_command(kill_cmd);
   2807     register_command(force_kill_cmd);
   2808     register_command(daemonize_session_cmd);
   2809     register_command(quit_cmd);
   2810     register_command(force_quit_cmd);
   2811     register_command(write_quit_cmd);
   2812     register_command(force_write_quit_cmd);
   2813     register_command(buffer_cmd);
   2814     register_command(buffer_next_cmd);
   2815     register_command(buffer_previous_cmd);
   2816     register_command(delete_buffer_cmd);
   2817     register_command(force_delete_buffer_cmd);
   2818     register_command(rename_buffer_cmd);
   2819     register_command(arrange_buffers_cmd);
   2820     register_command(add_highlighter_cmd);
   2821     register_command(remove_highlighter_cmd);
   2822     register_command(add_hook_cmd);
   2823     register_command(remove_hook_cmd);
   2824     register_command(trigger_user_hook_cmd);
   2825     register_command(define_command_cmd);
   2826     register_command(complete_command_cmd);
   2827     register_command(alias_cmd);
   2828     register_command(unalias_cmd);
   2829     register_command(echo_cmd);
   2830     register_command(debug_cmd);
   2831     register_command(source_cmd);
   2832     register_command(set_option_cmd);
   2833     register_command(unset_option_cmd);
   2834     register_command(update_option_cmd);
   2835     register_command(declare_option_cmd);
   2836     register_command(map_key_cmd);
   2837     register_command(unmap_key_cmd);
   2838     register_command(execute_keys_cmd);
   2839     register_command(evaluate_commands_cmd);
   2840     register_command(prompt_cmd);
   2841     register_command(on_key_cmd);
   2842     register_command(info_cmd);
   2843     register_command(try_catch_cmd);
   2844     register_command(set_face_cmd);
   2845     register_command(unset_face_cmd);
   2846     register_command(rename_client_cmd);
   2847     register_command(set_register_cmd);
   2848     register_command(select_cmd);
   2849     register_command(change_directory_cmd);
   2850     register_command(rename_session_cmd);
   2851     register_command(fail_cmd);
   2852     register_command(declare_user_mode_cmd);
   2853     register_command(enter_user_mode_cmd);
   2854     register_command(provide_module_cmd);
   2855     register_command(require_module_cmd);
   2856 }
   2857 
   2858 }