Editor.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  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/ScopeGuard.h>
  30. #include <AK/StringBuilder.h>
  31. #include <AK/Utf32View.h>
  32. #include <AK/Utf8View.h>
  33. #include <LibCore/ConfigFile.h>
  34. #include <LibCore/Event.h>
  35. #include <LibCore/EventLoop.h>
  36. #include <LibCore/Notifier.h>
  37. #include <ctype.h>
  38. #include <signal.h>
  39. #include <stdio.h>
  40. #include <sys/ioctl.h>
  41. #include <sys/select.h>
  42. #include <sys/time.h>
  43. #include <unistd.h>
  44. // #define SUGGESTIONS_DEBUG
  45. namespace {
  46. constexpr u32 ctrl(char c) { return c & 0x3f; }
  47. }
  48. namespace Line {
  49. Configuration Configuration::from_config(const StringView& libname)
  50. {
  51. Configuration configuration;
  52. auto config_file = Core::ConfigFile::get_for_lib(libname);
  53. // Read behaviour options.
  54. auto refresh = config_file->read_entry("behaviour", "refresh", "lazy");
  55. auto operation = config_file->read_entry("behaviour", "operation_mode");
  56. if (refresh.equals_ignoring_case("lazy"))
  57. configuration.set(Configuration::Lazy);
  58. else if (refresh.equals_ignoring_case("eager"))
  59. configuration.set(Configuration::Eager);
  60. if (operation.equals_ignoring_case("full"))
  61. configuration.set(Configuration::OperationMode::Full);
  62. else if (operation.equals_ignoring_case("noescapesequences"))
  63. configuration.set(Configuration::OperationMode::NoEscapeSequences);
  64. else if (operation.equals_ignoring_case("noninteractive"))
  65. configuration.set(Configuration::OperationMode::NonInteractive);
  66. else
  67. configuration.set(Configuration::OperationMode::Unset);
  68. // Read keybinds.
  69. for (auto& binding_key : config_file->keys("keybinds")) {
  70. GenericLexer key_lexer(binding_key);
  71. auto has_ctrl = false;
  72. auto alt = false;
  73. Vector<Key> keys;
  74. while (!key_lexer.is_eof()) {
  75. if (key_lexer.next_is("alt+")) {
  76. alt = key_lexer.consume_specific("alt+");
  77. continue;
  78. }
  79. if (key_lexer.next_is("^[")) {
  80. alt = key_lexer.consume_specific("^[");
  81. continue;
  82. }
  83. if (key_lexer.next_is("^")) {
  84. has_ctrl = key_lexer.consume_specific("^");
  85. continue;
  86. }
  87. if (key_lexer.next_is("ctrl+")) {
  88. has_ctrl = key_lexer.consume_specific("ctrl+");
  89. continue;
  90. }
  91. // FIXME: Support utf?
  92. unsigned key = key_lexer.consume();
  93. if (has_ctrl)
  94. key = ctrl(key);
  95. keys.append(Key { key, alt ? Key::Alt : Key::None });
  96. alt = false;
  97. has_ctrl = false;
  98. }
  99. auto value = config_file->read_entry("keybinds", binding_key);
  100. if (value.starts_with("internal:")) {
  101. configuration.set(KeyBinding {
  102. keys,
  103. KeyBinding::Kind::InternalFunction,
  104. value.substring(9, value.length() - 9) });
  105. } else {
  106. configuration.set(KeyBinding {
  107. keys,
  108. KeyBinding::Kind::Insertion,
  109. value });
  110. }
  111. }
  112. return configuration;
  113. }
  114. void Editor::set_default_keybinds()
  115. {
  116. register_key_input_callback(ctrl('N'), EDITOR_INTERNAL_FUNCTION(search_forwards));
  117. register_key_input_callback(ctrl('P'), EDITOR_INTERNAL_FUNCTION(search_backwards));
  118. // Normally ^W. `stty werase \^n` can change it to ^N (or something else), but Serenity doesn't have `stty` yet.
  119. register_key_input_callback(m_termios.c_cc[VWERASE], EDITOR_INTERNAL_FUNCTION(erase_word_backwards));
  120. // Normally ^U. `stty kill \^n` can change it to ^N (or something else), but Serenity doesn't have `stty` yet.
  121. register_key_input_callback(m_termios.c_cc[VKILL], EDITOR_INTERNAL_FUNCTION(kill_line));
  122. register_key_input_callback(ctrl('A'), EDITOR_INTERNAL_FUNCTION(go_home));
  123. register_key_input_callback(ctrl('B'), EDITOR_INTERNAL_FUNCTION(cursor_left_character));
  124. register_key_input_callback(ctrl('D'), EDITOR_INTERNAL_FUNCTION(erase_character_forwards));
  125. register_key_input_callback(ctrl('E'), EDITOR_INTERNAL_FUNCTION(go_end));
  126. register_key_input_callback(ctrl('F'), EDITOR_INTERNAL_FUNCTION(cursor_right_character));
  127. // ^H: ctrl('H') == '\b'
  128. register_key_input_callback(ctrl('H'), EDITOR_INTERNAL_FUNCTION(erase_character_backwards));
  129. register_key_input_callback(m_termios.c_cc[VERASE], EDITOR_INTERNAL_FUNCTION(erase_character_backwards));
  130. register_key_input_callback(ctrl('K'), EDITOR_INTERNAL_FUNCTION(erase_to_end));
  131. register_key_input_callback(ctrl('L'), EDITOR_INTERNAL_FUNCTION(clear_screen));
  132. register_key_input_callback(ctrl('R'), EDITOR_INTERNAL_FUNCTION(enter_search));
  133. register_key_input_callback(ctrl('T'), EDITOR_INTERNAL_FUNCTION(transpose_characters));
  134. register_key_input_callback('\n', EDITOR_INTERNAL_FUNCTION(finish));
  135. // ^[.: alt-.: insert last arg of previous command (similar to `!$`)
  136. register_key_input_callback(Key { '.', Key::Alt }, EDITOR_INTERNAL_FUNCTION(insert_last_words));
  137. register_key_input_callback(Key { 'b', Key::Alt }, EDITOR_INTERNAL_FUNCTION(cursor_left_word));
  138. register_key_input_callback(Key { 'f', Key::Alt }, EDITOR_INTERNAL_FUNCTION(cursor_right_word));
  139. // ^[^H: alt-backspace: backward delete word
  140. register_key_input_callback(Key { '\b', Key::Alt }, EDITOR_INTERNAL_FUNCTION(erase_alnum_word_backwards));
  141. register_key_input_callback(Key { 'd', Key::Alt }, EDITOR_INTERNAL_FUNCTION(erase_alnum_word_forwards));
  142. register_key_input_callback(Key { 'c', Key::Alt }, EDITOR_INTERNAL_FUNCTION(capitalize_word));
  143. register_key_input_callback(Key { 'l', Key::Alt }, EDITOR_INTERNAL_FUNCTION(lowercase_word));
  144. register_key_input_callback(Key { 'u', Key::Alt }, EDITOR_INTERNAL_FUNCTION(uppercase_word));
  145. register_key_input_callback(Key { 't', Key::Alt }, EDITOR_INTERNAL_FUNCTION(transpose_words));
  146. }
  147. Editor::Editor(Configuration configuration)
  148. : m_configuration(move(configuration))
  149. {
  150. m_always_refresh = configuration.refresh_behaviour == Configuration::RefreshBehaviour::Eager;
  151. m_pending_chars = ByteBuffer::create_uninitialized(0);
  152. get_terminal_size();
  153. m_suggestion_display = make<XtermSuggestionDisplay>(m_num_lines, m_num_columns);
  154. }
  155. Editor::~Editor()
  156. {
  157. if (m_initialized)
  158. restore();
  159. }
  160. void Editor::get_terminal_size()
  161. {
  162. struct winsize ws;
  163. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  164. m_num_columns = 80;
  165. m_num_lines = 25;
  166. } else {
  167. m_num_columns = ws.ws_col;
  168. m_num_lines = ws.ws_row;
  169. }
  170. }
  171. void Editor::add_to_history(const String& line)
  172. {
  173. if (line.is_empty())
  174. return;
  175. if ((m_history.size() + 1) > m_history_capacity)
  176. m_history.take_first();
  177. m_history.append(line);
  178. }
  179. void Editor::clear_line()
  180. {
  181. for (size_t i = 0; i < m_cursor; ++i)
  182. fputc(0x8, stderr);
  183. fputs("\033[K", stderr);
  184. fflush(stderr);
  185. m_buffer.clear();
  186. m_cursor = 0;
  187. m_inline_search_cursor = m_cursor;
  188. }
  189. void Editor::insert(const Utf32View& string)
  190. {
  191. for (size_t i = 0; i < string.length(); ++i)
  192. insert(string.code_points()[i]);
  193. }
  194. void Editor::insert(const String& string)
  195. {
  196. for (auto ch : Utf8View { string })
  197. insert(ch);
  198. }
  199. void Editor::insert(const StringView& string_view)
  200. {
  201. for (auto ch : Utf8View { string_view })
  202. insert(ch);
  203. }
  204. void Editor::insert(const u32 cp)
  205. {
  206. StringBuilder builder;
  207. builder.append(Utf32View(&cp, 1));
  208. auto str = builder.build();
  209. m_pending_chars.append(str.characters(), str.length());
  210. readjust_anchored_styles(m_cursor, ModificationKind::Insertion);
  211. if (m_cursor == m_buffer.size()) {
  212. m_buffer.append(cp);
  213. m_cursor = m_buffer.size();
  214. m_inline_search_cursor = m_cursor;
  215. return;
  216. }
  217. m_buffer.insert(m_cursor, cp);
  218. ++m_chars_inserted_in_the_middle;
  219. ++m_cursor;
  220. m_inline_search_cursor = m_cursor;
  221. }
  222. void Editor::register_key_input_callback(const KeyBinding& binding)
  223. {
  224. if (binding.kind == KeyBinding::Kind::InternalFunction) {
  225. auto internal_function = find_internal_function(binding.binding);
  226. if (!internal_function) {
  227. dbg() << "LibLine: Unknown internal function '" << binding.binding << "'";
  228. return;
  229. }
  230. return register_key_input_callback(binding.keys, move(internal_function));
  231. }
  232. return register_key_input_callback(binding.keys, [binding = String(binding.binding)](auto& editor) {
  233. editor.insert(binding);
  234. return false;
  235. });
  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. m_callback_machine.interrupted(*this);
  472. if (!m_callback_machine.should_process_last_pressed_key())
  473. return;
  474. fprintf(stderr, "^C");
  475. fflush(stderr);
  476. if (on_interrupt_handled)
  477. on_interrupt_handled();
  478. m_buffer.clear();
  479. m_cursor = 0;
  480. finish();
  481. }
  482. void Editor::handle_read_event()
  483. {
  484. char keybuf[16];
  485. ssize_t nread = 0;
  486. if (!m_incomplete_data.size())
  487. nread = read(0, keybuf, sizeof(keybuf));
  488. if (nread < 0) {
  489. if (errno == EINTR) {
  490. if (!m_was_interrupted) {
  491. if (m_was_resized)
  492. return;
  493. finish();
  494. return;
  495. }
  496. handle_interrupt_event();
  497. return;
  498. }
  499. ScopedValueRollback errno_restorer(errno);
  500. perror("read failed");
  501. m_input_error = Error::ReadFailure;
  502. finish();
  503. return;
  504. }
  505. m_incomplete_data.append(keybuf, nread);
  506. nread = m_incomplete_data.size();
  507. if (nread == 0) {
  508. m_input_error = Error::Empty;
  509. finish();
  510. return;
  511. }
  512. auto reverse_tab = false;
  513. // Discard starting bytes until they make sense as utf-8.
  514. size_t valid_bytes = 0;
  515. while (nread) {
  516. Utf8View { StringView { m_incomplete_data.data(), (size_t)nread } }.validate(valid_bytes);
  517. if (valid_bytes)
  518. break;
  519. m_incomplete_data.take_first();
  520. --nread;
  521. }
  522. Utf8View input_view { StringView { m_incomplete_data.data(), valid_bytes } };
  523. size_t consumed_code_points = 0;
  524. Vector<u8, 4> csi_parameter_bytes;
  525. Vector<unsigned, 4> csi_parameters;
  526. Vector<u8> csi_intermediate_bytes;
  527. u8 csi_final;
  528. enum CSIMod {
  529. Shift = 1,
  530. Alt = 2,
  531. Ctrl = 4,
  532. };
  533. for (auto code_point : input_view) {
  534. if (m_finish)
  535. break;
  536. ++consumed_code_points;
  537. if (code_point == 0)
  538. continue;
  539. switch (m_state) {
  540. case InputState::GotEscape:
  541. switch (code_point) {
  542. case '[':
  543. m_state = InputState::CSIExpectParameter;
  544. continue;
  545. default: {
  546. m_state = InputState::Free;
  547. m_callback_machine.key_pressed(*this, { code_point, Key::Alt });
  548. cleanup_suggestions();
  549. continue;
  550. }
  551. }
  552. case InputState::CSIExpectParameter:
  553. if (code_point >= 0x30 && code_point <= 0x3f) { // '0123456789:;<=>?'
  554. csi_parameter_bytes.append(code_point);
  555. continue;
  556. }
  557. m_state = InputState::CSIExpectIntermediate;
  558. [[fallthrough]];
  559. case InputState::CSIExpectIntermediate:
  560. if (code_point >= 0x20 && code_point <= 0x2f) { // ' !"#$%&\'()*+,-./'
  561. csi_intermediate_bytes.append(code_point);
  562. continue;
  563. }
  564. m_state = InputState::CSIExpectFinal;
  565. [[fallthrough]];
  566. case InputState::CSIExpectFinal: {
  567. m_state = InputState::Free;
  568. if (!(code_point >= 0x40 && code_point <= 0x7f)) {
  569. dbgprintf("LibLine: Invalid CSI: %02x (%c)\r\n", code_point, code_point);
  570. continue;
  571. }
  572. csi_final = code_point;
  573. for (auto& parameter : String::copy(csi_parameter_bytes).split(';')) {
  574. if (auto value = parameter.to_uint(); value.has_value())
  575. csi_parameters.append(value.value());
  576. else
  577. csi_parameters.append(0);
  578. }
  579. unsigned param1 = 0, param2 = 0;
  580. if (csi_parameters.size() >= 1)
  581. param1 = csi_parameters[0];
  582. if (csi_parameters.size() >= 2)
  583. param2 = csi_parameters[1];
  584. unsigned modifiers = param2 ? param2 - 1 : 0;
  585. if (csi_final == 'Z') {
  586. // 'reverse tab'
  587. reverse_tab = true;
  588. break;
  589. }
  590. cleanup_suggestions();
  591. switch (csi_final) {
  592. case 'A': // ^[[A: arrow up
  593. search_backwards();
  594. continue;
  595. case 'B': // ^[[B: arrow down
  596. search_forwards();
  597. continue;
  598. case 'D': // ^[[D: arrow left
  599. if (modifiers == CSIMod::Alt || modifiers == CSIMod::Ctrl)
  600. cursor_left_word();
  601. else
  602. cursor_left_character();
  603. continue;
  604. case 'C': // ^[[C: arrow right
  605. if (modifiers == CSIMod::Alt || modifiers == CSIMod::Ctrl)
  606. cursor_right_word();
  607. else
  608. cursor_right_character();
  609. continue;
  610. case 'H': // ^[[H: home
  611. go_home();
  612. continue;
  613. case 'F': // ^[[F: end
  614. go_end();
  615. continue;
  616. case '~':
  617. if (param1 == 3) { // ^[[3~: delete
  618. if (modifiers == CSIMod::Ctrl)
  619. erase_alnum_word_forwards();
  620. else
  621. erase_character_forwards();
  622. m_search_offset = 0;
  623. continue;
  624. }
  625. // ^[[5~: page up
  626. // ^[[6~: page down
  627. dbgprintf("LibLine: Unhandled '~': %d\r\n", param1);
  628. continue;
  629. default:
  630. dbgprintf("LibLine: Unhandled final: %02x (%c)\r\n", code_point, code_point);
  631. continue;
  632. }
  633. break;
  634. }
  635. case InputState::Free:
  636. if (code_point == 27) {
  637. m_state = InputState::GotEscape;
  638. continue;
  639. }
  640. break;
  641. }
  642. // There are no sequences past this point, so short of 'tab', we will want to cleanup the suggestions.
  643. ArmedScopeGuard suggestion_cleanup { [this] { cleanup_suggestions(); } };
  644. // Normally ^D. `stty eof \^n` can change it to ^N (or something else), but Serenity doesn't have `stty` yet.
  645. // Process this here since the keybinds might override its behaviour.
  646. // This only applies when the buffer is empty. at any other time, the behaviour should be configurable.
  647. if (code_point == m_termios.c_cc[VEOF] && m_buffer.size() == 0) {
  648. finish_edit();
  649. continue;
  650. }
  651. m_callback_machine.key_pressed(*this, code_point);
  652. if (!m_callback_machine.should_process_last_pressed_key())
  653. continue;
  654. m_search_offset = 0; // reset search offset on any key
  655. if (code_point == '\t' || reverse_tab) {
  656. suggestion_cleanup.disarm();
  657. if (!on_tab_complete)
  658. continue;
  659. // Reverse tab can count as regular tab here.
  660. m_times_tab_pressed++;
  661. int token_start = m_cursor;
  662. // Ask for completions only on the first tab
  663. // and scan for the largest common prefix to display,
  664. // further tabs simply show the cached completions.
  665. if (m_times_tab_pressed == 1) {
  666. m_suggestion_manager.set_suggestions(on_tab_complete(*this));
  667. m_prompt_lines_at_suggestion_initiation = num_lines();
  668. if (m_suggestion_manager.count() == 0) {
  669. // There are no suggestions, beep.
  670. fputc('\a', stderr);
  671. fflush(stderr);
  672. }
  673. }
  674. // Adjust already incremented / decremented index when switching tab direction.
  675. if (reverse_tab && m_tab_direction != TabDirection::Backward) {
  676. m_suggestion_manager.previous();
  677. m_suggestion_manager.previous();
  678. m_tab_direction = TabDirection::Backward;
  679. }
  680. if (!reverse_tab && m_tab_direction != TabDirection::Forward) {
  681. m_suggestion_manager.next();
  682. m_suggestion_manager.next();
  683. m_tab_direction = TabDirection::Forward;
  684. }
  685. reverse_tab = false;
  686. auto completion_mode = m_times_tab_pressed == 1 ? SuggestionManager::CompletePrefix : m_times_tab_pressed == 2 ? SuggestionManager::ShowSuggestions : SuggestionManager::CycleSuggestions;
  687. auto completion_result = m_suggestion_manager.attempt_completion(completion_mode, token_start);
  688. auto new_cursor = m_cursor + completion_result.new_cursor_offset;
  689. for (size_t i = completion_result.offset_region_to_remove.start; i < completion_result.offset_region_to_remove.end; ++i)
  690. remove_at_index(new_cursor);
  691. m_cursor = new_cursor;
  692. m_inline_search_cursor = new_cursor;
  693. m_refresh_needed = true;
  694. for (auto& view : completion_result.insert)
  695. insert(view);
  696. if (completion_result.style_to_apply.has_value()) {
  697. // Apply the style of the last suggestion.
  698. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  699. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, completion_result.style_to_apply.value());
  700. }
  701. switch (completion_result.new_completion_mode) {
  702. case SuggestionManager::DontComplete:
  703. m_times_tab_pressed = 0;
  704. break;
  705. case SuggestionManager::CompletePrefix:
  706. break;
  707. default:
  708. ++m_times_tab_pressed;
  709. break;
  710. }
  711. if (m_times_tab_pressed > 1) {
  712. if (m_suggestion_manager.count() > 0) {
  713. if (m_suggestion_display->cleanup())
  714. reposition_cursor();
  715. m_suggestion_display->set_initial_prompt_lines(m_prompt_lines_at_suggestion_initiation);
  716. m_suggestion_display->display(m_suggestion_manager);
  717. m_origin_row = m_suggestion_display->origin_row();
  718. }
  719. }
  720. if (m_times_tab_pressed > 2) {
  721. if (m_tab_direction == TabDirection::Forward)
  722. m_suggestion_manager.next();
  723. else
  724. m_suggestion_manager.previous();
  725. }
  726. if (m_suggestion_manager.count() < 2) {
  727. // We have none, or just one suggestion,
  728. // we should just commit that and continue
  729. // after it, as if it were auto-completed.
  730. suggest(0, 0, Span::CodepointOriented);
  731. m_times_tab_pressed = 0;
  732. m_suggestion_manager.reset();
  733. m_suggestion_display->finish();
  734. }
  735. continue;
  736. }
  737. insert(code_point);
  738. }
  739. if (consumed_code_points == m_incomplete_data.size()) {
  740. m_incomplete_data.clear();
  741. } else {
  742. for (size_t i = 0; i < consumed_code_points; ++i)
  743. m_incomplete_data.take_first();
  744. }
  745. }
  746. void Editor::cleanup_suggestions()
  747. {
  748. if (m_times_tab_pressed) {
  749. // Apply the style of the last suggestion.
  750. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  751. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, m_suggestion_manager.current_suggestion().style);
  752. // We probably have some suggestions drawn,
  753. // let's clean them up.
  754. if (m_suggestion_display->cleanup()) {
  755. reposition_cursor();
  756. m_refresh_needed = true;
  757. }
  758. m_suggestion_manager.reset();
  759. suggest(0, 0, Span::CodepointOriented);
  760. m_suggestion_display->finish();
  761. }
  762. m_times_tab_pressed = 0; // Safe to say if we get here, the user didn't press TAB
  763. }
  764. bool Editor::search(const StringView& phrase, bool allow_empty, bool from_beginning)
  765. {
  766. int last_matching_offset = -1;
  767. bool found = false;
  768. // Do not search for empty strings.
  769. if (allow_empty || phrase.length() > 0) {
  770. size_t search_offset = m_search_offset;
  771. for (size_t i = m_history_cursor; i > 0; --i) {
  772. auto& entry = m_history[i - 1];
  773. auto contains = from_beginning ? entry.starts_with(phrase) : entry.contains(phrase);
  774. if (contains) {
  775. last_matching_offset = i - 1;
  776. if (search_offset == 0) {
  777. found = true;
  778. break;
  779. }
  780. --search_offset;
  781. }
  782. }
  783. if (!found) {
  784. fputc('\a', stderr);
  785. fflush(stderr);
  786. }
  787. }
  788. if (found) {
  789. m_buffer.clear();
  790. m_cursor = 0;
  791. insert(m_history[last_matching_offset]);
  792. // Always needed, as we have cleared the buffer above.
  793. m_refresh_needed = true;
  794. }
  795. return found;
  796. }
  797. void Editor::recalculate_origin()
  798. {
  799. // Changing the columns can affect our origin if
  800. // the new size is smaller than our prompt, which would
  801. // cause said prompt to take up more space, so we should
  802. // compensate for that.
  803. if (m_cached_prompt_metrics.max_line_length >= m_num_columns) {
  804. auto added_lines = (m_cached_prompt_metrics.max_line_length + 1) / m_num_columns - 1;
  805. m_origin_row += added_lines;
  806. }
  807. // We also need to recalculate our cursor position,
  808. // but that will be calculated and applied at the next
  809. // refresh cycle.
  810. }
  811. void Editor::cleanup()
  812. {
  813. auto current_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  814. auto new_lines = current_prompt_metrics().lines_with_addition(current_buffer_metrics, m_num_columns);
  815. auto shown_lines = num_lines();
  816. if (new_lines < shown_lines)
  817. m_extra_forward_lines = max(shown_lines - new_lines, m_extra_forward_lines);
  818. VT::move_relative(-m_extra_forward_lines, m_pending_chars.size() - m_chars_inserted_in_the_middle);
  819. auto current_line = cursor_line();
  820. // There's a newline at the top, don't clear that line.
  821. if (current_prompt_metrics().line_lengths.first() == 0)
  822. --current_line;
  823. VT::clear_lines(current_line - 1, num_lines() - current_line + m_extra_forward_lines);
  824. m_extra_forward_lines = 0;
  825. reposition_cursor();
  826. };
  827. void Editor::refresh_display()
  828. {
  829. auto has_cleaned_up = false;
  830. // Someone changed the window size, figure it out
  831. // and react to it, we might need to redraw.
  832. if (m_was_resized) {
  833. if (m_previous_num_columns != m_num_columns) {
  834. // We need to cleanup and redo everything.
  835. m_cached_prompt_valid = false;
  836. m_refresh_needed = true;
  837. swap(m_previous_num_columns, m_num_columns);
  838. recalculate_origin();
  839. cleanup();
  840. swap(m_previous_num_columns, m_num_columns);
  841. has_cleaned_up = true;
  842. }
  843. m_was_resized = false;
  844. }
  845. // Do not call hook on pure cursor movement.
  846. if (m_cached_prompt_valid && !m_refresh_needed && m_pending_chars.size() == 0) {
  847. // Probably just moving around.
  848. reposition_cursor();
  849. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  850. return;
  851. }
  852. // We might be at the last line, and have more than one line;
  853. // Refreshing the display will cause the terminal to scroll,
  854. // so note that fact and bring origin up.
  855. auto current_num_lines = num_lines();
  856. if (m_origin_row + current_num_lines > m_num_lines + 1) {
  857. if (current_num_lines > m_num_lines)
  858. m_origin_row = 0;
  859. else
  860. m_origin_row = m_num_lines - current_num_lines + 1;
  861. }
  862. if (on_display_refresh)
  863. on_display_refresh(*this);
  864. if (m_cached_prompt_valid) {
  865. if (!m_refresh_needed && m_cursor == m_buffer.size()) {
  866. // Just write the characters out and continue,
  867. // no need to refresh the entire line.
  868. char null = 0;
  869. m_pending_chars.append(&null, 1);
  870. fputs((char*)m_pending_chars.data(), stderr);
  871. m_pending_chars.clear();
  872. m_drawn_cursor = m_cursor;
  873. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  874. fflush(stderr);
  875. return;
  876. }
  877. }
  878. // Ouch, reflow entire line.
  879. if (!has_cleaned_up) {
  880. cleanup();
  881. }
  882. VT::move_absolute(m_origin_row, m_origin_column);
  883. fputs(m_new_prompt.characters(), stderr);
  884. VT::clear_to_end_of_line();
  885. HashMap<u32, Style> empty_styles {};
  886. StringBuilder builder;
  887. for (size_t i = 0; i < m_buffer.size(); ++i) {
  888. auto ends = m_spans_ending.get(i).value_or(empty_styles);
  889. auto starts = m_spans_starting.get(i).value_or(empty_styles);
  890. auto anchored_ends = m_anchored_spans_ending.get(i).value_or(empty_styles);
  891. auto anchored_starts = m_anchored_spans_starting.get(i).value_or(empty_styles);
  892. if (ends.size() || anchored_ends.size()) {
  893. Style style;
  894. for (auto& applicable_style : ends)
  895. style.unify_with(applicable_style.value);
  896. for (auto& applicable_style : anchored_ends)
  897. style.unify_with(applicable_style.value);
  898. // Disable any style that should be turned off.
  899. VT::apply_style(style, false);
  900. // Reapply styles for overlapping spans that include this one.
  901. style = find_applicable_style(i);
  902. VT::apply_style(style, true);
  903. }
  904. if (starts.size() || anchored_starts.size()) {
  905. Style style;
  906. for (auto& applicable_style : starts)
  907. style.unify_with(applicable_style.value);
  908. for (auto& applicable_style : anchored_starts)
  909. style.unify_with(applicable_style.value);
  910. // Set new styles.
  911. VT::apply_style(style, true);
  912. }
  913. builder.clear();
  914. builder.append(Utf32View { &m_buffer[i], 1 });
  915. fputs(builder.to_string().characters(), stderr);
  916. }
  917. VT::apply_style(Style::reset_style()); // don't bleed to EOL
  918. m_pending_chars.clear();
  919. m_refresh_needed = false;
  920. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  921. m_chars_inserted_in_the_middle = 0;
  922. if (!m_cached_prompt_valid) {
  923. m_cached_prompt_valid = true;
  924. }
  925. reposition_cursor();
  926. fflush(stderr);
  927. }
  928. void Editor::strip_styles(bool strip_anchored)
  929. {
  930. m_spans_starting.clear();
  931. m_spans_ending.clear();
  932. if (strip_anchored) {
  933. m_anchored_spans_starting.clear();
  934. m_anchored_spans_ending.clear();
  935. }
  936. m_refresh_needed = true;
  937. }
  938. void Editor::reposition_cursor(bool to_end)
  939. {
  940. auto cursor = m_cursor;
  941. auto saved_cursor = m_cursor;
  942. if (to_end)
  943. cursor = m_buffer.size();
  944. m_cursor = cursor;
  945. m_drawn_cursor = cursor;
  946. auto line = cursor_line() - 1;
  947. auto column = offset_in_line();
  948. VT::move_absolute(line + m_origin_row, column + m_origin_column);
  949. m_cursor = saved_cursor;
  950. }
  951. void VT::move_absolute(u32 row, u32 col)
  952. {
  953. fprintf(stderr, "\033[%d;%dH", row, col);
  954. fflush(stderr);
  955. }
  956. void VT::move_relative(int row, int col)
  957. {
  958. char x_op = 'A', y_op = 'D';
  959. if (row > 0)
  960. x_op = 'B';
  961. else
  962. row = -row;
  963. if (col > 0)
  964. y_op = 'C';
  965. else
  966. col = -col;
  967. if (row > 0)
  968. fprintf(stderr, "\033[%d%c", row, x_op);
  969. if (col > 0)
  970. fprintf(stderr, "\033[%d%c", col, y_op);
  971. }
  972. Style Editor::find_applicable_style(size_t offset) const
  973. {
  974. // Walk through our styles and merge all that fit in the offset.
  975. auto style = Style::reset_style();
  976. auto unify = [&](auto& entry) {
  977. if (entry.key >= offset)
  978. return;
  979. for (auto& style_value : entry.value) {
  980. if (style_value.key <= offset)
  981. return;
  982. style.unify_with(style_value.value, true);
  983. }
  984. };
  985. for (auto& entry : m_spans_starting) {
  986. unify(entry);
  987. }
  988. for (auto& entry : m_anchored_spans_starting) {
  989. unify(entry);
  990. }
  991. return style;
  992. }
  993. String Style::Background::to_vt_escape() const
  994. {
  995. if (is_default())
  996. return "";
  997. if (m_is_rgb) {
  998. return String::format("\033[48;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  999. } else {
  1000. return String::format("\033[%dm", (u8)m_xterm_color + 40);
  1001. }
  1002. }
  1003. String Style::Foreground::to_vt_escape() const
  1004. {
  1005. if (is_default())
  1006. return "";
  1007. if (m_is_rgb) {
  1008. return String::format("\033[38;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1009. } else {
  1010. return String::format("\033[%dm", (u8)m_xterm_color + 30);
  1011. }
  1012. }
  1013. String Style::Hyperlink::to_vt_escape(bool starting) const
  1014. {
  1015. if (is_empty())
  1016. return "";
  1017. return String::format("\033]8;;%s\033\\", starting ? m_link.characters() : "");
  1018. }
  1019. void Style::unify_with(const Style& other, bool prefer_other)
  1020. {
  1021. // Unify colors.
  1022. if (prefer_other || m_background.is_default())
  1023. m_background = other.background();
  1024. if (prefer_other || m_foreground.is_default())
  1025. m_foreground = other.foreground();
  1026. // Unify graphic renditions.
  1027. if (other.bold())
  1028. set(Bold);
  1029. if (other.italic())
  1030. set(Italic);
  1031. if (other.underline())
  1032. set(Underline);
  1033. // Unify links.
  1034. if (prefer_other || m_hyperlink.is_empty())
  1035. m_hyperlink = other.hyperlink();
  1036. }
  1037. String Style::to_string() const
  1038. {
  1039. StringBuilder builder;
  1040. builder.append("Style { ");
  1041. if (!m_foreground.is_default()) {
  1042. builder.append("Foreground(");
  1043. if (m_foreground.m_is_rgb) {
  1044. builder.join(", ", m_foreground.m_rgb_color);
  1045. } else {
  1046. builder.appendf("(XtermColor) %d", m_foreground.m_xterm_color);
  1047. }
  1048. builder.append("), ");
  1049. }
  1050. if (!m_background.is_default()) {
  1051. builder.append("Background(");
  1052. if (m_background.m_is_rgb) {
  1053. builder.join(' ', m_background.m_rgb_color);
  1054. } else {
  1055. builder.appendf("(XtermColor) %d", m_background.m_xterm_color);
  1056. }
  1057. builder.append("), ");
  1058. }
  1059. if (bold())
  1060. builder.append("Bold, ");
  1061. if (underline())
  1062. builder.append("Underline, ");
  1063. if (italic())
  1064. builder.append("Italic, ");
  1065. if (!m_hyperlink.is_empty())
  1066. builder.appendf("Hyperlink(\"%s\"), ", m_hyperlink.m_link.characters());
  1067. builder.append("}");
  1068. return builder.build();
  1069. }
  1070. void VT::apply_style(const Style& style, bool is_starting)
  1071. {
  1072. if (is_starting) {
  1073. fprintf(stderr,
  1074. "\033[%d;%d;%dm%s%s%s",
  1075. style.bold() ? 1 : 22,
  1076. style.underline() ? 4 : 24,
  1077. style.italic() ? 3 : 23,
  1078. style.background().to_vt_escape().characters(),
  1079. style.foreground().to_vt_escape().characters(),
  1080. style.hyperlink().to_vt_escape(true).characters());
  1081. } else {
  1082. fprintf(stderr, "%s", style.hyperlink().to_vt_escape(false).characters());
  1083. }
  1084. }
  1085. void VT::clear_lines(size_t count_above, size_t count_below)
  1086. {
  1087. // Go down count_below lines.
  1088. if (count_below > 0)
  1089. fprintf(stderr, "\033[%dB", (int)count_below);
  1090. // Then clear lines going upwards.
  1091. for (size_t i = count_below + count_above; i > 0; --i)
  1092. fputs(i == 1 ? "\033[2K" : "\033[2K\033[A", stderr);
  1093. }
  1094. void VT::save_cursor()
  1095. {
  1096. fputs("\033[s", stderr);
  1097. fflush(stderr);
  1098. }
  1099. void VT::restore_cursor()
  1100. {
  1101. fputs("\033[u", stderr);
  1102. fflush(stderr);
  1103. }
  1104. void VT::clear_to_end_of_line()
  1105. {
  1106. fputs("\033[K", stderr);
  1107. fflush(stderr);
  1108. }
  1109. StringMetrics Editor::actual_rendered_string_metrics(const StringView& string)
  1110. {
  1111. size_t length { 0 };
  1112. StringMetrics metrics;
  1113. VTState state { Free };
  1114. Utf8View view { string };
  1115. auto it = view.begin();
  1116. for (; it != view.end(); ++it) {
  1117. auto c = *it;
  1118. auto it_copy = it;
  1119. ++it_copy;
  1120. auto next_c = it_copy == view.end() ? 0 : *it_copy;
  1121. state = actual_rendered_string_length_step(metrics, length, c, next_c, state);
  1122. }
  1123. metrics.line_lengths.append(length);
  1124. for (auto& line : metrics.line_lengths)
  1125. metrics.max_line_length = max(line, metrics.max_line_length);
  1126. return metrics;
  1127. }
  1128. StringMetrics Editor::actual_rendered_string_metrics(const Utf32View& view)
  1129. {
  1130. size_t length { 0 };
  1131. StringMetrics metrics;
  1132. VTState state { Free };
  1133. for (size_t i = 0; i < view.length(); ++i) {
  1134. auto c = view.code_points()[i];
  1135. auto next_c = i + 1 < view.length() ? view.code_points()[i + 1] : 0;
  1136. state = actual_rendered_string_length_step(metrics, length, c, next_c, state);
  1137. }
  1138. metrics.line_lengths.append(length);
  1139. for (auto& line : metrics.line_lengths)
  1140. metrics.max_line_length = max(line, metrics.max_line_length);
  1141. return metrics;
  1142. }
  1143. Editor::VTState Editor::actual_rendered_string_length_step(StringMetrics& metrics, size_t& length, u32 c, u32 next_c, VTState state)
  1144. {
  1145. switch (state) {
  1146. case Free:
  1147. if (c == '\x1b') { // escape
  1148. return Escape;
  1149. }
  1150. if (c == '\r') { // carriage return
  1151. length = 0;
  1152. if (!metrics.line_lengths.is_empty())
  1153. metrics.line_lengths.last() = 0;
  1154. return state;
  1155. }
  1156. if (c == '\n') { // return
  1157. metrics.line_lengths.append(length);
  1158. length = 0;
  1159. return state;
  1160. }
  1161. // FIXME: This will not support anything sophisticated
  1162. ++length;
  1163. ++metrics.total_length;
  1164. return state;
  1165. case Escape:
  1166. if (c == ']') {
  1167. if (next_c == '0')
  1168. state = Title;
  1169. return state;
  1170. }
  1171. if (c == '[') {
  1172. return Bracket;
  1173. }
  1174. // FIXME: This does not support non-VT (aside from set-title) escapes
  1175. return state;
  1176. case Bracket:
  1177. if (isdigit(c)) {
  1178. return BracketArgsSemi;
  1179. }
  1180. return state;
  1181. case BracketArgsSemi:
  1182. if (c == ';') {
  1183. return Bracket;
  1184. }
  1185. if (!isdigit(c))
  1186. state = Free;
  1187. return state;
  1188. case Title:
  1189. if (c == 7)
  1190. state = Free;
  1191. return state;
  1192. }
  1193. return state;
  1194. }
  1195. Vector<size_t, 2> Editor::vt_dsr()
  1196. {
  1197. char buf[16];
  1198. u32 length { 0 };
  1199. // Read whatever junk there is before talking to the terminal
  1200. // and insert them later when we're reading user input.
  1201. bool more_junk_to_read { false };
  1202. timeval timeout { 0, 0 };
  1203. fd_set readfds;
  1204. FD_ZERO(&readfds);
  1205. FD_SET(0, &readfds);
  1206. do {
  1207. more_junk_to_read = false;
  1208. (void)select(1, &readfds, nullptr, nullptr, &timeout);
  1209. if (FD_ISSET(0, &readfds)) {
  1210. auto nread = read(0, buf, 16);
  1211. if (nread < 0) {
  1212. m_input_error = Error::ReadFailure;
  1213. finish();
  1214. break;
  1215. }
  1216. if (nread == 0)
  1217. break;
  1218. m_incomplete_data.append(buf, nread);
  1219. more_junk_to_read = true;
  1220. }
  1221. } while (more_junk_to_read);
  1222. if (m_input_error.has_value())
  1223. return { 1, 1 };
  1224. fputs("\033[6n", stderr);
  1225. fflush(stderr);
  1226. do {
  1227. auto nread = read(0, buf + length, 16 - length);
  1228. if (nread < 0) {
  1229. if (errno == 0) {
  1230. // ????
  1231. continue;
  1232. }
  1233. dbg() << "Error while reading DSR: " << strerror(errno);
  1234. m_input_error = Error::ReadFailure;
  1235. finish();
  1236. return { 1, 1 };
  1237. }
  1238. if (nread == 0) {
  1239. m_input_error = Error::Empty;
  1240. finish();
  1241. dbg() << "Terminal DSR issue; received no response";
  1242. return { 1, 1 };
  1243. }
  1244. length += nread;
  1245. } while (buf[length - 1] != 'R' && length < 16);
  1246. size_t row { 1 }, col { 1 };
  1247. if (buf[0] == '\033' && buf[1] == '[') {
  1248. auto parts = StringView(buf + 2, length - 3).split_view(';');
  1249. auto row_opt = parts[0].to_int();
  1250. if (!row_opt.has_value()) {
  1251. dbg() << "Terminal DSR issue; received garbage row";
  1252. } else {
  1253. row = row_opt.value();
  1254. }
  1255. auto col_opt = parts[1].to_int();
  1256. if (!col_opt.has_value()) {
  1257. dbg() << "Terminal DSR issue; received garbage col";
  1258. } else {
  1259. col = col_opt.value();
  1260. }
  1261. }
  1262. return { row, col };
  1263. }
  1264. String Editor::line(size_t up_to_index) const
  1265. {
  1266. StringBuilder builder;
  1267. builder.append(Utf32View { m_buffer.data(), min(m_buffer.size(), up_to_index) });
  1268. return builder.build();
  1269. }
  1270. void Editor::remove_at_index(size_t index)
  1271. {
  1272. // See if we have any anchored styles, and reposition them if needed.
  1273. readjust_anchored_styles(index, ModificationKind::Removal);
  1274. auto cp = m_buffer[index];
  1275. m_buffer.remove(index);
  1276. if (cp == '\n')
  1277. ++m_extra_forward_lines;
  1278. }
  1279. void Editor::readjust_anchored_styles(size_t hint_index, ModificationKind modification)
  1280. {
  1281. struct Anchor {
  1282. Span old_span;
  1283. Span new_span;
  1284. Style style;
  1285. };
  1286. Vector<Anchor> anchors_to_relocate;
  1287. auto index_shift = modification == ModificationKind::Insertion ? 1 : -1;
  1288. auto forced_removal = modification == ModificationKind::ForcedOverlapRemoval;
  1289. for (auto& start_entry : m_anchored_spans_starting) {
  1290. for (auto& end_entry : start_entry.value) {
  1291. if (forced_removal) {
  1292. if (start_entry.key <= hint_index && end_entry.key > hint_index) {
  1293. // Remove any overlapping regions.
  1294. continue;
  1295. }
  1296. }
  1297. if (start_entry.key >= hint_index) {
  1298. if (start_entry.key == hint_index && end_entry.key == hint_index + 1 && modification == ModificationKind::Removal) {
  1299. // Remove the anchor, as all its text was wiped.
  1300. continue;
  1301. }
  1302. // Shift everything.
  1303. 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 });
  1304. continue;
  1305. }
  1306. if (end_entry.key > hint_index) {
  1307. // Shift just the end.
  1308. 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 });
  1309. continue;
  1310. }
  1311. 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 });
  1312. }
  1313. }
  1314. m_anchored_spans_ending.clear();
  1315. m_anchored_spans_starting.clear();
  1316. // Pass over the relocations and update the stale entries.
  1317. for (auto& relocation : anchors_to_relocate) {
  1318. stylize(relocation.new_span, relocation.style);
  1319. }
  1320. }
  1321. size_t StringMetrics::lines_with_addition(const StringMetrics& offset, size_t column_width) const
  1322. {
  1323. size_t lines = 0;
  1324. for (size_t i = 0; i < line_lengths.size() - 1; ++i)
  1325. lines += (line_lengths[i] + column_width) / column_width;
  1326. auto last = line_lengths.last();
  1327. last += offset.line_lengths.first();
  1328. lines += (last + column_width) / column_width;
  1329. for (size_t i = 1; i < offset.line_lengths.size(); ++i)
  1330. lines += (offset.line_lengths[i] + column_width) / column_width;
  1331. return lines;
  1332. }
  1333. }