kakoune

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

input_handler.cc (66335B)


      1 #include "input_handler.hh"
      2 
      3 #include "buffer.hh"
      4 #include "debug.hh"
      5 #include "command_manager.hh"
      6 #include "client.hh"
      7 #include "event_manager.hh"
      8 #include "hook_manager.hh"
      9 #include "face_registry.hh"
     10 #include "keymap_manager.hh"
     11 #include "option_manager.hh"
     12 #include "insert_completer.hh"
     13 #include "normal.hh"
     14 #include "option_types.hh"
     15 #include "regex.hh"
     16 #include "register_manager.hh"
     17 #include "user_interface.hh"
     18 #include "window.hh"
     19 #include "word_db.hh"
     20 
     21 #include <concepts>
     22 #include <utility>
     23 #include <limits>
     24 
     25 namespace Kakoune
     26 {
     27 
     28 class InputMode : public RefCountable
     29 {
     30 public:
     31     InputMode(InputHandler& input_handler) : m_input_handler(input_handler) {}
     32     ~InputMode() override = default;
     33     InputMode(const InputMode&) = delete;
     34     InputMode& operator=(const InputMode&) = delete;
     35 
     36     void handle_key(Key key) { RefPtr<InputMode> keep_alive{this}; on_key(key); }
     37     virtual void paste(StringView content);
     38     virtual void on_raw_key() {}
     39 
     40     virtual void on_enabled(bool from_pop) {}
     41     virtual void on_disabled(bool from_push) {}
     42 
     43     virtual void refresh_ifn() {}
     44 
     45     virtual unsigned int take_pending_count() { return 1; }
     46 
     47     bool enabled() const { return &m_input_handler.current_mode() == this; }
     48     Context& context() const { return m_input_handler.context(); }
     49 
     50     virtual ModeInfo mode_info() const = 0;
     51 
     52     virtual KeymapMode keymap_mode() const = 0;
     53 
     54     virtual StringView name() const = 0;
     55 
     56     using Insertion = InputHandler::Insertion;
     57 
     58 protected:
     59     virtual void on_key(Key key) = 0;
     60 
     61     void push_mode(InputMode* new_mode) { m_input_handler.push_mode(new_mode); }
     62     void pop_mode() { m_input_handler.pop_mode(this); }
     63 
     64     void record_key(Key key) { m_input_handler.record_key(key); }
     65     void drop_last_recorded_key() { m_input_handler.drop_last_recorded_key(); }
     66 
     67 private:
     68     InputHandler& m_input_handler;
     69 };
     70 
     71 void InputMode::paste(StringView content)
     72 {
     73     try
     74     {
     75         Buffer& buffer = context().buffer();
     76         const bool linewise = not content.empty() and content.back() == '\n';
     77         ScopedEdition edition{context()};
     78         ScopedSelectionEdition selection_edition{context()};
     79         context().selections().for_each([&buffer, content=std::move(content), linewise]
     80                                         (size_t index, Selection& sel) {
     81             auto& min = sel.min();
     82             auto& max = sel.max();
     83             BufferRange range =
     84                 buffer.insert(paste_pos(buffer, min, max, PasteMode::Insert, linewise), content);
     85             min = range.begin;
     86             max = range.end > range.begin ? buffer.char_prev(range.end) : range.begin;
     87         }, false);
     88     }
     89     catch (Kakoune::runtime_error& error)
     90     {
     91         write_to_debug_buffer(format("Error: {}", error.what()));
     92         context().print_status({error.what().str(), context().faces()["Error"] });
     93         context().hooks().run_hook(Hook::RuntimeError, error.what(), context());
     94     }
     95 }
     96 
     97 namespace InputModes
     98 {
     99 
    100 std::chrono::milliseconds get_idle_timeout(const Context& context)
    101 {
    102     return std::chrono::milliseconds{context.options()["idle_timeout"].get<int>()};
    103 }
    104 
    105 std::chrono::milliseconds get_fs_check_timeout(const Context& context)
    106 {
    107     return std::chrono::milliseconds{context.options()["fs_check_timeout"].get<int>()};
    108 }
    109 
    110 struct MouseHandler
    111 {
    112     bool handle_key(Key key, Context& context)
    113     {
    114         if (not context.has_window())
    115             return false;
    116 
    117         Buffer& buffer = context.buffer();
    118         // bits above these potentially store additional information
    119         constexpr auto mask = (Key::Modifiers) 0x7FF;
    120         constexpr auto modifiers = Key::Modifiers::Control | Key::Modifiers::Alt | Key::Modifiers::Shift | Key::Modifiers::MouseButtonMask | ~mask;
    121 
    122         switch ((key.modifiers & ~modifiers).value)
    123         {
    124         case Key::Modifiers::MousePress:
    125             switch (key.mouse_button())
    126             {
    127             case Key::MouseButton::Right: {
    128                 m_dragging.reset();
    129                 auto cursor = context.window().buffer_coord(key.coord());
    130                 if (not cursor)
    131                 {
    132                     context.ensure_cursor_visible = false;
    133                     return true;
    134                 }
    135                 ScopedSelectionEdition selection_edition{context};
    136                 auto& selections = context.selections();
    137                 if (key.modifiers & Key::Modifiers::Control)
    138                     selections = {{selections.begin()->anchor(), *cursor}};
    139                 else
    140                     selections.main() = {selections.main().anchor(), *cursor};
    141                 selections.sort_and_merge_overlapping();
    142                 return true;
    143             }
    144 
    145             case Key::MouseButton::Left: {
    146                 m_dragging.reset(new ScopedSelectionEdition{context});
    147                 auto anchor = context.window().buffer_coord(key.coord());
    148                 if (not anchor)
    149                 {
    150                     context.ensure_cursor_visible = false;
    151                     return true;
    152                 }
    153                 m_anchor = *anchor;
    154                 if (not (key.modifiers & Key::Modifiers::Control))
    155                     context.selections_write_only() = { buffer, m_anchor};
    156                 else
    157                 {
    158                     auto& selections = context.selections();
    159                     size_t main = selections.size();
    160                     selections.push_back({m_anchor});
    161                     selections.set_main_index(main);
    162                     selections.sort_and_merge_overlapping();
    163                 }
    164                 return true;
    165             }
    166 
    167             default: return true;
    168             }
    169 
    170         case Key::Modifiers::MouseRelease: {
    171             auto cursor = context.window().buffer_coord(key.coord());
    172             if (not m_dragging or not cursor)
    173             {
    174                 context.ensure_cursor_visible = false;
    175                 return true;
    176             }
    177             auto& selections = context.selections();
    178             selections.main() = {buffer.clamp(m_anchor), *cursor};
    179             selections.sort_and_merge_overlapping();
    180             m_dragging.reset();
    181             return true;
    182         }
    183 
    184         case Key::Modifiers::MousePos: {
    185             auto cursor = context.window().buffer_coord(key.coord());
    186             if (not m_dragging or not cursor)
    187             {
    188                 context.ensure_cursor_visible = false;
    189                 return true;
    190             }
    191             auto& selections = context.selections();
    192             selections.main() = {buffer.clamp(m_anchor), *cursor};
    193             selections.sort_and_merge_overlapping();
    194             return true;
    195         }
    196 
    197         case Key::Modifiers::Scroll:
    198             scroll_window(context, key.scroll_amount(), m_dragging ? OnHiddenCursor::MoveCursor : OnHiddenCursor::PreserveSelections);
    199             return true;
    200 
    201         default: return false;
    202         }
    203     }
    204 
    205 private:
    206     UniquePtr<ScopedSelectionEdition> m_dragging;
    207     BufferCoord m_anchor;
    208 };
    209 
    210 constexpr StringView register_doc =
    211     "Special registers:\n"
    212     "[0-9]: selections capture group\n"
    213     "%:     buffer name\n"
    214     ".:     selection contents\n"
    215     "#:     selection index\n"
    216     "_:     null register\n"
    217     "\":     default yank/paste register\n"
    218     "@:     default macro register\n"
    219     "/:     default search register\n"
    220     "^:     default mark register\n"
    221     "|:     default shell command register\n"
    222     "::     last entered command\n";
    223 
    224 class Normal : public InputMode
    225 {
    226 public:
    227     Normal(InputHandler& input_handler, bool single_command = false)
    228         : InputMode(input_handler),
    229           m_idle_timer{TimePoint::max(),
    230                        context().flags() & Context::Flags::Draft ?
    231                            Timer::Callback{} : [this](Timer&) {
    232               RefPtr<InputMode> keep_alive{this}; // hook could trigger pop_mode()
    233               if (context().has_client())
    234                   context().client().clear_pending();
    235 
    236               context().hooks().run_hook(Hook::NormalIdle, "", context());
    237           }},
    238           m_fs_check_timer{TimePoint::max(),
    239                            context().flags() & Context::Flags::Draft ?
    240                             Timer::Callback{} : Timer::Callback{[this](Timer& timer) {
    241               if (context().has_client())
    242                   context().client().check_if_buffer_needs_reloading();
    243               timer.set_next_date(Clock::now() + get_fs_check_timeout(context()));
    244           }}},
    245           m_state(single_command ? State::SingleCommand : State::Normal)
    246     {}
    247 
    248     void on_enabled(bool from_pop) override
    249     {
    250         if (m_state == State::PopOnEnabled)
    251             return pop_mode();
    252 
    253         if (not (context().flags() & Context::Flags::Draft))
    254         {
    255             if (context().has_client())
    256                 context().client().check_if_buffer_needs_reloading();
    257 
    258             m_fs_check_timer.set_next_date(Clock::now() + get_fs_check_timeout(context()));
    259             m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
    260         }
    261 
    262         if (m_hooks_disabled and not m_in_on_key)
    263         {
    264             context().hooks_disabled().unset();
    265             m_hooks_disabled = false;
    266         }
    267     }
    268 
    269     void on_disabled(bool from_push) override
    270     {
    271         m_idle_timer.disable();
    272         m_fs_check_timer.disable();
    273 
    274         if (not from_push and m_hooks_disabled)
    275         {
    276             context().hooks_disabled().unset();
    277             m_hooks_disabled = false;
    278         }
    279     }
    280 
    281     void on_key(Key key) override
    282     {
    283         bool should_clear = false;
    284 
    285         kak_assert(m_state != State::PopOnEnabled);
    286         ScopedSetBool set_in_on_key{m_in_on_key};
    287 
    288         bool do_restore_hooks = false;
    289         auto restore_hooks = OnScopeEnd([&, this]{
    290             if (m_hooks_disabled and enabled() and do_restore_hooks)
    291             {
    292                 context().hooks_disabled().unset();
    293                 m_hooks_disabled = false;
    294             }
    295         });
    296 
    297         const bool transient = context().flags() & Context::Flags::Draft;
    298 
    299         if (m_mouse_handler.handle_key(key, context()))
    300         {
    301             should_clear = true;
    302 
    303             if (not transient)
    304                 m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
    305         }
    306         else if (auto cp = key.codepoint(); cp and isdigit(*cp))
    307         {
    308             long long new_val = (long long)m_params.count * 10 + *cp - '0';
    309             if (new_val > std::numeric_limits<int>::max())
    310                 context().print_status({ "parameter overflowed", context().faces()["Error"] });
    311             else
    312                 m_params.count = new_val;
    313         }
    314         else if (key == Key::Backspace)
    315             m_params.count /= 10;
    316         else if (key == '\\')
    317         {
    318             if (not m_hooks_disabled)
    319             {
    320                 m_hooks_disabled = true;
    321                 context().hooks_disabled().set();
    322             }
    323         }
    324         else if (key == '"')
    325         {
    326             on_next_key_with_autoinfo(context(), "register", KeymapMode::None,
    327                 [this](Key key, Context& context) {
    328                     auto cp = key.codepoint();
    329                     if (not cp or key == Key::Escape)
    330                         return;
    331                     if (*cp <= 127)
    332                         m_params.reg = *cp;
    333                     else
    334                         context.print_status(
    335                             { format("invalid register '{}'", *cp),
    336                               context.faces()["Error"] });
    337                 }, "enter target register", register_doc.str());
    338         }
    339         else
    340         {
    341             auto pop_if_single_command = OnScopeEnd([this] {
    342                 if (m_state == State::SingleCommand and enabled())
    343                      pop_mode();
    344                 else if (m_state == State::SingleCommand)
    345                      m_state = State::PopOnEnabled;
    346             });
    347 
    348             should_clear = true;
    349 
    350             // Hack to parse keys sent by terminals using the 8th bit to mark the
    351             // meta key. In normal mode, give priority to a potential alt-key than
    352             // the accentuated character.
    353             if (key.key >= 127 and key.key < 256)
    354             {
    355                 key.modifiers |= Key::Modifiers::Alt;
    356                 key.key &= 0x7f;
    357             }
    358 
    359             do_restore_hooks = true;
    360             if (auto command = get_normal_command(key))
    361             {
    362                 auto autoinfo = context().options()["autoinfo"].get<AutoInfo>();
    363                 if (autoinfo & AutoInfo::Normal and context().has_client())
    364                     context().client().info_show(to_string(key), command->docstring.str(),
    365                                                  {}, InfoStyle::Prompt);
    366 
    367                 // reset m_params now to be reentrant
    368                 NormalParams params = m_params;
    369                 m_params = { 0, 0 };
    370 
    371                 command->func(context(), params);
    372             }
    373             else
    374                 m_params = { 0, 0 };
    375         }
    376 
    377         context().hooks().run_hook(Hook::NormalKey, to_string(key), context());
    378         if (should_clear and not transient and context().has_client())
    379             context().client().schedule_clear();
    380         if (enabled() and not transient) // The hook might have changed mode
    381             m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
    382     }
    383 
    384     ModeInfo mode_info() const override
    385     {
    386         auto info_face = context().faces()["StatusLineInfo"];
    387         auto value_face = context().faces()["StatusLineValue"];
    388 
    389         auto& sels = context().selections();
    390         int hidden_count = 0;
    391         for (auto& sel : sels)
    392             hidden_count += context().has_window() and not context().window().display_coord(sel.cursor());
    393 
    394         AtomList atoms;
    395         if (sels.size() == 1)
    396         {
    397             atoms.emplace_back(format("{} sel", sels.size()), info_face);
    398             if (hidden_count)
    399                 atoms.emplace_back(" (hidden)", info_face);
    400         }
    401         else
    402         {
    403             atoms.emplace_back(format("{} sels ({})", sels.size(), sels.main_index() + 1), info_face);
    404             if (hidden_count)
    405                 atoms.emplace_back(format(" ({} hidden)", hidden_count), info_face);
    406         }
    407 
    408         if (m_params.count != 0)
    409         {
    410             atoms.emplace_back(" param=", info_face);
    411             atoms.emplace_back(to_string(m_params.count), value_face);
    412         }
    413         if (m_params.reg)
    414         {
    415             atoms.emplace_back(" reg=", info_face);
    416             atoms.emplace_back(StringView(m_params.reg).str(), value_face);
    417         }
    418         return {atoms, m_params};
    419     }
    420 
    421     void paste(StringView content) override
    422     {
    423         InputMode::paste(content);
    424         if (not (context().flags() & Context::Flags::Draft))
    425         {
    426             if (context().has_client())
    427                 context().client().schedule_clear();
    428             m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
    429         }
    430     }
    431 
    432     unsigned int take_pending_count() override
    433     {
    434         unsigned int count = std::max(m_params.count, 1);
    435         m_params.count = 0;
    436         return count;
    437     }
    438 
    439     KeymapMode keymap_mode() const override { return KeymapMode::Normal; }
    440 
    441     StringView name() const override { return "normal"; }
    442 
    443 private:
    444     friend struct InputHandler::ScopedForceNormal;
    445 
    446     NormalParams m_params = { 0, 0 };
    447     bool m_hooks_disabled = false;
    448     NestedBool m_in_on_key;
    449     Timer m_idle_timer;
    450     Timer m_fs_check_timer;
    451     MouseHandler m_mouse_handler;
    452 
    453     enum class State { Normal, SingleCommand, PopOnEnabled };
    454     State m_state;
    455 };
    456 
    457 template<WordType word_type>
    458 void to_next_word_begin(CharCount& pos, StringView line)
    459 {
    460     const CharCount len = line.char_length();
    461     if (pos == len)
    462         return;
    463     if (word_type == Word and is_punctuation(line[pos]))
    464     {
    465         while (pos != len and is_punctuation(line[pos]))
    466             ++pos;
    467     }
    468     else if (is_word<word_type>(line[pos]))
    469     {
    470         while (pos != len and is_word<word_type>(line[pos]))
    471             ++pos;
    472     }
    473     while (pos != len and is_horizontal_blank(line[pos]))
    474         ++pos;
    475 }
    476 
    477 template<WordType word_type>
    478 void to_next_word_end(CharCount& pos, StringView line)
    479 {
    480     const CharCount len = line.char_length();
    481     if (pos + 1 >= len)
    482         return;
    483     ++pos;
    484 
    485     while (pos != len and is_horizontal_blank(line[pos]))
    486         ++pos;
    487 
    488     if (word_type == Word and is_punctuation(line[pos]))
    489     {
    490         while (pos != len and is_punctuation(line[pos]))
    491             ++pos;
    492     }
    493     else if (is_word<word_type>(line[pos]))
    494     {
    495         while (pos != len and is_word<word_type>(line[pos]))
    496             ++pos;
    497     }
    498     --pos;
    499 }
    500 
    501 template<WordType word_type>
    502 void to_prev_word_begin(CharCount& pos, StringView line)
    503 {
    504     if (pos == 0_char)
    505         return;
    506     --pos;
    507 
    508     while (pos != 0_char and is_horizontal_blank(line[pos]))
    509         --pos;
    510 
    511     if (word_type == Word and is_punctuation(line[pos]))
    512     {
    513         while (pos != 0_char and is_punctuation(line[pos]))
    514             --pos;
    515         if (not is_punctuation(line[pos]))
    516             ++pos;
    517     }
    518     else if (is_word<word_type>(line[pos]))
    519     {
    520         while (pos != 0_char and is_word<word_type>(line[pos]))
    521             --pos;
    522         if (not is_word<word_type>(line[pos]))
    523             ++pos;
    524      }
    525 }
    526 
    527 class LineEditor
    528 {
    529 public:
    530     LineEditor(const FaceRegistry& faces) : m_faces{faces} {}
    531 
    532     void handle_key(Key key)
    533     {
    534         auto erase_move = [this](auto&& move_func) {
    535             auto old_pos = m_cursor_pos;
    536             move_func(m_cursor_pos, m_line);
    537             if (m_cursor_pos > old_pos)
    538                 std::swap(m_cursor_pos, old_pos);
    539             m_clipboard = m_line.substr(m_cursor_pos, old_pos - m_cursor_pos).str();
    540             m_line = m_line.substr(0, m_cursor_pos) + m_line.substr(old_pos);
    541         };
    542 
    543         if (key == Key::Left or key == ctrl('b'))
    544         {
    545             if (m_cursor_pos > 0)
    546                 --m_cursor_pos;
    547         }
    548         else if (key == Key::Right or key == ctrl('f'))
    549         {
    550             if (m_cursor_pos < m_line.char_length())
    551                 ++m_cursor_pos;
    552         }
    553         else if (key == Key::Home or key == ctrl('a'))
    554             m_cursor_pos = 0;
    555         else if (key == Key::End or key == ctrl('e'))
    556             m_cursor_pos = m_line.char_length();
    557         else if (key == Key::Backspace or key == shift(Key::Backspace) or key == ctrl('h'))
    558         {
    559             if (m_cursor_pos != 0)
    560             {
    561                 m_line = m_line.substr(0_char, m_cursor_pos - 1)
    562                        + m_line.substr(m_cursor_pos);
    563 
    564                 --m_cursor_pos;
    565             }
    566         }
    567         else if (key == Key::Delete or key == ctrl('d'))
    568         {
    569             if (m_cursor_pos != m_line.char_length())
    570                 m_line = m_line.substr(0, m_cursor_pos)
    571                        + m_line.substr(m_cursor_pos+1);
    572         }
    573         else if (key == alt('f'))
    574             to_next_word_begin<Word>(m_cursor_pos, m_line);
    575         else if (key == alt('F'))
    576             to_next_word_begin<WORD>(m_cursor_pos, m_line);
    577         else if (key == alt('b'))
    578             to_prev_word_begin<Word>(m_cursor_pos, m_line);
    579         else if (key == alt('B'))
    580             to_prev_word_begin<WORD>(m_cursor_pos, m_line);
    581         else if (key == alt('e'))
    582             to_next_word_end<Word>(m_cursor_pos, m_line);
    583         else if (key == alt('E'))
    584             to_next_word_end<WORD>(m_cursor_pos, m_line);
    585         else if (key == ctrl('k'))
    586         {
    587             m_clipboard = m_line.substr(m_cursor_pos).str();
    588             m_line = m_line.substr(0, m_cursor_pos).str();
    589         }
    590         else if (key == ctrl('u'))
    591         {
    592             m_clipboard = m_line.substr(0, m_cursor_pos).str();
    593             m_line = m_line.substr(m_cursor_pos).str();
    594             m_cursor_pos = 0;
    595         }
    596         else if (key == ctrl('w') or key == alt(Key::Backspace))
    597             erase_move(&to_prev_word_begin<Word>);
    598         else if (key == ctrl('W'))
    599             erase_move(&to_prev_word_begin<WORD>);
    600         else if (key == alt('d'))
    601             erase_move(&to_next_word_begin<Word>);
    602         else if (key == alt('D'))
    603             erase_move(&to_next_word_begin<WORD>);
    604         else if (key == ctrl('y'))
    605         {
    606             m_line = m_line.substr(0, m_cursor_pos) + m_clipboard + m_line.substr(m_cursor_pos);
    607             m_cursor_pos += m_clipboard.char_length();
    608         }
    609         else if (auto cp = key.codepoint())
    610             insert(*cp);
    611     }
    612 
    613     void insert(Codepoint cp)
    614     {
    615         m_line = m_line.substr(0, m_cursor_pos) + String{cp}
    616                + m_line.substr(m_cursor_pos);
    617         ++m_cursor_pos;
    618     }
    619 
    620     void insert(StringView str)
    621     {
    622         insert_from(m_cursor_pos, str);
    623     }
    624 
    625     void insert_from(CharCount start, StringView str)
    626     {
    627         kak_assert(start <= m_cursor_pos);
    628         m_line = m_line.substr(0, start) + str
    629                + m_line.substr(m_cursor_pos);
    630        m_cursor_pos = start + str.char_length();
    631     }
    632 
    633     void reset(String line, StringView empty_text)
    634     {
    635         m_line = std::move(line);
    636         m_empty_text = empty_text;
    637         m_cursor_pos = m_line.char_length();
    638     }
    639 
    640     const String& line() const { return m_line; }
    641     CharCount cursor_pos() const { return m_cursor_pos; }
    642 
    643     ColumnCount cursor_display_column() const
    644     {
    645         return m_line.substr(0, m_cursor_pos).column_length();
    646     }
    647 
    648     DisplayLine build_display_line(ColumnCount in_width)
    649     {
    650         const bool empty = m_line.empty();
    651         StringView str = empty ? m_empty_text : m_line;
    652 
    653         const Face line_face = m_faces[empty ? "StatusLineInfo" : "StatusLine"];
    654         const Face cursor_face = m_faces["StatusCursor"];
    655 
    656         if (m_cursor_pos == str.char_length())
    657             return DisplayLine{{ { str.str(), line_face }, { " "_str, cursor_face} } };
    658         else
    659             return DisplayLine({ { str.substr(0, m_cursor_pos).str(), line_face },
    660                                  { str.substr(m_cursor_pos,1).str(), cursor_face },
    661                                  { str.substr(m_cursor_pos+1).str(), line_face } });
    662     }
    663 private:
    664     CharCount  m_cursor_pos = 0;
    665 
    666     String     m_line;
    667     StringView m_empty_text = {};
    668     String     m_clipboard;
    669 
    670     const FaceRegistry& m_faces;
    671 };
    672 
    673 static Optional<Codepoint> get_raw_codepoint(Key key)
    674 {
    675     if (auto cp = key.codepoint())
    676         return cp;
    677     else if (key.modifiers == Key::Modifiers::Control and
    678              ((key.key >= '@' and key.key <= '_') or
    679               (key.key >= 'a' and key.key <= 'z')))
    680         return {(Codepoint)(to_upper((char)key.key) - '@')};
    681     return {};
    682 }
    683 
    684 class Prompt : public InputMode
    685 {
    686 public:
    687     Prompt(InputHandler& input_handler, StringView prompt,
    688            String initstr, String emptystr, Face face, PromptFlags flags,
    689            char history_register, PromptCompleter completer, PromptCallback callback)
    690         : InputMode(input_handler), m_callback(std::move(callback)), m_completer(std::move(completer)),
    691           m_prompt(prompt.str()), m_prompt_face(face),
    692           m_empty_text{std::move(emptystr)},
    693           // This prompt may outlive local scopes so ignore local faces.
    694           m_line_editor{context().faces(false)}, m_flags(flags),
    695           m_history{RegisterManager::instance()[history_register]},
    696           m_current_history{-1},
    697           m_auto_complete{context().options()["autocomplete"].get<AutoComplete>() & AutoComplete::Prompt},
    698           m_idle_timer{TimePoint::max(), context().flags() & Context::Flags::Draft ?
    699                            Timer::Callback{} : [this](Timer&) {
    700                            RefPtr<InputMode> keep_alive{this}; // hook or m_callback could trigger pop_mode()
    701                            if (m_auto_complete and m_refresh_completion_pending)
    702                                refresh_completions();
    703                            if (m_line_changed)
    704                            {
    705                                m_callback(m_line_editor.line(), PromptEvent::Change, context());
    706                                m_line_changed = false;
    707                            }
    708                            context().hooks().run_hook(Hook::PromptIdle, "", context());
    709                        }}
    710     {
    711         m_line_editor.reset(std::move(initstr), m_empty_text);
    712     }
    713 
    714     void on_key(Key key) override
    715     {
    716         const String& line = m_line_editor.line();
    717 
    718         auto can_auto_insert_completion = [&] {
    719             const bool has_completions = not m_completions.candidates.empty();
    720             const bool completion_selected = m_current_completion != -1;
    721             const bool text_entered = m_completions.start != line.byte_count_to(m_line_editor.cursor_pos());
    722             const bool at_end = line.byte_count_to(m_line_editor.cursor_pos()) == line.length();
    723             return (m_completions.flags & Completions::Flags::Menu) and
    724                 has_completions and
    725                 not completion_selected and at_end and
    726                 (not (m_completions.flags & Completions::Flags::NoEmpty) or text_entered);
    727         };
    728 
    729         if (key == Key::Return)
    730         {
    731             if (can_auto_insert_completion())
    732             {
    733                 const String& completion = m_completions.candidates.front();
    734                 m_line_editor.insert_from(line.char_count_to(m_completions.start),
    735                                           completion);
    736             }
    737 
    738             history_push(line);
    739             context().print_status(DisplayLine{});
    740             if (context().has_client())
    741                 context().client().menu_hide();
    742 
    743             // Maintain hooks disabled in callback if they were before pop_mode
    744             ScopedSetBool disable_hooks(context().hooks_disabled(),
    745                                         context().hooks_disabled());
    746             pop_mode();
    747             // call callback after pop_mode so that callback
    748             // may change the mode
    749             m_callback(line, PromptEvent::Validate, context());
    750             return;
    751         }
    752         else if (key == Key::Escape or key == ctrl('c') or
    753                  ((key == Key::Backspace or key == shift(Key::Backspace) or key == ctrl('h')) and line.empty()))
    754         {
    755             history_push(line);
    756             context().print_status(DisplayLine{});
    757             if (context().has_client())
    758                 context().client().menu_hide();
    759 
    760             // Maintain hooks disabled in callback if they were before pop_mode
    761             ScopedSetBool disable_hooks(context().hooks_disabled(),
    762                                         context().hooks_disabled());
    763             pop_mode();
    764             m_callback(line, PromptEvent::Abort, context());
    765             return;
    766         }
    767         else if (key == ctrl('r'))
    768         {
    769             on_next_key_with_autoinfo(context(), "register", KeymapMode::None,
    770                 [this](Key key, Context&) {
    771                     const bool joined = (bool)(key.modifiers & Key::Modifiers::Alt);
    772                     const bool quoted = (bool)(key.modifiers & Key::Modifiers::Control);
    773                     key.modifiers &= ~(Key::Modifiers::Alt | Key::Modifiers::Control);
    774 
    775                     auto cp = key.codepoint();
    776                     if (not cp or key == Key::Escape)
    777                         return;
    778 
    779                     auto* quoter = Kakoune::quoter(quoted ? Quoting::Kakoune : Quoting::Raw);
    780                     m_line_editor.insert(
    781                         joined ? join(RegisterManager::instance()[*cp].get(context()) | transform(quoter), ' ', false)
    782                                : quoter(context().main_sel_register_value(String{*cp})));
    783 
    784                     display();
    785                     m_line_changed = true;
    786                     m_refresh_completion_pending = true;
    787                 }, "enter register name", register_doc.str());
    788             display();
    789             return;
    790         }
    791         else if (key == ctrl('v'))
    792         {
    793             on_next_key_with_autoinfo(context(), "raw-key", KeymapMode::None,
    794                 [this](Key key, Context&) {
    795                     if (auto cp = get_raw_codepoint(key))
    796                     {
    797                         m_line_editor.insert(*cp);
    798                         display();
    799                         m_line_changed = true;
    800                         m_refresh_completion_pending = true;
    801                     }
    802                 }, "raw insert", "enter key to insert");
    803             display();
    804             return;
    805         }
    806         else if (key == Key::Up or key == ctrl('p'))
    807         {
    808             auto history = m_history.get(context());
    809             m_current_history = std::min(static_cast<int>(history.size()) - 1, m_current_history);
    810             if (m_current_history == -1)
    811                m_prefix = line;
    812             auto next = find_if(history.subrange(m_current_history + 1), [this](StringView s) { return prefix_match(s, m_prefix); });
    813             if (next != history.end())
    814             {
    815                 m_current_history = next - history.begin();
    816                 m_line_editor.reset(*next, m_empty_text);
    817             }
    818             clear_completions();
    819             m_refresh_completion_pending = true;
    820         }
    821         else if (key == Key::Down or key == ctrl('n')) // next
    822         {
    823             auto history = m_history.get(context());
    824             m_current_history = std::min(static_cast<int>(history.size()) - 1, m_current_history);
    825             if (m_current_history >= 0)
    826             {
    827                 auto next = find_if(history.subrange(0, m_current_history) | reverse(), [this](StringView s) { return prefix_match(s, m_prefix); });
    828                 m_current_history = history.rend() - next - 1;
    829                 m_line_editor.reset(next != history.rend() ? *next : m_prefix, m_empty_text);
    830                 clear_completions();
    831                 m_refresh_completion_pending = true;
    832             }
    833         }
    834         else if (key == Key::Tab or key == shift(Key::Tab) or key.modifiers == Key::Modifiers::MenuSelect) // completion
    835         {
    836             CandidateList& candidates = m_completions.candidates;
    837 
    838             if (m_auto_complete and m_refresh_completion_pending)
    839                 refresh_completions();
    840             if (candidates.empty()) // manual completion, we need to ask our completer for completions
    841             {
    842                 refresh_completions();
    843                 if ((not m_prefix_in_completions and candidates.size() > 1) or
    844                     candidates.size() > 2)
    845                     return;
    846             }
    847 
    848             if (candidates.empty())
    849                 return;
    850 
    851             const bool reverse = (key == shift(Key::Tab));
    852             if (key.modifiers == Key::Modifiers::MenuSelect)
    853                 m_current_completion = clamp<int>(key.key, 0, candidates.size() - 1);
    854             else if (not reverse and ++m_current_completion >= candidates.size())
    855                 m_current_completion = 0;
    856             else if (reverse and --m_current_completion < 0)
    857                 m_current_completion = candidates.size()-1;
    858 
    859             const String& completion = candidates[m_current_completion];
    860             if (context().has_client())
    861                 context().client().menu_select(m_current_completion);
    862 
    863             m_line_editor.insert_from(line.char_count_to(m_completions.start),
    864                                       completion);
    865 
    866             // when we have only one completion candidate, make next tab complete
    867             // from the new content.
    868             if (candidates.size() == 1 or
    869                 (m_prefix_in_completions and candidates.size() == 2))
    870             {
    871                 m_current_completion = -1;
    872                 candidates.clear();
    873                 m_refresh_completion_pending = true;
    874             }
    875         }
    876         else if (key == ctrl('x'))
    877         {
    878             on_next_key_with_autoinfo(context(), "explicit-completion", KeymapMode::None,
    879                 [this](Key key, Context&) {
    880                     m_explicit_completer = ArgCompleter{};
    881 
    882                     if (key.key == 'f')
    883                         use_explicit_completer([](const Context& context, StringView token) {
    884                             return complete_filename(token, context.options()["ignored_files"].get<Regex>(),
    885                                                      token.length(), FilenameFlags::Expand);
    886                         });
    887                     else if (key.key == 'w')
    888                         use_explicit_completer([](const Context& context, StringView token) {
    889                             CandidateList candidates;
    890                             for_n_best(get_word_db(context.buffer()).find_matching(token),
    891                                        100, [](auto& lhs, auto& rhs){ return rhs < lhs; },
    892                                        [&](RankedMatch& m) {
    893                                 candidates.push_back(m.candidate().str());
    894                                 return true;
    895                             });
    896                             return candidates;
    897                         });
    898 
    899                     if (m_explicit_completer)
    900                         refresh_completions();
    901                 }, "enter completion type",
    902                 "f: filename\n"
    903                 "w: buffer word\n");
    904         }
    905         else if (key == ctrl('o'))
    906         {
    907             m_explicit_completer = ArgCompleter{};
    908             m_auto_complete = not m_auto_complete;
    909 
    910             if (m_auto_complete)
    911                 refresh_completions();
    912             else if (context().has_client())
    913             {
    914                 clear_completions();
    915                 context().client().menu_hide();
    916             }
    917         }
    918         else if (key == alt('!'))
    919         {
    920             try
    921             {
    922                 m_line_editor.reset(expand(line, context()), m_empty_text);
    923             }
    924             catch (std::runtime_error& error)
    925             {
    926                 context().print_status({error.what(), context().faces()["Error"]});
    927                 return;
    928             }
    929         }
    930         else if (key == alt(';'))
    931         {
    932             push_mode(new Normal(context().input_handler(), true));
    933             return;
    934         }
    935         else
    936         {
    937             if ((key == Key::Space or key == shift(Key::Space)) and
    938                 not (m_completions.flags & Completions::Flags::Quoted) and // if token is quoted, this space does not end it
    939                 can_auto_insert_completion())
    940                 m_line_editor.insert_from(line.char_count_to(m_completions.start),
    941                                           m_completions.candidates.front());
    942 
    943             m_line_editor.handle_key(key);
    944             clear_completions();
    945             m_refresh_completion_pending = true;
    946         }
    947 
    948         display();
    949         m_line_changed = true;
    950         if (enabled() and not (context().flags() & Context::Flags::Draft)) // The callback might have disabled us
    951             m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
    952     }
    953 
    954     void refresh_ifn() override
    955     {
    956         bool explicit_completion_selected = m_current_completion != -1 and
    957             (not m_prefix_in_completions or m_current_completion != m_completions.candidates.size() - 1);
    958         if (not enabled() or (context().flags() & Context::Flags::Draft) or explicit_completion_selected)
    959             return;
    960 
    961         if (auto next_date = Clock::now() + get_idle_timeout(context());
    962             next_date < m_idle_timer.next_date())
    963             m_idle_timer.set_next_date(next_date);
    964         m_refresh_completion_pending = true;
    965     }
    966 
    967     void paste(StringView content) override
    968     {
    969         m_line_editor.insert(content);
    970         clear_completions();
    971         m_refresh_completion_pending = true;
    972         display();
    973         m_line_changed = true;
    974         if (not (context().flags() & Context::Flags::Draft))
    975             m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
    976     }
    977 
    978     void on_raw_key() override {
    979         m_was_interactive = true;
    980     }
    981 
    982     void set_prompt_face(Face face)
    983     {
    984         if (face != m_prompt_face)
    985         {
    986             m_prompt_face = face;
    987             display();
    988         }
    989     }
    990 
    991     ModeInfo mode_info() const override
    992     {
    993         return {{ "prompt", context().faces()["StatusLineMode"] }, {}};
    994     }
    995 
    996     KeymapMode keymap_mode() const override { return KeymapMode::Prompt; }
    997 
    998     StringView name() const override { return "prompt"; }
    999 
   1000 private:
   1001     template<typename Completer>
   1002     void use_explicit_completer(Completer&& completer)
   1003     {
   1004         m_explicit_completer = [completer](const Context& context, StringView content, ByteCount cursor_pos) {
   1005             Optional<Token> last_token;
   1006             CommandParser parser{content.substr(0_byte, cursor_pos)};
   1007             while (auto token = parser.read_token(false))
   1008                 last_token = std::move(token);
   1009 
   1010             if (last_token and (last_token->pos + last_token->content.length() < cursor_pos))
   1011                 last_token.reset();
   1012 
   1013             auto token_start = last_token.map([&](auto&& t) { return t.pos; }).value_or(cursor_pos);
   1014             auto token_content = last_token.map([](auto&& t) -> StringView { return t.content; }).value_or(StringView{});
   1015 
   1016             return Completions{token_start, cursor_pos, completer(context, token_content)};
   1017         };
   1018     }
   1019 
   1020     void refresh_completions()
   1021     {
   1022         try
   1023         {
   1024             m_refresh_completion_pending = false;
   1025             auto& completer = m_explicit_completer ? m_explicit_completer : m_completer;
   1026             if (not completer)
   1027                 return;
   1028             m_current_completion = -1;
   1029             const String& line = m_line_editor.line();
   1030             m_completions = completer(context(), line,
   1031                                       line.byte_count_to(m_line_editor.cursor_pos()));
   1032             if (not context().has_client())
   1033                 return;
   1034             if (m_completions.candidates.empty())
   1035                 return context().client().menu_hide();
   1036 
   1037             show_completions();
   1038             const bool menu = (bool)(m_completions.flags & Completions::Flags::Menu);
   1039             if (menu)
   1040                 context().client().menu_select(0);
   1041             auto prefix = line.substr(m_completions.start, m_completions.end - m_completions.start);
   1042             m_prefix_in_completions = not menu and not contains(m_completions.candidates, prefix);
   1043             if (m_prefix_in_completions)
   1044             {
   1045                 m_current_completion = m_completions.candidates.size();
   1046                 m_completions.candidates.push_back(prefix.str());
   1047             }
   1048         } catch (runtime_error&) {}
   1049     }
   1050 
   1051     void show_completions()
   1052     {
   1053         Vector<DisplayLine> items;
   1054         for (auto& candidate : m_completions.candidates)
   1055             items.push_back({ candidate, {} });
   1056 
   1057         const auto menu_style = (m_flags & PromptFlags::Search) ? MenuStyle::Search : MenuStyle::Prompt;
   1058         context().client().menu_show(std::move(items), {}, menu_style);
   1059     }
   1060 
   1061     void clear_completions()
   1062     {
   1063         m_current_completion = -1;
   1064         m_completions.candidates.clear();
   1065     }
   1066 
   1067     void display()
   1068     {
   1069         if (not context().has_client())
   1070             return;
   1071 
   1072         auto width = context().client().dimensions().column - m_prompt.column_length();
   1073         DisplayLine display_line;
   1074         if (not (m_flags & PromptFlags::Password))
   1075             display_line = m_line_editor.build_display_line(width);
   1076 
   1077         auto status_style = (m_flags & PromptFlags::Search)  ? StatusStyle::Search
   1078                            : (m_flags & PromptFlags::Command) ? StatusStyle::Command
   1079                            : StatusStyle::Prompt;
   1080         context().print_status({m_prompt, m_prompt_face}, display_line, m_line_editor.cursor_display_column(), status_style);
   1081     }
   1082 
   1083     void on_enabled(bool from_pop) override
   1084     {
   1085         display();
   1086         if (from_pop)
   1087         {
   1088             if (context().has_client() and not m_completions.candidates.empty())
   1089             {
   1090                 show_completions();
   1091                 const bool menu = (bool)(m_completions.flags & Completions::Flags::Menu);
   1092                 if (m_current_completion != -1)
   1093                     context().client().menu_select(m_current_completion);
   1094                 else if (menu)
   1095                     context().client().menu_select(0);
   1096             }
   1097         }
   1098 
   1099         if (not (context().flags() & Context::Flags::Draft))
   1100             m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
   1101     }
   1102 
   1103     void on_disabled(bool from_push) override
   1104     {
   1105         if (not from_push)
   1106             context().print_status({});
   1107 
   1108         m_idle_timer.disable();
   1109         if (context().has_client())
   1110             context().client().menu_hide();
   1111     }
   1112 
   1113     PromptCallback  m_callback;
   1114     PromptCompleter m_completer;
   1115     PromptCompleter m_explicit_completer;
   1116     const String   m_prompt;
   1117     Face           m_prompt_face;
   1118     Completions    m_completions;
   1119     int            m_current_completion = -1;
   1120     bool           m_prefix_in_completions = false;
   1121     String         m_prefix;
   1122     String         m_empty_text;
   1123     LineEditor     m_line_editor;
   1124     bool           m_line_changed = false;
   1125     PromptFlags    m_flags;
   1126     bool           m_was_interactive = false;
   1127     Register&      m_history;
   1128     int            m_current_history;
   1129     bool           m_auto_complete;
   1130     bool           m_refresh_completion_pending = true;
   1131     Timer          m_idle_timer;
   1132 
   1133     void history_push(StringView entry)
   1134     {
   1135         if (entry.empty() or not m_was_interactive or
   1136             (m_flags & PromptFlags::DropHistoryEntriesWithBlankPrefix and
   1137              is_horizontal_blank(entry[0_byte])))
   1138             return;
   1139 
   1140         m_history.set(context(), {entry.str()});
   1141     }
   1142 };
   1143 
   1144 class NextKey : public InputMode
   1145 {
   1146 public:
   1147     NextKey(InputHandler& input_handler, String name, KeymapMode keymap_mode, KeyCallback callback,
   1148             Timer::Callback idle_callback)
   1149         : InputMode(input_handler), m_name{std::move(name)}, m_callback(std::move(callback)), m_keymap_mode(keymap_mode),
   1150           m_idle_timer{Clock::now() + get_idle_timeout(context()), std::move(idle_callback)} {}
   1151 
   1152     void on_key(Key key) override
   1153     {
   1154         // maintain hooks disabled in the callback if they were before pop_mode
   1155         ScopedSetBool disable_hooks(context().hooks_disabled(),
   1156                                     context().hooks_disabled());
   1157         pop_mode();
   1158         m_callback(key, context());
   1159     }
   1160 
   1161     ModeInfo mode_info() const override
   1162     {
   1163         return {{ "enter key", context().faces()["StatusLineMode"] }, {}};
   1164     }
   1165 
   1166     KeymapMode keymap_mode() const override { return m_keymap_mode; }
   1167 
   1168     StringView name() const override { return m_name; }
   1169 
   1170 private:
   1171     String         m_name;
   1172     KeyCallback    m_callback;
   1173     KeymapMode     m_keymap_mode;
   1174     Timer          m_idle_timer;
   1175 };
   1176 
   1177 class Insert : public InputMode
   1178 {
   1179 public:
   1180     Insert(InputHandler& input_handler, InsertMode mode, int count, Insertion* last_insert)
   1181         : InputMode(input_handler),
   1182           m_edition(context()),
   1183           m_selection_edition(context()),
   1184           m_completer(context()),
   1185           m_last_insert(last_insert),
   1186           m_restore_cursor(mode == InsertMode::Append),
   1187           m_auto_complete{context().options()["autocomplete"].get<AutoComplete>() & AutoComplete::Insert},
   1188           m_idle_timer{TimePoint::max(), context().flags() & Context::Flags::Draft ?
   1189                        Timer::Callback{} : [this](Timer&) {
   1190                            RefPtr<InputMode> keep_alive{this}; // hook could trigger pop_mode()
   1191                            if (context().has_client())
   1192                                context().client().clear_pending();
   1193                            m_completer.update(m_auto_complete);
   1194                            context().hooks().run_hook(Hook::InsertIdle, "", context());
   1195                        }},
   1196           m_disable_hooks{context().hooks_disabled(), context().hooks_disabled()}
   1197     {
   1198         context().buffer().throw_if_read_only();
   1199 
   1200         if (m_last_insert)
   1201         {
   1202             m_last_insert->recording.set();
   1203             m_last_insert->mode = mode;
   1204             m_last_insert->keys.clear();
   1205             m_last_insert->disable_hooks = context().hooks_disabled();
   1206             m_last_insert->count = count;
   1207         }
   1208         prepare(mode, count);
   1209     }
   1210 
   1211     void on_enabled(bool from_pop) override
   1212     {
   1213         if (not (context().flags() & Context::Flags::Draft))
   1214             m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
   1215     }
   1216 
   1217     void on_disabled(bool from_push) override
   1218     {
   1219         m_idle_timer.disable();
   1220 
   1221         if (not from_push)
   1222         {
   1223             if (m_last_insert)
   1224                 m_last_insert->recording.unset();
   1225 
   1226             auto& selections = context().selections();
   1227             if (m_restore_cursor)
   1228             {
   1229                 for (auto& sel : selections)
   1230                 {
   1231                     if (sel.cursor() > sel.anchor() and sel.cursor() > BufferCoord{0, 0})
   1232                         sel.cursor() = context().buffer().char_prev(sel.cursor());
   1233                 }
   1234             }
   1235         }
   1236     }
   1237 
   1238     void on_key(Key key) override
   1239     {
   1240         auto& buffer = context().buffer();
   1241 
   1242         const bool transient = context().flags() & Context::Flags::Draft;
   1243         bool update_completions = true;
   1244         bool moved = false;
   1245         if (m_mouse_handler.handle_key(key, context()))
   1246         {
   1247             if (not transient)
   1248                 m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
   1249         }
   1250         else if (key == Key::Escape or key == ctrl('c'))
   1251         {
   1252             m_completer.reset();
   1253             pop_mode();
   1254         }
   1255         else if (key == Key::Backspace or key == shift(Key::Backspace))
   1256         {
   1257             Vector<Selection> sels;
   1258             for (auto& sel : context().selections())
   1259             {
   1260                 if (sel.cursor() == BufferCoord{0,0})
   1261                     continue;
   1262                 auto pos = sel.cursor();
   1263                 sels.emplace_back(buffer.char_prev(pos));
   1264             }
   1265             auto& main = context().selections().main();
   1266             String main_char;
   1267             if (main.cursor() != BufferCoord{0, 0})
   1268                 main_char = buffer.string(buffer.char_prev(main.cursor()),
   1269                                           main.cursor());
   1270             if (not sels.empty())
   1271                 SelectionList{buffer, std::move(sels)}.erase();
   1272 
   1273             if (not main_char.empty())
   1274                 context().hooks().run_hook(Hook::InsertDelete, main_char, context());
   1275 
   1276             context().selections_write_only().update(false);
   1277         }
   1278         else if (key == Key::Delete)
   1279         {
   1280             Vector<Selection> sels;
   1281             for (auto& sel : context().selections())
   1282                 sels.emplace_back(sel.cursor());
   1283             SelectionList{buffer, std::move(sels)}.erase();
   1284         }
   1285         else if (key == Key::Left)
   1286         {
   1287             move(-1_char);
   1288             moved = true;
   1289         }
   1290         else if (key == Key::Right)
   1291         {
   1292             move(1_char);
   1293             moved = true;
   1294         }
   1295         else if (key == Key::Up)
   1296         {
   1297             move(-1_line);
   1298             moved = true;
   1299         }
   1300         else if (key == Key::Down)
   1301         {
   1302             move(1_line);
   1303             moved = true;
   1304         }
   1305         else if (key == Key::Home)
   1306         {
   1307             auto& selections = context().selections();
   1308             for (auto& sel : selections)
   1309                 sel.anchor() = sel.cursor() = BufferCoord{sel.cursor().line, 0};
   1310             selections.sort_and_merge_overlapping();
   1311         }
   1312         else if (key == Key::End)
   1313         {
   1314             auto& buffer = context().buffer();
   1315             auto& selections = context().selections();
   1316             for (auto& sel : selections)
   1317             {
   1318                 const LineCount line = sel.cursor().line;
   1319                 sel.anchor() = sel.cursor() = buffer.clamp({line, buffer[line].length()});
   1320             }
   1321             selections.sort_and_merge_overlapping();
   1322         }
   1323         else if (auto cp = key.codepoint())
   1324         {
   1325             m_completer.try_accept();
   1326             insert(*cp);
   1327         }
   1328         else if (key == ctrl('r'))
   1329         {
   1330             m_completer.try_accept();
   1331             on_next_key_with_autoinfo(context(), "register", KeymapMode::None,
   1332                 [this](Key key, Context&) {
   1333                     auto cp = key.codepoint();
   1334                     if (not cp or key == Key::Escape)
   1335                         return;
   1336                     insert(RegisterManager::instance()[*cp].get(context()));
   1337                 }, "enter register name", register_doc.str());
   1338             update_completions = false;
   1339         }
   1340         else if (key == ctrl('n') or key == ctrl('p') or key.modifiers == Key::Modifiers::MenuSelect)
   1341         {
   1342             drop_last_recorded_key();
   1343             bool relative = key.modifiers != Key::Modifiers::MenuSelect;
   1344             int index = relative ? (key == ctrl('n') ? 1 : -1) : key.key;
   1345             m_completer.select(index, relative, [&](Key key) { record_key(key); });
   1346             update_completions = false;
   1347         }
   1348         else if (key == ctrl('x'))
   1349         {
   1350             on_next_key_with_autoinfo(context(), "explicit-completion", KeymapMode::None,
   1351                 [this](Key key, Context&) {
   1352                     if (key.key == 'f')
   1353                         m_completer.explicit_file_complete();
   1354                     if (key.key == 'w')
   1355                         m_completer.explicit_word_buffer_complete();
   1356                     if (key.key == 'W')
   1357                         m_completer.explicit_word_all_complete();
   1358                     if (key.key == 'l')
   1359                         m_completer.explicit_line_buffer_complete();
   1360                     if (key.key == 'L')
   1361                         m_completer.explicit_line_all_complete();
   1362             }, "enter completion type",
   1363             "f: filename\n"
   1364             "w: word (current buffer)\n"
   1365             "W: word (all buffers)\n"
   1366             "l: line (current buffer)\n"
   1367             "L: line (all buffers)\n");
   1368             update_completions = false;
   1369         }
   1370         else if (key == ctrl('o'))
   1371         {
   1372             m_auto_complete = not m_auto_complete;
   1373             m_completer.reset();
   1374         }
   1375         else if (key == ctrl('u'))
   1376         {
   1377             context().buffer().commit_undo_group();
   1378             context().print_status({ format("committed change #{}",
   1379                                             (size_t)context().buffer().current_history_id()),
   1380                                      context().faces()["Information"] });
   1381         }
   1382         else if (key == ctrl('v'))
   1383         {
   1384             m_completer.try_accept();
   1385             on_next_key_with_autoinfo(context(), "raw-insert", KeymapMode::None,
   1386                 [this, transient](Key key, Context&) {
   1387                     if (auto cp = get_raw_codepoint(key))
   1388                     {
   1389                         insert(*cp);
   1390                         context().hooks().run_hook(Hook::InsertKey, to_string(key), context());
   1391                         if (enabled() and not transient)
   1392                             m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
   1393                     }
   1394                 }, "raw insert", "enter key to insert");
   1395             update_completions = false;
   1396         }
   1397         else if (key == alt(';'))
   1398         {
   1399             push_mode(new Normal(context().input_handler(), true));
   1400             return;
   1401         }
   1402 
   1403         context().hooks().run_hook(Hook::InsertKey, to_string(key), context());
   1404         if (moved)
   1405             context().hooks().run_hook(Hook::InsertMove, to_string(key), context());
   1406 
   1407         if (update_completions and enabled() and not transient) // Hooks might have disabled us
   1408             m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
   1409     }
   1410 
   1411     void paste(StringView content) override
   1412     {
   1413         m_completer.try_accept();
   1414         insert(ConstArrayView<StringView>{content});
   1415         m_idle_timer.set_next_date(Clock::now() + get_idle_timeout(context()));
   1416     }
   1417 
   1418     ModeInfo mode_info() const override
   1419     {
   1420         auto num_sel = context().selections().size();
   1421         auto main_index = context().selections().main_index();
   1422         return {{AtomList{ { "insert", context().faces()["StatusLineMode"] },
   1423                            { " ", context().faces()["StatusLine"] },
   1424                            { num_sel == 1 ? format("{} sel", num_sel)
   1425                                : format("{} sels ({})", num_sel, main_index + 1),
   1426                              context().faces()["StatusLineInfo"] } }},
   1427                 {}};
   1428     }
   1429 
   1430     KeymapMode keymap_mode() const override { return KeymapMode::Insert; }
   1431 
   1432     StringView name() const override { return "insert"; }
   1433 
   1434 private:
   1435     template<typename Type>
   1436     void move(Type offset)
   1437     {
   1438         auto& selections = context().selections();
   1439         const ColumnCount tabstop = context().options()["tabstop"].get<int>();
   1440         for (auto& sel : selections)
   1441         {
   1442             auto cursor = context().buffer().offset_coord(sel.cursor(), offset, tabstop);
   1443             sel.anchor() = sel.cursor() = cursor;
   1444         }
   1445         selections.sort_and_merge_overlapping();
   1446     }
   1447 
   1448     template<typename S>
   1449     void insert(ConstArrayView<S> strings)
   1450     {
   1451         kak_assert(not m_completer.has_candidate_selected());
   1452         context().selections().for_each([strings, &buffer=context().buffer()]
   1453                                         (size_t index, Selection& sel) {
   1454             Kakoune::insert(buffer, sel, sel.cursor(), strings[std::min(strings.size()-1, index)]);
   1455         }, false);
   1456     }
   1457 
   1458     void insert(Codepoint key)
   1459     {
   1460         String str{key};
   1461         insert(ConstArrayView<String>{str});
   1462         context().hooks().run_hook(Hook::InsertChar, str, context());
   1463     }
   1464 
   1465     void prepare(InsertMode mode, int count)
   1466     {
   1467         SelectionList& selections = context().selections();
   1468         Buffer& buffer = context().buffer();
   1469 
   1470         switch (mode)
   1471         {
   1472         case InsertMode::Insert:
   1473             for (auto& sel : selections)
   1474                 sel.set(sel.max(), sel.min());
   1475             break;
   1476         case InsertMode::Replace:
   1477             selections.erase();
   1478             break;
   1479         case InsertMode::Append:
   1480             for (auto& sel : selections)
   1481             {
   1482                 sel.set(sel.min(),  buffer.char_next(sel.max()));
   1483                 if (sel.cursor() == buffer.end_coord())
   1484                     buffer.insert(buffer.end_coord(), "\n");
   1485             }
   1486             break;
   1487         case InsertMode::AppendAtLineEnd:
   1488             for (auto& sel : selections)
   1489                 sel.set({sel.max().line, buffer[sel.max().line].length() - 1});
   1490             break;
   1491         case InsertMode::OpenLineBelow:
   1492         {
   1493             Vector<Selection> new_sels;
   1494             count = count > 0 ? count : 1;
   1495             LineCount inserted_count = 0;
   1496             for (auto sel : selections)
   1497             {
   1498                 buffer.insert(sel.max().line + inserted_count + 1,
   1499                               String{'\n', CharCount{count}});
   1500                 for (int i = 0; i < count; ++i)
   1501                     new_sels.push_back(BufferCoord{sel.max().line + inserted_count + i + 1});
   1502                 inserted_count += count;
   1503             }
   1504             selections.set(std::move(new_sels),
   1505                            selections.main_index() * count + count - 1);
   1506             context().hooks().run_hook(Hook::InsertChar, "\n", context());
   1507             break;
   1508         }
   1509         case InsertMode::OpenLineAbove:
   1510         {
   1511             Vector<Selection> new_sels;
   1512             count = count > 0 ? count : 1;
   1513             LineCount inserted_count = 0;
   1514             for (auto sel : selections)
   1515             {
   1516                 buffer.insert(sel.min().line + inserted_count,
   1517                               String{'\n', CharCount{count}});
   1518                 for (int i = 0; i < count; ++i)
   1519                     new_sels.push_back(BufferCoord{sel.min().line + inserted_count + i});
   1520                 inserted_count += count;
   1521             }
   1522             selections.set(std::move(new_sels),
   1523                            selections.main_index() * count + count - 1);
   1524             context().hooks().run_hook(Hook::InsertChar, "\n", context());
   1525             break;
   1526         }
   1527         case InsertMode::InsertAtLineBegin:
   1528             for (auto& sel : selections)
   1529             {
   1530                 BufferCoord pos = sel.min().line;
   1531                 auto pos_non_blank = buffer.iterator_at(pos);
   1532                 while (*pos_non_blank == ' ' or *pos_non_blank == '\t')
   1533                     ++pos_non_blank;
   1534                 if (*pos_non_blank != '\n')
   1535                     pos = pos_non_blank.coord();
   1536                 sel.set(pos);
   1537             }
   1538             break;
   1539         }
   1540         selections.check_invariant();
   1541         buffer.check_invariant();
   1542     }
   1543 
   1544     ScopedEdition   m_edition;
   1545     ScopedSelectionEdition m_selection_edition;
   1546     InsertCompleter m_completer;
   1547     Insertion*      m_last_insert;
   1548     const bool      m_restore_cursor;
   1549     bool            m_auto_complete;
   1550     Timer           m_idle_timer;
   1551     MouseHandler    m_mouse_handler;
   1552     ScopedSetBool   m_disable_hooks;
   1553 };
   1554 
   1555 }
   1556 
   1557 InputHandler::InputHandler(SelectionList selections, Context::Flags flags, String name)
   1558     : m_context(*this, std::move(selections), flags, std::move(name))
   1559 {
   1560     m_mode_stack.emplace_back(new InputModes::Normal(*this));
   1561     current_mode().on_enabled(false);
   1562 }
   1563 
   1564 InputHandler::~InputHandler() = default;
   1565 
   1566 void InputHandler::push_mode(InputMode* new_mode)
   1567 {
   1568     StringView prev_name = current_mode().name();
   1569 
   1570     current_mode().on_disabled(true);
   1571     m_mode_stack.emplace_back(new_mode);
   1572     new_mode->on_enabled(false);
   1573 
   1574     context().hooks().run_hook(Hook::ModeChange, format("push:{}:{}", prev_name, new_mode->name()), context());
   1575 }
   1576 
   1577 void InputHandler::pop_mode(InputMode* mode)
   1578 {
   1579     kak_assert(m_mode_stack.back().get() == mode);
   1580     kak_assert(m_mode_stack.size() > 1);
   1581 
   1582     RefPtr<InputMode> keep_alive{mode}; // Ensure prev_name stays valid
   1583     StringView prev_name = mode->name();
   1584 
   1585     current_mode().on_disabled(false);
   1586     m_mode_stack.pop_back();
   1587     current_mode().on_enabled(true);
   1588 
   1589     context().hooks().run_hook(Hook::ModeChange, format("pop:{}:{}", prev_name, current_mode().name()), context());
   1590 }
   1591 
   1592 void InputHandler::reset_normal_mode()
   1593 {
   1594     kak_assert(dynamic_cast<InputModes::Normal*>(m_mode_stack[0].get()) != nullptr);
   1595     if (m_mode_stack.size() == 1)
   1596         return;
   1597 
   1598     while (m_mode_stack.size() > 1)
   1599         pop_mode(m_mode_stack.back().get());
   1600 }
   1601 
   1602 void InputHandler::insert(InsertMode mode, int count)
   1603 {
   1604     push_mode(new InputModes::Insert(*this, mode, count, m_handle_key_level <= 1 ? &m_last_insert : nullptr));
   1605 }
   1606 
   1607 void InputHandler::repeat_last_insert()
   1608 {
   1609     if (m_last_insert.keys.empty())
   1610         return;
   1611 
   1612     if (dynamic_cast<InputModes::Normal*>(&current_mode()) == nullptr or
   1613         m_last_insert.recording or m_last_insert.repeating)
   1614         throw runtime_error{"repeating last insert not available in this context"};
   1615 
   1616     ScopedSetBool disable_hooks(context().hooks_disabled(),
   1617                                 m_last_insert.disable_hooks);
   1618     m_last_insert.repeating = true;
   1619     OnScopeEnd stop_repeating = [&] { m_last_insert.repeating = false; };
   1620 
   1621     push_mode(new InputModes::Insert(*this, m_last_insert.mode, m_last_insert.count, nullptr));
   1622     for (auto& key : m_last_insert.keys)
   1623         handle_key(key);
   1624     kak_assert(dynamic_cast<InputModes::Normal*>(&current_mode()) != nullptr);
   1625 }
   1626 
   1627 void InputHandler::paste(StringView content)
   1628 {
   1629     current_mode().paste(content);
   1630 }
   1631 
   1632 void InputHandler::prompt(StringView prompt, String initstr, String emptystr,
   1633                           Face prompt_face, PromptFlags flags, char history_register,
   1634                           PromptCompleter completer, PromptCallback callback)
   1635 {
   1636     push_mode(new InputModes::Prompt(*this, prompt, std::move(initstr), std::move(emptystr),
   1637                                      prompt_face, flags, history_register,
   1638                                      std::move(completer), std::move(callback)));
   1639 }
   1640 
   1641 void InputHandler::set_prompt_face(Face prompt_face)
   1642 {
   1643     if (auto* prompt = dynamic_cast<InputModes::Prompt*>(&current_mode()))
   1644         prompt->set_prompt_face(prompt_face);
   1645 }
   1646 
   1647 void InputHandler::on_next_key(StringView mode_name, KeymapMode keymap_mode, KeyCallback callback,
   1648                                Timer::Callback idle_callback)
   1649 {
   1650     push_mode(new InputModes::NextKey(*this, format("next-key[{}]", mode_name), keymap_mode, std::move(callback),
   1651                                       std::move(idle_callback)));
   1652 }
   1653 
   1654 InputHandler::ScopedForceNormal::ScopedForceNormal(InputHandler& handler, NormalParams params)
   1655     : m_handler(handler), m_mode(nullptr)
   1656 {
   1657     if (handler.m_mode_stack.size() != 1)
   1658     {
   1659         handler.push_mode(new InputModes::Normal(handler));
   1660         m_mode = handler.m_mode_stack.back().get();
   1661     }
   1662 
   1663     static_cast<InputModes::Normal*>(handler.m_mode_stack.back().get())->m_params = params;
   1664 }
   1665 
   1666 InputHandler::ScopedForceNormal::~ScopedForceNormal()
   1667 {
   1668     if (not m_mode)
   1669         return;
   1670 
   1671     if (m_mode == m_handler.m_mode_stack.back().get())
   1672         m_handler.pop_mode(m_mode);
   1673     else if (auto it = find(m_handler.m_mode_stack, m_mode);
   1674              it != m_handler.m_mode_stack.end())
   1675         m_handler.m_mode_stack.erase(it);
   1676 }
   1677 
   1678 static bool is_valid(Key key)
   1679 {
   1680     constexpr Key::Modifiers valid_mods = (Key::Modifiers::Control | Key::Modifiers::Alt | Key::Modifiers::Shift);
   1681 
   1682     return ((key.modifiers & ~valid_mods) or key.key <= 0x10FFFF);
   1683 }
   1684 
   1685 void InputHandler::handle_key(Key key, bool synthesized)
   1686 {
   1687     if (not is_valid(key))
   1688         return;
   1689 
   1690     ++m_handle_key_level;
   1691     auto dec = OnScopeEnd([this]{ --m_handle_key_level;} );
   1692 
   1693     if (not synthesized)
   1694         current_mode().on_raw_key();
   1695 
   1696     auto process_key = [this](Key k) {
   1697         record_key(k);
   1698         current_mode().handle_key(k);
   1699     };
   1700 
   1701     const auto keymap_mode = current_mode().keymap_mode();
   1702     KeymapManager& keymaps = m_context.keymaps();
   1703     if (auto* mapping = keymaps.get_mapping(key, keymap_mode);
   1704         mapping and not m_context.keymaps_disabled())
   1705     {
   1706         auto keys = mapping->keys; // copy to allow reentrant unmap
   1707         unsigned int count = mapping->atomic ? current_mode().take_pending_count() : 1;
   1708         while (count--)
   1709             for (auto& k : keys)
   1710                 process_key(k);
   1711     }
   1712     else
   1713         process_key(key);
   1714 
   1715     if (m_handle_key_level < m_recording_level)
   1716     {
   1717         write_to_debug_buffer("Macro recording started but not finished");
   1718         m_recording_reg = 0;
   1719         m_recording_level = -1;
   1720     }
   1721 }
   1722 
   1723 void InputHandler::record_key(Key key)
   1724 {
   1725     if (m_last_insert.recording and m_handle_key_level <= 1)
   1726         m_last_insert.keys.push_back(key);
   1727     if (is_recording() and m_handle_key_level == m_recording_level)
   1728         m_recorded_keys.push_back(key);
   1729 }
   1730 
   1731 void InputHandler::drop_last_recorded_key()
   1732 {
   1733     if (m_last_insert.recording and m_handle_key_level <= 1)
   1734     {
   1735         kak_assert(not m_last_insert.keys.empty());
   1736         m_last_insert.keys.pop_back();
   1737     }
   1738 
   1739     if (is_recording() and m_handle_key_level == m_recording_level)
   1740     {
   1741         kak_assert(not m_recorded_keys.empty());
   1742         m_recorded_keys.pop_back();
   1743     }
   1744 }
   1745 
   1746 void InputHandler::refresh_ifn()
   1747 {
   1748     current_mode().refresh_ifn();
   1749 }
   1750 
   1751 void InputHandler::start_recording(char reg)
   1752 {
   1753     kak_assert(m_recording_reg == 0);
   1754     m_recording_level = m_handle_key_level;
   1755     m_recorded_keys.clear();
   1756     m_recording_reg = reg;
   1757 }
   1758 
   1759 bool InputHandler::is_recording() const
   1760 {
   1761     return m_recording_reg != 0;
   1762 }
   1763 
   1764 void InputHandler::stop_recording()
   1765 {
   1766     kak_assert(m_recording_reg != 0);
   1767     if (not m_recorded_keys.empty())
   1768     {
   1769         // Forget the key that got us to exit recording
   1770         if (m_handle_key_level == m_recording_level)
   1771             m_recorded_keys.pop_back();
   1772 
   1773         String keys;
   1774         for (auto& key : m_recorded_keys)
   1775             keys += to_string(key);
   1776         RegisterManager::instance()[m_recording_reg].set(context(), {keys});
   1777     }
   1778 
   1779     m_recording_reg = 0;
   1780     m_recording_level = -1;
   1781 }
   1782 
   1783 ModeInfo InputHandler::mode_info() const
   1784 {
   1785     return current_mode().mode_info();
   1786 }
   1787 
   1788 bool should_show_info(AutoInfo mask, const Context& context)
   1789 {
   1790   return (context.options()["autoinfo"].get<AutoInfo>() & mask) and context.has_client();
   1791 }
   1792 
   1793 bool show_auto_info_ifn(StringView title, StringView info, AutoInfo mask, const Context& context)
   1794 {
   1795     if (not should_show_info(mask, context))
   1796         return false;
   1797 
   1798     context.client().info_show(title.str(), info.str(), {}, InfoStyle::Prompt);
   1799     return true;
   1800 }
   1801 
   1802 void hide_auto_info_ifn(const Context& context, bool hide)
   1803 {
   1804     if (hide)
   1805         context.client().info_hide();
   1806 }
   1807 
   1808 void scroll_window(Context& context, LineCount offset, OnHiddenCursor on_hidden_cursor)
   1809 {
   1810     Window& window = context.window();
   1811     Buffer& buffer = context.buffer();
   1812     const LineCount line_count = buffer.line_count();
   1813 
   1814     DisplayCoord win_pos = window.position();
   1815     DisplayCoord win_dim = window.dimensions();
   1816 
   1817     if (on_hidden_cursor == OnHiddenCursor::PreserveSelections)
   1818         context.ensure_cursor_visible = false;
   1819 
   1820     if ((offset < 0 and win_pos.line == 0) or (offset > 0 and win_pos.line == line_count - 1))
   1821         return;
   1822 
   1823     const DisplayCoord max_offset{(win_dim.line - 1)/2, (win_dim.column - 1)/2};
   1824     const DisplayCoord scrolloff =
   1825         std::min(context.options()["scrolloff"].get<DisplayCoord>(), max_offset);
   1826 
   1827     win_pos.line = clamp(win_pos.line + offset, 0_line, line_count-1);
   1828 
   1829     window.set_position(win_pos);
   1830     if (on_hidden_cursor != OnHiddenCursor::PreserveSelections)
   1831     {
   1832         ScopedSelectionEdition selection_edition{context};
   1833         SelectionList& selections = context.selections();
   1834         Selection& main_selection = selections.main();
   1835         const BufferCoord anchor = main_selection.anchor();
   1836         const BufferCoordAndTarget cursor = main_selection.cursor();
   1837 
   1838         auto cursor_off = win_pos.line - window.position().line;
   1839 
   1840         auto line = clamp(cursor.line + cursor_off, win_pos.line + scrolloff.line,
   1841                           win_pos.line + win_dim.line - 1 - scrolloff.line);
   1842 
   1843         const ColumnCount tabstop = context.options()["tabstop"].get<int>();
   1844         auto new_cursor = buffer.offset_coord(cursor, line - cursor.line, tabstop);
   1845 
   1846         main_selection = {on_hidden_cursor == OnHiddenCursor::MoveCursor ? anchor : new_cursor, new_cursor};
   1847 
   1848         selections.sort_and_merge_overlapping();
   1849     }
   1850 }
   1851 
   1852 }