Editor.h 16 KB

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