Editor.cpp 65 KB

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