Editor.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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/DeprecatedString.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/Notifier.h>
  23. #include <LibCore/Object.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. DeprecatedString 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. DeprecatedString 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. DeprecatedString 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_right_character) \
  96. M(cursor_right_word) \
  97. M(enter_search) \
  98. M(erase_character_backwards) \
  99. M(erase_character_forwards) \
  100. M(erase_to_beginning) \
  101. M(erase_to_end) \
  102. M(erase_word_backwards) \
  103. M(finish_edit) \
  104. M(go_end) \
  105. M(go_home) \
  106. M(kill_line) \
  107. M(search_backwards) \
  108. M(search_forwards) \
  109. M(transpose_characters) \
  110. M(transpose_words) \
  111. M(insert_last_words) \
  112. M(erase_alnum_word_backwards) \
  113. M(erase_alnum_word_forwards) \
  114. M(capitalize_word) \
  115. M(lowercase_word) \
  116. M(uppercase_word) \
  117. M(edit_in_external_editor)
  118. #define EDITOR_INTERNAL_FUNCTION(name) \
  119. [](auto& editor) { editor.name(); return false; }
  120. class Editor : public Core::Object {
  121. C_OBJECT(Editor);
  122. public:
  123. enum class Error {
  124. ReadFailure,
  125. Empty,
  126. Eof,
  127. };
  128. ~Editor();
  129. Result<DeprecatedString, Error> get_line(DeprecatedString const& prompt);
  130. void initialize();
  131. void refetch_default_termios();
  132. void add_to_history(DeprecatedString const& line);
  133. bool load_history(DeprecatedString const& path);
  134. bool save_history(DeprecatedString const& path);
  135. auto const& history() const { return m_history; }
  136. bool is_history_dirty() const { return m_history_dirty; }
  137. void register_key_input_callback(KeyBinding const&);
  138. void register_key_input_callback(Vector<Key> keys, Function<bool(Editor&)> callback) { m_callback_machine.register_key_input_callback(move(keys), move(callback)); }
  139. void register_key_input_callback(Key key, Function<bool(Editor&)> callback) { register_key_input_callback(Vector<Key> { key }, move(callback)); }
  140. static StringMetrics actual_rendered_string_metrics(StringView, RedBlackTree<u32, Optional<Style::Mask>> const& masks = {}, Optional<size_t> maximum_line_width = {});
  141. static StringMetrics actual_rendered_string_metrics(Utf32View const&, RedBlackTree<u32, Optional<Style::Mask>> const& masks = {});
  142. Function<Vector<CompletionSuggestion>(Editor const&)> on_tab_complete;
  143. Function<void(Utf32View, Editor&)> on_paste;
  144. Function<void()> on_interrupt_handled;
  145. Function<void(Editor&)> on_display_refresh;
  146. static Function<bool(Editor&)> find_internal_function(StringView name);
  147. enum class CaseChangeOp {
  148. Lowercase,
  149. Uppercase,
  150. Capital,
  151. };
  152. void case_change_word(CaseChangeOp);
  153. #define __ENUMERATE_EDITOR_INTERNAL_FUNCTION(name) \
  154. void name();
  155. ENUMERATE_EDITOR_INTERNAL_FUNCTIONS(__ENUMERATE_EDITOR_INTERNAL_FUNCTION)
  156. #undef __ENUMERATE_EDITOR_INTERNAL_FUNCTION
  157. ErrorOr<void> interrupted();
  158. ErrorOr<void> resized();
  159. size_t cursor() const { return m_cursor; }
  160. void set_cursor(size_t cursor)
  161. {
  162. if (cursor > m_buffer.size())
  163. cursor = m_buffer.size();
  164. m_cursor = cursor;
  165. }
  166. Vector<u32, 1024> const& buffer() const { return m_buffer; }
  167. u32 buffer_at(size_t pos) const { return m_buffer.at(pos); }
  168. DeprecatedString line() const { return line(m_buffer.size()); }
  169. DeprecatedString line(size_t up_to_index) const;
  170. // Only makes sense inside a character_input callback or on_* callback.
  171. void set_prompt(DeprecatedString const& prompt)
  172. {
  173. if (m_cached_prompt_valid)
  174. m_old_prompt_metrics = m_cached_prompt_metrics;
  175. m_cached_prompt_valid = false;
  176. m_cached_prompt_metrics = actual_rendered_string_metrics(prompt, {});
  177. m_new_prompt = prompt;
  178. }
  179. void clear_line();
  180. void insert(DeprecatedString const&);
  181. void insert(StringView);
  182. void insert(Utf32View const&);
  183. void insert(const u32);
  184. void stylize(Span const&, Style const&);
  185. void strip_styles(bool strip_anchored = false);
  186. // Invariant Offset is an offset into the suggested data, hinting the editor what parts of the suggestion will not change
  187. // Static Offset is an offset into the token, signifying where the suggestions start
  188. // e.g.
  189. // foobar<suggestion initiated>, on_tab_complete returns "barx", "bary", "barz"
  190. // ^ ^
  191. // +-|- static offset: the suggestions start here
  192. // +- invariant offset: the suggestions do not change up to here
  193. //
  194. void transform_suggestion_offsets(size_t& invariant_offset, size_t& static_offset, Span::Mode offset_mode = Span::ByteOriented) const;
  195. const struct termios& termios() const { return m_termios; }
  196. const struct termios& default_termios() const { return m_default_termios; }
  197. struct winsize terminal_size() const
  198. {
  199. winsize ws { (u16)m_num_lines, (u16)m_num_columns, 0, 0 };
  200. return ws;
  201. }
  202. void finish()
  203. {
  204. m_finish = true;
  205. }
  206. bool is_editing() const { return m_is_editing; }
  207. const Utf32View buffer_view() const { return { m_buffer.data(), m_buffer.size() }; }
  208. auto prohibit_input()
  209. {
  210. auto previous_value = m_prohibit_input_processing;
  211. m_prohibit_input_processing = true;
  212. m_have_unprocessed_read_event = false;
  213. return ScopeGuard {
  214. [this, previous_value] {
  215. m_prohibit_input_processing = previous_value;
  216. if (!m_prohibit_input_processing && m_have_unprocessed_read_event)
  217. handle_read_event().release_value_but_fixme_should_propagate_errors();
  218. }
  219. };
  220. }
  221. private:
  222. explicit Editor(Configuration configuration = Configuration::from_config());
  223. void set_default_keybinds();
  224. enum LoopExitCode {
  225. Exit = 0,
  226. Retry
  227. };
  228. // FIXME: Port to Core::Property
  229. void save_to(JsonObject&);
  230. ErrorOr<void> try_update_once();
  231. void handle_interrupt_event();
  232. ErrorOr<void> handle_read_event();
  233. ErrorOr<void> handle_resize_event(bool reset_origin);
  234. void ensure_free_lines_from_origin(size_t count);
  235. Result<Vector<size_t, 2>, Error> vt_dsr();
  236. void remove_at_index(size_t);
  237. enum class ModificationKind {
  238. Insertion,
  239. Removal,
  240. ForcedOverlapRemoval,
  241. };
  242. void readjust_anchored_styles(size_t hint_index, ModificationKind);
  243. Style find_applicable_style(size_t offset) const;
  244. bool search(StringView, bool allow_empty = false, bool from_beginning = true);
  245. inline void end_search()
  246. {
  247. m_is_searching = false;
  248. m_refresh_needed = true;
  249. m_search_offset = 0;
  250. if (m_reset_buffer_on_search_end) {
  251. m_buffer.clear();
  252. for (auto ch : m_pre_search_buffer)
  253. m_buffer.append(ch);
  254. m_cursor = m_pre_search_cursor;
  255. }
  256. m_reset_buffer_on_search_end = true;
  257. m_search_editor = nullptr;
  258. }
  259. void reset()
  260. {
  261. m_cached_buffer_metrics.reset();
  262. m_cached_prompt_valid = false;
  263. m_cursor = 0;
  264. m_drawn_cursor = 0;
  265. m_inline_search_cursor = 0;
  266. m_search_offset = 0;
  267. m_search_offset_state = SearchOffsetState::Unbiased;
  268. m_old_prompt_metrics = m_cached_prompt_metrics;
  269. set_origin(0, 0);
  270. m_prompt_lines_at_suggestion_initiation = 0;
  271. m_refresh_needed = true;
  272. m_input_error.clear();
  273. m_returned_line = DeprecatedString::empty();
  274. m_chars_touched_in_the_middle = 0;
  275. m_drawn_end_of_line_offset = 0;
  276. m_drawn_spans = {};
  277. m_paste_buffer.clear_with_capacity();
  278. }
  279. ErrorOr<void> refresh_display();
  280. ErrorOr<void> cleanup();
  281. ErrorOr<void> cleanup_suggestions();
  282. ErrorOr<void> really_quit_event_loop();
  283. void restore()
  284. {
  285. VERIFY(m_initialized);
  286. tcsetattr(0, TCSANOW, &m_default_termios);
  287. m_initialized = false;
  288. if (m_configuration.enable_bracketed_paste)
  289. warn("\x1b[?2004l");
  290. for (auto id : m_signal_handlers)
  291. Core::EventLoop::unregister_signal(id);
  292. }
  293. StringMetrics const& current_prompt_metrics() const
  294. {
  295. return m_cached_prompt_valid ? m_cached_prompt_metrics : m_old_prompt_metrics;
  296. }
  297. size_t num_lines() const
  298. {
  299. return current_prompt_metrics().lines_with_addition(m_cached_buffer_metrics, m_num_columns);
  300. }
  301. size_t cursor_line() const
  302. {
  303. auto cursor = m_drawn_cursor;
  304. if (cursor > m_cursor)
  305. cursor = m_cursor;
  306. return current_prompt_metrics().lines_with_addition(
  307. actual_rendered_string_metrics(buffer_view().substring_view(0, cursor), m_current_masks),
  308. m_num_columns);
  309. }
  310. size_t offset_in_line() const
  311. {
  312. auto cursor = m_drawn_cursor;
  313. if (cursor > m_cursor)
  314. cursor = m_cursor;
  315. auto buffer_metrics = actual_rendered_string_metrics(buffer_view().substring_view(0, cursor), m_current_masks);
  316. return current_prompt_metrics().offset_with_addition(buffer_metrics, m_num_columns);
  317. }
  318. bool set_origin(bool quit_on_error = true)
  319. {
  320. auto position = vt_dsr();
  321. if (!position.is_error()) {
  322. set_origin(position.value()[0], position.value()[1]);
  323. return true;
  324. }
  325. if (quit_on_error && position.is_error()) {
  326. m_input_error = position.error();
  327. finish();
  328. }
  329. return false;
  330. }
  331. void set_origin(int row, int col)
  332. {
  333. m_origin_row = row;
  334. m_origin_column = col;
  335. m_suggestion_display->set_origin(row, col, {});
  336. }
  337. void recalculate_origin();
  338. ErrorOr<void> reposition_cursor(Stream&, bool to_end = false);
  339. struct CodepointRange {
  340. size_t start { 0 };
  341. size_t end { 0 };
  342. };
  343. 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;
  344. void get_terminal_size();
  345. bool m_finish { false };
  346. RefPtr<Editor> m_search_editor;
  347. bool m_is_searching { false };
  348. bool m_reset_buffer_on_search_end { true };
  349. size_t m_search_offset { 0 };
  350. enum class SearchOffsetState {
  351. Unbiased,
  352. Backwards,
  353. Forwards,
  354. } m_search_offset_state { SearchOffsetState::Unbiased };
  355. size_t m_pre_search_cursor { 0 };
  356. Vector<u32, 1024> m_pre_search_buffer;
  357. Vector<u32, 1024> m_buffer;
  358. ByteBuffer m_pending_chars;
  359. Vector<char, 512> m_incomplete_data;
  360. Optional<Error> m_input_error;
  361. DeprecatedString m_returned_line;
  362. size_t m_cursor { 0 };
  363. size_t m_drawn_cursor { 0 };
  364. size_t m_drawn_end_of_line_offset { 0 };
  365. size_t m_inline_search_cursor { 0 };
  366. size_t m_chars_touched_in_the_middle { 0 };
  367. size_t m_times_tab_pressed { 0 };
  368. size_t m_num_columns { 0 };
  369. size_t m_num_lines { 1 };
  370. size_t m_previous_num_columns { 0 };
  371. size_t m_extra_forward_lines { 0 };
  372. size_t m_shown_lines { 0 };
  373. StringMetrics m_cached_prompt_metrics;
  374. StringMetrics m_old_prompt_metrics;
  375. StringMetrics m_cached_buffer_metrics;
  376. size_t m_prompt_lines_at_suggestion_initiation { 0 };
  377. bool m_cached_prompt_valid { false };
  378. // Exact position before our prompt in the terminal.
  379. size_t m_origin_row { 0 };
  380. size_t m_origin_column { 0 };
  381. bool m_has_origin_reset_scheduled { false };
  382. OwnPtr<SuggestionDisplay> m_suggestion_display;
  383. Vector<u32, 32> m_remembered_suggestion_static_data;
  384. DeprecatedString m_new_prompt;
  385. SuggestionManager m_suggestion_manager;
  386. bool m_always_refresh { false };
  387. enum class TabDirection {
  388. Forward,
  389. Backward,
  390. };
  391. TabDirection m_tab_direction { TabDirection::Forward };
  392. KeyCallbackMachine m_callback_machine;
  393. struct termios m_termios {
  394. };
  395. struct termios m_default_termios {
  396. };
  397. bool m_was_interrupted { false };
  398. bool m_previous_interrupt_was_handled_as_interrupt { true };
  399. bool m_was_resized { false };
  400. // FIXME: This should be something more take_first()-friendly.
  401. struct HistoryEntry {
  402. DeprecatedString entry;
  403. time_t timestamp;
  404. };
  405. Vector<HistoryEntry> m_history;
  406. size_t m_history_cursor { 0 };
  407. size_t m_history_capacity { 1024 };
  408. bool m_history_dirty { false };
  409. enum class InputState {
  410. Free,
  411. Verbatim,
  412. Paste,
  413. GotEscape,
  414. CSIExpectParameter,
  415. CSIExpectIntermediate,
  416. CSIExpectFinal,
  417. };
  418. InputState m_state { InputState::Free };
  419. InputState m_previous_free_state { InputState::Free };
  420. struct Spans {
  421. HashMap<u32, HashMap<u32, Style>> m_spans_starting;
  422. HashMap<u32, HashMap<u32, Style>> m_spans_ending;
  423. HashMap<u32, HashMap<u32, Style>> m_anchored_spans_starting;
  424. HashMap<u32, HashMap<u32, Style>> m_anchored_spans_ending;
  425. bool contains_up_to_offset(Spans const& other, size_t offset) const;
  426. } m_drawn_spans, m_current_spans;
  427. RedBlackTree<u32, Optional<Style::Mask>> m_current_masks;
  428. RefPtr<Core::Notifier> m_notifier;
  429. Vector<u32> m_paste_buffer;
  430. bool m_initialized { false };
  431. bool m_refresh_needed { false };
  432. Vector<int, 2> m_signal_handlers;
  433. bool m_is_editing { false };
  434. bool m_prohibit_input_processing { false };
  435. bool m_have_unprocessed_read_event { false };
  436. Configuration m_configuration;
  437. };
  438. }