Editor.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/BinarySearch.h>
  9. #include <AK/ByteBuffer.h>
  10. #include <AK/ByteString.h>
  11. #include <AK/Function.h>
  12. #include <AK/HashMap.h>
  13. #include <AK/OwnPtr.h>
  14. #include <AK/RedBlackTree.h>
  15. #include <AK/Result.h>
  16. #include <AK/Traits.h>
  17. #include <AK/Utf32View.h>
  18. #include <AK/Utf8View.h>
  19. #include <AK/Vector.h>
  20. #include <LibCore/DirIterator.h>
  21. #include <LibCore/EventLoop.h>
  22. #include <LibCore/EventReceiver.h>
  23. #include <LibCore/Notifier.h>
  24. #include <LibLine/KeyCallbackMachine.h>
  25. #include <LibLine/Span.h>
  26. #include <LibLine/StringMetrics.h>
  27. #include <LibLine/Style.h>
  28. #include <LibLine/SuggestionDisplay.h>
  29. #include <LibLine/SuggestionManager.h>
  30. #include <LibLine/VT.h>
  31. #include <sys/ioctl.h>
  32. #include <sys/stat.h>
  33. #include <termios.h>
  34. namespace Line {
  35. struct KeyBinding {
  36. Vector<Key> keys;
  37. enum class Kind {
  38. InternalFunction,
  39. Insertion,
  40. } kind { Kind::InternalFunction };
  41. ByteString binding;
  42. };
  43. struct Configuration {
  44. enum RefreshBehavior {
  45. Lazy,
  46. Eager,
  47. };
  48. enum OperationMode {
  49. Unset,
  50. Full,
  51. NoEscapeSequences,
  52. NonInteractive,
  53. };
  54. enum SignalHandler {
  55. WithSignalHandlers,
  56. NoSignalHandlers,
  57. };
  58. enum Flags : u32 {
  59. None = 0,
  60. BracketedPaste = 1,
  61. };
  62. struct DefaultTextEditor {
  63. ByteString command;
  64. };
  65. Configuration()
  66. {
  67. }
  68. template<typename Arg, typename... Rest>
  69. Configuration(Arg arg, Rest... rest)
  70. : Configuration(rest...)
  71. {
  72. set(arg);
  73. }
  74. void set(RefreshBehavior refresh) { refresh_behavior = refresh; }
  75. void set(OperationMode mode) { operation_mode = mode; }
  76. void set(SignalHandler mode) { m_signal_mode = mode; }
  77. void set(KeyBinding const& binding) { keybindings.append(binding); }
  78. void set(DefaultTextEditor editor) { m_default_text_editor = move(editor.command); }
  79. void set(Flags flags)
  80. {
  81. enable_bracketed_paste = flags & Flags::BracketedPaste;
  82. }
  83. static Configuration from_config(StringView libname = "line"sv);
  84. RefreshBehavior refresh_behavior { RefreshBehavior::Lazy };
  85. SignalHandler m_signal_mode { SignalHandler::WithSignalHandlers };
  86. OperationMode operation_mode { OperationMode::Unset };
  87. Vector<KeyBinding> keybindings;
  88. ByteString m_default_text_editor {};
  89. bool enable_bracketed_paste { false };
  90. };
  91. #define ENUMERATE_EDITOR_INTERNAL_FUNCTIONS(M) \
  92. M(clear_screen) \
  93. M(cursor_left_character) \
  94. M(cursor_left_word) \
  95. M(cursor_left_nonspace_word) \
  96. M(cursor_right_character) \
  97. M(cursor_right_word) \
  98. M(cursor_right_nonspace_word) \
  99. M(enter_search) \
  100. M(search_character_backwards) \
  101. M(search_character_forwards) \
  102. M(erase_character_backwards) \
  103. M(erase_character_forwards) \
  104. M(erase_to_beginning) \
  105. M(erase_to_end) \
  106. M(erase_word_backwards) \
  107. M(finish_edit) \
  108. M(go_end) \
  109. M(go_home) \
  110. M(kill_line) \
  111. M(search_backwards) \
  112. M(search_forwards) \
  113. M(transpose_characters) \
  114. M(transpose_words) \
  115. M(insert_last_words) \
  116. M(insert_last_erased) \
  117. M(erase_alnum_word_backwards) \
  118. M(erase_alnum_word_forwards) \
  119. M(erase_spaces) \
  120. M(capitalize_word) \
  121. M(lowercase_word) \
  122. M(uppercase_word) \
  123. M(edit_in_external_editor)
  124. #define EDITOR_INTERNAL_FUNCTION(name) \
  125. [](auto& editor) { editor.name(); return false; }
  126. class Editor : public Core::EventReceiver {
  127. C_OBJECT(Editor);
  128. public:
  129. enum class Error {
  130. ReadFailure,
  131. Empty,
  132. Eof,
  133. };
  134. ~Editor();
  135. Result<ByteString, Error> get_line(ByteString const& prompt);
  136. void initialize();
  137. void refetch_default_termios();
  138. void add_to_history(ByteString const& line);
  139. bool load_history(ByteString const& path);
  140. bool save_history(ByteString const& path);
  141. auto const& history() const { return m_history; }
  142. bool is_history_dirty() const { return m_history_dirty; }
  143. void register_key_input_callback(KeyBinding const&);
  144. void register_key_input_callback(Vector<Key> keys, Function<bool(Editor&)> callback) { m_callback_machine.register_key_input_callback(move(keys), move(callback)); }
  145. void register_key_input_callback(Key key, Function<bool(Editor&)> callback) { register_key_input_callback(Vector<Key> { key }, move(callback)); }
  146. static StringMetrics actual_rendered_string_metrics(StringView, RedBlackTree<u32, Optional<Style::Mask>> const& masks = {}, Optional<size_t> maximum_line_width = {});
  147. static StringMetrics actual_rendered_string_metrics(Utf32View const&, RedBlackTree<u32, Optional<Style::Mask>> const& masks = {}, Optional<size_t> maximum_line_width = {});
  148. Function<Vector<CompletionSuggestion>(Editor const&)> on_tab_complete;
  149. Function<void(Utf32View, Editor&)> on_paste;
  150. Function<void()> on_interrupt_handled;
  151. Function<void(Editor&)> on_display_refresh;
  152. static Function<bool(Editor&)> find_internal_function(StringView name);
  153. enum class CaseChangeOp {
  154. Lowercase,
  155. Uppercase,
  156. Capital,
  157. };
  158. void case_change_word(CaseChangeOp);
  159. #define __ENUMERATE_EDITOR_INTERNAL_FUNCTION(name) \
  160. void name();
  161. ENUMERATE_EDITOR_INTERNAL_FUNCTIONS(__ENUMERATE_EDITOR_INTERNAL_FUNCTION)
  162. #undef __ENUMERATE_EDITOR_INTERNAL_FUNCTION
  163. ErrorOr<void> interrupted();
  164. ErrorOr<void> resized();
  165. size_t cursor() const { return m_cursor; }
  166. void set_cursor(size_t cursor)
  167. {
  168. if (cursor > m_buffer.size())
  169. cursor = m_buffer.size();
  170. m_cursor = cursor;
  171. }
  172. Vector<u32, 1024> const& buffer() const { return m_buffer; }
  173. u32 buffer_at(size_t pos) const { return m_buffer.at(pos); }
  174. ByteString line() const { return line(m_buffer.size()); }
  175. ByteString line(size_t up_to_index) const;
  176. // Only makes sense inside a character_input callback or on_* callback.
  177. void set_prompt(ByteString const& prompt)
  178. {
  179. if (m_cached_prompt_valid)
  180. m_old_prompt_metrics = m_cached_prompt_metrics;
  181. m_cached_prompt_valid = false;
  182. m_cached_prompt_metrics = actual_rendered_string_metrics(prompt, {});
  183. m_new_prompt = prompt;
  184. }
  185. void clear_line();
  186. void insert(ByteString const&);
  187. void insert(StringView);
  188. void insert(Utf32View const&);
  189. void insert(const u32);
  190. void stylize(Span const&, Style const&);
  191. void strip_styles(bool strip_anchored = false);
  192. // Invariant Offset is an offset into the suggested data, hinting the editor what parts of the suggestion will not change
  193. // Static Offset is an offset into the token, signifying where the suggestions start
  194. // e.g.
  195. // foobar<suggestion initiated>, on_tab_complete returns "barx", "bary", "barz"
  196. // ^ ^
  197. // +-|- static offset: the suggestions start here
  198. // +- invariant offset: the suggestions do not change up to here
  199. //
  200. void transform_suggestion_offsets(size_t& invariant_offset, size_t& static_offset, Span::Mode offset_mode = Span::ByteOriented) const;
  201. const struct termios& termios() const { return m_termios; }
  202. const struct termios& default_termios() const { return m_default_termios; }
  203. struct winsize terminal_size() const
  204. {
  205. winsize ws { (u16)m_num_lines, (u16)m_num_columns, 0, 0 };
  206. return ws;
  207. }
  208. void finish()
  209. {
  210. m_finish = true;
  211. }
  212. bool is_editing() const { return m_is_editing; }
  213. const Utf32View buffer_view() const { return { m_buffer.data(), m_buffer.size() }; }
  214. auto prohibit_input()
  215. {
  216. auto previous_value = m_prohibit_input_processing;
  217. m_prohibit_input_processing = true;
  218. m_have_unprocessed_read_event = false;
  219. return ScopeGuard {
  220. [this, previous_value] {
  221. m_prohibit_input_processing = previous_value;
  222. if (!m_prohibit_input_processing && m_have_unprocessed_read_event)
  223. handle_read_event().release_value_but_fixme_should_propagate_errors();
  224. }
  225. };
  226. }
  227. private:
  228. explicit Editor(Configuration configuration = Configuration::from_config());
  229. void set_default_keybinds();
  230. enum LoopExitCode {
  231. Exit = 0,
  232. Retry
  233. };
  234. ErrorOr<void> try_update_once();
  235. void handle_interrupt_event();
  236. ErrorOr<void> handle_read_event();
  237. ErrorOr<void> handle_resize_event(bool reset_origin);
  238. void ensure_free_lines_from_origin(size_t count);
  239. Result<Vector<size_t, 2>, Error> vt_dsr();
  240. void remove_at_index(size_t);
  241. enum class ModificationKind {
  242. Insertion,
  243. Removal,
  244. ForcedOverlapRemoval,
  245. };
  246. void readjust_anchored_styles(size_t hint_index, ModificationKind);
  247. Style find_applicable_style(size_t offset) const;
  248. bool search(StringView, bool allow_empty = false, bool from_beginning = true);
  249. inline void end_search()
  250. {
  251. m_is_searching = false;
  252. m_refresh_needed = true;
  253. m_search_offset = 0;
  254. if (m_reset_buffer_on_search_end) {
  255. m_buffer.clear();
  256. for (auto ch : m_pre_search_buffer)
  257. m_buffer.append(ch);
  258. m_cursor = m_pre_search_cursor;
  259. }
  260. m_reset_buffer_on_search_end = true;
  261. m_search_editor = nullptr;
  262. }
  263. void reset()
  264. {
  265. m_cached_buffer_metrics.reset();
  266. m_cached_prompt_valid = false;
  267. m_cursor = 0;
  268. m_drawn_cursor = 0;
  269. m_inline_search_cursor = 0;
  270. m_search_offset = 0;
  271. m_search_offset_state = SearchOffsetState::Unbiased;
  272. m_old_prompt_metrics = m_cached_prompt_metrics;
  273. set_origin(0, 0);
  274. m_prompt_lines_at_suggestion_initiation = 0;
  275. m_refresh_needed = true;
  276. m_input_error.clear();
  277. m_returned_line = ByteString::empty();
  278. m_chars_touched_in_the_middle = 0;
  279. m_drawn_end_of_line_offset = 0;
  280. m_drawn_spans = {};
  281. m_paste_buffer.clear_with_capacity();
  282. }
  283. ErrorOr<void> refresh_display();
  284. ErrorOr<void> cleanup();
  285. ErrorOr<void> cleanup_suggestions();
  286. ErrorOr<void> really_quit_event_loop();
  287. void restore()
  288. {
  289. VERIFY(m_initialized);
  290. tcsetattr(0, TCSANOW, &m_default_termios);
  291. m_initialized = false;
  292. if (m_configuration.enable_bracketed_paste)
  293. warn("\x1b[?2004l");
  294. for (auto id : m_signal_handlers)
  295. Core::EventLoop::unregister_signal(id);
  296. }
  297. StringMetrics const& current_prompt_metrics() const
  298. {
  299. return m_cached_prompt_valid ? m_cached_prompt_metrics : m_old_prompt_metrics;
  300. }
  301. size_t num_lines() const
  302. {
  303. return current_prompt_metrics().lines_with_addition(m_cached_buffer_metrics, m_num_columns);
  304. }
  305. size_t cursor_line() const
  306. {
  307. auto cursor = m_drawn_cursor;
  308. if (cursor > m_cursor)
  309. cursor = m_cursor;
  310. return current_prompt_metrics().lines_with_addition(
  311. actual_rendered_string_metrics(buffer_view().substring_view(0, cursor), m_current_masks),
  312. m_num_columns);
  313. }
  314. size_t offset_in_line() const
  315. {
  316. auto cursor = m_drawn_cursor;
  317. if (cursor > m_cursor)
  318. cursor = m_cursor;
  319. auto buffer_metrics = actual_rendered_string_metrics(buffer_view().substring_view(0, cursor), m_current_masks);
  320. return current_prompt_metrics().offset_with_addition(buffer_metrics, m_num_columns);
  321. }
  322. bool set_origin(bool quit_on_error = true)
  323. {
  324. auto position = vt_dsr();
  325. if (!position.is_error()) {
  326. set_origin(position.value()[0], position.value()[1]);
  327. return true;
  328. }
  329. if (quit_on_error && position.is_error()) {
  330. m_input_error = position.error();
  331. finish();
  332. }
  333. return false;
  334. }
  335. void set_origin(int row, int col)
  336. {
  337. m_origin_row = row;
  338. m_origin_column = col;
  339. m_suggestion_display->set_origin(row, col, {});
  340. }
  341. void recalculate_origin();
  342. ErrorOr<void> reposition_cursor(Stream&, bool to_end = false);
  343. struct CodepointRange {
  344. size_t start { 0 };
  345. size_t end { 0 };
  346. };
  347. CodepointRange byte_offset_range_to_code_point_offset_range(size_t byte_start, size_t byte_end, size_t code_point_scan_offset, bool reverse = false) const;
  348. void get_terminal_size();
  349. bool m_finish { false };
  350. RefPtr<Editor> m_search_editor;
  351. bool m_is_searching { false };
  352. bool m_reset_buffer_on_search_end { true };
  353. size_t m_search_offset { 0 };
  354. enum class SearchOffsetState {
  355. Unbiased,
  356. Backwards,
  357. Forwards,
  358. } m_search_offset_state { SearchOffsetState::Unbiased };
  359. size_t m_pre_search_cursor { 0 };
  360. Vector<u32, 1024> m_pre_search_buffer;
  361. Vector<u32, 1024> m_buffer;
  362. ByteBuffer m_pending_chars;
  363. Vector<char, 512> m_incomplete_data;
  364. Optional<Error> m_input_error;
  365. ByteString m_returned_line;
  366. size_t m_cursor { 0 };
  367. size_t m_drawn_cursor { 0 };
  368. size_t m_drawn_end_of_line_offset { 0 };
  369. size_t m_inline_search_cursor { 0 };
  370. size_t m_chars_touched_in_the_middle { 0 };
  371. size_t m_times_tab_pressed { 0 };
  372. size_t m_num_columns { 0 };
  373. size_t m_num_lines { 1 };
  374. size_t m_previous_num_columns { 0 };
  375. size_t m_extra_forward_lines { 0 };
  376. size_t m_shown_lines { 0 };
  377. StringMetrics m_cached_prompt_metrics;
  378. StringMetrics m_old_prompt_metrics;
  379. StringMetrics m_cached_buffer_metrics;
  380. size_t m_prompt_lines_at_suggestion_initiation { 0 };
  381. bool m_cached_prompt_valid { false };
  382. // Exact position before our prompt in the terminal.
  383. size_t m_origin_row { 0 };
  384. size_t m_origin_column { 0 };
  385. bool m_expected_origin_changed { false };
  386. bool m_has_origin_reset_scheduled { false };
  387. OwnPtr<SuggestionDisplay> m_suggestion_display;
  388. Vector<u32, 32> m_remembered_suggestion_static_data;
  389. ByteString m_new_prompt;
  390. SuggestionManager m_suggestion_manager;
  391. bool m_always_refresh { false };
  392. enum class TabDirection {
  393. Forward,
  394. Backward,
  395. };
  396. TabDirection m_tab_direction { TabDirection::Forward };
  397. KeyCallbackMachine m_callback_machine;
  398. struct termios m_termios {
  399. };
  400. struct termios m_default_termios {
  401. };
  402. bool m_was_interrupted { false };
  403. bool m_previous_interrupt_was_handled_as_interrupt { true };
  404. bool m_was_resized { false };
  405. // FIXME: This should be something more take_first()-friendly.
  406. struct HistoryEntry {
  407. ByteString entry;
  408. time_t timestamp;
  409. };
  410. Vector<HistoryEntry> m_history;
  411. size_t m_history_cursor { 0 };
  412. size_t m_history_capacity { 1024 };
  413. bool m_history_dirty { false };
  414. static ErrorOr<Vector<HistoryEntry>> try_load_history(StringView path);
  415. enum class InputState {
  416. Free,
  417. Verbatim,
  418. Paste,
  419. GotEscape,
  420. CSIExpectParameter,
  421. CSIExpectIntermediate,
  422. CSIExpectFinal,
  423. };
  424. InputState m_state { InputState::Free };
  425. InputState m_previous_free_state { InputState::Free };
  426. struct Spans {
  427. HashMap<u32, HashMap<u32, Style>> m_spans_starting;
  428. HashMap<u32, HashMap<u32, Style>> m_spans_ending;
  429. HashMap<u32, HashMap<u32, Style>> m_anchored_spans_starting;
  430. HashMap<u32, HashMap<u32, Style>> m_anchored_spans_ending;
  431. bool contains_up_to_offset(Spans const& other, size_t offset) const;
  432. } m_drawn_spans, m_current_spans;
  433. RedBlackTree<u32, Optional<Style::Mask>> m_current_masks;
  434. RefPtr<Core::Notifier> m_notifier;
  435. Vector<u32> m_paste_buffer;
  436. Vector<u32> m_last_erased;
  437. bool m_initialized { false };
  438. bool m_refresh_needed { false };
  439. Vector<int, 2> m_signal_handlers;
  440. bool m_is_editing { false };
  441. bool m_prohibit_input_processing { false };
  442. bool m_have_unprocessed_read_event { false };
  443. Configuration m_configuration;
  444. };
  445. }