kakoune

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

main.cc (48951B)


      1 #include "assert.hh"
      2 #include "backtrace.hh"
      3 #include "buffer.hh"
      4 #include "buffer_utils.hh"
      5 #include "buffer_manager.hh"
      6 #include "client_manager.hh"
      7 #include "command_manager.hh"
      8 #include "commands.hh"
      9 #include "context.hh"
     10 #include "debug.hh"
     11 #include "event_manager.hh"
     12 #include "face_registry.hh"
     13 #include "file.hh"
     14 #include "hook_manager.hh"
     15 #include "highlighters.hh"
     16 #include "insert_completer.hh"
     17 #include "json_ui.hh"
     18 #include "keymap_manager.hh"
     19 #include "terminal_ui.hh"
     20 #include "option_manager.hh"
     21 #include "option_types.hh"
     22 #include "parameters_parser.hh"
     23 #include "profile.hh"
     24 #include "ranges.hh"
     25 #include "regex.hh"
     26 #include "register_manager.hh"
     27 #include "remote.hh"
     28 #include "scope.hh"
     29 #include "shared_string.hh"
     30 #include "shell_manager.hh"
     31 #include "string.hh"
     32 #include "unit_tests.hh"
     33 #include "window.hh"
     34 
     35 #include <fcntl.h>
     36 #include <locale.h>
     37 #include <sys/stat.h>
     38 #include <sys/types.h>
     39 #include <unistd.h>
     40 #include <pwd.h>
     41 
     42 namespace Kakoune
     43 {
     44 
     45 extern const char* version;
     46 
     47 namespace
     48 {
     49 
     50 struct {
     51     unsigned int version;
     52     StringView notes;
     53 } constexpr version_notes[] = { {
     54         0,
     55         "» local scope for command line evaluation\n"
     56     }, {
     57         20260521,
     58         "» support the {+b}\\N{} escape sequence in regex (matches {+b}[^\\n]{})\n"
     59         "» count and register forwarding to user modes\n"
     60         "» back switch added for the arrange-buffers command\n"
     61     }, {
     62         20260412,
     63         "» {+u}finaleol{} option to preserve files with no final end-of-line\n"
     64         "» {+b}%val\\{buffile}{} is now empty for scratch buffers\n"
     65         "» {+b}FocusIn{}/{+b}FocusOut{} events on suspend\n"
     66         "» {+u}number-lines -full-relative{} switch to keep a smaller line number gutter\n"
     67         "» {+b}<a-I>{} and {+b}<a-A>{} to select nested text objects\n"
     68         "» {+b}kak -C <session>{} to connect-or-create a session\n"
     69     }, {
     70         20250603,
     71         "» kak_* appearing in shell arguments will be added to the environment\n"
     72         "» {+U}double underline{} support\n"
     73         "» {+u}git apply{} can stage/revert selected changes to current buffer\n"
     74         "» {+u}exec/eval -client{} accepts '*' and comma separated list\n"
     75     }
     76 };
     77 
     78 static_assert(sizeof(version_notes) / sizeof(version_notes[0]) <= 4 - (version_notes[0].version != 0 ? 1 : 0),
     79               "Maximum 3 versions should be displayed in version notes, not including the development version");
     80 
     81 void show_startup_info(Client* local_client, int last_version)
     82 {
     83     const Face version_face{.attributes=Attribute::Bold};
     84     DisplayLineList info;
     85     for (auto [version, notes] : version_notes)
     86     {
     87         if (version and version <= last_version)
     88             continue;
     89 
     90         if (not version)
     91             info.push_back({"• Development version", version_face});
     92         else
     93         {
     94             const auto year = version / 10000;
     95             const auto month = (version / 100) % 100;
     96             const auto day = version % 100;
     97             info.push_back({format("• Kakoune v{}.{:02}.{:02}", year, month, day), version_face});
     98         }
     99 
    100         for (auto&& line : notes | split<StringView>('\n'))
    101             info.push_back(parse_display_line(line, GlobalScope::instance().faces()));
    102     }
    103     if (not info.empty())
    104         local_client->info_show({{{format("Kakoune {}", version), version_face},
    105                                   {", more info at ", {}},
    106                                   {":doc changelog", {.attributes=Attribute::Underline}}}},
    107                                  std::move(info), {}, InfoStyle::Prompt);
    108 }
    109 
    110 inline void write_stdout(StringView str) { try { write(STDOUT_FILENO, str); } catch (runtime_error&) {} }
    111 inline void write_stderr(StringView str) { try { write(STDERR_FILENO, str); } catch (runtime_error&) {} }
    112 
    113 String runtime_directory()
    114 {
    115     if (const char* runtime_directory = getenv("KAKOUNE_RUNTIME"))
    116         return runtime_directory;
    117 
    118     char relpath[PATH_MAX+1];
    119     format_to(relpath, "{}../share/kak", split_path(get_kak_binary_path()).first);
    120     struct stat st;
    121     if (stat(relpath, &st) == 0 and S_ISDIR(st.st_mode))
    122         return real_path(relpath);
    123 
    124     return "/usr/share/kak";
    125 }
    126 
    127 String config_directory()
    128 {
    129     if (StringView kak_cfg_dir = getenv("KAKOUNE_CONFIG_DIR"); not kak_cfg_dir.empty())
    130         return kak_cfg_dir.str();
    131     if (StringView xdg_cfg_home = getenv("XDG_CONFIG_HOME"); not xdg_cfg_home.empty())
    132         return format("{}/kak", xdg_cfg_home);
    133     return format("{}/.config/kak", homedir());
    134 }
    135 
    136 auto main_sel_first(const SelectionList& selections)
    137 {
    138     auto beg = &*selections.begin(), end = &*selections.end();
    139     auto main = beg + selections.main_index();
    140     using View = ConstArrayView<Selection>;
    141     return concatenated(View{main, end}, View{beg, main});
    142 }
    143 
    144 const EnvVarDesc builtin_env_vars[] = { {
    145         "bufname", false,
    146         [](StringView name, const Context& context) -> Vector<String>
    147         { return {context.buffer().display_name()}; }
    148     }, {
    149         "buffile", false,
    150         [](StringView name, const Context& context) -> Vector<String>
    151         { return {context.buffer().filename()}; }
    152     }, {
    153         "buflist", false,
    154         [](StringView name, const Context& context) -> Vector<String>
    155         { return BufferManager::instance() | transform(&Buffer::display_name) | gather<Vector<String>>(); }
    156     }, {
    157         "buf_line_count", false,
    158         [](StringView name, const Context& context) -> Vector<String>
    159         { return {to_string(context.buffer().line_count())}; }
    160     }, {
    161         "timestamp", false,
    162         [](StringView name, const Context& context) -> Vector<String>
    163         { return {to_string(context.buffer().timestamp())}; }
    164     }, {
    165         "history_id", false,
    166         [](StringView name, const Context& context) -> Vector<String>
    167         { return {to_string((size_t)context.buffer().current_history_id())}; }
    168     }, {
    169         "selection", false,
    170         [](StringView name, const Context& context) -> Vector<String>
    171         { const Selection& sel = context.selections().main();
    172           return {content(context.buffer(), sel)}; }
    173     }, {
    174         "selections", false,
    175         [](StringView name, const Context& context) -> Vector<String>
    176         { return context.selections_content(); }
    177     }, {
    178         "runtime", false,
    179         [](StringView name, const Context& context) -> Vector<String>
    180         { return {runtime_directory()}; }
    181     }, {
    182         "config", false,
    183         [](StringView name, const Context& context) -> Vector<String>
    184         { return {config_directory()}; }
    185     }, {
    186         "version", false,
    187         [](StringView name, const Context& context) -> Vector<String>
    188         { return {version}; }
    189     }, {
    190         "opt_", true,
    191         [](StringView name, const Context& context) -> Vector<String>
    192         { return context.options()[name.substr(4_byte)].get_as_strings(); }
    193     }, {
    194         "main_reg_", true,
    195         [](StringView name, const Context& context) -> Vector<String>
    196         { return {context.main_sel_register_value(name.substr(9_byte)).str()}; }
    197     }, {
    198         "reg_", true,
    199         [](StringView name, const Context& context)
    200         { return RegisterManager::instance()[name.substr(4_byte)].get(context) |
    201                      gather<Vector<String>>(); }
    202     }, {
    203         "client_env_", true,
    204         [](StringView name, const Context& context) -> Vector<String>
    205         { return {context.client().get_env_var(name.substr(11_byte)).str()}; }
    206     }, {
    207         "session", false,
    208         [](StringView name, const Context& context) -> Vector<String>
    209         { return {Server::instance().session()}; }
    210     }, {
    211         "client", false,
    212         [](StringView name, const Context& context) -> Vector<String>
    213         { return {context.name()}; }
    214     }, {
    215         "client_pid", false,
    216         [](StringView name, const Context& context) -> Vector<String>
    217         { return {to_string(context.client().pid())}; }
    218     }, {
    219         "client_list", false,
    220         [](StringView name, const Context& context) -> Vector<String>
    221         { return ClientManager::instance() |
    222                       transform([](const UniquePtr<Client>& c) -> const String&
    223                                 { return c->context().name(); }) | gather<Vector<String>>(); }
    224     }, {
    225         "modified", false,
    226         [](StringView name, const Context& context) -> Vector<String>
    227         { return {context.buffer().is_modified() ? "true" : "false"}; }
    228     }, {
    229         "cursor_line", false,
    230         [](StringView name, const Context& context) -> Vector<String>
    231         { return {to_string(context.selections().main().cursor().line + 1)}; }
    232     }, {
    233         "cursor_column", false,
    234         [](StringView name, const Context& context) -> Vector<String>
    235         { return {to_string(context.selections().main().cursor().column + 1)}; }
    236     }, {
    237         "cursor_char_value", false,
    238         [](StringView name, const Context& context) -> Vector<String>
    239         { auto coord = context.selections().main().cursor();
    240           auto& buffer = context.buffer();
    241           return {to_string((size_t)utf8::codepoint(buffer.iterator_at(coord), buffer.end()))}; }
    242     }, {
    243         "cursor_char_column", false,
    244         [](StringView name, const Context& context) -> Vector<String>
    245         { auto coord = context.selections().main().cursor();
    246           return {to_string(context.buffer()[coord.line].char_count_to(coord.column) + 1)}; }
    247     }, {
    248         "cursor_display_column", false,
    249         [](StringView name, const Context& context) -> Vector<String>
    250         { auto coord = context.selections().main().cursor();
    251           return {to_string(get_column(context.buffer(),
    252                                        context.options()["tabstop"].get<int>(),
    253                                        coord) + 1)}; }
    254     }, {
    255         "cursor_byte_offset", false,
    256         [](StringView name, const Context& context) -> Vector<String>
    257         { auto cursor = context.selections().main().cursor();
    258           return {to_string(context.buffer().distance({0,0}, cursor))}; }
    259     }, {
    260         "recording_register", false,
    261         [](StringView name, const Context& context) -> Vector<String>
    262         { const char reg = context.client().input_handler().recording_reg();
    263           return {reg ? String{static_cast<Codepoint>(reg)} : ""}; }
    264     }, {
    265         "selection_desc", false,
    266         [](StringView name, const Context& context) -> Vector<String>
    267         { return {selection_to_string(ColumnType::Byte, context.buffer(), context.selections().main())}; }
    268     }, {
    269         "selections_desc", false,
    270         [](StringView name, const Context& context) -> Vector<String>
    271         { return main_sel_first(context.selections()) |
    272                      transform([&buffer=context.buffer()](const Selection& sel) {
    273                          return selection_to_string(ColumnType::Byte, buffer, sel);
    274                      }) | gather<Vector<String>>(); }
    275     }, {
    276         "selections_char_desc", false,
    277         [](StringView name, const Context& context) -> Vector<String>
    278         { return main_sel_first(context.selections()) |
    279                      transform([&buffer=context.buffer()](const Selection& sel) {
    280                          return selection_to_string(ColumnType::Codepoint, buffer, sel);
    281                      }) | gather<Vector<String>>(); }
    282     }, {
    283         "selections_display_column_desc", false,
    284         [](StringView name, const Context& context) -> Vector<String>
    285         { return main_sel_first(context.selections()) |
    286                      transform([&buffer=context.buffer(), tabstop=context.options()["tabstop"].get<int>()](const Selection& sel) {
    287                          return selection_to_string(ColumnType::DisplayColumn, buffer, sel, tabstop);
    288                      }) | gather<Vector<String>>(); }
    289     }, {
    290         "selection_length", false,
    291         [](StringView name, const Context& context) -> Vector<String>
    292         { return {to_string(char_length(context.buffer(), context.selections().main()))}; }
    293     }, {
    294         "selections_length", false,
    295         [](StringView name, const Context& context) -> Vector<String>
    296         { return context.selections() |
    297                      transform([&](const Selection& s) -> String {
    298                          return to_string(char_length(context.buffer(), s));
    299                      }) | gather<Vector<String>>(); }
    300     }, {
    301         "selection_count", false,
    302         [](StringView name, const Context& context) -> Vector<String>
    303         { return {to_string(context.selections().size())}; }
    304     }, {
    305         "window_width", false,
    306         [](StringView name, const Context& context) -> Vector<String>
    307         { return {to_string(context.window().dimensions().column)}; }
    308     }, {
    309         "window_height", false,
    310         [](StringView name, const Context& context) -> Vector<String>
    311         { return {to_string(context.window().dimensions().line)}; }
    312     }, {
    313         "user_modes", false,
    314         [](StringView name, const Context& context) -> Vector<String>
    315         { return context.keymaps().user_modes(); }
    316     }, {
    317         "window_range", false,
    318         [](StringView name, const Context& context) -> Vector<String>
    319         {
    320             const auto& setup = context.window().last_display_setup();
    321             const auto width = context.window().dimensions().column - setup.widget_columns;
    322             return {to_string(setup.first_line), to_string(setup.first_column),
    323                     to_string(setup.line_count), to_string(width)};
    324         }
    325     }, {
    326         "history", false,
    327         [](StringView name, const Context& context) -> Vector<String>
    328         { return history_as_strings(context.buffer().history()); }
    329     }, {
    330         "history_since_", true,
    331         [](StringView name, const Context& context) -> Vector<String>
    332         { return history_as_strings(
    333             ArrayView(context.buffer().history())
    334                 .subrange(str_to_int(name.substr(14_byte)) + 1)
    335         ); }
    336     }, {
    337         "uncommitted_modifications", false,
    338         [](StringView name, const Context& context) -> Vector<String>
    339         { return undo_group_as_strings(context.buffer().current_undo_group()); }
    340     }
    341 };
    342 
    343 void register_registers()
    344 {
    345     RegisterManager& register_manager = RegisterManager::instance();
    346 
    347     for (Codepoint c : StringView{"abcdefghijklmnopqrstuvwxyz\"^@"})
    348         register_manager.add_register(c, make_unique_ptr<StaticRegister>(String{c}));
    349 
    350     for (Codepoint c : StringView{"/|:\\"})
    351         register_manager.add_register(c, make_unique_ptr<HistoryRegister>(String{c}));
    352 
    353     using StringList = Vector<String, MemoryDomain::Registers>;
    354 
    355     register_manager.add_register('%', make_dyn_reg(
    356         "%",
    357         [](const Context& context)
    358         { return StringList{{context.buffer().display_name()}}; }));
    359 
    360     register_manager.add_register('.', make_dyn_reg(
    361         ".",
    362         [](const Context& context) {
    363             auto content = context.selections_content();
    364             return StringList{content.begin(), content.end()};
    365          }));
    366 
    367     register_manager.add_register('#', make_dyn_reg(
    368         "#",
    369         [](const Context& context) {
    370             const size_t count = context.selections().size();
    371             StringList res;
    372             res.reserve(count);
    373             for (size_t i = 1; i < count+1; ++i)
    374                 res.push_back(to_string((int)i));
    375             return res;
    376         }));
    377 
    378     for (size_t i = 0; i < 10; ++i)
    379     {
    380         register_manager.add_register('0'+i, make_dyn_reg(
    381             String{Codepoint('0'+i)},
    382             [i](const Context& context) {
    383                 StringList result;
    384                 for (auto& sel : context.selections())
    385                     result.emplace_back(i < sel.captures().size() ? sel.captures()[i] : "");
    386                 return result;
    387             },
    388             [i](Context& context, ConstArrayView<String> values) {
    389                 if (values.empty())
    390                     return;
    391 
    392                 auto& sels = context.selections();
    393                 for (size_t sel_index = 0; sel_index < sels.size(); ++sel_index)
    394                 {
    395                     auto& sel = sels[sel_index];
    396                     if (sel.captures().size() < i+1)
    397                         sel.captures().resize(i+1);
    398                     sel.captures()[i] = values[std::min(sel_index, values.size()-1)];
    399                 }
    400             }));
    401     }
    402 
    403     register_manager.add_register('_', make_unique_ptr<NullRegister>());
    404 }
    405 
    406 void register_keymaps()
    407 {
    408     auto& keymaps = GlobalScope::instance().keymaps();
    409     keymaps.map_key(Key::Left, KeymapMode::Normal, {'h'}, "");
    410     keymaps.map_key(Key::Right, KeymapMode::Normal, {'l'}, "");
    411     keymaps.map_key(Key::Down, KeymapMode::Normal, {'j'}, "");
    412     keymaps.map_key(Key::Up, KeymapMode::Normal, {'k'}, "");
    413 
    414     keymaps.map_key(shift(Key::Left), KeymapMode::Normal, {'H'}, "");
    415     keymaps.map_key(shift(Key::Right), KeymapMode::Normal, {'L'}, "");
    416     keymaps.map_key(shift(Key::Down), KeymapMode::Normal, {'J'}, "");
    417     keymaps.map_key(shift(Key::Up), KeymapMode::Normal, {'K'}, "");
    418 
    419     keymaps.map_key(Key::End, KeymapMode::Normal, {alt('l')}, "");
    420     keymaps.map_key(Key::Home, KeymapMode::Normal, {alt('h')}, "");
    421     keymaps.map_key(shift(Key::End), KeymapMode::Normal, {alt('L')}, "");
    422     keymaps.map_key(shift(Key::Home), KeymapMode::Normal, {alt('H')}, "");
    423 }
    424 
    425 void check_tabstop(const int& val)
    426 {
    427     if (val < 1) throw runtime_error{"tabstop should be strictly positive"};
    428 }
    429 
    430 void check_indentwidth(const int& val)
    431 {
    432     if (val < 0) throw runtime_error{"indentwidth should be positive or zero"};
    433 }
    434 
    435 void check_scrolloff(const DisplayCoord& so)
    436 {
    437     if (so.line < 0 or so.column < 0)
    438         throw runtime_error{"scroll offset must be positive or zero"};
    439 }
    440 
    441 void check_timeout(const int& timeout)
    442 {
    443     if (timeout < 50)
    444         throw runtime_error{"the minimum acceptable timeout is 50 milliseconds"};
    445 }
    446 
    447 void check_extra_word_chars(const Vector<Codepoint, MemoryDomain::Options>& extra_chars)
    448 {
    449     if (any_of(extra_chars, is_blank))
    450         throw runtime_error{"blanks are not accepted for extra completion characters"};
    451 }
    452 
    453 void check_matching_pairs(const Vector<Codepoint, MemoryDomain::Options>& pairs)
    454 {
    455     if ((pairs.size() % 2) != 0)
    456         throw runtime_error{"matching pairs should have a pair number of element"};
    457     if (not all_of(pairs, [](Codepoint cp) { return is_punctuation(cp); }))
    458         throw runtime_error{"matching pairs can only be punctuation"};
    459 }
    460 
    461 void register_options()
    462 {
    463     OptionsRegistry& reg = GlobalScope::instance().option_registry();
    464 
    465     reg.declare_option<int, check_tabstop>("tabstop", "size of a tab character", 8);
    466     reg.declare_option<int, check_indentwidth>("indentwidth", "indentation width", 4);
    467     reg.declare_option<DisplayCoord, check_scrolloff>(
    468         "scrolloff", "number of lines and columns to keep visible main cursor when scrolling",
    469         {0,0});
    470     reg.declare_option("eolformat", "end of line format", EolFormat::Lf);
    471     reg.declare_option("finaleol", "write and end of line at end of file", FinalEol::Present);
    472     reg.declare_option("BOM", "byte order mark to use when writing buffer",
    473                        ByteOrderMark::None);
    474     reg.declare_option("incsearch",
    475                        "incrementally apply search/select/split regex",
    476                        true);
    477     reg.declare_option("autoinfo",
    478                        "automatically display contextual help",
    479                        AutoInfo::Command | AutoInfo::OnKey);
    480     reg.declare_option("autocomplete",
    481                        "automatically display possible completions",
    482                        AutoComplete::Insert | AutoComplete::Prompt);
    483     reg.declare_option("aligntab",
    484                        "use tab characters when possible for alignment",
    485                        false);
    486     reg.declare_option("ignored_files",
    487                        "patterns to ignore when completing filenames",
    488                        Regex{R"(^(\..*|.*\.(o|so|a))$)"});
    489     reg.declare_option("disabled_hooks",
    490                       "patterns to disable hooks whose group is matched",
    491                       Regex{});
    492     reg.declare_option("filetype", "buffer filetype", ""_str);
    493     reg.declare_option("path", "path to consider when trying to find a file",
    494                    Vector<String, MemoryDomain::Options>({ "./", "%/", "/usr/include" }));
    495     reg.declare_option("completers", "insert mode completers to execute.",
    496                        InsertCompleterDescList({
    497                            InsertCompleterDesc{ InsertCompleterDesc::Filename, {} },
    498                            InsertCompleterDesc{ InsertCompleterDesc::Word, "all"_str }
    499                        }), OptionFlags::None);
    500     reg.declare_option("static_words", "list of words to always consider for insert word completion",
    501                    Vector<String, MemoryDomain::Options>{});
    502     reg.declare_option("autoreload",
    503                        "autoreload buffer when a filesystem modification is detected",
    504                        Autoreload::Ask);
    505     reg.declare_option("writemethod",
    506                        "how to write buffer to files",
    507                        WriteMethod::Overwrite);
    508     reg.declare_option<int, check_timeout>(
    509         "idle_timeout", "timeout, in milliseconds, before idle hooks are triggered", 50);
    510     reg.declare_option<int, check_timeout>(
    511         "fs_check_timeout", "timeout, in milliseconds, between file system buffer modification checks",
    512         500);
    513     reg.declare_option("ui_options",
    514                        "space separated list of <key>=<value> options that are "
    515                        "passed to and interpreted by the user interface\n"
    516                        "\n"
    517                        "The terminal ui supports the following options:\n"
    518                        "    <key>:                        <value>:\n"
    519                        "    terminal_assistant             clippy|cat|dilbert|none|off\n"
    520                        "    terminal_status_on_top         bool\n"
    521                        "    terminal_set_title             bool\n"
    522                        "    terminal_title                 str\n"
    523                        "    terminal_enable_mouse          bool\n"
    524                        "    terminal_synchronized          bool\n"
    525                        "    terminal_wheel_scroll_amount   int\n"
    526                        "    terminal_shift_function_key    int\n"
    527                        "    terminal_padding_char          codepoint\n"
    528                        "    terminal_padding_fill          bool\n"
    529                        "    terminal_cursor_native         bool\n"
    530                        "    terminal_info_max_width        int\n",
    531                        UserInterface::Options{});
    532     reg.declare_option("modelinefmt", "format string used to generate the modeline",
    533                        "%val{bufname} %val{cursor_line}:%val{cursor_char_column} {{context_info}} {{mode_info}} - %val{client}@[%val{session}]"_str);
    534 
    535     reg.declare_option("debug", "various debug flags", DebugFlags::None);
    536     reg.declare_option("readonly", "prevent buffers from being modified", false);
    537     reg.declare_option<Vector<Codepoint, MemoryDomain::Options>, check_extra_word_chars>(
    538         "extra_word_chars",
    539         "Additional characters to be considered as words for insert completion",
    540         { '_' });
    541     reg.declare_option<Vector<Codepoint, MemoryDomain::Options>, check_matching_pairs>(
    542         "matching_pairs",
    543         "set of pair of characters to be considered as matching pairs",
    544         { '(', ')', '{', '}', '[', ']', '<', '>' });
    545     reg.declare_option<int>("startup_info_version", "version up to which startup info changes should be hidden", 0);
    546 }
    547 
    548 Client* local_client = nullptr;
    549 bool convert_to_client_pending = false;
    550 
    551 enum class UIType
    552 {
    553     Terminal,
    554     Json,
    555     Dummy,
    556 };
    557 
    558 UIType parse_ui_type(StringView ui_name)
    559 {
    560     if (ui_name == "terminal") return UIType::Terminal;
    561     if (ui_name == "json") return UIType::Json;
    562     if (ui_name == "dummy") return UIType::Dummy;
    563 
    564     throw parameter_error(format("error: unknown ui type: '{}'", ui_name));
    565 }
    566 
    567 UniquePtr<UserInterface> make_ui(UIType ui_type)
    568 {
    569     struct DummyUI : UserInterface
    570     {
    571         DummyUI() { set_signal_handler(SIGINT, SIG_DFL); }
    572         bool is_ok() const override { return true; }
    573         void menu_show(ConstArrayView<DisplayLine>, DisplayCoord,
    574                        Face, Face, MenuStyle) override {}
    575         void menu_select(int) override {}
    576         void menu_hide() override {}
    577 
    578         void info_show(const DisplayLine&, const DisplayLineList&, DisplayCoord, Face, InfoStyle) override {}
    579         void info_hide() override {}
    580 
    581         void draw(const DisplayBuffer&, DisplayCoord, const Face&, const Face&, ColumnCount) override {}
    582         void draw_status(const DisplayLine&, const DisplayLine&, const ColumnCount, const DisplayLine&, const Face&, StatusStyle) override {}
    583         DisplayCoord dimensions() override { return {24,80}; }
    584         void refresh(bool) override {}
    585         void set_on_key(OnKeyCallback) override {}
    586         void set_on_paste(OnPasteCallback) override {}
    587         void set_ui_options(const Options&) override {}
    588     };
    589 
    590     switch (ui_type)
    591     {
    592         case UIType::Terminal: return make_unique_ptr<TerminalUI>();
    593         case UIType::Json: return make_unique_ptr<JsonUI>();
    594         case UIType::Dummy: return make_unique_ptr<DummyUI>();
    595     }
    596     throw logic_error{};
    597 }
    598 
    599 pid_t fork_server_to_background()
    600 {
    601     if (pid_t pid = fork())
    602         return pid;
    603 
    604     setsid();
    605     if (fork()) // double fork to orphan the server
    606         exit(0);
    607 
    608     write_stderr(format("Kakoune forked server to background ({}), for session '{}'\n",
    609                         getpid(), Server::instance().session()));
    610     return 0;
    611 }
    612 
    613 UniquePtr<UserInterface> create_local_ui(UIType ui_type)
    614 {
    615     auto ui = make_ui(ui_type);
    616 
    617     static SignalHandler old_handler = set_signal_handler(SIGTSTP, [](int sig) {
    618         if (ClientManager::instance().count() == 1 and
    619             *ClientManager::instance().begin() == local_client and
    620             not Server::instance().is_daemon())
    621             old_handler(sig);
    622         else
    623         {
    624             convert_to_client_pending = true;
    625             set_signal_handler(SIGTSTP, old_handler);
    626         }
    627     });
    628     return ui;
    629 }
    630 
    631 int run_client(StringView session, StringView name, StringView client_init,
    632                Optional<BufferCoord> init_coord, UIType ui_type,
    633                bool suspend)
    634 {
    635     try
    636     {
    637         Optional<int> stdin_fd;
    638         // json-ui (or dummy) is not intended to be user interactive.
    639         // So only worry about making the tty your stdin if:
    640         // (a) ui_type is Terminal, *and*
    641         // (b) fd 0 is not interactive.
    642         if (ui_type == UIType::Terminal and not isatty(0))
    643         {
    644             // move stdin to another fd, and restore tty as stdin
    645             stdin_fd = dup(0);
    646             int tty = open("/dev/tty", O_RDONLY);
    647             dup2(tty, 0);
    648             close(tty);
    649         }
    650 
    651         EventManager event_manager;
    652         RemoteClient client{session, name, make_ui(ui_type), getpid(), get_env_vars(),
    653                             client_init, std::move(init_coord), stdin_fd};
    654         stdin_fd.map(close);
    655 
    656         if (suspend)
    657             raise(SIGTSTP);
    658         while (not client.exit_status() and client.is_ui_ok())
    659             event_manager.handle_next_events(EventMode::Normal);
    660         return client.exit_status().value_or(-1);
    661     }
    662     catch (disconnected& e)
    663     {
    664         write_stderr(format("{}\ndisconnecting\n", e.what()));
    665         return -1;
    666     }
    667 }
    668 
    669 struct convert_to_client_mode
    670 {
    671     String session;
    672     String client_name;
    673     String buffer_name;
    674     String selections;
    675 };
    676 
    677 enum class ServerFlags
    678 {
    679     None        = 0,
    680     IgnoreKakrc = 1 << 0,
    681     Daemon      = 1 << 1,
    682     ReadOnly    = 1 << 2,
    683     StartupInfo = 1 << 3,
    684 };
    685 constexpr bool with_bit_ops(Meta::Type<ServerFlags>) { return true; }
    686 
    687 int run_server(StringView session, StringView server_init,
    688                StringView client_init, StringView init_buffer, Optional<BufferCoord> init_coord,
    689                ServerFlags flags, UIType ui_type, DebugFlags debug_flags,
    690                ConstArrayView<StringView> files)
    691 {
    692     static bool terminate = false;
    693     set_signal_handler(SIGTERM, [](int) { terminate = true; });
    694     set_signal_handler(SIGINT, [](int) { terminate = true; });
    695     if ((flags & ServerFlags::Daemon) and session.empty())
    696     {
    697         write_stderr("-d needs a session name to be specified with -s\n");
    698         return -1;
    699     }
    700 
    701     EventManager        event_manager;
    702     Server              server{session.empty() ? to_string(getpid()) : session.str(),
    703                                (bool)(flags & ServerFlags::Daemon)};
    704 
    705     StringRegistry      string_registry;
    706     GlobalScope         global_scope;
    707     ShellManager        shell_manager{builtin_env_vars};
    708     CommandManager      command_manager;
    709     RegisterManager     register_manager;
    710     HighlighterRegistry highlighter_registry;
    711     SharedHighlighters  defined_highlighters;
    712     ClientManager       client_manager;
    713     BufferManager       buffer_manager;
    714 
    715     register_options();
    716     register_registers();
    717     register_keymaps();
    718     register_commands();
    719     register_highlighters();
    720 
    721     global_scope.options()["debug"].set(debug_flags);
    722 
    723     write_to_debug_buffer("*** This is the debug buffer, where debug info will be written ***");
    724 
    725 #ifdef KAK_DEBUG
    726     {
    727         ProfileScope profile{debug_flags, [&](std::chrono::microseconds duration) {
    728             write_to_debug_buffer(format("running the unit tests took {} ms", duration.count()));
    729         }};
    730         UnitTest::run_all_tests();
    731     }
    732 #endif
    733 
    734     bool startup_error = false;
    735     if (not (flags & ServerFlags::IgnoreKakrc)) try
    736     {
    737         Context init_context{Context::EmptyContextFlag{}};
    738         command_manager.execute(format("source {}/kakrc", runtime_directory()),
    739                                 init_context);
    740     }
    741     catch (runtime_error& error)
    742     {
    743         startup_error = true;
    744         write_to_debug_buffer(format("error while parsing kakrc:\n"
    745                                      "    {}", error.what()));
    746     }
    747 
    748     {
    749         Context empty_context{Context::EmptyContextFlag{}};
    750         global_scope.hooks().run_hook(Hook::EnterDirectory, real_path("."), empty_context);
    751         global_scope.hooks().run_hook(Hook::KakBegin, session, empty_context);
    752     }
    753 
    754     if (not server_init.empty()) try
    755     {
    756         Context init_context{Context::EmptyContextFlag{}};
    757         command_manager.execute(server_init, init_context);
    758     }
    759     catch (const kill_session& kill)
    760     {
    761         Context empty_context{Context::EmptyContextFlag{}};
    762         global_scope.hooks().run_hook(Hook::KakEnd, "", empty_context);
    763         return kill.exit_status;
    764     }
    765     catch (runtime_error& error)
    766     {
    767         startup_error = true;
    768         write_to_debug_buffer(format("error while running server init commands:\n"
    769                                      "    {}", error.what()));
    770     }
    771 
    772     if (not files.empty()) try
    773     {
    774         for (auto& file : files)
    775         {
    776             try
    777             {
    778                 Buffer *buffer = open_or_create_file_buffer(file);
    779                 if (flags & ServerFlags::ReadOnly)
    780                 {
    781                     buffer->flags() |= Buffer::Flags::ReadOnly;
    782                     buffer->options().get_local_option("readonly").set(true);
    783                 }
    784             }
    785             catch (runtime_error& error)
    786             {
    787                 startup_error = true;
    788                 write_to_debug_buffer(format("error while opening file '{}':\n"
    789                                              "    {}", file, error.what()));
    790             }
    791         }
    792     }
    793     catch (runtime_error& error)
    794     {
    795          write_to_debug_buffer(format("error while opening command line files: {}", error.what()));
    796     }
    797 
    798     int exit_status = 0;
    799     try
    800     {
    801         if (ui_type == UIType::Terminal and not isatty(0))
    802         {
    803             // move stdin to another fd, and restore tty as stdin
    804             int fd = dup(0);
    805             int tty = open("/dev/tty", O_RDONLY);
    806             dup2(tty, 0);
    807             close(tty);
    808             create_fifo_buffer("*stdin*", fd, Buffer::Flags::None, AutoScroll::NotInitially);
    809         }
    810 
    811         if (not server.is_daemon())
    812         {
    813             local_client = client_manager.create_client(
    814                  create_local_ui(ui_type), getpid(), {}, get_env_vars(), client_init, init_buffer, std::move(init_coord),
    815                  [&](int status) { exit_status = status; });
    816 
    817             if (startup_error and local_client)
    818                 local_client->print_status({}, {
    819                     "error during startup, see `:buffer *debug*` for details",
    820                     local_client->context().faces()["Error"]
    821                 }, -1, StatusStyle::Status);
    822 
    823             if (flags & ServerFlags::StartupInfo and local_client)
    824                 show_startup_info(local_client, global_scope.options()["startup_info_version"].get<int>());
    825         }
    826 
    827         while (not terminate and
    828                (not client_manager.empty() or server.negotiating() or server.is_daemon()))
    829         {
    830             client_manager.redraw_clients();
    831 
    832             // Loop so that eventual inputs happening during the processing are handled as
    833             // well, avoiding unneeded redraws.
    834             Optional<std::chrono::nanoseconds> timeout;
    835             if (client_manager.has_pending_inputs())
    836                 timeout = std::chrono::nanoseconds{};
    837             try
    838             {
    839                 while (event_manager.handle_next_events(EventMode::Normal, nullptr, timeout))
    840                 {
    841                     if (client_manager.process_pending_inputs())
    842                         break;
    843                     timeout = std::chrono::nanoseconds{};
    844                 }
    845             }
    846             catch (const cancel&) {}
    847 
    848             client_manager.process_pending_inputs();
    849 
    850             client_manager.clear_client_trash();
    851             client_manager.clear_window_trash();
    852             buffer_manager.clear_buffer_trash();
    853             global_scope.option_registry().clear_option_trash();
    854 
    855             if (local_client and not contains(client_manager, local_client))
    856             {
    857                 local_client = nullptr;
    858                 if ((not client_manager.empty() or server.is_daemon()) and fork_server_to_background())
    859                     exit(exit_status); // We do not want to run destructors and hooks here
    860             }
    861             else if (convert_to_client_pending)
    862             {
    863                 kak_assert(local_client);
    864                 auto& local_context = local_client->context();
    865                 String client_name = local_context.name();
    866                 String buffer_name = local_context.buffer().name();
    867                 String selections = selection_list_to_string(ColumnType::Byte, local_context.selections());
    868 
    869                 ClientManager::instance().remove_client(*local_client, true, 0);
    870                 client_manager.clear_client_trash();
    871                 local_client = nullptr;
    872                 convert_to_client_pending = false;
    873 
    874                 if (fork_server_to_background())
    875                 {
    876                     ClientManager::instance().clear(false);
    877                     String session = server.session();
    878                     server.close_session(false);
    879                     throw convert_to_client_mode{ std::move(session), std::move(client_name), std::move(buffer_name), std::move(selections) };
    880                 }
    881             }
    882         }
    883     }
    884     catch (const kill_session& kill)
    885     {
    886         exit_status = kill.exit_status;
    887     }
    888 
    889     {
    890         Context empty_context{Context::EmptyContextFlag{}};
    891         global_scope.hooks().run_hook(Hook::KakEnd, "", empty_context);
    892     }
    893 
    894     return exit_status;
    895 }
    896 
    897 int run_filter(StringView keystr, ConstArrayView<StringView> files, bool quiet, StringView suffix_backup)
    898 {
    899     StringRegistry  string_registry;
    900     GlobalScope     global_scope;
    901     EventManager    event_manager;
    902     ShellManager    shell_manager{builtin_env_vars};
    903     RegisterManager register_manager;
    904     BufferManager   buffer_manager;
    905 
    906     register_options();
    907     register_registers();
    908 
    909     try
    910     {
    911         auto keys = parse_keys(keystr);
    912 
    913         auto apply_to_buffer = [&](Buffer& buffer)
    914         {
    915             try
    916             {
    917                 InputHandler input_handler{
    918                     { buffer, Selection{{0,0}, buffer.back_coord()} },
    919                     Context::Flags::Draft
    920                 };
    921 
    922                 for (auto& key : keys)
    923                     input_handler.handle_key(key);
    924             }
    925             catch (runtime_error& err)
    926             {
    927                 if (not quiet)
    928                     write_stderr(format("error while applying keys to buffer '{}': {}\n",
    929                                         buffer.display_name(), err.what()));
    930             }
    931         };
    932 
    933         for (auto& file : files)
    934         {
    935             Buffer* buffer = open_file_buffer(file, Buffer::Flags::NoHooks);
    936             if (not suffix_backup.empty())
    937                 write_buffer_to_file(*buffer, buffer->filename() + suffix_backup,
    938                                      WriteMethod::Overwrite, WriteFlags::None);
    939             apply_to_buffer(*buffer);
    940             write_buffer_to_file(*buffer, buffer->filename(),
    941                                  WriteMethod::Overwrite, WriteFlags::None);
    942             buffer_manager.delete_buffer(*buffer);
    943         }
    944         if (not isatty(0))
    945         {
    946             Buffer& buffer = *create_buffer_from_string(
    947                 "*stdin*", Buffer::Flags::NoHooks, read_fd(0));
    948             apply_to_buffer(buffer);
    949             write_buffer_to_fd(buffer, 1);
    950             buffer_manager.delete_buffer(buffer);
    951         }
    952     }
    953     catch (runtime_error& err)
    954     {
    955         write_stderr(format("error: {}\n", err.what()));
    956     }
    957 
    958     buffer_manager.clear_buffer_trash();
    959     return 0;
    960 }
    961 
    962 int run_pipe(StringView session)
    963 {
    964     try
    965     {
    966         send_command(session, read_fd(0));
    967     }
    968     catch (disconnected& e)
    969     {
    970         write_stderr(format("{}\ndisconnecting\n", e.what()));
    971         return -1;
    972     }
    973     return 0;
    974 }
    975 
    976 void signal_handler(int signal)
    977 {
    978     TerminalUI::restore_terminal();
    979     const char* text = nullptr;
    980     switch (signal)
    981     {
    982         case SIGSEGV: text = "SIGSEGV"; break;
    983         case SIGFPE:  text = "SIGFPE";  break;
    984         case SIGQUIT: text = "SIGQUIT"; break;
    985         case SIGPIPE: text = "SIGPIPE"; break;
    986     }
    987     auto msg = format("Received {}, exiting.\nPid: {}\nCallstack:\n{}",
    988                       text, getpid(), Backtrace{}.desc());
    989     write_stderr(msg);
    990     notify_fatal_error(msg);
    991 
    992     if (Server::has_instance())
    993         Server::instance().close_session();
    994     if (BufferManager::has_instance())
    995         BufferManager::instance().backup_modified_buffers();
    996 
    997     if (signal == SIGSEGV)
    998     {
    999         // generate core dump
   1000         ::signal(SIGSEGV, SIG_DFL);
   1001         ::kill(getpid(), SIGSEGV);
   1002     }
   1003     else
   1004         abort();
   1005 }
   1006 
   1007 }
   1008 
   1009 }
   1010 
   1011 int main(int argc, char* argv[])
   1012 {
   1013     using namespace Kakoune;
   1014 
   1015     setlocale(LC_ALL, "");
   1016 
   1017     set_signal_handler(SIGSEGV, signal_handler);
   1018     set_signal_handler(SIGFPE,  signal_handler);
   1019     set_signal_handler(SIGQUIT, signal_handler);
   1020     set_signal_handler(SIGTERM, signal_handler);
   1021     set_signal_handler(SIGPIPE, [](int){});
   1022     set_signal_handler(SIGINT, [](int){});
   1023     set_signal_handler(SIGCHLD, [](int){});
   1024     set_signal_handler(SIGTTOU, SIG_IGN);
   1025 
   1026     const ParameterDesc param_desc{
   1027         SwitchMap{ { "c", { ArgCompleter{},  "connect to given session" } },
   1028                    { "C", { ArgCompleter{},  "connect to given session, create if it does not exist" } },
   1029                    { "e", { ArgCompleter{},  "execute argument on client initialisation" } },
   1030                    { "E", { ArgCompleter{},  "execute argument on server initialisation" } },
   1031                    { "n", { {}, "do not source kakrc files on startup" } },
   1032                    { "s", { ArgCompleter{},  "set session name" } },
   1033                    { "d", { {}, "run as a headless session (requires -s)" } },
   1034                    { "p", { ArgCompleter{},  "just send stdin as commands to the given session" } },
   1035                    { "f", { ArgCompleter{},  "filter: for each file, select the entire buffer and execute the given keys" } },
   1036                    { "i", { ArgCompleter{}, "backup the files on which a filter is applied using the given suffix" } },
   1037                    { "q", { {}, "in filter mode, be quiet about errors applying keys" } },
   1038                    { "ui", { ArgCompleter{}, "set the type of user interface to use (terminal, dummy, or json)" } },
   1039                    { "l", { {}, "list existing sessions" } },
   1040                    { "clear", { {}, "clear dead sessions" } },
   1041                    { "debug", { ArgCompleter{}, "initial debug option value" } },
   1042                    { "version", { {}, "display kakoune version and exit" } },
   1043                    { "ro", { {}, "readonly mode" } },
   1044                    { "help", { {}, "display a help message and quit" } } }
   1045     };
   1046 
   1047     try
   1048     {
   1049         auto show_usage = [&]() {
   1050             write_stdout(format("Usage: {} [options] [file]... [+<line>[:<col>]|+:]\n\n"
   1051                     "Options:\n"
   1052                     "{}\n"
   1053                     "Prefixing a positional argument with a plus (`+`) sign will place the\n"
   1054                     "cursor at a given set of coordinates, or the end of the buffer if the plus\n"
   1055                     "sign is followed only by a colon (`:`)\n",
   1056                     argv[0], generate_switches_doc(param_desc.switches)));
   1057             return 0;
   1058         };
   1059 
   1060         const auto params = ArrayView<char*>{argv+1, argv + argc}
   1061                           | transform([](auto* s) { return String{s}; })
   1062                           | gather<Vector<String>>();
   1063 
   1064         if (contains(params, "--help"_sv))
   1065             return show_usage();
   1066 
   1067         ParametersParser parser{params, param_desc};
   1068 
   1069         const bool show_help_message = (bool)parser.get_switch("help");
   1070         if (show_help_message)
   1071             return show_usage();
   1072 
   1073         if (parser.get_switch("version"))
   1074         {
   1075             write_stdout(format("Kakoune {}\n", Kakoune::version));
   1076             return 0;
   1077         }
   1078 
   1079         const bool list_sessions = (bool)parser.get_switch("l");
   1080         const bool clear_sessions = (bool)parser.get_switch("clear");
   1081         if (list_sessions or clear_sessions)
   1082         {
   1083             list_files(session_directory(), [&](StringView session, auto&) {
   1084                 if (session.substr(0_byte, 1_byte) == ".")
   1085                     return;
   1086 
   1087                 const bool valid = check_session(session);
   1088                 if (list_sessions)
   1089                     write_stdout(format("{}{}\n", session, valid ? "" : " (dead)"));
   1090                 if (not valid and clear_sessions)
   1091                     unlink(session_path(session).c_str());
   1092             });
   1093             return 0;
   1094         }
   1095 
   1096         if (auto session = parser.get_switch("p"))
   1097         {
   1098             for (auto opt : { "c", "n", "s", "d", "e", "E", "ro" })
   1099             {
   1100                 if (parser.get_switch(opt))
   1101                 {
   1102                     write_stderr(format("error: -{} is incompatible with -p\n", opt));
   1103                     return -1;
   1104                 }
   1105             }
   1106             return run_pipe(*session);
   1107         }
   1108 
   1109         auto client_init = parser.get_switch("e").value_or(StringView{});
   1110         auto server_init = parser.get_switch("E").value_or(StringView{});
   1111         const UIType ui_type = parse_ui_type(parser.get_switch("ui").value_or("terminal"));
   1112 
   1113         if (auto keys = parser.get_switch("f"))
   1114         {
   1115             if (parser.get_switch("ro"))
   1116             {
   1117                 write_stderr("error: -ro is incompatible with -f\n");
   1118                 return -1;
   1119             }
   1120 
   1121             Vector<StringView> files;
   1122             for (size_t i = 0; i < parser.positional_count(); ++i)
   1123                 files.emplace_back(parser[i]);
   1124 
   1125             return run_filter(*keys, files, (bool)parser.get_switch("q"),
   1126                               parser.get_switch("i").value_or(StringView{}));
   1127         }
   1128 
   1129         Vector<StringView> files;
   1130         Optional<BufferCoord> init_coord;
   1131         for (auto& name : parser)
   1132         {
   1133             if (not name.empty() and name[0_byte] == '+')
   1134             {
   1135                 if (name == "+" or name == "+:")
   1136                 {
   1137                     client_init = client_init + "; exec gj";
   1138                     continue;
   1139                 }
   1140                 auto colon = find(name, ':');
   1141                 if (auto line = str_to_int_ifp({name.begin()+1, colon}))
   1142                 {
   1143                     init_coord = std::max<BufferCoord>({0,0}, {
   1144                         *line - 1,
   1145                         colon != name.end() ?
   1146                             str_to_int_ifp({colon+1, name.end()}).value_or(1) - 1
   1147                           : 0
   1148                     });
   1149                     continue;
   1150                 }
   1151             }
   1152 
   1153             files.emplace_back(name);
   1154         }
   1155 
   1156         if ((bool)parser.get_switch("c") + (bool)parser.get_switch("C") + (bool)parser.get_switch("s") > 1)
   1157         {
   1158             write_stderr("error: -s, -c and -C are mutually exclusive\n");
   1159             return -1;
   1160         }
   1161         if (parser.get_switch("c") or (parser.get_switch("C") and check_session(*parser.get_switch("C"))))
   1162         {
   1163             for (auto opt : { "n", "d", "E", "ro" })
   1164             {
   1165                 if (parser.get_switch(opt))
   1166                 {
   1167                     write_stderr(format("error: -{} incompatible with connecting to an existing session\n", opt));
   1168                     return -1;
   1169                 }
   1170             }
   1171             StringView session = parser.get_switch("c") ? *parser.get_switch("c") : *parser.get_switch("C");
   1172             String new_files;
   1173             for (auto name : files) {
   1174                 new_files += format("edit '{}'", escape(real_path(name), "'", '\''));
   1175                 if (init_coord) {
   1176                     new_files += format(" {} {}", init_coord->line + 1, init_coord->column + 1);
   1177                     init_coord.reset();
   1178                 }
   1179                 new_files += ";";
   1180             }
   1181 
   1182             return run_client(session, {}, new_files + client_init, init_coord, ui_type, false);
   1183         }
   1184         else
   1185         {
   1186             StringView session = parser.get_switch("C").value_or(parser.get_switch("s").value_or(StringView{}));
   1187             try
   1188             {
   1189                 auto ignore_kakrc = (bool)parser.get_switch("n");
   1190                 auto flags = (ignore_kakrc                                ? ServerFlags::IgnoreKakrc : ServerFlags::None) |
   1191                              (parser.get_switch("d")                      ? ServerFlags::Daemon      : ServerFlags::None) |
   1192                              (parser.get_switch("ro")                     ? ServerFlags::ReadOnly    : ServerFlags::None) |
   1193                              ((argc == 1 or (ignore_kakrc and argc == 2))
   1194                               and isatty(0)                               ? ServerFlags::StartupInfo : ServerFlags::None);
   1195                 auto debug_flags = option_from_string(Meta::Type<DebugFlags>{}, parser.get_switch("debug").value_or(""));
   1196                 return run_server(session, server_init, client_init, files.empty() ? StringView{} : files[0], init_coord, flags, ui_type, debug_flags, files);
   1197             }
   1198             catch (convert_to_client_mode& convert)
   1199             {
   1200                 return run_client(convert.session, convert.client_name,
   1201                                   format("try %^buffer '{}'; select '{}'^; echo converted to client only mode",
   1202                                          escape(convert.buffer_name, "'^", '\\'), convert.selections), {}, ui_type, true);
   1203             }
   1204         }
   1205     }
   1206     catch (parameter_error& error)
   1207     {
   1208         write_stderr(format("Error while parsing parameters: {}\n"
   1209                             "Valid switches:\n"
   1210                             "{}", error.what(),
   1211                             generate_switches_doc(param_desc.switches)));
   1212        return -1;
   1213     }
   1214     catch (Kakoune::exception& error)
   1215     {
   1216         write_stderr(format("Fatal error: {}\n", error.what()));
   1217         return -1;
   1218     }
   1219     catch (std::exception& error)
   1220     {
   1221         write_stderr(format("uncaught exception ({}):\n{}\n", typeid(error).name(), error.what()));
   1222         return -1;
   1223     }
   1224     catch (...)
   1225     {
   1226         write_stderr("uncaught exception");
   1227         return -1;
   1228     }
   1229     return 0;
   1230 }
   1231 
   1232 #if defined(__ELF__)
   1233 #ifdef __arm__
   1234 # define PROGBITS "%progbits"
   1235 #else
   1236 # define PROGBITS "@progbits"
   1237 #endif
   1238 asm(".pushsection \".debug_gdb_scripts\", \"MS\"," PROGBITS ",1" R"(
   1239 .byte 4
   1240 .ascii "kakoune-inline-gdb.py\n"
   1241 .ascii "import os.path\n"
   1242 .ascii "sys.path.insert(0, os.path.dirname(gdb.current_objfile().filename) + '/../share/kak/gdb/')\n"
   1243 .ascii "import gdb.printing\n"
   1244 .ascii "import kakoune\n"
   1245 .ascii "gdb.printing.register_pretty_printer(gdb.current_objfile(), kakoune.build_pretty_printer())\n\0"
   1246 .popsection
   1247 )");
   1248 #endif