Editor.cpp 51 KB

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