Editor.cpp 50 KB

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