Editor.h 16 KB

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