Editor.h 15 KB

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