Editor.cpp 76 KB

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