Editor.h 16 KB

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