Editor.cpp 67 KB

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