Editor.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Editor.h"
  27. #include <AK/GenericLexer.h>
  28. #include <AK/JsonObject.h>
  29. #include <AK/StringBuilder.h>
  30. #include <AK/Utf32View.h>
  31. #include <AK/Utf8View.h>
  32. #include <LibCore/ConfigFile.h>
  33. #include <LibCore/Event.h>
  34. #include <LibCore/EventLoop.h>
  35. #include <LibCore/Notifier.h>
  36. #include <ctype.h>
  37. #include <signal.h>
  38. #include <stdio.h>
  39. #include <sys/ioctl.h>
  40. #include <sys/select.h>
  41. #include <sys/time.h>
  42. #include <unistd.h>
  43. // #define SUGGESTIONS_DEBUG
  44. namespace {
  45. constexpr u32 ctrl(char c) { return c & 0x3f; }
  46. }
  47. namespace Line {
  48. Configuration Configuration::from_config(const StringView& libname)
  49. {
  50. Configuration configuration;
  51. auto config_file = Core::ConfigFile::get_for_lib(libname);
  52. // Read behaviour options.
  53. auto refresh = config_file->read_entry("behaviour", "refresh", "lazy");
  54. auto operation = config_file->read_entry("behaviour", "operation_mode");
  55. if (refresh.equals_ignoring_case("lazy"))
  56. configuration.set(Configuration::Lazy);
  57. else if (refresh.equals_ignoring_case("eager"))
  58. configuration.set(Configuration::Eager);
  59. if (operation.equals_ignoring_case("full"))
  60. configuration.set(Configuration::OperationMode::Full);
  61. else if (operation.equals_ignoring_case("noescapesequences"))
  62. configuration.set(Configuration::OperationMode::NoEscapeSequences);
  63. else if (operation.equals_ignoring_case("noninteractive"))
  64. configuration.set(Configuration::OperationMode::NonInteractive);
  65. else
  66. configuration.set(Configuration::OperationMode::Unset);
  67. // Read keybinds.
  68. for (auto& binding_key : config_file->keys("keybinds")) {
  69. GenericLexer key_lexer(binding_key);
  70. auto has_ctrl = false;
  71. auto alt = false;
  72. unsigned key = 0;
  73. while (!key && !key_lexer.is_eof()) {
  74. if (key_lexer.next_is("alt+")) {
  75. alt = key_lexer.consume_specific("alt+");
  76. continue;
  77. }
  78. if (key_lexer.next_is("^[")) {
  79. alt = key_lexer.consume_specific("^[");
  80. continue;
  81. }
  82. if (key_lexer.next_is("^")) {
  83. has_ctrl = key_lexer.consume_specific("^");
  84. continue;
  85. }
  86. if (key_lexer.next_is("ctrl+")) {
  87. has_ctrl = key_lexer.consume_specific("ctrl+");
  88. continue;
  89. }
  90. // FIXME: Support utf?
  91. key = key_lexer.consume();
  92. }
  93. if (has_ctrl)
  94. key = ctrl(key);
  95. auto value = config_file->read_entry("keybinds", binding_key);
  96. if (value.starts_with("internal:")) {
  97. configuration.set(KeyBinding {
  98. Key { key, alt ? Key::Alt : Key::None },
  99. KeyBinding::Kind::InternalFunction,
  100. value.substring(9, value.length() - 9) });
  101. } else {
  102. configuration.set(KeyBinding {
  103. Key { key, alt ? Key::Alt : Key::None },
  104. KeyBinding::Kind::Insertion,
  105. value });
  106. }
  107. }
  108. return configuration;
  109. }
  110. void Editor::set_default_keybinds()
  111. {
  112. register_key_input_callback(ctrl('N'), EDITOR_INTERNAL_FUNCTION(search_forwards));
  113. register_key_input_callback(ctrl('P'), EDITOR_INTERNAL_FUNCTION(search_backwards));
  114. // Normally ^W. `stty werase \^n` can change it to ^N (or something else), but Serenity doesn't have `stty` yet.
  115. register_key_input_callback(m_termios.c_cc[VWERASE], EDITOR_INTERNAL_FUNCTION(erase_word_backwards));
  116. // Normally ^U. `stty kill \^n` can change it to ^N (or something else), but Serenity doesn't have `stty` yet.
  117. register_key_input_callback(m_termios.c_cc[VKILL], EDITOR_INTERNAL_FUNCTION(kill_line));
  118. register_key_input_callback(ctrl('A'), EDITOR_INTERNAL_FUNCTION(go_home));
  119. register_key_input_callback(ctrl('B'), EDITOR_INTERNAL_FUNCTION(cursor_left_character));
  120. register_key_input_callback(ctrl('D'), EDITOR_INTERNAL_FUNCTION(erase_character_forwards));
  121. register_key_input_callback(ctrl('E'), EDITOR_INTERNAL_FUNCTION(go_end));
  122. register_key_input_callback(ctrl('F'), EDITOR_INTERNAL_FUNCTION(cursor_right_character));
  123. // ^H: ctrl('H') == '\b'
  124. register_key_input_callback(ctrl('H'), EDITOR_INTERNAL_FUNCTION(erase_character_backwards));
  125. register_key_input_callback(m_termios.c_cc[VERASE], EDITOR_INTERNAL_FUNCTION(erase_character_backwards));
  126. register_key_input_callback(ctrl('K'), EDITOR_INTERNAL_FUNCTION(erase_to_end));
  127. register_key_input_callback(ctrl('L'), EDITOR_INTERNAL_FUNCTION(clear_screen));
  128. register_key_input_callback(ctrl('R'), EDITOR_INTERNAL_FUNCTION(enter_search));
  129. register_key_input_callback(ctrl('T'), EDITOR_INTERNAL_FUNCTION(transpose_characters));
  130. register_key_input_callback('\n', EDITOR_INTERNAL_FUNCTION(finish));
  131. // ^[.: alt-.: insert last arg of previous command (similar to `!$`)
  132. register_key_input_callback({ '.', Key::Alt }, EDITOR_INTERNAL_FUNCTION(insert_last_words));
  133. register_key_input_callback({ 'b', Key::Alt }, EDITOR_INTERNAL_FUNCTION(cursor_left_word));
  134. register_key_input_callback({ 'f', Key::Alt }, EDITOR_INTERNAL_FUNCTION(cursor_right_word));
  135. // ^[^H: alt-backspace: backward delete word
  136. register_key_input_callback({ '\b', Key::Alt }, EDITOR_INTERNAL_FUNCTION(erase_alnum_word_backwards));
  137. register_key_input_callback({ 'd', Key::Alt }, EDITOR_INTERNAL_FUNCTION(erase_alnum_word_forwards));
  138. register_key_input_callback({ 'c', Key::Alt }, EDITOR_INTERNAL_FUNCTION(capitalize_word));
  139. register_key_input_callback({ 'l', Key::Alt }, EDITOR_INTERNAL_FUNCTION(lowercase_word));
  140. register_key_input_callback({ 'u', Key::Alt }, EDITOR_INTERNAL_FUNCTION(uppercase_word));
  141. register_key_input_callback({ 't', Key::Alt }, EDITOR_INTERNAL_FUNCTION(transpose_words));
  142. }
  143. Editor::Editor(Configuration configuration)
  144. : m_configuration(move(configuration))
  145. {
  146. m_always_refresh = configuration.refresh_behaviour == Configuration::RefreshBehaviour::Eager;
  147. m_pending_chars = ByteBuffer::create_uninitialized(0);
  148. get_terminal_size();
  149. m_suggestion_display = make<XtermSuggestionDisplay>(m_num_lines, m_num_columns);
  150. }
  151. Editor::~Editor()
  152. {
  153. if (m_initialized)
  154. restore();
  155. }
  156. void Editor::get_terminal_size()
  157. {
  158. struct winsize ws;
  159. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  160. m_num_columns = 80;
  161. m_num_lines = 25;
  162. } else {
  163. m_num_columns = ws.ws_col;
  164. m_num_lines = ws.ws_row;
  165. }
  166. }
  167. void Editor::add_to_history(const String& line)
  168. {
  169. if (line.is_empty())
  170. return;
  171. if ((m_history.size() + 1) > m_history_capacity)
  172. m_history.take_first();
  173. m_history.append(line);
  174. }
  175. void Editor::clear_line()
  176. {
  177. for (size_t i = 0; i < m_cursor; ++i)
  178. fputc(0x8, stderr);
  179. fputs("\033[K", stderr);
  180. fflush(stderr);
  181. m_buffer.clear();
  182. m_cursor = 0;
  183. m_inline_search_cursor = m_cursor;
  184. }
  185. void Editor::insert(const Utf32View& string)
  186. {
  187. for (size_t i = 0; i < string.length(); ++i)
  188. insert(string.code_points()[i]);
  189. }
  190. void Editor::insert(const String& string)
  191. {
  192. for (auto ch : Utf8View { string })
  193. insert(ch);
  194. }
  195. void Editor::insert(const StringView& string_view)
  196. {
  197. for (auto ch : Utf8View { string_view })
  198. insert(ch);
  199. }
  200. void Editor::insert(const u32 cp)
  201. {
  202. StringBuilder builder;
  203. builder.append(Utf32View(&cp, 1));
  204. auto str = builder.build();
  205. m_pending_chars.append(str.characters(), str.length());
  206. readjust_anchored_styles(m_cursor, ModificationKind::Insertion);
  207. if (m_cursor == m_buffer.size()) {
  208. m_buffer.append(cp);
  209. m_cursor = m_buffer.size();
  210. m_inline_search_cursor = m_cursor;
  211. return;
  212. }
  213. m_buffer.insert(m_cursor, cp);
  214. ++m_chars_inserted_in_the_middle;
  215. ++m_cursor;
  216. m_inline_search_cursor = m_cursor;
  217. }
  218. void Editor::register_key_input_callback(const KeyBinding& binding)
  219. {
  220. if (binding.kind == KeyBinding::Kind::InternalFunction) {
  221. auto internal_function = find_internal_function(binding.binding);
  222. if (!internal_function) {
  223. dbg() << "LibLine: Unknown internal function '" << binding.binding << "'";
  224. return;
  225. }
  226. return register_key_input_callback(binding.key, move(internal_function));
  227. }
  228. return register_key_input_callback(binding.key, [binding = String(binding.binding)](auto& editor) {
  229. editor.insert(binding);
  230. return false;
  231. });
  232. }
  233. void Editor::register_key_input_callback(Key key, Function<bool(Editor&)> callback)
  234. {
  235. m_key_callbacks.set(key, make<KeyCallback>(move(callback)));
  236. }
  237. static size_t code_point_length_in_utf8(u32 code_point)
  238. {
  239. if (code_point <= 0x7f)
  240. return 1;
  241. if (code_point <= 0x07ff)
  242. return 2;
  243. if (code_point <= 0xffff)
  244. return 3;
  245. if (code_point <= 0x10ffff)
  246. return 4;
  247. return 3;
  248. }
  249. // buffer [ 0 1 2 3 . . . A . . . B . . . M . . . N ]
  250. // ^ ^ ^ ^
  251. // | | | +- end of buffer
  252. // | | +- scan offset = M
  253. // | +- range end = M - B
  254. // +- range start = M - A
  255. // This method converts a byte range defined by [start_byte_offset, end_byte_offset] to a code_point range [M - A, M - B] as shown in the diagram above.
  256. // If `reverse' is true, A and B are before M, if not, A and B are after M.
  257. Editor::CodepointRange Editor::byte_offset_range_to_code_point_offset_range(size_t start_byte_offset, size_t end_byte_offset, size_t scan_code_point_offset, bool reverse) const
  258. {
  259. size_t byte_offset = 0;
  260. size_t code_point_offset = scan_code_point_offset + (reverse ? 1 : 0);
  261. CodepointRange range;
  262. for (;;) {
  263. if (!reverse) {
  264. if (code_point_offset >= m_buffer.size())
  265. break;
  266. } else {
  267. if (code_point_offset == 0)
  268. break;
  269. }
  270. if (byte_offset > end_byte_offset)
  271. break;
  272. if (byte_offset < start_byte_offset)
  273. ++range.start;
  274. if (byte_offset < end_byte_offset)
  275. ++range.end;
  276. byte_offset += code_point_length_in_utf8(m_buffer[reverse ? --code_point_offset : code_point_offset++]);
  277. }
  278. return range;
  279. }
  280. void Editor::stylize(const Span& span, const Style& style)
  281. {
  282. if (style.is_empty())
  283. return;
  284. auto start = span.beginning();
  285. auto end = span.end();
  286. if (span.mode() == Span::ByteOriented) {
  287. auto offsets = byte_offset_range_to_code_point_offset_range(start, end, 0);
  288. start = offsets.start;
  289. end = offsets.end;
  290. }
  291. auto& spans_starting = style.is_anchored() ? m_anchored_spans_starting : m_spans_starting;
  292. auto& spans_ending = style.is_anchored() ? m_anchored_spans_ending : m_spans_ending;
  293. auto starting_map = spans_starting.get(start).value_or({});
  294. if (!starting_map.contains(end))
  295. m_refresh_needed = true;
  296. starting_map.set(end, style);
  297. spans_starting.set(start, starting_map);
  298. auto ending_map = spans_ending.get(end).value_or({});
  299. if (!ending_map.contains(start))
  300. m_refresh_needed = true;
  301. ending_map.set(start, style);
  302. spans_ending.set(end, ending_map);
  303. }
  304. void Editor::suggest(size_t invariant_offset, size_t static_offset, Span::Mode offset_mode) const
  305. {
  306. auto internal_static_offset = static_offset;
  307. auto internal_invariant_offset = invariant_offset;
  308. if (offset_mode == Span::Mode::ByteOriented) {
  309. // FIXME: We're assuming that invariant_offset points to the end of the available data
  310. // this is not necessarily true, but is true in most cases.
  311. auto offsets = byte_offset_range_to_code_point_offset_range(internal_static_offset, internal_invariant_offset + internal_static_offset, m_cursor - 1, true);
  312. internal_static_offset = offsets.start;
  313. internal_invariant_offset = offsets.end - offsets.start;
  314. }
  315. m_suggestion_manager.set_suggestion_variants(internal_static_offset, internal_invariant_offset, 0);
  316. }
  317. void Editor::initialize()
  318. {
  319. if (m_initialized)
  320. return;
  321. struct termios termios;
  322. tcgetattr(0, &termios);
  323. m_default_termios = termios; // grab a copy to restore
  324. if (m_was_resized)
  325. get_terminal_size();
  326. if (m_configuration.operation_mode == Configuration::Unset) {
  327. auto istty = isatty(STDIN_FILENO) && isatty(STDERR_FILENO);
  328. if (!istty) {
  329. m_configuration.set(Configuration::NonInteractive);
  330. } else {
  331. auto* term = getenv("TERM");
  332. if (StringView { term }.starts_with("xterm"))
  333. m_configuration.set(Configuration::Full);
  334. else
  335. m_configuration.set(Configuration::NoEscapeSequences);
  336. }
  337. }
  338. // Because we use our own line discipline which includes echoing,
  339. // we disable ICANON and ECHO.
  340. if (m_configuration.operation_mode == Configuration::Full) {
  341. termios.c_lflag &= ~(ECHO | ICANON);
  342. tcsetattr(0, TCSANOW, &termios);
  343. }
  344. m_termios = termios;
  345. set_default_keybinds();
  346. for (auto& keybind : m_configuration.keybindings)
  347. register_key_input_callback(keybind);
  348. Core::EventLoop::register_signal(SIGINT, [this](int) {
  349. interrupted();
  350. });
  351. Core::EventLoop::register_signal(SIGWINCH, [this](int) {
  352. resized();
  353. });
  354. m_initialized = true;
  355. }
  356. void Editor::interrupted()
  357. {
  358. if (!m_is_editing)
  359. return;
  360. m_was_interrupted = true;
  361. handle_interrupt_event();
  362. if (!m_finish)
  363. return;
  364. m_finish = false;
  365. reposition_cursor(true);
  366. if (m_suggestion_display->cleanup())
  367. reposition_cursor();
  368. cleanup();
  369. fprintf(stderr, "\n");
  370. fflush(stderr);
  371. m_buffer.clear();
  372. m_is_editing = false;
  373. restore();
  374. m_notifier->set_event_mask(Core::Notifier::None);
  375. deferred_invoke([this](auto&) {
  376. remove_child(*m_notifier);
  377. m_notifier = nullptr;
  378. Core::EventLoop::current().quit(Retry);
  379. });
  380. }
  381. void Editor::really_quit_event_loop()
  382. {
  383. m_finish = false;
  384. reposition_cursor(true);
  385. fprintf(stderr, "\n");
  386. fflush(stderr);
  387. auto string = line();
  388. m_buffer.clear();
  389. m_is_editing = false;
  390. restore();
  391. m_returned_line = string;
  392. m_notifier->set_event_mask(Core::Notifier::None);
  393. deferred_invoke([this](auto&) {
  394. remove_child(*m_notifier);
  395. m_notifier = nullptr;
  396. Core::EventLoop::current().quit(Exit);
  397. });
  398. }
  399. auto Editor::get_line(const String& prompt) -> Result<String, Editor::Error>
  400. {
  401. initialize();
  402. m_is_editing = true;
  403. if (m_configuration.operation_mode == Configuration::NoEscapeSequences || m_configuration.operation_mode == Configuration::NonInteractive) {
  404. // Do not use escape sequences, instead, use LibC's getline.
  405. size_t size = 0;
  406. char* line = nullptr;
  407. // Show the prompt only on interactive mode (NoEscapeSequences in this case).
  408. if (m_configuration.operation_mode != Configuration::NonInteractive)
  409. fputs(prompt.characters(), stderr);
  410. auto line_length = getline(&line, &size, stdin);
  411. // getline() returns -1 and sets errno=0 on EOF.
  412. if (line_length == -1) {
  413. if (line)
  414. free(line);
  415. if (errno == 0)
  416. return Error::Eof;
  417. return Error::ReadFailure;
  418. }
  419. restore();
  420. if (line) {
  421. String result { line, (size_t)line_length, Chomp };
  422. free(line);
  423. return result;
  424. }
  425. return Error::ReadFailure;
  426. }
  427. set_prompt(prompt);
  428. reset();
  429. set_origin();
  430. strip_styles(true);
  431. m_history_cursor = m_history.size();
  432. refresh_display();
  433. Core::EventLoop loop;
  434. m_notifier = Core::Notifier::construct(STDIN_FILENO, Core::Notifier::Read);
  435. add_child(*m_notifier);
  436. m_notifier->on_ready_to_read = [&] {
  437. if (m_was_interrupted) {
  438. handle_interrupt_event();
  439. }
  440. handle_read_event();
  441. if (m_always_refresh)
  442. m_refresh_needed = true;
  443. refresh_display();
  444. if (m_finish)
  445. really_quit_event_loop();
  446. };
  447. if (loop.exec() == Retry)
  448. return get_line(prompt);
  449. return m_input_error.has_value() ? Result<String, Editor::Error> { m_input_error.value() } : Result<String, Editor::Error> { m_returned_line };
  450. }
  451. void Editor::save_to(JsonObject& object)
  452. {
  453. Core::Object::save_to(object);
  454. object.set("is_searching", m_is_searching);
  455. object.set("is_editing", m_is_editing);
  456. object.set("cursor_offset", m_cursor);
  457. object.set("needs_refresh", m_refresh_needed);
  458. object.set("unprocessed_characters", m_incomplete_data.size());
  459. object.set("history_size", m_history.size());
  460. object.set("current_prompt", m_new_prompt);
  461. object.set("was_interrupted", m_was_interrupted);
  462. JsonObject display_area;
  463. display_area.set("top_left_row", m_origin_row);
  464. display_area.set("top_left_column", m_origin_column);
  465. display_area.set("line_count", num_lines());
  466. object.set("used_display_area", move(display_area));
  467. }
  468. void Editor::handle_interrupt_event()
  469. {
  470. m_was_interrupted = false;
  471. auto cb = m_key_callbacks.get(ctrl('C'));
  472. if (cb.has_value()) {
  473. if (!cb.value()->callback(*this)) {
  474. // Oh well.
  475. return;
  476. }
  477. }
  478. fprintf(stderr, "^C");
  479. fflush(stderr);
  480. if (on_interrupt_handled)
  481. on_interrupt_handled();
  482. m_buffer.clear();
  483. m_cursor = 0;
  484. finish();
  485. }
  486. void Editor::handle_read_event()
  487. {
  488. char keybuf[16];
  489. ssize_t nread = 0;
  490. if (!m_incomplete_data.size())
  491. nread = read(0, keybuf, sizeof(keybuf));
  492. if (nread < 0) {
  493. if (errno == EINTR) {
  494. if (!m_was_interrupted) {
  495. if (m_was_resized)
  496. return;
  497. finish();
  498. return;
  499. }
  500. handle_interrupt_event();
  501. return;
  502. }
  503. ScopedValueRollback errno_restorer(errno);
  504. perror("read failed");
  505. m_input_error = Error::ReadFailure;
  506. finish();
  507. return;
  508. }
  509. m_incomplete_data.append(keybuf, nread);
  510. nread = m_incomplete_data.size();
  511. if (nread == 0) {
  512. m_input_error = Error::Empty;
  513. finish();
  514. return;
  515. }
  516. auto reverse_tab = false;
  517. auto ctrl_held = false;
  518. // Discard starting bytes until they make sense as utf-8.
  519. size_t valid_bytes = 0;
  520. while (nread) {
  521. Utf8View { StringView { m_incomplete_data.data(), (size_t)nread } }.validate(valid_bytes);
  522. if (valid_bytes)
  523. break;
  524. m_incomplete_data.take_first();
  525. --nread;
  526. }
  527. Utf8View input_view { StringView { m_incomplete_data.data(), valid_bytes } };
  528. size_t consumed_code_points = 0;
  529. for (auto code_point : input_view) {
  530. if (m_finish)
  531. break;
  532. ++consumed_code_points;
  533. if (code_point == 0)
  534. continue;
  535. switch (m_state) {
  536. case InputState::GotEscape:
  537. switch (code_point) {
  538. case '[':
  539. m_state = InputState::GotEscapeFollowedByLeftBracket;
  540. continue;
  541. default: {
  542. m_state = InputState::Free;
  543. auto cb = m_key_callbacks.get({ code_point, Key::Alt });
  544. if (cb.has_value()) {
  545. if (!cb.value()->callback(*this)) {
  546. // There's nothing interesting to do here.
  547. }
  548. }
  549. continue;
  550. }
  551. }
  552. case InputState::GotEscapeFollowedByLeftBracket:
  553. switch (code_point) {
  554. case 'O': // mod_ctrl
  555. ctrl_held = true;
  556. continue;
  557. case 'A': // ^[[A: arrow up
  558. search_backwards();
  559. m_state = InputState::Free;
  560. ctrl_held = false;
  561. continue;
  562. case 'B': // ^[[B: arrow down
  563. search_forwards();
  564. m_state = InputState::Free;
  565. ctrl_held = false;
  566. continue;
  567. case 'D': // ^[[D: arrow left
  568. if (ctrl_held)
  569. cursor_left_word();
  570. else
  571. cursor_left_character();
  572. m_state = InputState::Free;
  573. ctrl_held = false;
  574. continue;
  575. case 'C': // ^[[C: arrow right
  576. if (ctrl_held)
  577. cursor_right_word();
  578. else
  579. cursor_right_character();
  580. m_state = InputState::Free;
  581. ctrl_held = false;
  582. continue;
  583. case 'H': // ^[[H: home
  584. go_home();
  585. m_state = InputState::Free;
  586. ctrl_held = false;
  587. continue;
  588. case 'F': // ^[[F: end
  589. go_end();
  590. m_state = InputState::Free;
  591. ctrl_held = false;
  592. continue;
  593. case 'Z': // ^[[Z: shift+tab
  594. reverse_tab = true;
  595. m_state = InputState::Free;
  596. ctrl_held = false;
  597. break;
  598. case '3': // ^[[3~: delete
  599. erase_character_forwards();
  600. m_search_offset = 0;
  601. m_state = InputState::ExpectTerminator;
  602. ctrl_held = false;
  603. continue;
  604. default:
  605. dbgprintf("LibLine: Unhandled final: %02x (%c)\r\n", code_point, code_point);
  606. m_state = InputState::Free;
  607. ctrl_held = false;
  608. continue;
  609. }
  610. break;
  611. case InputState::ExpectTerminator:
  612. m_state = InputState::Free;
  613. continue;
  614. case InputState::Free:
  615. if (code_point == 27) {
  616. m_state = InputState::GotEscape;
  617. continue;
  618. }
  619. break;
  620. }
  621. // Normally ^D. `stty eof \^n` can change it to ^N (or something else), but Serenity doesn't have `stty` yet.
  622. // Process this here since the keybinds might override its behaviour.
  623. if (code_point == m_termios.c_cc[VEOF] && m_cursor == 0) {
  624. finish_edit();
  625. continue;
  626. }
  627. auto cb = m_key_callbacks.get(code_point);
  628. if (cb.has_value()) {
  629. if (!cb.value()->callback(*this)) {
  630. continue;
  631. }
  632. }
  633. m_search_offset = 0; // reset search offset on any key
  634. if (code_point == '\t' || reverse_tab) {
  635. if (!on_tab_complete)
  636. continue;
  637. // Reverse tab can count as regular tab here.
  638. m_times_tab_pressed++;
  639. int token_start = m_cursor;
  640. // Ask for completions only on the first tab
  641. // and scan for the largest common prefix to display,
  642. // further tabs simply show the cached completions.
  643. if (m_times_tab_pressed == 1) {
  644. m_suggestion_manager.set_suggestions(on_tab_complete(*this));
  645. m_prompt_lines_at_suggestion_initiation = num_lines();
  646. if (m_suggestion_manager.count() == 0) {
  647. // There are no suggestions, beep.
  648. fputc('\a', stderr);
  649. fflush(stderr);
  650. }
  651. }
  652. // Adjust already incremented / decremented index when switching tab direction.
  653. if (reverse_tab && m_tab_direction != TabDirection::Backward) {
  654. m_suggestion_manager.previous();
  655. m_suggestion_manager.previous();
  656. m_tab_direction = TabDirection::Backward;
  657. }
  658. if (!reverse_tab && m_tab_direction != TabDirection::Forward) {
  659. m_suggestion_manager.next();
  660. m_suggestion_manager.next();
  661. m_tab_direction = TabDirection::Forward;
  662. }
  663. reverse_tab = false;
  664. auto completion_mode = m_times_tab_pressed == 1 ? SuggestionManager::CompletePrefix : m_times_tab_pressed == 2 ? SuggestionManager::ShowSuggestions : SuggestionManager::CycleSuggestions;
  665. auto completion_result = m_suggestion_manager.attempt_completion(completion_mode, token_start);
  666. auto new_cursor = m_cursor + completion_result.new_cursor_offset;
  667. for (size_t i = completion_result.offset_region_to_remove.start; i < completion_result.offset_region_to_remove.end; ++i)
  668. remove_at_index(new_cursor);
  669. m_cursor = new_cursor;
  670. m_inline_search_cursor = new_cursor;
  671. m_refresh_needed = true;
  672. for (auto& view : completion_result.insert)
  673. insert(view);
  674. if (completion_result.style_to_apply.has_value()) {
  675. // Apply the style of the last suggestion.
  676. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  677. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, completion_result.style_to_apply.value());
  678. }
  679. switch (completion_result.new_completion_mode) {
  680. case SuggestionManager::DontComplete:
  681. m_times_tab_pressed = 0;
  682. break;
  683. case SuggestionManager::CompletePrefix:
  684. break;
  685. default:
  686. ++m_times_tab_pressed;
  687. break;
  688. }
  689. if (m_times_tab_pressed > 1) {
  690. if (m_suggestion_manager.count() > 0) {
  691. if (m_suggestion_display->cleanup())
  692. reposition_cursor();
  693. m_suggestion_display->set_initial_prompt_lines(m_prompt_lines_at_suggestion_initiation);
  694. m_suggestion_display->display(m_suggestion_manager);
  695. m_origin_row = m_suggestion_display->origin_row();
  696. }
  697. }
  698. if (m_times_tab_pressed > 2) {
  699. if (m_tab_direction == TabDirection::Forward)
  700. m_suggestion_manager.next();
  701. else
  702. m_suggestion_manager.previous();
  703. }
  704. if (m_suggestion_manager.count() < 2) {
  705. // We have none, or just one suggestion,
  706. // we should just commit that and continue
  707. // after it, as if it were auto-completed.
  708. suggest(0, 0, Span::CodepointOriented);
  709. m_times_tab_pressed = 0;
  710. m_suggestion_manager.reset();
  711. m_suggestion_display->finish();
  712. }
  713. continue;
  714. }
  715. if (m_times_tab_pressed) {
  716. // Apply the style of the last suggestion.
  717. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  718. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, m_suggestion_manager.current_suggestion().style);
  719. // We probably have some suggestions drawn,
  720. // let's clean them up.
  721. if (m_suggestion_display->cleanup()) {
  722. reposition_cursor();
  723. m_refresh_needed = true;
  724. }
  725. m_suggestion_manager.reset();
  726. suggest(0, 0, Span::CodepointOriented);
  727. m_suggestion_display->finish();
  728. }
  729. m_times_tab_pressed = 0; // Safe to say if we get here, the user didn't press TAB
  730. insert(code_point);
  731. }
  732. if (consumed_code_points == m_incomplete_data.size()) {
  733. m_incomplete_data.clear();
  734. } else {
  735. for (size_t i = 0; i < consumed_code_points; ++i)
  736. m_incomplete_data.take_first();
  737. }
  738. }
  739. bool Editor::search(const StringView& phrase, bool allow_empty, bool from_beginning)
  740. {
  741. int last_matching_offset = -1;
  742. // Do not search for empty strings.
  743. if (allow_empty || phrase.length() > 0) {
  744. size_t search_offset = m_search_offset;
  745. for (size_t i = m_history_cursor; i > 0; --i) {
  746. auto contains = from_beginning ? m_history[i - 1].starts_with(phrase) : m_history[i - 1].contains(phrase);
  747. if (contains) {
  748. last_matching_offset = i - 1;
  749. if (search_offset == 0)
  750. break;
  751. --search_offset;
  752. }
  753. }
  754. if (last_matching_offset == -1) {
  755. fputc('\a', stderr);
  756. fflush(stderr);
  757. }
  758. }
  759. m_buffer.clear();
  760. m_cursor = 0;
  761. if (last_matching_offset >= 0) {
  762. insert(m_history[last_matching_offset]);
  763. }
  764. // Always needed, as we have cleared the buffer above.
  765. m_refresh_needed = true;
  766. return last_matching_offset >= 0;
  767. }
  768. void Editor::recalculate_origin()
  769. {
  770. // Changing the columns can affect our origin if
  771. // the new size is smaller than our prompt, which would
  772. // cause said prompt to take up more space, so we should
  773. // compensate for that.
  774. if (m_cached_prompt_metrics.max_line_length >= m_num_columns) {
  775. auto added_lines = (m_cached_prompt_metrics.max_line_length + 1) / m_num_columns - 1;
  776. m_origin_row += added_lines;
  777. }
  778. // We also need to recalculate our cursor position,
  779. // but that will be calculated and applied at the next
  780. // refresh cycle.
  781. }
  782. void Editor::cleanup()
  783. {
  784. auto current_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  785. auto new_lines = current_prompt_metrics().lines_with_addition(current_buffer_metrics, m_num_columns);
  786. auto shown_lines = num_lines();
  787. if (new_lines < shown_lines)
  788. m_extra_forward_lines = max(shown_lines - new_lines, m_extra_forward_lines);
  789. VT::move_relative(-m_extra_forward_lines, m_pending_chars.size() - m_chars_inserted_in_the_middle);
  790. auto current_line = cursor_line();
  791. // There's a newline at the top, don't clear that line.
  792. if (current_prompt_metrics().line_lengths.first() == 0)
  793. --current_line;
  794. VT::clear_lines(current_line - 1, num_lines() - current_line + m_extra_forward_lines);
  795. m_extra_forward_lines = 0;
  796. reposition_cursor();
  797. };
  798. void Editor::refresh_display()
  799. {
  800. auto has_cleaned_up = false;
  801. // Someone changed the window size, figure it out
  802. // and react to it, we might need to redraw.
  803. if (m_was_resized) {
  804. if (m_previous_num_columns != m_num_columns) {
  805. // We need to cleanup and redo everything.
  806. m_cached_prompt_valid = false;
  807. m_refresh_needed = true;
  808. swap(m_previous_num_columns, m_num_columns);
  809. recalculate_origin();
  810. cleanup();
  811. swap(m_previous_num_columns, m_num_columns);
  812. has_cleaned_up = true;
  813. }
  814. m_was_resized = false;
  815. }
  816. // Do not call hook on pure cursor movement.
  817. if (m_cached_prompt_valid && !m_refresh_needed && m_pending_chars.size() == 0) {
  818. // Probably just moving around.
  819. reposition_cursor();
  820. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  821. return;
  822. }
  823. // We might be at the last line, and have more than one line;
  824. // Refreshing the display will cause the terminal to scroll,
  825. // so note that fact and bring origin up.
  826. auto current_num_lines = num_lines();
  827. if (m_origin_row + current_num_lines > m_num_lines + 1) {
  828. if (current_num_lines > m_num_lines)
  829. m_origin_row = 0;
  830. else
  831. m_origin_row = m_num_lines - current_num_lines + 1;
  832. }
  833. if (on_display_refresh)
  834. on_display_refresh(*this);
  835. if (m_cached_prompt_valid) {
  836. if (!m_refresh_needed && m_cursor == m_buffer.size()) {
  837. // Just write the characters out and continue,
  838. // no need to refresh the entire line.
  839. char null = 0;
  840. m_pending_chars.append(&null, 1);
  841. fputs((char*)m_pending_chars.data(), stderr);
  842. m_pending_chars.clear();
  843. m_drawn_cursor = m_cursor;
  844. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  845. fflush(stderr);
  846. return;
  847. }
  848. }
  849. // Ouch, reflow entire line.
  850. if (!has_cleaned_up) {
  851. cleanup();
  852. }
  853. VT::move_absolute(m_origin_row, m_origin_column);
  854. fputs(m_new_prompt.characters(), stderr);
  855. VT::clear_to_end_of_line();
  856. HashMap<u32, Style> empty_styles {};
  857. StringBuilder builder;
  858. for (size_t i = 0; i < m_buffer.size(); ++i) {
  859. auto ends = m_spans_ending.get(i).value_or(empty_styles);
  860. auto starts = m_spans_starting.get(i).value_or(empty_styles);
  861. auto anchored_ends = m_anchored_spans_ending.get(i).value_or(empty_styles);
  862. auto anchored_starts = m_anchored_spans_starting.get(i).value_or(empty_styles);
  863. if (ends.size() || anchored_ends.size()) {
  864. Style style;
  865. for (auto& applicable_style : ends)
  866. style.unify_with(applicable_style.value);
  867. for (auto& applicable_style : anchored_ends)
  868. style.unify_with(applicable_style.value);
  869. // Disable any style that should be turned off.
  870. VT::apply_style(style, false);
  871. // Reapply styles for overlapping spans that include this one.
  872. style = find_applicable_style(i);
  873. VT::apply_style(style, true);
  874. }
  875. if (starts.size() || anchored_starts.size()) {
  876. Style style;
  877. for (auto& applicable_style : starts)
  878. style.unify_with(applicable_style.value);
  879. for (auto& applicable_style : anchored_starts)
  880. style.unify_with(applicable_style.value);
  881. // Set new styles.
  882. VT::apply_style(style, true);
  883. }
  884. builder.clear();
  885. builder.append(Utf32View { &m_buffer[i], 1 });
  886. fputs(builder.to_string().characters(), stderr);
  887. }
  888. VT::apply_style(Style::reset_style()); // don't bleed to EOL
  889. m_pending_chars.clear();
  890. m_refresh_needed = false;
  891. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  892. m_chars_inserted_in_the_middle = 0;
  893. if (!m_cached_prompt_valid) {
  894. m_cached_prompt_valid = true;
  895. }
  896. reposition_cursor();
  897. fflush(stderr);
  898. }
  899. void Editor::strip_styles(bool strip_anchored)
  900. {
  901. m_spans_starting.clear();
  902. m_spans_ending.clear();
  903. if (strip_anchored) {
  904. m_anchored_spans_starting.clear();
  905. m_anchored_spans_ending.clear();
  906. }
  907. m_refresh_needed = true;
  908. }
  909. void Editor::reposition_cursor(bool to_end)
  910. {
  911. auto cursor = m_cursor;
  912. auto saved_cursor = m_cursor;
  913. if (to_end)
  914. cursor = m_buffer.size();
  915. m_cursor = cursor;
  916. m_drawn_cursor = cursor;
  917. auto line = cursor_line() - 1;
  918. auto column = offset_in_line();
  919. VT::move_absolute(line + m_origin_row, column + m_origin_column);
  920. m_cursor = saved_cursor;
  921. }
  922. void VT::move_absolute(u32 row, u32 col)
  923. {
  924. fprintf(stderr, "\033[%d;%dH", row, col);
  925. fflush(stderr);
  926. }
  927. void VT::move_relative(int row, int col)
  928. {
  929. char x_op = 'A', y_op = 'D';
  930. if (row > 0)
  931. x_op = 'B';
  932. else
  933. row = -row;
  934. if (col > 0)
  935. y_op = 'C';
  936. else
  937. col = -col;
  938. if (row > 0)
  939. fprintf(stderr, "\033[%d%c", row, x_op);
  940. if (col > 0)
  941. fprintf(stderr, "\033[%d%c", col, y_op);
  942. }
  943. Style Editor::find_applicable_style(size_t offset) const
  944. {
  945. // Walk through our styles and merge all that fit in the offset.
  946. auto style = Style::reset_style();
  947. auto unify = [&](auto& entry) {
  948. if (entry.key >= offset)
  949. return;
  950. for (auto& style_value : entry.value) {
  951. if (style_value.key <= offset)
  952. return;
  953. style.unify_with(style_value.value, true);
  954. }
  955. };
  956. for (auto& entry : m_spans_starting) {
  957. unify(entry);
  958. }
  959. for (auto& entry : m_anchored_spans_starting) {
  960. unify(entry);
  961. }
  962. return style;
  963. }
  964. String Style::Background::to_vt_escape() const
  965. {
  966. if (is_default())
  967. return "";
  968. if (m_is_rgb) {
  969. return String::format("\033[48;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  970. } else {
  971. return String::format("\033[%dm", (u8)m_xterm_color + 40);
  972. }
  973. }
  974. String Style::Foreground::to_vt_escape() const
  975. {
  976. if (is_default())
  977. return "";
  978. if (m_is_rgb) {
  979. return String::format("\033[38;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  980. } else {
  981. return String::format("\033[%dm", (u8)m_xterm_color + 30);
  982. }
  983. }
  984. String Style::Hyperlink::to_vt_escape(bool starting) const
  985. {
  986. if (is_empty())
  987. return "";
  988. return String::format("\033]8;;%s\033\\", starting ? m_link.characters() : "");
  989. }
  990. void Style::unify_with(const Style& other, bool prefer_other)
  991. {
  992. // Unify colors.
  993. if (prefer_other || m_background.is_default())
  994. m_background = other.background();
  995. if (prefer_other || m_foreground.is_default())
  996. m_foreground = other.foreground();
  997. // Unify graphic renditions.
  998. if (other.bold())
  999. set(Bold);
  1000. if (other.italic())
  1001. set(Italic);
  1002. if (other.underline())
  1003. set(Underline);
  1004. // Unify links.
  1005. if (prefer_other || m_hyperlink.is_empty())
  1006. m_hyperlink = other.hyperlink();
  1007. }
  1008. String Style::to_string() const
  1009. {
  1010. StringBuilder builder;
  1011. builder.append("Style { ");
  1012. if (!m_foreground.is_default()) {
  1013. builder.append("Foreground(");
  1014. if (m_foreground.m_is_rgb) {
  1015. builder.join(", ", m_foreground.m_rgb_color);
  1016. } else {
  1017. builder.appendf("(XtermColor) %d", m_foreground.m_xterm_color);
  1018. }
  1019. builder.append("), ");
  1020. }
  1021. if (!m_background.is_default()) {
  1022. builder.append("Background(");
  1023. if (m_background.m_is_rgb) {
  1024. builder.join(' ', m_background.m_rgb_color);
  1025. } else {
  1026. builder.appendf("(XtermColor) %d", m_background.m_xterm_color);
  1027. }
  1028. builder.append("), ");
  1029. }
  1030. if (bold())
  1031. builder.append("Bold, ");
  1032. if (underline())
  1033. builder.append("Underline, ");
  1034. if (italic())
  1035. builder.append("Italic, ");
  1036. if (!m_hyperlink.is_empty())
  1037. builder.appendf("Hyperlink(\"%s\"), ", m_hyperlink.m_link.characters());
  1038. builder.append("}");
  1039. return builder.build();
  1040. }
  1041. void VT::apply_style(const Style& style, bool is_starting)
  1042. {
  1043. if (is_starting) {
  1044. fprintf(stderr,
  1045. "\033[%d;%d;%dm%s%s%s",
  1046. style.bold() ? 1 : 22,
  1047. style.underline() ? 4 : 24,
  1048. style.italic() ? 3 : 23,
  1049. style.background().to_vt_escape().characters(),
  1050. style.foreground().to_vt_escape().characters(),
  1051. style.hyperlink().to_vt_escape(true).characters());
  1052. } else {
  1053. fprintf(stderr, "%s", style.hyperlink().to_vt_escape(false).characters());
  1054. }
  1055. }
  1056. void VT::clear_lines(size_t count_above, size_t count_below)
  1057. {
  1058. // Go down count_below lines.
  1059. if (count_below > 0)
  1060. fprintf(stderr, "\033[%dB", (int)count_below);
  1061. // Then clear lines going upwards.
  1062. for (size_t i = count_below + count_above; i > 0; --i)
  1063. fputs(i == 1 ? "\033[2K" : "\033[2K\033[A", stderr);
  1064. }
  1065. void VT::save_cursor()
  1066. {
  1067. fputs("\033[s", stderr);
  1068. fflush(stderr);
  1069. }
  1070. void VT::restore_cursor()
  1071. {
  1072. fputs("\033[u", stderr);
  1073. fflush(stderr);
  1074. }
  1075. void VT::clear_to_end_of_line()
  1076. {
  1077. fputs("\033[K", stderr);
  1078. fflush(stderr);
  1079. }
  1080. StringMetrics Editor::actual_rendered_string_metrics(const StringView& string)
  1081. {
  1082. size_t length { 0 };
  1083. StringMetrics metrics;
  1084. VTState state { Free };
  1085. Utf8View view { string };
  1086. auto it = view.begin();
  1087. for (; it != view.end(); ++it) {
  1088. auto c = *it;
  1089. auto it_copy = it;
  1090. ++it_copy;
  1091. auto next_c = it_copy == view.end() ? 0 : *it_copy;
  1092. state = actual_rendered_string_length_step(metrics, length, c, next_c, state);
  1093. }
  1094. metrics.line_lengths.append(length);
  1095. for (auto& line : metrics.line_lengths)
  1096. metrics.max_line_length = max(line, metrics.max_line_length);
  1097. return metrics;
  1098. }
  1099. StringMetrics Editor::actual_rendered_string_metrics(const Utf32View& view)
  1100. {
  1101. size_t length { 0 };
  1102. StringMetrics metrics;
  1103. VTState state { Free };
  1104. for (size_t i = 0; i < view.length(); ++i) {
  1105. auto c = view.code_points()[i];
  1106. auto next_c = i + 1 < view.length() ? view.code_points()[i + 1] : 0;
  1107. state = actual_rendered_string_length_step(metrics, length, c, next_c, state);
  1108. }
  1109. metrics.line_lengths.append(length);
  1110. for (auto& line : metrics.line_lengths)
  1111. metrics.max_line_length = max(line, metrics.max_line_length);
  1112. return metrics;
  1113. }
  1114. Editor::VTState Editor::actual_rendered_string_length_step(StringMetrics& metrics, size_t& length, u32 c, u32 next_c, VTState state)
  1115. {
  1116. switch (state) {
  1117. case Free:
  1118. if (c == '\x1b') { // escape
  1119. return Escape;
  1120. }
  1121. if (c == '\r') { // carriage return
  1122. length = 0;
  1123. if (!metrics.line_lengths.is_empty())
  1124. metrics.line_lengths.last() = 0;
  1125. return state;
  1126. }
  1127. if (c == '\n') { // return
  1128. metrics.line_lengths.append(length);
  1129. length = 0;
  1130. return state;
  1131. }
  1132. // FIXME: This will not support anything sophisticated
  1133. ++length;
  1134. ++metrics.total_length;
  1135. return state;
  1136. case Escape:
  1137. if (c == ']') {
  1138. if (next_c == '0')
  1139. state = Title;
  1140. return state;
  1141. }
  1142. if (c == '[') {
  1143. return Bracket;
  1144. }
  1145. // FIXME: This does not support non-VT (aside from set-title) escapes
  1146. return state;
  1147. case Bracket:
  1148. if (isdigit(c)) {
  1149. return BracketArgsSemi;
  1150. }
  1151. return state;
  1152. case BracketArgsSemi:
  1153. if (c == ';') {
  1154. return Bracket;
  1155. }
  1156. if (!isdigit(c))
  1157. state = Free;
  1158. return state;
  1159. case Title:
  1160. if (c == 7)
  1161. state = Free;
  1162. return state;
  1163. }
  1164. return state;
  1165. }
  1166. Vector<size_t, 2> Editor::vt_dsr()
  1167. {
  1168. char buf[16];
  1169. u32 length { 0 };
  1170. // Read whatever junk there is before talking to the terminal
  1171. // and insert them later when we're reading user input.
  1172. bool more_junk_to_read { false };
  1173. timeval timeout { 0, 0 };
  1174. fd_set readfds;
  1175. FD_ZERO(&readfds);
  1176. FD_SET(0, &readfds);
  1177. do {
  1178. more_junk_to_read = false;
  1179. (void)select(1, &readfds, nullptr, nullptr, &timeout);
  1180. if (FD_ISSET(0, &readfds)) {
  1181. auto nread = read(0, buf, 16);
  1182. if (nread < 0) {
  1183. m_input_error = Error::ReadFailure;
  1184. finish();
  1185. break;
  1186. }
  1187. if (nread == 0)
  1188. break;
  1189. m_incomplete_data.append(buf, nread);
  1190. more_junk_to_read = true;
  1191. }
  1192. } while (more_junk_to_read);
  1193. if (m_input_error.has_value())
  1194. return { 1, 1 };
  1195. fputs("\033[6n", stderr);
  1196. fflush(stderr);
  1197. do {
  1198. auto nread = read(0, buf + length, 16 - length);
  1199. if (nread < 0) {
  1200. if (errno == 0) {
  1201. // ????
  1202. continue;
  1203. }
  1204. dbg() << "Error while reading DSR: " << strerror(errno);
  1205. m_input_error = Error::ReadFailure;
  1206. finish();
  1207. return { 1, 1 };
  1208. }
  1209. if (nread == 0) {
  1210. m_input_error = Error::Empty;
  1211. finish();
  1212. dbg() << "Terminal DSR issue; received no response";
  1213. return { 1, 1 };
  1214. }
  1215. length += nread;
  1216. } while (buf[length - 1] != 'R' && length < 16);
  1217. size_t row { 1 }, col { 1 };
  1218. if (buf[0] == '\033' && buf[1] == '[') {
  1219. auto parts = StringView(buf + 2, length - 3).split_view(';');
  1220. auto row_opt = parts[0].to_int();
  1221. if (!row_opt.has_value()) {
  1222. dbg() << "Terminal DSR issue; received garbage row";
  1223. } else {
  1224. row = row_opt.value();
  1225. }
  1226. auto col_opt = parts[1].to_int();
  1227. if (!col_opt.has_value()) {
  1228. dbg() << "Terminal DSR issue; received garbage col";
  1229. } else {
  1230. col = col_opt.value();
  1231. }
  1232. }
  1233. return { row, col };
  1234. }
  1235. String Editor::line(size_t up_to_index) const
  1236. {
  1237. StringBuilder builder;
  1238. builder.append(Utf32View { m_buffer.data(), min(m_buffer.size(), up_to_index) });
  1239. return builder.build();
  1240. }
  1241. void Editor::remove_at_index(size_t index)
  1242. {
  1243. // See if we have any anchored styles, and reposition them if needed.
  1244. readjust_anchored_styles(index, ModificationKind::Removal);
  1245. auto cp = m_buffer[index];
  1246. m_buffer.remove(index);
  1247. if (cp == '\n')
  1248. ++m_extra_forward_lines;
  1249. }
  1250. void Editor::readjust_anchored_styles(size_t hint_index, ModificationKind modification)
  1251. {
  1252. struct Anchor {
  1253. Span old_span;
  1254. Span new_span;
  1255. Style style;
  1256. };
  1257. Vector<Anchor> anchors_to_relocate;
  1258. auto index_shift = modification == ModificationKind::Insertion ? 1 : -1;
  1259. auto forced_removal = modification == ModificationKind::ForcedOverlapRemoval;
  1260. for (auto& start_entry : m_anchored_spans_starting) {
  1261. for (auto& end_entry : start_entry.value) {
  1262. if (forced_removal) {
  1263. if (start_entry.key <= hint_index && end_entry.key > hint_index) {
  1264. // Remove any overlapping regions.
  1265. continue;
  1266. }
  1267. }
  1268. if (start_entry.key >= hint_index) {
  1269. if (start_entry.key == hint_index && end_entry.key == hint_index + 1 && modification == ModificationKind::Removal) {
  1270. // Remove the anchor, as all its text was wiped.
  1271. continue;
  1272. }
  1273. // Shift everything.
  1274. anchors_to_relocate.append({ { start_entry.key, end_entry.key, Span::Mode::CodepointOriented }, { start_entry.key + index_shift, end_entry.key + index_shift, Span::Mode::CodepointOriented }, end_entry.value });
  1275. continue;
  1276. }
  1277. if (end_entry.key > hint_index) {
  1278. // Shift just the end.
  1279. anchors_to_relocate.append({ { start_entry.key, end_entry.key, Span::Mode::CodepointOriented }, { start_entry.key, end_entry.key + index_shift, Span::Mode::CodepointOriented }, end_entry.value });
  1280. continue;
  1281. }
  1282. anchors_to_relocate.append({ { start_entry.key, end_entry.key, Span::Mode::CodepointOriented }, { start_entry.key, end_entry.key, Span::Mode::CodepointOriented }, end_entry.value });
  1283. }
  1284. }
  1285. m_anchored_spans_ending.clear();
  1286. m_anchored_spans_starting.clear();
  1287. // Pass over the relocations and update the stale entries.
  1288. for (auto& relocation : anchors_to_relocate) {
  1289. stylize(relocation.new_span, relocation.style);
  1290. }
  1291. }
  1292. size_t StringMetrics::lines_with_addition(const StringMetrics& offset, size_t column_width) const
  1293. {
  1294. size_t lines = 0;
  1295. for (size_t i = 0; i < line_lengths.size() - 1; ++i)
  1296. lines += (line_lengths[i] + column_width) / column_width;
  1297. auto last = line_lengths.last();
  1298. last += offset.line_lengths.first();
  1299. lines += (last + column_width) / column_width;
  1300. for (size_t i = 1; i < offset.line_lengths.size(); ++i)
  1301. lines += (offset.line_lengths[i] + column_width) / column_width;
  1302. return lines;
  1303. }
  1304. }