Editor.cpp 62 KB

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