Editor.cpp 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Editor.h"
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/Debug.h>
  10. #include <AK/GenericLexer.h>
  11. #include <AK/JsonObject.h>
  12. #include <AK/MemoryStream.h>
  13. #include <AK/RedBlackTree.h>
  14. #include <AK/ScopeGuard.h>
  15. #include <AK/ScopedValueRollback.h>
  16. #include <AK/StringBuilder.h>
  17. #include <AK/Utf32View.h>
  18. #include <AK/Utf8View.h>
  19. #include <LibCore/ConfigFile.h>
  20. #include <LibCore/DeprecatedFile.h>
  21. #include <LibCore/Event.h>
  22. #include <LibCore/EventLoop.h>
  23. #include <LibCore/Notifier.h>
  24. #include <errno.h>
  25. #include <fcntl.h>
  26. #include <signal.h>
  27. #include <stdio.h>
  28. #include <sys/ioctl.h>
  29. #include <sys/select.h>
  30. #include <sys/time.h>
  31. #include <unistd.h>
  32. namespace {
  33. constexpr u32 ctrl(char c) { return c & 0x3f; }
  34. }
  35. namespace Line {
  36. Configuration Configuration::from_config(StringView libname)
  37. {
  38. Configuration configuration;
  39. auto config_file = Core::ConfigFile::open_for_lib(libname).release_value_but_fixme_should_propagate_errors();
  40. // Read behavior options.
  41. auto refresh = config_file->read_entry("behavior", "refresh", "lazy");
  42. auto operation = config_file->read_entry("behavior", "operation_mode");
  43. auto bracketed_paste = config_file->read_bool_entry("behavior", "bracketed_paste", true);
  44. auto default_text_editor = config_file->read_entry("behavior", "default_text_editor");
  45. Configuration::Flags flags { Configuration::Flags::None };
  46. if (bracketed_paste)
  47. flags = static_cast<Flags>(flags | Configuration::Flags::BracketedPaste);
  48. configuration.set(flags);
  49. if (refresh.equals_ignoring_ascii_case("lazy"sv))
  50. configuration.set(Configuration::Lazy);
  51. else if (refresh.equals_ignoring_ascii_case("eager"sv))
  52. configuration.set(Configuration::Eager);
  53. if (operation.equals_ignoring_ascii_case("full"sv))
  54. configuration.set(Configuration::OperationMode::Full);
  55. else if (operation.equals_ignoring_ascii_case("noescapesequences"sv))
  56. configuration.set(Configuration::OperationMode::NoEscapeSequences);
  57. else if (operation.equals_ignoring_ascii_case("noninteractive"sv))
  58. configuration.set(Configuration::OperationMode::NonInteractive);
  59. else
  60. configuration.set(Configuration::OperationMode::Unset);
  61. if (!default_text_editor.is_empty())
  62. configuration.set(DefaultTextEditor { move(default_text_editor) });
  63. else
  64. configuration.set(DefaultTextEditor { "/bin/TextEditor" });
  65. // Read keybinds.
  66. for (auto& binding_key : config_file->keys("keybinds")) {
  67. GenericLexer key_lexer(binding_key);
  68. auto has_ctrl = false;
  69. auto alt = false;
  70. auto escape = false;
  71. Vector<Key> keys;
  72. while (!key_lexer.is_eof()) {
  73. unsigned key;
  74. if (escape) {
  75. key = key_lexer.consume_escaped_character();
  76. escape = false;
  77. } else {
  78. if (key_lexer.next_is("alt+")) {
  79. alt = key_lexer.consume_specific("alt+");
  80. continue;
  81. }
  82. if (key_lexer.next_is("^[")) {
  83. alt = key_lexer.consume_specific("^[");
  84. continue;
  85. }
  86. if (key_lexer.next_is("^")) {
  87. has_ctrl = key_lexer.consume_specific("^");
  88. continue;
  89. }
  90. if (key_lexer.next_is("ctrl+")) {
  91. has_ctrl = key_lexer.consume_specific("ctrl+");
  92. continue;
  93. }
  94. if (key_lexer.next_is("\\")) {
  95. escape = true;
  96. continue;
  97. }
  98. // FIXME: Support utf?
  99. key = key_lexer.consume();
  100. }
  101. if (has_ctrl)
  102. key = ctrl(key);
  103. keys.append(Key { key, alt ? Key::Alt : Key::None });
  104. alt = false;
  105. has_ctrl = false;
  106. }
  107. GenericLexer value_lexer { config_file->read_entry("keybinds", binding_key) };
  108. StringBuilder value_builder;
  109. while (!value_lexer.is_eof())
  110. value_builder.append(value_lexer.consume_escaped_character());
  111. auto value = value_builder.string_view();
  112. if (value.starts_with("internal:"sv)) {
  113. configuration.set(KeyBinding {
  114. keys,
  115. KeyBinding::Kind::InternalFunction,
  116. value.substring_view(9, value.length() - 9) });
  117. } else {
  118. configuration.set(KeyBinding {
  119. keys,
  120. KeyBinding::Kind::Insertion,
  121. value });
  122. }
  123. }
  124. return configuration;
  125. }
  126. void Editor::set_default_keybinds()
  127. {
  128. register_key_input_callback(ctrl('N'), EDITOR_INTERNAL_FUNCTION(search_forwards));
  129. register_key_input_callback(ctrl('P'), EDITOR_INTERNAL_FUNCTION(search_backwards));
  130. register_key_input_callback(ctrl('A'), EDITOR_INTERNAL_FUNCTION(go_home));
  131. register_key_input_callback(ctrl('B'), EDITOR_INTERNAL_FUNCTION(cursor_left_character));
  132. register_key_input_callback(ctrl('D'), EDITOR_INTERNAL_FUNCTION(erase_character_forwards));
  133. register_key_input_callback(ctrl('E'), EDITOR_INTERNAL_FUNCTION(go_end));
  134. register_key_input_callback(ctrl('F'), EDITOR_INTERNAL_FUNCTION(cursor_right_character));
  135. // ^H: ctrl('H') == '\b'
  136. register_key_input_callback(ctrl('H'), EDITOR_INTERNAL_FUNCTION(erase_character_backwards));
  137. // DEL - Some terminals send this instead of ^H.
  138. register_key_input_callback((char)127, EDITOR_INTERNAL_FUNCTION(erase_character_backwards));
  139. register_key_input_callback(ctrl('K'), EDITOR_INTERNAL_FUNCTION(erase_to_end));
  140. register_key_input_callback(ctrl('L'), EDITOR_INTERNAL_FUNCTION(clear_screen));
  141. register_key_input_callback(ctrl('R'), EDITOR_INTERNAL_FUNCTION(enter_search));
  142. register_key_input_callback(ctrl('T'), EDITOR_INTERNAL_FUNCTION(transpose_characters));
  143. register_key_input_callback('\n', EDITOR_INTERNAL_FUNCTION(finish));
  144. // ^X^E: Edit in external editor
  145. register_key_input_callback(Vector<Key> { ctrl('X'), ctrl('E') }, EDITOR_INTERNAL_FUNCTION(edit_in_external_editor));
  146. // ^[.: alt-.: insert last arg of previous command (similar to `!$`)
  147. register_key_input_callback(Key { '.', Key::Alt }, EDITOR_INTERNAL_FUNCTION(insert_last_words));
  148. register_key_input_callback(Key { 'b', Key::Alt }, EDITOR_INTERNAL_FUNCTION(cursor_left_word));
  149. register_key_input_callback(Key { 'f', Key::Alt }, EDITOR_INTERNAL_FUNCTION(cursor_right_word));
  150. // ^[^H: alt-backspace: backward delete word
  151. register_key_input_callback(Key { '\b', Key::Alt }, EDITOR_INTERNAL_FUNCTION(erase_alnum_word_backwards));
  152. register_key_input_callback(Key { 'd', Key::Alt }, EDITOR_INTERNAL_FUNCTION(erase_alnum_word_forwards));
  153. register_key_input_callback(Key { 'c', Key::Alt }, EDITOR_INTERNAL_FUNCTION(capitalize_word));
  154. register_key_input_callback(Key { 'l', Key::Alt }, EDITOR_INTERNAL_FUNCTION(lowercase_word));
  155. register_key_input_callback(Key { 'u', Key::Alt }, EDITOR_INTERNAL_FUNCTION(uppercase_word));
  156. register_key_input_callback(Key { 't', Key::Alt }, EDITOR_INTERNAL_FUNCTION(transpose_words));
  157. // Register these last to all the user to override the previous key bindings
  158. // Normally ^W. `stty werase \^n` can change it to ^N (or something else).
  159. register_key_input_callback(m_termios.c_cc[VWERASE], EDITOR_INTERNAL_FUNCTION(erase_word_backwards));
  160. // Normally ^U. `stty kill \^n` can change it to ^N (or something else).
  161. register_key_input_callback(m_termios.c_cc[VKILL], EDITOR_INTERNAL_FUNCTION(kill_line));
  162. register_key_input_callback(m_termios.c_cc[VERASE], EDITOR_INTERNAL_FUNCTION(erase_character_backwards));
  163. }
  164. Editor::Editor(Configuration configuration)
  165. : m_configuration(move(configuration))
  166. {
  167. m_always_refresh = m_configuration.refresh_behavior == Configuration::RefreshBehavior::Eager;
  168. m_pending_chars = {};
  169. get_terminal_size();
  170. m_suggestion_display = make<XtermSuggestionDisplay>(m_num_lines, m_num_columns);
  171. }
  172. Editor::~Editor()
  173. {
  174. if (m_initialized)
  175. restore();
  176. }
  177. void Editor::ensure_free_lines_from_origin(size_t count)
  178. {
  179. if (count > m_num_lines) {
  180. // FIXME: Implement paging
  181. }
  182. if (m_origin_row + count <= m_num_lines)
  183. return;
  184. auto diff = m_origin_row + count - m_num_lines - 1;
  185. out(stderr, "\x1b[{}S", diff);
  186. fflush(stderr);
  187. m_origin_row -= diff;
  188. m_refresh_needed = false;
  189. m_chars_touched_in_the_middle = 0;
  190. }
  191. void Editor::get_terminal_size()
  192. {
  193. struct winsize ws;
  194. ioctl(STDERR_FILENO, TIOCGWINSZ, &ws);
  195. if (ws.ws_col == 0 || ws.ws_row == 0) {
  196. // LLDB uses ttys which "work" and then gives us a zero sized
  197. // terminal which is far from useful
  198. if (int fd = open("/dev/tty", O_RDONLY); fd != -1) {
  199. ioctl(fd, TIOCGWINSZ, &ws);
  200. close(fd);
  201. }
  202. }
  203. m_num_columns = ws.ws_col;
  204. m_num_lines = ws.ws_row;
  205. }
  206. void Editor::add_to_history(DeprecatedString const& line)
  207. {
  208. if (line.is_empty())
  209. return;
  210. DeprecatedString histcontrol = getenv("HISTCONTROL");
  211. auto ignoredups = histcontrol == "ignoredups" || histcontrol == "ignoreboth";
  212. auto ignorespace = histcontrol == "ignorespace" || histcontrol == "ignoreboth";
  213. if (ignoredups && !m_history.is_empty() && line == m_history.last().entry)
  214. return;
  215. if (ignorespace && line.starts_with(' '))
  216. return;
  217. if ((m_history.size() + 1) > m_history_capacity)
  218. m_history.take_first();
  219. struct timeval tv;
  220. gettimeofday(&tv, nullptr);
  221. m_history.append({ line, tv.tv_sec });
  222. m_history_dirty = true;
  223. }
  224. bool Editor::load_history(DeprecatedString const& path)
  225. {
  226. auto history_file = Core::DeprecatedFile::construct(path);
  227. if (!history_file->open(Core::OpenMode::ReadOnly))
  228. return false;
  229. auto data = history_file->read_all();
  230. auto hist = StringView { data.data(), data.size() };
  231. for (auto& str : hist.split_view("\n\n"sv)) {
  232. auto it = str.find("::"sv).value_or(0);
  233. auto time = str.substring_view(0, it).to_int<time_t>().value_or(0);
  234. auto string = str.substring_view(it == 0 ? it : it + 2);
  235. m_history.append({ string, time });
  236. }
  237. return true;
  238. }
  239. template<typename It0, typename It1, typename OutputT, typename MapperT, typename LessThan>
  240. static void merge(It0&& begin0, It0 const& end0, It1&& begin1, It1 const& end1, OutputT& output, MapperT left_mapper, LessThan less_than)
  241. {
  242. for (;;) {
  243. if (begin0 == end0 && begin1 == end1)
  244. return;
  245. if (begin0 == end0) {
  246. auto&& right = *begin1;
  247. if (output.last().entry != right.entry)
  248. output.append(right);
  249. ++begin1;
  250. continue;
  251. }
  252. auto&& left = left_mapper(*begin0);
  253. if (left.entry.is_whitespace()) {
  254. ++begin0;
  255. continue;
  256. }
  257. if (begin1 == end1) {
  258. if (output.last().entry != left.entry)
  259. output.append(left);
  260. ++begin0;
  261. continue;
  262. }
  263. auto&& right = *begin1;
  264. if (less_than(left, right)) {
  265. if (output.last().entry != left.entry)
  266. output.append(left);
  267. ++begin0;
  268. } else {
  269. if (output.last().entry != right.entry)
  270. output.append(right);
  271. ++begin1;
  272. if (right.entry == left.entry)
  273. ++begin0;
  274. }
  275. }
  276. }
  277. bool Editor::save_history(DeprecatedString const& path)
  278. {
  279. Vector<HistoryEntry> final_history { { "", 0 } };
  280. {
  281. auto file_or_error = Core::DeprecatedFile::open(path, Core::OpenMode::ReadWrite, 0600);
  282. if (file_or_error.is_error())
  283. return false;
  284. auto file = file_or_error.release_value();
  285. merge(
  286. file->line_begin(), file->line_end(), m_history.begin(), m_history.end(), final_history,
  287. [](StringView str) {
  288. auto it = str.find("::"sv).value_or(0);
  289. auto time = str.substring_view(0, it).to_int<time_t>().value_or(0);
  290. auto string = str.substring_view(it == 0 ? it : it + 2);
  291. return HistoryEntry { string, time };
  292. },
  293. [](HistoryEntry const& left, HistoryEntry const& right) { return left.timestamp < right.timestamp; });
  294. }
  295. auto file_or_error = Core::DeprecatedFile::open(path, Core::OpenMode::WriteOnly, 0600);
  296. if (file_or_error.is_error())
  297. return false;
  298. auto file = file_or_error.release_value();
  299. final_history.take_first();
  300. for (auto const& entry : final_history)
  301. file->write(DeprecatedString::formatted("{}::{}\n\n", entry.timestamp, entry.entry));
  302. m_history_dirty = false;
  303. return true;
  304. }
  305. void Editor::clear_line()
  306. {
  307. for (size_t i = 0; i < m_cursor; ++i)
  308. fputc(0x8, stderr);
  309. fputs("\033[K", stderr);
  310. fflush(stderr);
  311. m_chars_touched_in_the_middle = buffer().size();
  312. m_buffer.clear();
  313. m_cursor = 0;
  314. m_inline_search_cursor = m_cursor;
  315. }
  316. void Editor::insert(Utf32View const& string)
  317. {
  318. for (size_t i = 0; i < string.length(); ++i)
  319. insert(string.code_points()[i]);
  320. }
  321. void Editor::insert(DeprecatedString const& string)
  322. {
  323. for (auto ch : Utf8View { string })
  324. insert(ch);
  325. }
  326. void Editor::insert(StringView string_view)
  327. {
  328. for (auto ch : Utf8View { string_view })
  329. insert(ch);
  330. }
  331. void Editor::insert(const u32 cp)
  332. {
  333. StringBuilder builder;
  334. builder.append(Utf32View(&cp, 1));
  335. auto str = builder.to_deprecated_string();
  336. if (m_pending_chars.try_append(str.characters(), str.length()).is_error())
  337. return;
  338. readjust_anchored_styles(m_cursor, ModificationKind::Insertion);
  339. if (m_cursor == m_buffer.size()) {
  340. m_buffer.append(cp);
  341. m_cursor = m_buffer.size();
  342. m_inline_search_cursor = m_cursor;
  343. return;
  344. }
  345. m_buffer.insert(m_cursor, cp);
  346. ++m_chars_touched_in_the_middle;
  347. ++m_cursor;
  348. m_inline_search_cursor = m_cursor;
  349. }
  350. void Editor::register_key_input_callback(KeyBinding const& binding)
  351. {
  352. if (binding.kind == KeyBinding::Kind::InternalFunction) {
  353. auto internal_function = find_internal_function(binding.binding);
  354. if (!internal_function) {
  355. dbgln("LibLine: Unknown internal function '{}'", binding.binding);
  356. return;
  357. }
  358. return register_key_input_callback(binding.keys, move(internal_function));
  359. }
  360. return register_key_input_callback(binding.keys, [binding = DeprecatedString(binding.binding)](auto& editor) {
  361. editor.insert(binding);
  362. return false;
  363. });
  364. }
  365. static size_t code_point_length_in_utf8(u32 code_point)
  366. {
  367. if (code_point <= 0x7f)
  368. return 1;
  369. if (code_point <= 0x07ff)
  370. return 2;
  371. if (code_point <= 0xffff)
  372. return 3;
  373. if (code_point <= 0x10ffff)
  374. return 4;
  375. return 3;
  376. }
  377. // buffer [ 0 1 2 3 . . . A . . . B . . . M . . . N ]
  378. // ^ ^ ^ ^
  379. // | | | +- end of buffer
  380. // | | +- scan offset = M
  381. // | +- range end = M - B
  382. // +- range start = M - A
  383. // 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.
  384. // If `reverse' is true, A and B are before M, if not, A and B are after M.
  385. 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
  386. {
  387. size_t byte_offset = 0;
  388. size_t code_point_offset = scan_code_point_offset + (reverse ? 1 : 0);
  389. CodepointRange range;
  390. for (;;) {
  391. if (!reverse) {
  392. if (code_point_offset >= m_buffer.size())
  393. break;
  394. } else {
  395. if (code_point_offset == 0)
  396. break;
  397. }
  398. if (byte_offset > end_byte_offset)
  399. break;
  400. if (byte_offset < start_byte_offset)
  401. ++range.start;
  402. if (byte_offset < end_byte_offset)
  403. ++range.end;
  404. byte_offset += code_point_length_in_utf8(m_buffer[reverse ? --code_point_offset : code_point_offset++]);
  405. }
  406. return range;
  407. }
  408. void Editor::stylize(Span const& span, Style const& style)
  409. {
  410. if (!span.is_empty())
  411. return;
  412. if (style.is_empty())
  413. return;
  414. auto start = span.beginning();
  415. auto end = span.end();
  416. if (span.mode() == Span::ByteOriented) {
  417. auto offsets = byte_offset_range_to_code_point_offset_range(start, end, 0);
  418. start = offsets.start;
  419. end = offsets.end;
  420. }
  421. if (auto maybe_mask = style.mask(); maybe_mask.has_value()) {
  422. auto it = m_current_masks.find_smallest_not_below_iterator(span.beginning());
  423. Optional<Style::Mask> last_encountered_entry;
  424. if (!it.is_end()) {
  425. // Delete all overlapping old masks.
  426. while (true) {
  427. auto next_it = m_current_masks.find_largest_not_above_iterator(span.end());
  428. if (next_it.is_end())
  429. break;
  430. if (it->has_value())
  431. last_encountered_entry = *it;
  432. m_current_masks.remove(next_it.key());
  433. }
  434. }
  435. m_current_masks.insert(span.beginning(), move(maybe_mask));
  436. m_current_masks.insert(span.end(), {});
  437. if (last_encountered_entry.has_value())
  438. m_current_masks.insert(span.end() + 1, move(last_encountered_entry));
  439. style.unset_mask();
  440. }
  441. auto& spans_starting = style.is_anchored() ? m_current_spans.m_anchored_spans_starting : m_current_spans.m_spans_starting;
  442. auto& spans_ending = style.is_anchored() ? m_current_spans.m_anchored_spans_ending : m_current_spans.m_spans_ending;
  443. auto& starting_map = spans_starting.ensure(start);
  444. if (!starting_map.contains(end))
  445. m_refresh_needed = true;
  446. starting_map.set(end, style);
  447. auto& ending_map = spans_ending.ensure(end);
  448. if (!ending_map.contains(start))
  449. m_refresh_needed = true;
  450. ending_map.set(start, style);
  451. }
  452. void Editor::transform_suggestion_offsets(size_t& invariant_offset, size_t& static_offset, Span::Mode offset_mode) const
  453. {
  454. auto internal_static_offset = static_offset;
  455. auto internal_invariant_offset = invariant_offset;
  456. if (offset_mode == Span::Mode::ByteOriented) {
  457. // FIXME: We're assuming that invariant_offset points to the end of the available data
  458. // this is not necessarily true, but is true in most cases.
  459. auto offsets = byte_offset_range_to_code_point_offset_range(internal_static_offset, internal_invariant_offset + internal_static_offset, m_cursor - 1, true);
  460. internal_static_offset = offsets.start;
  461. internal_invariant_offset = offsets.end - offsets.start;
  462. }
  463. invariant_offset = internal_invariant_offset;
  464. static_offset = internal_static_offset;
  465. }
  466. void Editor::initialize()
  467. {
  468. if (m_initialized)
  469. return;
  470. struct termios termios;
  471. tcgetattr(0, &termios);
  472. m_default_termios = termios; // grab a copy to restore
  473. get_terminal_size();
  474. if (m_configuration.operation_mode == Configuration::Unset) {
  475. auto istty = isatty(STDIN_FILENO) && isatty(STDERR_FILENO);
  476. if (!istty) {
  477. m_configuration.set(Configuration::NonInteractive);
  478. } else {
  479. auto* term = getenv("TERM");
  480. if (term != NULL && StringView { term, strlen(term) }.starts_with("xterm"sv))
  481. m_configuration.set(Configuration::Full);
  482. else
  483. m_configuration.set(Configuration::NoEscapeSequences);
  484. }
  485. }
  486. // Because we use our own line discipline which includes echoing,
  487. // we disable ICANON and ECHO.
  488. if (m_configuration.operation_mode == Configuration::Full) {
  489. termios.c_lflag &= ~(ECHO | ICANON);
  490. tcsetattr(0, TCSANOW, &termios);
  491. }
  492. m_termios = termios;
  493. set_default_keybinds();
  494. for (auto& keybind : m_configuration.keybindings)
  495. register_key_input_callback(keybind);
  496. if (m_configuration.m_signal_mode == Configuration::WithSignalHandlers) {
  497. m_signal_handlers.append(Core::EventLoop::register_signal(SIGINT, [this](int) {
  498. interrupted().release_value_but_fixme_should_propagate_errors();
  499. }));
  500. m_signal_handlers.append(Core::EventLoop::register_signal(SIGWINCH, [this](int) {
  501. resized().release_value_but_fixme_should_propagate_errors();
  502. }));
  503. }
  504. m_initialized = true;
  505. }
  506. void Editor::refetch_default_termios()
  507. {
  508. struct termios termios;
  509. tcgetattr(0, &termios);
  510. m_default_termios = termios;
  511. if (m_configuration.operation_mode == Configuration::Full)
  512. termios.c_lflag &= ~(ECHO | ICANON);
  513. m_termios = termios;
  514. }
  515. ErrorOr<void> Editor::interrupted()
  516. {
  517. if (m_is_searching)
  518. return m_search_editor->interrupted();
  519. if (!m_is_editing)
  520. return {};
  521. m_was_interrupted = true;
  522. handle_interrupt_event();
  523. if (!m_finish || !m_previous_interrupt_was_handled_as_interrupt)
  524. return {};
  525. m_finish = false;
  526. {
  527. auto stderr_stream = TRY(Core::File::standard_error());
  528. TRY(reposition_cursor(*stderr_stream, true));
  529. if (TRY(m_suggestion_display->cleanup()))
  530. TRY(reposition_cursor(*stderr_stream, true));
  531. TRY(stderr_stream->write_until_depleted("\n"sv.bytes()));
  532. }
  533. m_buffer.clear();
  534. m_chars_touched_in_the_middle = buffer().size();
  535. m_is_editing = false;
  536. restore();
  537. m_notifier->set_enabled(false);
  538. m_notifier = nullptr;
  539. Core::EventLoop::current().quit(Retry);
  540. return {};
  541. }
  542. ErrorOr<void> Editor::resized()
  543. {
  544. m_was_resized = true;
  545. m_previous_num_columns = m_num_columns;
  546. get_terminal_size();
  547. if (!m_has_origin_reset_scheduled) {
  548. // Reset the origin, but make sure it doesn't blow up if we can't read it
  549. if (set_origin(false)) {
  550. TRY(handle_resize_event(false));
  551. } else {
  552. deferred_invoke([this] { handle_resize_event(true).release_value_but_fixme_should_propagate_errors(); });
  553. m_has_origin_reset_scheduled = true;
  554. }
  555. }
  556. return {};
  557. }
  558. ErrorOr<void> Editor::handle_resize_event(bool reset_origin)
  559. {
  560. m_has_origin_reset_scheduled = false;
  561. if (reset_origin && !set_origin(false)) {
  562. m_has_origin_reset_scheduled = true;
  563. deferred_invoke([this] { handle_resize_event(true).release_value_but_fixme_should_propagate_errors(); });
  564. return {};
  565. }
  566. set_origin(m_origin_row, 1);
  567. auto stderr_stream = TRY(Core::File::standard_error());
  568. TRY(reposition_cursor(*stderr_stream, true));
  569. TRY(m_suggestion_display->redisplay(m_suggestion_manager, m_num_lines, m_num_columns));
  570. m_origin_row = m_suggestion_display->origin_row();
  571. TRY(reposition_cursor(*stderr_stream));
  572. if (m_is_searching)
  573. TRY(m_search_editor->resized());
  574. return {};
  575. }
  576. ErrorOr<void> Editor::really_quit_event_loop()
  577. {
  578. m_finish = false;
  579. {
  580. auto stderr_stream = TRY(Core::File::standard_error());
  581. TRY(reposition_cursor(*stderr_stream, true));
  582. TRY(stderr_stream->write_until_depleted("\n"sv.bytes()));
  583. }
  584. auto string = line();
  585. m_buffer.clear();
  586. m_chars_touched_in_the_middle = buffer().size();
  587. m_is_editing = false;
  588. if (m_initialized)
  589. restore();
  590. m_returned_line = string;
  591. m_notifier->set_enabled(false);
  592. m_notifier = nullptr;
  593. Core::EventLoop::current().quit(Exit);
  594. return {};
  595. }
  596. auto Editor::get_line(DeprecatedString const& prompt) -> Result<DeprecatedString, Editor::Error>
  597. {
  598. initialize();
  599. m_is_editing = true;
  600. if (m_configuration.operation_mode == Configuration::NoEscapeSequences || m_configuration.operation_mode == Configuration::NonInteractive) {
  601. // Do not use escape sequences, instead, use LibC's getline.
  602. size_t size = 0;
  603. char* line = nullptr;
  604. // Show the prompt only on interactive mode (NoEscapeSequences in this case).
  605. if (m_configuration.operation_mode != Configuration::NonInteractive)
  606. fputs(prompt.characters(), stderr);
  607. auto line_length = getline(&line, &size, stdin);
  608. // getline() returns -1 and sets errno=0 on EOF.
  609. if (line_length == -1) {
  610. if (line)
  611. free(line);
  612. if (errno == 0)
  613. return Error::Eof;
  614. return Error::ReadFailure;
  615. }
  616. restore();
  617. if (line) {
  618. DeprecatedString result { line, (size_t)line_length, Chomp };
  619. free(line);
  620. return result;
  621. }
  622. return Error::ReadFailure;
  623. }
  624. auto old_cols = m_num_columns;
  625. auto old_lines = m_num_lines;
  626. get_terminal_size();
  627. if (m_configuration.enable_bracketed_paste)
  628. fprintf(stderr, "\x1b[?2004h");
  629. if (m_num_columns != old_cols || m_num_lines != old_lines)
  630. m_refresh_needed = true;
  631. set_prompt(prompt);
  632. reset();
  633. strip_styles(true);
  634. {
  635. auto stderr_stream = Core::File::standard_error().release_value_but_fixme_should_propagate_errors();
  636. auto prompt_lines = max(current_prompt_metrics().line_metrics.size(), 1ul) - 1;
  637. for (size_t i = 0; i < prompt_lines; ++i)
  638. stderr_stream->write_until_depleted("\n"sv.bytes()).release_value_but_fixme_should_propagate_errors();
  639. VT::move_relative(-static_cast<int>(prompt_lines), 0, *stderr_stream).release_value_but_fixme_should_propagate_errors();
  640. }
  641. set_origin();
  642. m_history_cursor = m_history.size();
  643. refresh_display().release_value_but_fixme_should_propagate_errors();
  644. Core::EventLoop loop;
  645. m_notifier = Core::Notifier::construct(STDIN_FILENO, Core::Notifier::Type::Read);
  646. m_notifier->on_activation = [&] {
  647. if (try_update_once().is_error())
  648. loop.quit(Exit);
  649. };
  650. if (!m_incomplete_data.is_empty()) {
  651. deferred_invoke([&] {
  652. if (try_update_once().is_error())
  653. loop.quit(Exit);
  654. });
  655. }
  656. if (loop.exec() == Retry)
  657. return get_line(prompt);
  658. return m_input_error.has_value() ? Result<DeprecatedString, Editor::Error> { m_input_error.value() } : Result<DeprecatedString, Editor::Error> { m_returned_line };
  659. }
  660. ErrorOr<void> Editor::try_update_once()
  661. {
  662. if (m_was_interrupted) {
  663. handle_interrupt_event();
  664. }
  665. TRY(handle_read_event());
  666. if (m_always_refresh)
  667. m_refresh_needed = true;
  668. TRY(refresh_display());
  669. if (m_finish)
  670. TRY(really_quit_event_loop());
  671. return {};
  672. }
  673. void Editor::handle_interrupt_event()
  674. {
  675. m_was_interrupted = false;
  676. m_previous_interrupt_was_handled_as_interrupt = false;
  677. m_callback_machine.interrupted(*this);
  678. if (!m_callback_machine.should_process_last_pressed_key())
  679. return;
  680. m_previous_interrupt_was_handled_as_interrupt = true;
  681. fprintf(stderr, "^C");
  682. fflush(stderr);
  683. if (on_interrupt_handled)
  684. on_interrupt_handled();
  685. m_buffer.clear();
  686. m_chars_touched_in_the_middle = buffer().size();
  687. m_cursor = 0;
  688. finish();
  689. }
  690. ErrorOr<void> Editor::handle_read_event()
  691. {
  692. if (m_prohibit_input_processing) {
  693. m_have_unprocessed_read_event = true;
  694. return {};
  695. }
  696. auto prohibit_scope = prohibit_input();
  697. char keybuf[16];
  698. ssize_t nread = 0;
  699. if (!m_incomplete_data.size())
  700. nread = read(0, keybuf, sizeof(keybuf));
  701. if (nread < 0) {
  702. if (errno == EINTR) {
  703. if (!m_was_interrupted) {
  704. if (m_was_resized)
  705. return {};
  706. finish();
  707. return {};
  708. }
  709. handle_interrupt_event();
  710. return {};
  711. }
  712. ScopedValueRollback errno_restorer(errno);
  713. perror("read failed");
  714. m_input_error = Error::ReadFailure;
  715. finish();
  716. return {};
  717. }
  718. m_incomplete_data.append(keybuf, nread);
  719. auto available_bytes = m_incomplete_data.size();
  720. if (available_bytes == 0) {
  721. m_input_error = Error::Empty;
  722. finish();
  723. return {};
  724. }
  725. auto reverse_tab = false;
  726. // Discard starting bytes until they make sense as utf-8.
  727. size_t valid_bytes = 0;
  728. while (available_bytes > 0) {
  729. Utf8View { StringView { m_incomplete_data.data(), available_bytes } }.validate(valid_bytes);
  730. if (valid_bytes != 0)
  731. break;
  732. m_incomplete_data.take_first();
  733. --available_bytes;
  734. }
  735. Utf8View input_view { StringView { m_incomplete_data.data(), valid_bytes } };
  736. size_t consumed_code_points = 0;
  737. static Vector<u8, 4> csi_parameter_bytes;
  738. static Vector<u8> csi_intermediate_bytes;
  739. Vector<unsigned, 4> csi_parameters;
  740. u8 csi_final;
  741. enum CSIMod {
  742. Shift = 1,
  743. Alt = 2,
  744. Ctrl = 4,
  745. };
  746. for (auto code_point : input_view) {
  747. if (m_finish)
  748. break;
  749. ++consumed_code_points;
  750. if (code_point == 0)
  751. continue;
  752. switch (m_state) {
  753. case InputState::GotEscape:
  754. switch (code_point) {
  755. case '[':
  756. m_state = InputState::CSIExpectParameter;
  757. continue;
  758. default: {
  759. m_callback_machine.key_pressed(*this, { code_point, Key::Alt });
  760. m_state = InputState::Free;
  761. TRY(cleanup_suggestions());
  762. continue;
  763. }
  764. }
  765. case InputState::CSIExpectParameter:
  766. if (code_point >= 0x30 && code_point <= 0x3f) { // '0123456789:;<=>?'
  767. csi_parameter_bytes.append(code_point);
  768. continue;
  769. }
  770. m_state = InputState::CSIExpectIntermediate;
  771. [[fallthrough]];
  772. case InputState::CSIExpectIntermediate:
  773. if (code_point >= 0x20 && code_point <= 0x2f) { // ' !"#$%&\'()*+,-./'
  774. csi_intermediate_bytes.append(code_point);
  775. continue;
  776. }
  777. m_state = InputState::CSIExpectFinal;
  778. [[fallthrough]];
  779. case InputState::CSIExpectFinal: {
  780. m_state = m_previous_free_state;
  781. auto is_in_paste = m_state == InputState::Paste;
  782. for (auto& parameter : DeprecatedString::copy(csi_parameter_bytes).split(';')) {
  783. if (auto value = parameter.to_uint(); value.has_value())
  784. csi_parameters.append(value.value());
  785. else
  786. csi_parameters.append(0);
  787. }
  788. unsigned param1 = 0, param2 = 0;
  789. if (csi_parameters.size() >= 1)
  790. param1 = csi_parameters[0];
  791. if (csi_parameters.size() >= 2)
  792. param2 = csi_parameters[1];
  793. unsigned modifiers = param2 ? param2 - 1 : 0;
  794. if (is_in_paste && code_point != '~' && param1 != 201) {
  795. // The only valid escape to process in paste mode is the stop-paste sequence.
  796. // so treat everything else as part of the pasted data.
  797. insert('\x1b');
  798. insert('[');
  799. insert(StringView { csi_parameter_bytes.data(), csi_parameter_bytes.size() });
  800. insert(StringView { csi_intermediate_bytes.data(), csi_intermediate_bytes.size() });
  801. insert(code_point);
  802. continue;
  803. }
  804. if (!(code_point >= 0x40 && code_point <= 0x7f)) {
  805. dbgln("LibLine: Invalid CSI: {:02x} ({:c})", code_point, code_point);
  806. continue;
  807. }
  808. csi_final = code_point;
  809. csi_parameters.clear();
  810. csi_parameter_bytes.clear();
  811. csi_intermediate_bytes.clear();
  812. if (csi_final == 'Z') {
  813. // 'reverse tab'
  814. reverse_tab = true;
  815. break;
  816. }
  817. TRY(cleanup_suggestions());
  818. switch (csi_final) {
  819. case 'A': // ^[[A: arrow up
  820. search_backwards();
  821. continue;
  822. case 'B': // ^[[B: arrow down
  823. search_forwards();
  824. continue;
  825. case 'D': // ^[[D: arrow left
  826. if (modifiers == CSIMod::Alt || modifiers == CSIMod::Ctrl)
  827. cursor_left_word();
  828. else
  829. cursor_left_character();
  830. continue;
  831. case 'C': // ^[[C: arrow right
  832. if (modifiers == CSIMod::Alt || modifiers == CSIMod::Ctrl)
  833. cursor_right_word();
  834. else
  835. cursor_right_character();
  836. continue;
  837. case 'H': // ^[[H: home
  838. go_home();
  839. continue;
  840. case 'F': // ^[[F: end
  841. go_end();
  842. continue;
  843. case 127:
  844. if (modifiers == CSIMod::Ctrl)
  845. erase_alnum_word_backwards();
  846. else
  847. erase_character_backwards();
  848. continue;
  849. case '~':
  850. if (param1 == 3) { // ^[[3~: delete
  851. if (modifiers == CSIMod::Ctrl)
  852. erase_alnum_word_forwards();
  853. else
  854. erase_character_forwards();
  855. m_search_offset = 0;
  856. continue;
  857. }
  858. if (m_configuration.enable_bracketed_paste) {
  859. // ^[[200~: start bracketed paste
  860. // ^[[201~: end bracketed paste
  861. if (!is_in_paste && param1 == 200) {
  862. m_state = InputState::Paste;
  863. continue;
  864. }
  865. if (is_in_paste && param1 == 201) {
  866. m_state = InputState::Free;
  867. if (on_paste) {
  868. on_paste(Utf32View { m_paste_buffer.data(), m_paste_buffer.size() }, *this);
  869. m_paste_buffer.clear_with_capacity();
  870. }
  871. if (!m_paste_buffer.is_empty())
  872. insert(Utf32View { m_paste_buffer.data(), m_paste_buffer.size() });
  873. continue;
  874. }
  875. }
  876. // ^[[5~: page up
  877. // ^[[6~: page down
  878. dbgln("LibLine: Unhandled '~': {}", param1);
  879. continue;
  880. default:
  881. dbgln("LibLine: Unhandled final: {:02x} ({:c})", code_point, code_point);
  882. continue;
  883. }
  884. VERIFY_NOT_REACHED();
  885. }
  886. case InputState::Verbatim:
  887. m_state = InputState::Free;
  888. // Verbatim mode will bypass all mechanisms and just insert the code point.
  889. insert(code_point);
  890. continue;
  891. case InputState::Paste:
  892. if (code_point == 27) {
  893. m_previous_free_state = InputState::Paste;
  894. m_state = InputState::GotEscape;
  895. continue;
  896. }
  897. if (on_paste)
  898. m_paste_buffer.append(code_point);
  899. else
  900. insert(code_point);
  901. continue;
  902. case InputState::Free:
  903. m_previous_free_state = InputState::Free;
  904. if (code_point == 27) {
  905. m_callback_machine.key_pressed(*this, code_point);
  906. // Note that this should also deal with explicitly registered keys
  907. // that would otherwise be interpreted as escapes.
  908. if (m_callback_machine.should_process_last_pressed_key())
  909. m_state = InputState::GotEscape;
  910. continue;
  911. }
  912. if (code_point == 22) { // ^v
  913. m_callback_machine.key_pressed(*this, code_point);
  914. if (m_callback_machine.should_process_last_pressed_key())
  915. m_state = InputState::Verbatim;
  916. continue;
  917. }
  918. break;
  919. }
  920. // There are no sequences past this point, so short of 'tab', we will want to cleanup the suggestions.
  921. ArmedScopeGuard suggestion_cleanup { [this] { cleanup_suggestions().release_value_but_fixme_should_propagate_errors(); } };
  922. // Normally ^D. `stty eof \^n` can change it to ^N (or something else), but Serenity doesn't have `stty` yet.
  923. // Process this here since the keybinds might override its behavior.
  924. // This only applies when the buffer is empty. at any other time, the behavior should be configurable.
  925. if (code_point == m_termios.c_cc[VEOF] && m_buffer.size() == 0) {
  926. finish_edit();
  927. continue;
  928. }
  929. m_callback_machine.key_pressed(*this, code_point);
  930. if (!m_callback_machine.should_process_last_pressed_key())
  931. continue;
  932. m_search_offset = 0; // reset search offset on any key
  933. if (code_point == '\t' || reverse_tab) {
  934. suggestion_cleanup.disarm();
  935. if (!on_tab_complete)
  936. continue;
  937. // Reverse tab can count as regular tab here.
  938. m_times_tab_pressed++;
  939. int token_start = m_cursor;
  940. // Ask for completions only on the first tab
  941. // and scan for the largest common prefix to display,
  942. // further tabs simply show the cached completions.
  943. if (m_times_tab_pressed == 1) {
  944. m_suggestion_manager.set_suggestions(on_tab_complete(*this));
  945. m_suggestion_manager.set_start_index(0);
  946. m_prompt_lines_at_suggestion_initiation = num_lines();
  947. if (m_suggestion_manager.count() == 0) {
  948. // There are no suggestions, beep.
  949. fputc('\a', stderr);
  950. fflush(stderr);
  951. }
  952. }
  953. // Adjust already incremented / decremented index when switching tab direction.
  954. if (reverse_tab && m_tab_direction != TabDirection::Backward) {
  955. m_suggestion_manager.previous();
  956. m_suggestion_manager.previous();
  957. m_tab_direction = TabDirection::Backward;
  958. }
  959. if (!reverse_tab && m_tab_direction != TabDirection::Forward) {
  960. m_suggestion_manager.next();
  961. m_suggestion_manager.next();
  962. m_tab_direction = TabDirection::Forward;
  963. }
  964. reverse_tab = false;
  965. SuggestionManager::CompletionMode completion_mode;
  966. switch (m_times_tab_pressed) {
  967. case 1:
  968. completion_mode = SuggestionManager::CompletePrefix;
  969. break;
  970. case 2:
  971. completion_mode = SuggestionManager::ShowSuggestions;
  972. break;
  973. default:
  974. completion_mode = SuggestionManager::CycleSuggestions;
  975. break;
  976. }
  977. insert(Utf32View { m_remembered_suggestion_static_data.data(), m_remembered_suggestion_static_data.size() });
  978. m_remembered_suggestion_static_data.clear_with_capacity();
  979. auto completion_result = m_suggestion_manager.attempt_completion(completion_mode, token_start);
  980. auto new_cursor = m_cursor;
  981. new_cursor += completion_result.new_cursor_offset;
  982. for (size_t i = completion_result.offset_region_to_remove.start; i < completion_result.offset_region_to_remove.end; ++i)
  983. remove_at_index(new_cursor);
  984. new_cursor -= completion_result.static_offset_from_cursor;
  985. for (size_t i = 0; i < completion_result.static_offset_from_cursor; ++i) {
  986. m_remembered_suggestion_static_data.append(m_buffer[new_cursor]);
  987. remove_at_index(new_cursor);
  988. }
  989. m_cursor = new_cursor;
  990. m_inline_search_cursor = new_cursor;
  991. m_refresh_needed = true;
  992. m_chars_touched_in_the_middle++;
  993. for (auto& view : completion_result.insert)
  994. insert(view);
  995. auto stderr_stream = TRY(Core::File::standard_error());
  996. TRY(reposition_cursor(*stderr_stream));
  997. if (completion_result.style_to_apply.has_value()) {
  998. // Apply the style of the last suggestion.
  999. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  1000. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, completion_result.style_to_apply.value());
  1001. }
  1002. switch (completion_result.new_completion_mode) {
  1003. case SuggestionManager::DontComplete:
  1004. m_times_tab_pressed = 0;
  1005. m_remembered_suggestion_static_data.clear_with_capacity();
  1006. break;
  1007. case SuggestionManager::CompletePrefix:
  1008. break;
  1009. default:
  1010. ++m_times_tab_pressed;
  1011. break;
  1012. }
  1013. if (m_times_tab_pressed > 1 && m_suggestion_manager.count() > 0) {
  1014. if (TRY(m_suggestion_display->cleanup()))
  1015. TRY(reposition_cursor(*stderr_stream));
  1016. m_suggestion_display->set_initial_prompt_lines(m_prompt_lines_at_suggestion_initiation);
  1017. TRY(m_suggestion_display->display(m_suggestion_manager));
  1018. m_origin_row = m_suggestion_display->origin_row();
  1019. }
  1020. if (m_times_tab_pressed > 2) {
  1021. if (m_tab_direction == TabDirection::Forward)
  1022. m_suggestion_manager.next();
  1023. else
  1024. m_suggestion_manager.previous();
  1025. }
  1026. if (m_suggestion_manager.count() < 2 && !completion_result.avoid_committing_to_single_suggestion) {
  1027. // We have none, or just one suggestion,
  1028. // we should just commit that and continue
  1029. // after it, as if it were auto-completed.
  1030. TRY(reposition_cursor(*stderr_stream, true));
  1031. TRY(cleanup_suggestions());
  1032. m_remembered_suggestion_static_data.clear_with_capacity();
  1033. }
  1034. continue;
  1035. }
  1036. // If we got here, manually cleanup the suggestions and then insert the new code point.
  1037. m_remembered_suggestion_static_data.clear_with_capacity();
  1038. suggestion_cleanup.disarm();
  1039. TRY(cleanup_suggestions());
  1040. insert(code_point);
  1041. }
  1042. if (consumed_code_points == m_incomplete_data.size()) {
  1043. m_incomplete_data.clear();
  1044. } else {
  1045. for (size_t i = 0; i < consumed_code_points; ++i)
  1046. m_incomplete_data.take_first();
  1047. }
  1048. if (!m_incomplete_data.is_empty() && !m_finish)
  1049. deferred_invoke([&] { try_update_once().release_value_but_fixme_should_propagate_errors(); });
  1050. return {};
  1051. }
  1052. ErrorOr<void> Editor::cleanup_suggestions()
  1053. {
  1054. if (m_times_tab_pressed != 0) {
  1055. // Apply the style of the last suggestion.
  1056. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  1057. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, m_suggestion_manager.current_suggestion().style);
  1058. // We probably have some suggestions drawn,
  1059. // let's clean them up.
  1060. if (TRY(m_suggestion_display->cleanup())) {
  1061. auto stderr_stream = TRY(Core::File::standard_error());
  1062. TRY(reposition_cursor(*stderr_stream));
  1063. m_refresh_needed = true;
  1064. }
  1065. m_suggestion_manager.reset();
  1066. m_suggestion_display->finish();
  1067. }
  1068. m_times_tab_pressed = 0; // Safe to say if we get here, the user didn't press TAB
  1069. return {};
  1070. }
  1071. bool Editor::search(StringView phrase, bool allow_empty, bool from_beginning)
  1072. {
  1073. int last_matching_offset = -1;
  1074. bool found = false;
  1075. // Do not search for empty strings.
  1076. if (allow_empty || phrase.length() > 0) {
  1077. size_t search_offset = m_search_offset;
  1078. for (size_t i = m_history_cursor; i > 0; --i) {
  1079. auto& entry = m_history[i - 1];
  1080. auto contains = from_beginning ? entry.entry.starts_with(phrase) : entry.entry.contains(phrase);
  1081. if (contains) {
  1082. last_matching_offset = i - 1;
  1083. if (search_offset == 0) {
  1084. found = true;
  1085. break;
  1086. }
  1087. --search_offset;
  1088. }
  1089. }
  1090. if (!found) {
  1091. fputc('\a', stderr);
  1092. fflush(stderr);
  1093. }
  1094. }
  1095. if (found) {
  1096. // We plan to clear the buffer, so mark the entire thing touched.
  1097. m_chars_touched_in_the_middle = m_buffer.size();
  1098. m_buffer.clear();
  1099. m_cursor = 0;
  1100. insert(m_history[last_matching_offset].entry);
  1101. // Always needed, as we have cleared the buffer above.
  1102. m_refresh_needed = true;
  1103. }
  1104. return found;
  1105. }
  1106. void Editor::recalculate_origin()
  1107. {
  1108. // Changing the columns can affect our origin if
  1109. // the new size is smaller than our prompt, which would
  1110. // cause said prompt to take up more space, so we should
  1111. // compensate for that.
  1112. if (m_cached_prompt_metrics.max_line_length >= m_num_columns) {
  1113. auto added_lines = (m_cached_prompt_metrics.max_line_length + 1) / m_num_columns - 1;
  1114. m_origin_row += added_lines;
  1115. }
  1116. // We also need to recalculate our cursor position,
  1117. // but that will be calculated and applied at the next
  1118. // refresh cycle.
  1119. }
  1120. ErrorOr<void> Editor::cleanup()
  1121. {
  1122. auto current_buffer_metrics = actual_rendered_string_metrics(buffer_view(), m_current_masks);
  1123. auto new_lines = current_prompt_metrics().lines_with_addition(current_buffer_metrics, m_num_columns);
  1124. if (new_lines < m_shown_lines)
  1125. m_extra_forward_lines = max(m_shown_lines - new_lines, m_extra_forward_lines);
  1126. auto stderr_stream = TRY(Core::File::standard_error());
  1127. TRY(reposition_cursor(*stderr_stream, true));
  1128. auto current_line = num_lines() - 1;
  1129. TRY(VT::clear_lines(current_line, m_extra_forward_lines, *stderr_stream));
  1130. m_extra_forward_lines = 0;
  1131. TRY(reposition_cursor(*stderr_stream));
  1132. return {};
  1133. };
  1134. ErrorOr<void> Editor::refresh_display()
  1135. {
  1136. AllocatingMemoryStream output_stream;
  1137. ScopeGuard flush_stream {
  1138. [&] {
  1139. m_shown_lines = current_prompt_metrics().lines_with_addition(m_cached_buffer_metrics, m_num_columns);
  1140. if (output_stream.used_buffer_size() == 0)
  1141. return;
  1142. auto buffer = ByteBuffer::create_uninitialized(output_stream.used_buffer_size()).release_value_but_fixme_should_propagate_errors();
  1143. output_stream.read_until_filled(buffer).release_value_but_fixme_should_propagate_errors();
  1144. fwrite(buffer.data(), sizeof(char), buffer.size(), stderr);
  1145. }
  1146. };
  1147. auto has_cleaned_up = false;
  1148. // Someone changed the window size, figure it out
  1149. // and react to it, we might need to redraw.
  1150. if (m_was_resized) {
  1151. if (m_previous_num_columns != m_num_columns) {
  1152. // We need to cleanup and redo everything.
  1153. m_cached_prompt_valid = false;
  1154. m_refresh_needed = true;
  1155. swap(m_previous_num_columns, m_num_columns);
  1156. recalculate_origin();
  1157. TRY(cleanup());
  1158. swap(m_previous_num_columns, m_num_columns);
  1159. has_cleaned_up = true;
  1160. }
  1161. m_was_resized = false;
  1162. }
  1163. // We might be at the last line, and have more than one line;
  1164. // Refreshing the display will cause the terminal to scroll,
  1165. // so note that fact and bring origin up, making sure to
  1166. // reserve the space for however many lines we move it up.
  1167. auto current_num_lines = num_lines();
  1168. if (m_origin_row + current_num_lines > m_num_lines) {
  1169. if (current_num_lines > m_num_lines) {
  1170. for (size_t i = 0; i < m_num_lines; ++i)
  1171. TRY(output_stream.write_until_depleted("\n"sv.bytes()));
  1172. m_origin_row = 0;
  1173. } else {
  1174. auto old_origin_row = m_origin_row;
  1175. m_origin_row = m_num_lines - current_num_lines + 1;
  1176. for (size_t i = 0; i < old_origin_row - m_origin_row; ++i)
  1177. TRY(output_stream.write_until_depleted("\n"sv.bytes()));
  1178. }
  1179. }
  1180. // Do not call hook on pure cursor movement.
  1181. if (m_cached_prompt_valid && !m_refresh_needed && m_pending_chars.size() == 0) {
  1182. // Probably just moving around.
  1183. TRY(reposition_cursor(output_stream));
  1184. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view(), m_current_masks);
  1185. m_drawn_end_of_line_offset = m_buffer.size();
  1186. return {};
  1187. }
  1188. if (on_display_refresh)
  1189. on_display_refresh(*this);
  1190. if (m_cached_prompt_valid) {
  1191. if (!m_refresh_needed && m_cursor == m_buffer.size()) {
  1192. // Just write the characters out and continue,
  1193. // no need to refresh the entire line.
  1194. TRY(output_stream.write_until_depleted(m_pending_chars));
  1195. m_pending_chars.clear();
  1196. m_drawn_cursor = m_cursor;
  1197. m_drawn_end_of_line_offset = m_buffer.size();
  1198. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view(), m_current_masks);
  1199. m_drawn_spans = m_current_spans;
  1200. return {};
  1201. }
  1202. }
  1203. auto apply_styles = [&, empty_styles = HashMap<u32, Style> {}](size_t i) -> ErrorOr<void> {
  1204. auto ends = m_current_spans.m_spans_ending.get(i).value_or(empty_styles);
  1205. auto starts = m_current_spans.m_spans_starting.get(i).value_or(empty_styles);
  1206. auto anchored_ends = m_current_spans.m_anchored_spans_ending.get(i).value_or(empty_styles);
  1207. auto anchored_starts = m_current_spans.m_anchored_spans_starting.get(i).value_or(empty_styles);
  1208. if (ends.size() || anchored_ends.size()) {
  1209. Style style;
  1210. for (auto& applicable_style : ends)
  1211. style.unify_with(applicable_style.value);
  1212. for (auto& applicable_style : anchored_ends)
  1213. style.unify_with(applicable_style.value);
  1214. // Disable any style that should be turned off.
  1215. TRY(VT::apply_style(style, output_stream, false));
  1216. // Reapply styles for overlapping spans that include this one.
  1217. style = find_applicable_style(i);
  1218. TRY(VT::apply_style(style, output_stream, true));
  1219. }
  1220. if (starts.size() || anchored_starts.size()) {
  1221. Style style;
  1222. for (auto& applicable_style : starts)
  1223. style.unify_with(applicable_style.value);
  1224. for (auto& applicable_style : anchored_starts)
  1225. style.unify_with(applicable_style.value);
  1226. // Set new styles.
  1227. TRY(VT::apply_style(style, output_stream, true));
  1228. }
  1229. return {};
  1230. };
  1231. auto print_character_at = [&](size_t i) {
  1232. Variant<u32, Utf8View> c { Utf8View {} };
  1233. if (auto it = m_current_masks.find_largest_not_above_iterator(i); !it.is_end() && it->has_value()) {
  1234. auto offset = i - it.key();
  1235. if (it->value().mode == Style::Mask::Mode::ReplaceEntireSelection) {
  1236. auto& mask = it->value().replacement_view;
  1237. auto replacement = mask.begin().peek(offset);
  1238. if (!replacement.has_value())
  1239. return;
  1240. c = replacement.value();
  1241. ++it;
  1242. u32 next_offset = it.is_end() ? m_drawn_end_of_line_offset : it.key();
  1243. if (i + 1 == next_offset)
  1244. c = mask.unicode_substring_view(offset, mask.length() - offset);
  1245. } else {
  1246. c = it->value().replacement_view;
  1247. }
  1248. } else {
  1249. c = m_buffer[i];
  1250. }
  1251. auto print_single_character = [&](auto c) -> ErrorOr<void> {
  1252. StringBuilder builder;
  1253. bool should_print_masked = is_ascii_control(c) && c != '\n';
  1254. bool should_print_caret = c < 64 && should_print_masked;
  1255. if (should_print_caret)
  1256. builder.appendff("^{:c}", c + 64);
  1257. else if (should_print_masked)
  1258. builder.appendff("\\x{:0>2x}", c);
  1259. else
  1260. builder.append(Utf32View { &c, 1 });
  1261. if (should_print_masked)
  1262. TRY(output_stream.write_until_depleted("\033[7m"sv.bytes()));
  1263. TRY(output_stream.write_until_depleted(builder.string_view().bytes()));
  1264. if (should_print_masked)
  1265. TRY(output_stream.write_until_depleted("\033[27m"sv.bytes()));
  1266. return {};
  1267. };
  1268. c.visit(
  1269. [&](u32 c) { print_single_character(c).release_value_but_fixme_should_propagate_errors(); },
  1270. [&](auto& view) { for (auto c : view) print_single_character(c).release_value_but_fixme_should_propagate_errors(); });
  1271. };
  1272. // If there have been no changes to previous sections of the line (style or text)
  1273. // just append the new text with the appropriate styles.
  1274. if (!m_always_refresh && m_cached_prompt_valid && m_chars_touched_in_the_middle == 0 && m_drawn_spans.contains_up_to_offset(m_current_spans, m_drawn_cursor)) {
  1275. auto initial_style = find_applicable_style(m_drawn_end_of_line_offset);
  1276. TRY(VT::apply_style(initial_style, output_stream));
  1277. for (size_t i = m_drawn_end_of_line_offset; i < m_buffer.size(); ++i) {
  1278. TRY(apply_styles(i));
  1279. print_character_at(i);
  1280. }
  1281. TRY(VT::apply_style(Style::reset_style(), output_stream));
  1282. m_pending_chars.clear();
  1283. m_refresh_needed = false;
  1284. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view(), m_current_masks);
  1285. m_chars_touched_in_the_middle = 0;
  1286. m_drawn_cursor = m_cursor;
  1287. m_drawn_end_of_line_offset = m_buffer.size();
  1288. // No need to reposition the cursor, the cursor is already where it needs to be.
  1289. return {};
  1290. }
  1291. if constexpr (LINE_EDITOR_DEBUG) {
  1292. if (m_cached_prompt_valid && m_chars_touched_in_the_middle == 0) {
  1293. auto x = m_drawn_spans.contains_up_to_offset(m_current_spans, m_drawn_cursor);
  1294. dbgln("Contains: {} At offset: {}", x, m_drawn_cursor);
  1295. dbgln("Drawn Spans:");
  1296. for (auto& sentry : m_drawn_spans.m_spans_starting) {
  1297. for (auto& entry : sentry.value) {
  1298. dbgln("{}-{}: {}", sentry.key, entry.key, entry.value.to_deprecated_string());
  1299. }
  1300. }
  1301. dbgln("==========================================================================");
  1302. dbgln("Current Spans:");
  1303. for (auto& sentry : m_current_spans.m_spans_starting) {
  1304. for (auto& entry : sentry.value) {
  1305. dbgln("{}-{}: {}", sentry.key, entry.key, entry.value.to_deprecated_string());
  1306. }
  1307. }
  1308. }
  1309. }
  1310. // Ouch, reflow entire line.
  1311. if (!has_cleaned_up) {
  1312. TRY(cleanup());
  1313. }
  1314. TRY(VT::move_absolute(m_origin_row, m_origin_column, output_stream));
  1315. TRY(output_stream.write_until_depleted(m_new_prompt.bytes()));
  1316. TRY(VT::clear_to_end_of_line(output_stream));
  1317. StringBuilder builder;
  1318. for (size_t i = 0; i < m_buffer.size(); ++i) {
  1319. TRY(apply_styles(i));
  1320. print_character_at(i);
  1321. }
  1322. TRY(VT::apply_style(Style::reset_style(), output_stream)); // don't bleed to EOL
  1323. m_pending_chars.clear();
  1324. m_refresh_needed = false;
  1325. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view(), m_current_masks);
  1326. m_chars_touched_in_the_middle = 0;
  1327. m_drawn_spans = m_current_spans;
  1328. m_drawn_end_of_line_offset = m_buffer.size();
  1329. m_cached_prompt_valid = true;
  1330. TRY(reposition_cursor(output_stream));
  1331. return {};
  1332. }
  1333. void Editor::strip_styles(bool strip_anchored)
  1334. {
  1335. m_current_spans.m_spans_starting.clear();
  1336. m_current_spans.m_spans_ending.clear();
  1337. m_current_masks.clear();
  1338. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view(), {});
  1339. if (strip_anchored) {
  1340. m_current_spans.m_anchored_spans_starting.clear();
  1341. m_current_spans.m_anchored_spans_ending.clear();
  1342. }
  1343. m_refresh_needed = true;
  1344. }
  1345. ErrorOr<void> Editor::reposition_cursor(Stream& stream, bool to_end)
  1346. {
  1347. auto cursor = m_cursor;
  1348. auto saved_cursor = m_cursor;
  1349. if (to_end)
  1350. cursor = m_buffer.size();
  1351. m_cursor = cursor;
  1352. m_drawn_cursor = cursor;
  1353. auto line = cursor_line() - 1;
  1354. auto column = offset_in_line();
  1355. ensure_free_lines_from_origin(line);
  1356. VERIFY(column + m_origin_column <= m_num_columns);
  1357. TRY(VT::move_absolute(line + m_origin_row, column + m_origin_column, stream));
  1358. m_cursor = saved_cursor;
  1359. return {};
  1360. }
  1361. ErrorOr<void> VT::move_absolute(u32 row, u32 col, Stream& stream)
  1362. {
  1363. return stream.write_until_depleted(DeprecatedString::formatted("\033[{};{}H", row, col).bytes());
  1364. }
  1365. ErrorOr<void> VT::move_relative(int row, int col, Stream& stream)
  1366. {
  1367. char x_op = 'A', y_op = 'D';
  1368. if (row > 0)
  1369. x_op = 'B';
  1370. else
  1371. row = -row;
  1372. if (col > 0)
  1373. y_op = 'C';
  1374. else
  1375. col = -col;
  1376. if (row > 0)
  1377. TRY(stream.write_until_depleted(DeprecatedString::formatted("\033[{}{}", row, x_op).bytes()));
  1378. if (col > 0)
  1379. TRY(stream.write_until_depleted(DeprecatedString::formatted("\033[{}{}", col, y_op).bytes()));
  1380. return {};
  1381. }
  1382. Style Editor::find_applicable_style(size_t offset) const
  1383. {
  1384. // Walk through our styles and merge all that fit in the offset.
  1385. auto style = Style::reset_style();
  1386. auto unify = [&](auto& entry) {
  1387. if (entry.key >= offset)
  1388. return;
  1389. for (auto& style_value : entry.value) {
  1390. if (style_value.key <= offset)
  1391. return;
  1392. style.unify_with(style_value.value, true);
  1393. }
  1394. };
  1395. for (auto& entry : m_current_spans.m_spans_starting) {
  1396. unify(entry);
  1397. }
  1398. for (auto& entry : m_current_spans.m_anchored_spans_starting) {
  1399. unify(entry);
  1400. }
  1401. return style;
  1402. }
  1403. DeprecatedString Style::Background::to_vt_escape() const
  1404. {
  1405. if (is_default())
  1406. return "";
  1407. if (m_is_rgb) {
  1408. return DeprecatedString::formatted("\e[48;2;{};{};{}m", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1409. } else {
  1410. return DeprecatedString::formatted("\e[{}m", (u8)m_xterm_color + 40);
  1411. }
  1412. }
  1413. DeprecatedString Style::Foreground::to_vt_escape() const
  1414. {
  1415. if (is_default())
  1416. return "";
  1417. if (m_is_rgb) {
  1418. return DeprecatedString::formatted("\e[38;2;{};{};{}m", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1419. } else {
  1420. return DeprecatedString::formatted("\e[{}m", (u8)m_xterm_color + 30);
  1421. }
  1422. }
  1423. DeprecatedString Style::Hyperlink::to_vt_escape(bool starting) const
  1424. {
  1425. if (is_empty())
  1426. return "";
  1427. return DeprecatedString::formatted("\e]8;;{}\e\\", starting ? m_link : DeprecatedString::empty());
  1428. }
  1429. void Style::unify_with(Style const& other, bool prefer_other)
  1430. {
  1431. // Unify colors.
  1432. if (prefer_other || m_background.is_default())
  1433. m_background = other.background();
  1434. if (prefer_other || m_foreground.is_default())
  1435. m_foreground = other.foreground();
  1436. // Unify graphic renditions.
  1437. if (other.bold())
  1438. set(Bold);
  1439. if (other.italic())
  1440. set(Italic);
  1441. if (other.underline())
  1442. set(Underline);
  1443. // Unify links.
  1444. if (prefer_other || m_hyperlink.is_empty())
  1445. m_hyperlink = other.hyperlink();
  1446. m_is_empty &= other.m_is_empty;
  1447. }
  1448. DeprecatedString Style::to_deprecated_string() const
  1449. {
  1450. StringBuilder builder;
  1451. builder.append("Style { "sv);
  1452. if (!m_foreground.is_default()) {
  1453. builder.append("Foreground("sv);
  1454. if (m_foreground.m_is_rgb) {
  1455. builder.join(", "sv, m_foreground.m_rgb_color);
  1456. } else {
  1457. builder.appendff("(XtermColor) {}", (int)m_foreground.m_xterm_color);
  1458. }
  1459. builder.append("), "sv);
  1460. }
  1461. if (!m_background.is_default()) {
  1462. builder.append("Background("sv);
  1463. if (m_background.m_is_rgb) {
  1464. builder.join(' ', m_background.m_rgb_color);
  1465. } else {
  1466. builder.appendff("(XtermColor) {}", (int)m_background.m_xterm_color);
  1467. }
  1468. builder.append("), "sv);
  1469. }
  1470. if (bold())
  1471. builder.append("Bold, "sv);
  1472. if (underline())
  1473. builder.append("Underline, "sv);
  1474. if (italic())
  1475. builder.append("Italic, "sv);
  1476. if (!m_hyperlink.is_empty())
  1477. builder.appendff("Hyperlink(\"{}\"), ", m_hyperlink.m_link);
  1478. if (!m_mask.has_value()) {
  1479. builder.appendff("Mask(\"{}\", {}), ",
  1480. m_mask->replacement,
  1481. m_mask->mode == Mask::Mode::ReplaceEntireSelection
  1482. ? "ReplaceEntireSelection"
  1483. : "ReplaceEachCodePointInSelection");
  1484. }
  1485. builder.append('}');
  1486. return builder.to_deprecated_string();
  1487. }
  1488. ErrorOr<void> VT::apply_style(Style const& style, Stream& stream, bool is_starting)
  1489. {
  1490. if (is_starting) {
  1491. TRY(stream.write_until_depleted(DeprecatedString::formatted("\033[{};{};{}m{}{}{}",
  1492. style.bold() ? 1 : 22,
  1493. style.underline() ? 4 : 24,
  1494. style.italic() ? 3 : 23,
  1495. style.background().to_vt_escape(),
  1496. style.foreground().to_vt_escape(),
  1497. style.hyperlink().to_vt_escape(true))
  1498. .bytes()));
  1499. } else {
  1500. TRY(stream.write_until_depleted(style.hyperlink().to_vt_escape(false).bytes()));
  1501. }
  1502. return {};
  1503. }
  1504. ErrorOr<void> VT::clear_lines(size_t count_above, size_t count_below, Stream& stream)
  1505. {
  1506. if (count_below + count_above == 0) {
  1507. TRY(stream.write_until_depleted("\033[2K"sv.bytes()));
  1508. } else {
  1509. // Go down count_below lines.
  1510. if (count_below > 0)
  1511. TRY(stream.write_until_depleted(DeprecatedString::formatted("\033[{}B", count_below).bytes()));
  1512. // Then clear lines going upwards.
  1513. for (size_t i = count_below + count_above; i > 0; --i) {
  1514. TRY(stream.write_until_depleted("\033[2K"sv.bytes()));
  1515. if (i != 1)
  1516. TRY(stream.write_until_depleted("\033[A"sv.bytes()));
  1517. }
  1518. }
  1519. return {};
  1520. }
  1521. ErrorOr<void> VT::save_cursor(Stream& stream)
  1522. {
  1523. return stream.write_until_depleted("\033[s"sv.bytes());
  1524. }
  1525. ErrorOr<void> VT::restore_cursor(Stream& stream)
  1526. {
  1527. return stream.write_until_depleted("\033[u"sv.bytes());
  1528. }
  1529. ErrorOr<void> VT::clear_to_end_of_line(Stream& stream)
  1530. {
  1531. return stream.write_until_depleted("\033[K"sv.bytes());
  1532. }
  1533. enum VTState {
  1534. Free = 1,
  1535. Escape = 3,
  1536. Bracket = 5,
  1537. BracketArgsSemi = 7,
  1538. Title = 9,
  1539. URL = 11,
  1540. };
  1541. static VTState actual_rendered_string_length_step(StringMetrics& metrics, size_t index, StringMetrics::LineMetrics& current_line, u32 c, u32 next_c, VTState state, Optional<Style::Mask> const& mask, Optional<size_t> const& maximum_line_width = {}, Optional<size_t&> last_return = {});
  1542. enum class MaskedSelectionDecision {
  1543. Skip,
  1544. Continue,
  1545. };
  1546. static MaskedSelectionDecision resolve_masked_selection(Optional<Style::Mask>& mask, size_t& i, auto& mask_it, auto& view, auto& state, auto& metrics, auto& current_line)
  1547. {
  1548. if (mask.has_value() && mask->mode == Style::Mask::Mode::ReplaceEntireSelection) {
  1549. ++mask_it;
  1550. auto actual_end_offset = mask_it.is_end() ? view.length() : mask_it.key();
  1551. auto end_offset = min(actual_end_offset, view.length());
  1552. size_t j = 0;
  1553. for (auto it = mask->replacement_view.begin(); it != mask->replacement_view.end(); ++it) {
  1554. auto it_copy = it;
  1555. ++it_copy;
  1556. auto next_c = it_copy == mask->replacement_view.end() ? 0 : *it_copy;
  1557. state = actual_rendered_string_length_step(metrics, j, current_line, *it, next_c, state, {});
  1558. ++j;
  1559. if (j <= actual_end_offset - i && j + i >= view.length())
  1560. break;
  1561. }
  1562. current_line.masked_chars.empend(i, end_offset - i, j);
  1563. i = end_offset;
  1564. if (mask_it.is_end())
  1565. mask = {};
  1566. else
  1567. mask = *mask_it;
  1568. return MaskedSelectionDecision::Skip;
  1569. }
  1570. return MaskedSelectionDecision::Continue;
  1571. }
  1572. StringMetrics Editor::actual_rendered_string_metrics(StringView string, RedBlackTree<u32, Optional<Style::Mask>> const& masks, Optional<size_t> maximum_line_width)
  1573. {
  1574. StringMetrics metrics;
  1575. StringMetrics::LineMetrics current_line;
  1576. VTState state { Free };
  1577. Utf8View view { string };
  1578. size_t last_return {};
  1579. auto it = view.begin();
  1580. Optional<Style::Mask> mask;
  1581. size_t i = 0;
  1582. auto mask_it = masks.begin();
  1583. for (; it != view.end(); ++it) {
  1584. if (!mask_it.is_end() && mask_it.key() <= i)
  1585. mask = *mask_it;
  1586. auto c = *it;
  1587. auto it_copy = it;
  1588. ++it_copy;
  1589. if (resolve_masked_selection(mask, i, mask_it, view, state, metrics, current_line) == MaskedSelectionDecision::Skip)
  1590. continue;
  1591. auto next_c = it_copy == view.end() ? 0 : *it_copy;
  1592. state = actual_rendered_string_length_step(metrics, view.iterator_offset(it), current_line, c, next_c, state, mask, maximum_line_width, last_return);
  1593. if (!mask_it.is_end() && mask_it.key() <= i) {
  1594. auto mask_it_peek = mask_it;
  1595. ++mask_it_peek;
  1596. if (!mask_it_peek.is_end() && mask_it_peek.key() > i)
  1597. mask_it = mask_it_peek;
  1598. }
  1599. ++i;
  1600. }
  1601. metrics.line_metrics.append(current_line);
  1602. for (auto& line : metrics.line_metrics)
  1603. metrics.max_line_length = max(line.total_length(), metrics.max_line_length);
  1604. return metrics;
  1605. }
  1606. StringMetrics Editor::actual_rendered_string_metrics(Utf32View const& view, RedBlackTree<u32, Optional<Style::Mask>> const& masks)
  1607. {
  1608. StringMetrics metrics;
  1609. StringMetrics::LineMetrics current_line;
  1610. VTState state { Free };
  1611. Optional<Style::Mask> mask;
  1612. auto mask_it = masks.begin();
  1613. for (size_t i = 0; i < view.length(); ++i) {
  1614. auto c = view[i];
  1615. if (!mask_it.is_end() && mask_it.key() <= i)
  1616. mask = *mask_it;
  1617. if (resolve_masked_selection(mask, i, mask_it, view, state, metrics, current_line) == MaskedSelectionDecision::Skip) {
  1618. --i;
  1619. continue;
  1620. }
  1621. auto next_c = i + 1 < view.length() ? view.code_points()[i + 1] : 0;
  1622. state = actual_rendered_string_length_step(metrics, i, current_line, c, next_c, state, mask);
  1623. if (!mask_it.is_end() && mask_it.key() <= i) {
  1624. auto mask_it_peek = mask_it;
  1625. ++mask_it_peek;
  1626. if (!mask_it_peek.is_end() && mask_it_peek.key() > i)
  1627. mask_it = mask_it_peek;
  1628. }
  1629. }
  1630. metrics.line_metrics.append(current_line);
  1631. for (auto& line : metrics.line_metrics)
  1632. metrics.max_line_length = max(line.total_length(), metrics.max_line_length);
  1633. return metrics;
  1634. }
  1635. VTState actual_rendered_string_length_step(StringMetrics& metrics, size_t index, StringMetrics::LineMetrics& current_line, u32 c, u32 next_c, VTState state, Optional<Style::Mask> const& mask, Optional<size_t> const& maximum_line_width, Optional<size_t&> last_return)
  1636. {
  1637. auto const save_line = [&metrics, &current_line, &last_return, &index]() {
  1638. if (last_return.has_value()) {
  1639. auto const last_index = index - 1;
  1640. current_line.bit_length = last_index - *last_return + 1;
  1641. last_return.value() = last_index + 1;
  1642. }
  1643. metrics.line_metrics.append(current_line);
  1644. current_line.masked_chars = {};
  1645. current_line.length = 0;
  1646. current_line.visible_length = 0;
  1647. current_line.bit_length = {};
  1648. };
  1649. // FIXME: current_line.visible_length can go above maximum_line_width when using masks
  1650. if (maximum_line_width.has_value() && current_line.visible_length >= maximum_line_width.value())
  1651. save_line();
  1652. ScopeGuard bit_length_update { [&last_return, &current_line, &index]() {
  1653. if (last_return.has_value())
  1654. current_line.bit_length = index - *last_return + 1;
  1655. } };
  1656. switch (state) {
  1657. case Free: {
  1658. if (c == '\x1b') { // escape
  1659. return Escape;
  1660. }
  1661. if (c == '\r') { // carriage return
  1662. current_line.masked_chars = {};
  1663. current_line.length = 0;
  1664. current_line.visible_length = 0;
  1665. if (!metrics.line_metrics.is_empty())
  1666. metrics.line_metrics.last() = { {}, 0 };
  1667. return state;
  1668. }
  1669. if (c == '\n') { // return
  1670. save_line();
  1671. return state;
  1672. }
  1673. if (c == '\t') {
  1674. // Tabs are a special case, because their width is variable.
  1675. ++current_line.length;
  1676. current_line.visible_length += (8 - (current_line.visible_length % 8));
  1677. return state;
  1678. }
  1679. auto is_control = is_ascii_control(c);
  1680. if (is_control) {
  1681. if (mask.has_value())
  1682. current_line.masked_chars.append({ index, 1, mask->replacement_view.length() });
  1683. else
  1684. current_line.masked_chars.append({ index, 1, c < 64 ? 2u : 4u }); // if the character cannot be represented as ^c, represent it as \xbb.
  1685. }
  1686. // FIXME: This will not support anything sophisticated
  1687. if (mask.has_value()) {
  1688. current_line.length += mask->replacement_view.length();
  1689. current_line.visible_length += mask->replacement_view.length();
  1690. metrics.total_length += mask->replacement_view.length();
  1691. } else if (is_control) {
  1692. current_line.length += current_line.masked_chars.last().masked_length;
  1693. current_line.visible_length += current_line.masked_chars.last().masked_length;
  1694. metrics.total_length += current_line.masked_chars.last().masked_length;
  1695. } else {
  1696. ++current_line.length;
  1697. ++current_line.visible_length;
  1698. ++metrics.total_length;
  1699. }
  1700. return state;
  1701. }
  1702. case Escape:
  1703. if (c == ']') {
  1704. if (next_c == '0')
  1705. state = Title;
  1706. if (next_c == '8')
  1707. state = URL;
  1708. return state;
  1709. }
  1710. if (c == '[') {
  1711. return Bracket;
  1712. }
  1713. // FIXME: This does not support non-VT (aside from set-title) escapes
  1714. return state;
  1715. case Bracket:
  1716. if (is_ascii_digit(c)) {
  1717. return BracketArgsSemi;
  1718. }
  1719. return state;
  1720. case BracketArgsSemi:
  1721. if (c == ';') {
  1722. return Bracket;
  1723. }
  1724. if (!is_ascii_digit(c))
  1725. state = Free;
  1726. return state;
  1727. case Title:
  1728. if (c == 7)
  1729. state = Free;
  1730. return state;
  1731. case URL:
  1732. if (c == '\\')
  1733. state = Free;
  1734. return state;
  1735. }
  1736. return state;
  1737. }
  1738. Result<Vector<size_t, 2>, Editor::Error> Editor::vt_dsr()
  1739. {
  1740. char buf[16];
  1741. // Read whatever junk there is before talking to the terminal
  1742. // and insert them later when we're reading user input.
  1743. bool more_junk_to_read { false };
  1744. timeval timeout { 0, 0 };
  1745. fd_set readfds;
  1746. FD_ZERO(&readfds);
  1747. FD_SET(0, &readfds);
  1748. do {
  1749. more_junk_to_read = false;
  1750. [[maybe_unused]] auto rc = select(1, &readfds, nullptr, nullptr, &timeout);
  1751. if (FD_ISSET(0, &readfds)) {
  1752. auto nread = read(0, buf, 16);
  1753. if (nread < 0) {
  1754. m_input_error = Error::ReadFailure;
  1755. finish();
  1756. break;
  1757. }
  1758. if (nread == 0)
  1759. break;
  1760. m_incomplete_data.append(buf, nread);
  1761. more_junk_to_read = true;
  1762. }
  1763. } while (more_junk_to_read);
  1764. if (m_input_error.has_value())
  1765. return m_input_error.value();
  1766. fputs("\033[6n", stderr);
  1767. fflush(stderr);
  1768. // Parse the DSR response
  1769. // it should be of the form .*\e[\d+;\d+R.*
  1770. // Anything not part of the response is just added to the incomplete data.
  1771. enum {
  1772. Free,
  1773. SawEsc,
  1774. SawBracket,
  1775. InFirstCoordinate,
  1776. SawSemicolon,
  1777. InSecondCoordinate,
  1778. SawR,
  1779. } state { Free };
  1780. auto has_error = false;
  1781. Vector<char, 4> coordinate_buffer;
  1782. size_t row { 1 }, col { 1 };
  1783. do {
  1784. char c;
  1785. auto nread = read(0, &c, 1);
  1786. if (nread < 0) {
  1787. if (errno == 0 || errno == EINTR) {
  1788. // ????
  1789. continue;
  1790. }
  1791. dbgln("Error while reading DSR: {}", strerror(errno));
  1792. return Error::ReadFailure;
  1793. }
  1794. if (nread == 0) {
  1795. dbgln("Terminal DSR issue; received no response");
  1796. return Error::Empty;
  1797. }
  1798. switch (state) {
  1799. case Free:
  1800. if (c == '\x1b') {
  1801. state = SawEsc;
  1802. continue;
  1803. }
  1804. m_incomplete_data.append(c);
  1805. continue;
  1806. case SawEsc:
  1807. if (c == '[') {
  1808. state = SawBracket;
  1809. continue;
  1810. }
  1811. m_incomplete_data.append(c);
  1812. continue;
  1813. case SawBracket:
  1814. if (is_ascii_digit(c)) {
  1815. state = InFirstCoordinate;
  1816. coordinate_buffer.append(c);
  1817. continue;
  1818. }
  1819. m_incomplete_data.append(c);
  1820. continue;
  1821. case InFirstCoordinate:
  1822. if (is_ascii_digit(c)) {
  1823. coordinate_buffer.append(c);
  1824. continue;
  1825. }
  1826. if (c == ';') {
  1827. auto maybe_row = StringView { coordinate_buffer.data(), coordinate_buffer.size() }.to_uint();
  1828. if (!maybe_row.has_value())
  1829. has_error = true;
  1830. row = maybe_row.value_or(1u);
  1831. coordinate_buffer.clear_with_capacity();
  1832. state = SawSemicolon;
  1833. continue;
  1834. }
  1835. m_incomplete_data.append(c);
  1836. continue;
  1837. case SawSemicolon:
  1838. if (is_ascii_digit(c)) {
  1839. state = InSecondCoordinate;
  1840. coordinate_buffer.append(c);
  1841. continue;
  1842. }
  1843. m_incomplete_data.append(c);
  1844. continue;
  1845. case InSecondCoordinate:
  1846. if (is_ascii_digit(c)) {
  1847. coordinate_buffer.append(c);
  1848. continue;
  1849. }
  1850. if (c == 'R') {
  1851. auto maybe_column = StringView { coordinate_buffer.data(), coordinate_buffer.size() }.to_uint();
  1852. if (!maybe_column.has_value())
  1853. has_error = true;
  1854. col = maybe_column.value_or(1u);
  1855. coordinate_buffer.clear_with_capacity();
  1856. state = SawR;
  1857. continue;
  1858. }
  1859. m_incomplete_data.append(c);
  1860. continue;
  1861. case SawR:
  1862. m_incomplete_data.append(c);
  1863. continue;
  1864. default:
  1865. VERIFY_NOT_REACHED();
  1866. }
  1867. } while (state != SawR);
  1868. if (has_error)
  1869. dbgln("Terminal DSR issue, couldn't parse DSR response");
  1870. return Vector<size_t, 2> { row, col };
  1871. }
  1872. DeprecatedString Editor::line(size_t up_to_index) const
  1873. {
  1874. StringBuilder builder;
  1875. builder.append(Utf32View { m_buffer.data(), min(m_buffer.size(), up_to_index) });
  1876. return builder.to_deprecated_string();
  1877. }
  1878. void Editor::remove_at_index(size_t index)
  1879. {
  1880. // See if we have any anchored styles, and reposition them if needed.
  1881. readjust_anchored_styles(index, ModificationKind::Removal);
  1882. auto cp = m_buffer[index];
  1883. m_buffer.remove(index);
  1884. if (cp == '\n')
  1885. ++m_extra_forward_lines;
  1886. ++m_chars_touched_in_the_middle;
  1887. }
  1888. void Editor::readjust_anchored_styles(size_t hint_index, ModificationKind modification)
  1889. {
  1890. struct Anchor {
  1891. Span old_span;
  1892. Span new_span;
  1893. Style style;
  1894. };
  1895. Vector<Anchor> anchors_to_relocate;
  1896. auto index_shift = modification == ModificationKind::Insertion ? 1 : -1;
  1897. auto forced_removal = modification == ModificationKind::ForcedOverlapRemoval;
  1898. for (auto& start_entry : m_current_spans.m_anchored_spans_starting) {
  1899. for (auto& end_entry : start_entry.value) {
  1900. if (forced_removal) {
  1901. if (start_entry.key <= hint_index && end_entry.key > hint_index) {
  1902. // Remove any overlapping regions.
  1903. continue;
  1904. }
  1905. }
  1906. if (start_entry.key >= hint_index) {
  1907. if (start_entry.key == hint_index && end_entry.key == hint_index + 1 && modification == ModificationKind::Removal) {
  1908. // Remove the anchor, as all its text was wiped.
  1909. continue;
  1910. }
  1911. // Shift everything.
  1912. 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 });
  1913. continue;
  1914. }
  1915. if (end_entry.key > hint_index) {
  1916. // Shift just the end.
  1917. 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 });
  1918. continue;
  1919. }
  1920. 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 });
  1921. }
  1922. }
  1923. m_current_spans.m_anchored_spans_ending.clear();
  1924. m_current_spans.m_anchored_spans_starting.clear();
  1925. // Pass over the relocations and update the stale entries.
  1926. for (auto& relocation : anchors_to_relocate) {
  1927. stylize(relocation.new_span, relocation.style);
  1928. }
  1929. }
  1930. size_t StringMetrics::lines_with_addition(StringMetrics const& offset, size_t column_width) const
  1931. {
  1932. size_t lines = 0;
  1933. if (!line_metrics.is_empty()) {
  1934. for (size_t i = 0; i < line_metrics.size() - 1; ++i)
  1935. lines += (line_metrics[i].total_length() + column_width) / column_width;
  1936. auto last = line_metrics.last().total_length();
  1937. last += offset.line_metrics.first().total_length();
  1938. lines += (last + column_width) / column_width;
  1939. }
  1940. for (size_t i = 1; i < offset.line_metrics.size(); ++i)
  1941. lines += (offset.line_metrics[i].total_length() + column_width) / column_width;
  1942. return lines;
  1943. }
  1944. size_t StringMetrics::offset_with_addition(StringMetrics const& offset, size_t column_width) const
  1945. {
  1946. if (offset.line_metrics.size() > 1)
  1947. return offset.line_metrics.last().total_length() % column_width;
  1948. if (!line_metrics.is_empty()) {
  1949. auto last = line_metrics.last().total_length();
  1950. last += offset.line_metrics.first().total_length();
  1951. return last % column_width;
  1952. }
  1953. if (offset.line_metrics.is_empty())
  1954. return 0;
  1955. return offset.line_metrics.first().total_length() % column_width;
  1956. }
  1957. bool Editor::Spans::contains_up_to_offset(Spans const& other, size_t offset) const
  1958. {
  1959. auto compare = [&]<typename K, typename V>(HashMap<K, HashMap<K, V>> const& left, HashMap<K, HashMap<K, V>> const& right) -> bool {
  1960. for (auto& entry : right) {
  1961. if (entry.key > offset + 1)
  1962. continue;
  1963. auto left_map_it = left.find(entry.key);
  1964. if (left_map_it == left.end())
  1965. return false;
  1966. for (auto& left_entry : left_map_it->value) {
  1967. auto value_it = entry.value.find(left_entry.key);
  1968. if (value_it == entry.value.end()) {
  1969. // Might have the same thing with a longer span
  1970. bool found = false;
  1971. for (auto& possibly_longer_span_entry : entry.value) {
  1972. if (possibly_longer_span_entry.key > left_entry.key && possibly_longer_span_entry.key > offset && left_entry.value == possibly_longer_span_entry.value) {
  1973. found = true;
  1974. break;
  1975. }
  1976. }
  1977. if (found)
  1978. continue;
  1979. if constexpr (LINE_EDITOR_DEBUG) {
  1980. dbgln("Compare for {}-{} failed, no entry", entry.key, left_entry.key);
  1981. for (auto& x : entry.value)
  1982. dbgln("Have: {}-{} = {}", entry.key, x.key, x.value.to_deprecated_string());
  1983. }
  1984. return false;
  1985. } else if (value_it->value != left_entry.value) {
  1986. dbgln_if(LINE_EDITOR_DEBUG, "Compare for {}-{} failed, different values: {} != {}", entry.key, left_entry.key, value_it->value.to_deprecated_string(), left_entry.value.to_deprecated_string());
  1987. return false;
  1988. }
  1989. }
  1990. }
  1991. return true;
  1992. };
  1993. return compare(m_spans_starting, other.m_spans_starting)
  1994. && compare(m_anchored_spans_starting, other.m_anchored_spans_starting);
  1995. }
  1996. }