Editor.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877
  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_buffer.clear();
  292. m_chars_touched_in_the_middle = buffer().size();
  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. m_buffer.clear();
  943. m_cursor = 0;
  944. insert(m_history[last_matching_offset].entry);
  945. // Always needed, as we have cleared the buffer above.
  946. m_refresh_needed = true;
  947. }
  948. return found;
  949. }
  950. void Editor::recalculate_origin()
  951. {
  952. // Changing the columns can affect our origin if
  953. // the new size is smaller than our prompt, which would
  954. // cause said prompt to take up more space, so we should
  955. // compensate for that.
  956. if (m_cached_prompt_metrics.max_line_length >= m_num_columns) {
  957. auto added_lines = (m_cached_prompt_metrics.max_line_length + 1) / m_num_columns - 1;
  958. m_origin_row += added_lines;
  959. }
  960. // We also need to recalculate our cursor position,
  961. // but that will be calculated and applied at the next
  962. // refresh cycle.
  963. }
  964. void Editor::cleanup()
  965. {
  966. auto current_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  967. auto new_lines = current_prompt_metrics().lines_with_addition(current_buffer_metrics, m_num_columns);
  968. auto shown_lines = num_lines();
  969. if (new_lines < shown_lines)
  970. m_extra_forward_lines = max(shown_lines - new_lines, m_extra_forward_lines);
  971. reposition_cursor(true);
  972. auto current_line = num_lines() - 1;
  973. VT::clear_lines(current_line, m_extra_forward_lines);
  974. m_extra_forward_lines = 0;
  975. reposition_cursor();
  976. };
  977. void Editor::refresh_display()
  978. {
  979. auto has_cleaned_up = false;
  980. // Someone changed the window size, figure it out
  981. // and react to it, we might need to redraw.
  982. if (m_was_resized) {
  983. if (m_previous_num_columns != m_num_columns) {
  984. // We need to cleanup and redo everything.
  985. m_cached_prompt_valid = false;
  986. m_refresh_needed = true;
  987. swap(m_previous_num_columns, m_num_columns);
  988. recalculate_origin();
  989. cleanup();
  990. swap(m_previous_num_columns, m_num_columns);
  991. has_cleaned_up = true;
  992. }
  993. m_was_resized = false;
  994. }
  995. // We might be at the last line, and have more than one line;
  996. // Refreshing the display will cause the terminal to scroll,
  997. // so note that fact and bring origin up, making sure to
  998. // reserve the space for however many lines we move it up.
  999. auto current_num_lines = num_lines();
  1000. if (m_origin_row + current_num_lines > m_num_lines) {
  1001. if (current_num_lines > m_num_lines) {
  1002. for (size_t i = 0; i < m_num_lines; ++i)
  1003. putc('\n', stderr);
  1004. m_origin_row = 0;
  1005. } else {
  1006. auto old_origin_row = m_origin_row;
  1007. m_origin_row = m_num_lines - current_num_lines + 1;
  1008. for (size_t i = 0; i < old_origin_row - m_origin_row; ++i)
  1009. putc('\n', stderr);
  1010. }
  1011. fflush(stderr);
  1012. }
  1013. // Do not call hook on pure cursor movement.
  1014. if (m_cached_prompt_valid && !m_refresh_needed && m_pending_chars.size() == 0) {
  1015. // Probably just moving around.
  1016. reposition_cursor();
  1017. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1018. m_drawn_end_of_line_offset = m_buffer.size();
  1019. return;
  1020. }
  1021. if (on_display_refresh)
  1022. on_display_refresh(*this);
  1023. if (m_cached_prompt_valid) {
  1024. if (!m_refresh_needed && m_cursor == m_buffer.size()) {
  1025. // Just write the characters out and continue,
  1026. // no need to refresh the entire line.
  1027. char null = 0;
  1028. m_pending_chars.append(&null, 1);
  1029. fputs((char*)m_pending_chars.data(), stderr);
  1030. m_pending_chars.clear();
  1031. m_drawn_cursor = m_cursor;
  1032. m_drawn_end_of_line_offset = m_buffer.size();
  1033. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1034. m_drawn_spans = m_current_spans;
  1035. fflush(stderr);
  1036. return;
  1037. }
  1038. }
  1039. auto apply_styles = [&, empty_styles = HashMap<u32, Style> {}](size_t i) {
  1040. auto ends = m_current_spans.m_spans_ending.get(i).value_or(empty_styles);
  1041. auto starts = m_current_spans.m_spans_starting.get(i).value_or(empty_styles);
  1042. auto anchored_ends = m_current_spans.m_anchored_spans_ending.get(i).value_or(empty_styles);
  1043. auto anchored_starts = m_current_spans.m_anchored_spans_starting.get(i).value_or(empty_styles);
  1044. if (ends.size() || anchored_ends.size()) {
  1045. Style style;
  1046. for (auto& applicable_style : ends)
  1047. style.unify_with(applicable_style.value);
  1048. for (auto& applicable_style : anchored_ends)
  1049. style.unify_with(applicable_style.value);
  1050. // Disable any style that should be turned off.
  1051. VT::apply_style(style, false);
  1052. // Reapply styles for overlapping spans that include this one.
  1053. style = find_applicable_style(i);
  1054. VT::apply_style(style, true);
  1055. }
  1056. if (starts.size() || anchored_starts.size()) {
  1057. Style style;
  1058. for (auto& applicable_style : starts)
  1059. style.unify_with(applicable_style.value);
  1060. for (auto& applicable_style : anchored_starts)
  1061. style.unify_with(applicable_style.value);
  1062. // Set new styles.
  1063. VT::apply_style(style, true);
  1064. }
  1065. };
  1066. auto print_character_at = [this](size_t i) {
  1067. StringBuilder builder;
  1068. auto c = m_buffer[i];
  1069. bool should_print_caret = isascii(c) && iscntrl(c) && c != '\n';
  1070. if (should_print_caret)
  1071. builder.appendff("^{:c}", c + 64);
  1072. else
  1073. builder.append(Utf32View { &c, 1 });
  1074. if (should_print_caret)
  1075. fputs("\033[7m", stderr);
  1076. fputs(builder.to_string().characters(), stderr);
  1077. if (should_print_caret)
  1078. fputs("\033[27m", stderr);
  1079. };
  1080. // If there have been no changes to previous sections of the line (style or text)
  1081. // just append the new text with the appropriate styles.
  1082. 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)) {
  1083. auto initial_style = find_applicable_style(m_drawn_end_of_line_offset);
  1084. VT::apply_style(initial_style);
  1085. for (size_t i = m_drawn_end_of_line_offset; i < m_buffer.size(); ++i) {
  1086. apply_styles(i);
  1087. print_character_at(i);
  1088. }
  1089. VT::apply_style(Style::reset_style());
  1090. m_pending_chars.clear();
  1091. m_refresh_needed = false;
  1092. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1093. m_chars_touched_in_the_middle = 0;
  1094. m_drawn_cursor = m_cursor;
  1095. m_drawn_end_of_line_offset = m_buffer.size();
  1096. // No need to reposition the cursor, the cursor is already where it needs to be.
  1097. return;
  1098. }
  1099. if constexpr (LINE_EDITOR_DEBUG) {
  1100. if (m_cached_prompt_valid && m_chars_touched_in_the_middle == 0) {
  1101. auto x = m_drawn_spans.contains_up_to_offset(m_current_spans, m_drawn_cursor);
  1102. dbgln("Contains: {} At offset: {}", x, m_drawn_cursor);
  1103. dbgln("Drawn Spans:");
  1104. for (auto& sentry : m_drawn_spans.m_spans_starting) {
  1105. for (auto& entry : sentry.value) {
  1106. dbgln("{}-{}: {}", sentry.key, entry.key, entry.value.to_string());
  1107. }
  1108. }
  1109. dbgln("==========================================================================");
  1110. dbgln("Current Spans:");
  1111. for (auto& sentry : m_current_spans.m_spans_starting) {
  1112. for (auto& entry : sentry.value) {
  1113. dbgln("{}-{}: {}", sentry.key, entry.key, entry.value.to_string());
  1114. }
  1115. }
  1116. }
  1117. }
  1118. // Ouch, reflow entire line.
  1119. if (!has_cleaned_up) {
  1120. cleanup();
  1121. }
  1122. VT::move_absolute(m_origin_row, m_origin_column);
  1123. fputs(m_new_prompt.characters(), stderr);
  1124. VT::clear_to_end_of_line();
  1125. StringBuilder builder;
  1126. for (size_t i = 0; i < m_buffer.size(); ++i) {
  1127. apply_styles(i);
  1128. print_character_at(i);
  1129. }
  1130. VT::apply_style(Style::reset_style()); // don't bleed to EOL
  1131. m_pending_chars.clear();
  1132. m_refresh_needed = false;
  1133. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1134. m_chars_touched_in_the_middle = 0;
  1135. m_drawn_spans = m_current_spans;
  1136. m_drawn_end_of_line_offset = m_buffer.size();
  1137. m_cached_prompt_valid = true;
  1138. reposition_cursor();
  1139. fflush(stderr);
  1140. }
  1141. void Editor::strip_styles(bool strip_anchored)
  1142. {
  1143. m_current_spans.m_spans_starting.clear();
  1144. m_current_spans.m_spans_ending.clear();
  1145. if (strip_anchored) {
  1146. m_current_spans.m_anchored_spans_starting.clear();
  1147. m_current_spans.m_anchored_spans_ending.clear();
  1148. }
  1149. m_refresh_needed = true;
  1150. }
  1151. void Editor::reposition_cursor(bool to_end)
  1152. {
  1153. auto cursor = m_cursor;
  1154. auto saved_cursor = m_cursor;
  1155. if (to_end)
  1156. cursor = m_buffer.size();
  1157. m_cursor = cursor;
  1158. m_drawn_cursor = cursor;
  1159. auto line = cursor_line() - 1;
  1160. auto column = offset_in_line();
  1161. VERIFY(column + m_origin_column <= m_num_columns);
  1162. VT::move_absolute(line + m_origin_row, column + m_origin_column);
  1163. if (line + m_origin_row > m_num_lines) {
  1164. for (size_t i = m_num_lines; i < line + m_origin_row; ++i)
  1165. fputc('\n', stderr);
  1166. m_origin_row -= line + m_origin_row - m_num_lines;
  1167. VT::move_relative(0, column + m_origin_column);
  1168. }
  1169. m_cursor = saved_cursor;
  1170. }
  1171. void VT::move_absolute(u32 row, u32 col)
  1172. {
  1173. fprintf(stderr, "\033[%d;%dH", row, col);
  1174. fflush(stderr);
  1175. }
  1176. void VT::move_relative(int row, int col)
  1177. {
  1178. char x_op = 'A', y_op = 'D';
  1179. if (row > 0)
  1180. x_op = 'B';
  1181. else
  1182. row = -row;
  1183. if (col > 0)
  1184. y_op = 'C';
  1185. else
  1186. col = -col;
  1187. if (row > 0)
  1188. fprintf(stderr, "\033[%d%c", row, x_op);
  1189. if (col > 0)
  1190. fprintf(stderr, "\033[%d%c", col, y_op);
  1191. }
  1192. Style Editor::find_applicable_style(size_t offset) const
  1193. {
  1194. // Walk through our styles and merge all that fit in the offset.
  1195. auto style = Style::reset_style();
  1196. auto unify = [&](auto& entry) {
  1197. if (entry.key >= offset)
  1198. return;
  1199. for (auto& style_value : entry.value) {
  1200. if (style_value.key <= offset)
  1201. return;
  1202. style.unify_with(style_value.value, true);
  1203. }
  1204. };
  1205. for (auto& entry : m_current_spans.m_spans_starting) {
  1206. unify(entry);
  1207. }
  1208. for (auto& entry : m_current_spans.m_anchored_spans_starting) {
  1209. unify(entry);
  1210. }
  1211. return style;
  1212. }
  1213. String Style::Background::to_vt_escape() const
  1214. {
  1215. if (is_default())
  1216. return "";
  1217. if (m_is_rgb) {
  1218. return String::format("\033[48;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1219. } else {
  1220. return String::format("\033[%dm", (u8)m_xterm_color + 40);
  1221. }
  1222. }
  1223. String Style::Foreground::to_vt_escape() const
  1224. {
  1225. if (is_default())
  1226. return "";
  1227. if (m_is_rgb) {
  1228. return String::format("\033[38;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1229. } else {
  1230. return String::format("\033[%dm", (u8)m_xterm_color + 30);
  1231. }
  1232. }
  1233. String Style::Hyperlink::to_vt_escape(bool starting) const
  1234. {
  1235. if (is_empty())
  1236. return "";
  1237. return String::format("\033]8;;%s\033\\", starting ? m_link.characters() : "");
  1238. }
  1239. void Style::unify_with(const Style& other, bool prefer_other)
  1240. {
  1241. // Unify colors.
  1242. if (prefer_other || m_background.is_default())
  1243. m_background = other.background();
  1244. if (prefer_other || m_foreground.is_default())
  1245. m_foreground = other.foreground();
  1246. // Unify graphic renditions.
  1247. if (other.bold())
  1248. set(Bold);
  1249. if (other.italic())
  1250. set(Italic);
  1251. if (other.underline())
  1252. set(Underline);
  1253. // Unify links.
  1254. if (prefer_other || m_hyperlink.is_empty())
  1255. m_hyperlink = other.hyperlink();
  1256. }
  1257. String Style::to_string() const
  1258. {
  1259. StringBuilder builder;
  1260. builder.append("Style { ");
  1261. if (!m_foreground.is_default()) {
  1262. builder.append("Foreground(");
  1263. if (m_foreground.m_is_rgb) {
  1264. builder.join(", ", m_foreground.m_rgb_color);
  1265. } else {
  1266. builder.appendf("(XtermColor) %d", (int)m_foreground.m_xterm_color);
  1267. }
  1268. builder.append("), ");
  1269. }
  1270. if (!m_background.is_default()) {
  1271. builder.append("Background(");
  1272. if (m_background.m_is_rgb) {
  1273. builder.join(' ', m_background.m_rgb_color);
  1274. } else {
  1275. builder.appendf("(XtermColor) %d", (int)m_background.m_xterm_color);
  1276. }
  1277. builder.append("), ");
  1278. }
  1279. if (bold())
  1280. builder.append("Bold, ");
  1281. if (underline())
  1282. builder.append("Underline, ");
  1283. if (italic())
  1284. builder.append("Italic, ");
  1285. if (!m_hyperlink.is_empty())
  1286. builder.appendf("Hyperlink(\"%s\"), ", m_hyperlink.m_link.characters());
  1287. builder.append("}");
  1288. return builder.build();
  1289. }
  1290. void VT::apply_style(const Style& style, bool is_starting)
  1291. {
  1292. if (is_starting) {
  1293. fprintf(stderr,
  1294. "\033[%d;%d;%dm%s%s%s",
  1295. style.bold() ? 1 : 22,
  1296. style.underline() ? 4 : 24,
  1297. style.italic() ? 3 : 23,
  1298. style.background().to_vt_escape().characters(),
  1299. style.foreground().to_vt_escape().characters(),
  1300. style.hyperlink().to_vt_escape(true).characters());
  1301. } else {
  1302. fprintf(stderr, "%s", style.hyperlink().to_vt_escape(false).characters());
  1303. }
  1304. }
  1305. void VT::clear_lines(size_t count_above, size_t count_below)
  1306. {
  1307. if (count_below + count_above == 0) {
  1308. fputs("\033[2K", stderr);
  1309. } else {
  1310. // Go down count_below lines.
  1311. if (count_below > 0)
  1312. fprintf(stderr, "\033[%dB", (int)count_below);
  1313. // Then clear lines going upwards.
  1314. for (size_t i = count_below + count_above; i > 0; --i)
  1315. fputs(i == 1 ? "\033[2K" : "\033[2K\033[A", stderr);
  1316. }
  1317. }
  1318. void VT::save_cursor()
  1319. {
  1320. fputs("\033[s", stderr);
  1321. fflush(stderr);
  1322. }
  1323. void VT::restore_cursor()
  1324. {
  1325. fputs("\033[u", stderr);
  1326. fflush(stderr);
  1327. }
  1328. void VT::clear_to_end_of_line()
  1329. {
  1330. fputs("\033[K", stderr);
  1331. fflush(stderr);
  1332. }
  1333. StringMetrics Editor::actual_rendered_string_metrics(const StringView& string)
  1334. {
  1335. StringMetrics metrics;
  1336. StringMetrics::LineMetrics current_line;
  1337. VTState state { Free };
  1338. Utf8View view { string };
  1339. auto it = view.begin();
  1340. for (; it != view.end(); ++it) {
  1341. auto c = *it;
  1342. auto it_copy = it;
  1343. ++it_copy;
  1344. auto next_c = it_copy == view.end() ? 0 : *it_copy;
  1345. state = actual_rendered_string_length_step(metrics, view.iterator_offset(it), current_line, c, next_c, state);
  1346. }
  1347. metrics.line_metrics.append(current_line);
  1348. for (auto& line : metrics.line_metrics)
  1349. metrics.max_line_length = max(line.total_length(), metrics.max_line_length);
  1350. return metrics;
  1351. }
  1352. StringMetrics Editor::actual_rendered_string_metrics(const Utf32View& view)
  1353. {
  1354. StringMetrics metrics;
  1355. StringMetrics::LineMetrics current_line;
  1356. VTState state { Free };
  1357. for (size_t i = 0; i < view.length(); ++i) {
  1358. auto c = view.code_points()[i];
  1359. auto next_c = i + 1 < view.length() ? view.code_points()[i + 1] : 0;
  1360. state = actual_rendered_string_length_step(metrics, i, current_line, c, next_c, state);
  1361. }
  1362. metrics.line_metrics.append(current_line);
  1363. for (auto& line : metrics.line_metrics)
  1364. metrics.max_line_length = max(line.total_length(), metrics.max_line_length);
  1365. return metrics;
  1366. }
  1367. Editor::VTState Editor::actual_rendered_string_length_step(StringMetrics& metrics, size_t index, StringMetrics::LineMetrics& current_line, u32 c, u32 next_c, VTState state)
  1368. {
  1369. switch (state) {
  1370. case Free:
  1371. if (c == '\x1b') { // escape
  1372. return Escape;
  1373. }
  1374. if (c == '\r') { // carriage return
  1375. current_line.masked_chars = {};
  1376. current_line.length = 0;
  1377. if (!metrics.line_metrics.is_empty())
  1378. metrics.line_metrics.last() = { {}, 0 };
  1379. return state;
  1380. }
  1381. if (c == '\n') { // return
  1382. metrics.line_metrics.append(current_line);
  1383. current_line.masked_chars = {};
  1384. current_line.length = 0;
  1385. return state;
  1386. }
  1387. if (isascii(c) && iscntrl(c) && c != '\n')
  1388. current_line.masked_chars.append({ index, 1, 2 });
  1389. // FIXME: This will not support anything sophisticated
  1390. ++current_line.length;
  1391. ++metrics.total_length;
  1392. return state;
  1393. case Escape:
  1394. if (c == ']') {
  1395. if (next_c == '0')
  1396. state = Title;
  1397. return state;
  1398. }
  1399. if (c == '[') {
  1400. return Bracket;
  1401. }
  1402. // FIXME: This does not support non-VT (aside from set-title) escapes
  1403. return state;
  1404. case Bracket:
  1405. if (isdigit(c)) {
  1406. return BracketArgsSemi;
  1407. }
  1408. return state;
  1409. case BracketArgsSemi:
  1410. if (c == ';') {
  1411. return Bracket;
  1412. }
  1413. if (!isdigit(c))
  1414. state = Free;
  1415. return state;
  1416. case Title:
  1417. if (c == 7)
  1418. state = Free;
  1419. return state;
  1420. }
  1421. return state;
  1422. }
  1423. Vector<size_t, 2> Editor::vt_dsr()
  1424. {
  1425. char buf[16];
  1426. u32 length { 0 };
  1427. // Read whatever junk there is before talking to the terminal
  1428. // and insert them later when we're reading user input.
  1429. bool more_junk_to_read { false };
  1430. timeval timeout { 0, 0 };
  1431. fd_set readfds;
  1432. FD_ZERO(&readfds);
  1433. FD_SET(0, &readfds);
  1434. do {
  1435. more_junk_to_read = false;
  1436. [[maybe_unused]] auto rc = select(1, &readfds, nullptr, nullptr, &timeout);
  1437. if (FD_ISSET(0, &readfds)) {
  1438. auto nread = read(0, buf, 16);
  1439. if (nread < 0) {
  1440. m_input_error = Error::ReadFailure;
  1441. finish();
  1442. break;
  1443. }
  1444. if (nread == 0)
  1445. break;
  1446. m_incomplete_data.append(buf, nread);
  1447. more_junk_to_read = true;
  1448. }
  1449. } while (more_junk_to_read);
  1450. if (m_input_error.has_value())
  1451. return { 1, 1 };
  1452. fputs("\033[6n", stderr);
  1453. fflush(stderr);
  1454. do {
  1455. auto nread = read(0, buf + length, 16 - length);
  1456. if (nread < 0) {
  1457. if (errno == 0 || errno == EINTR) {
  1458. // ????
  1459. continue;
  1460. }
  1461. dbgln("Error while reading DSR: {}", strerror(errno));
  1462. m_input_error = Error::ReadFailure;
  1463. finish();
  1464. return { 1, 1 };
  1465. }
  1466. if (nread == 0) {
  1467. m_input_error = Error::Empty;
  1468. finish();
  1469. dbgln("Terminal DSR issue; received no response");
  1470. return { 1, 1 };
  1471. }
  1472. length += nread;
  1473. } while (buf[length - 1] != 'R' && length < 16);
  1474. size_t row { 1 }, col { 1 };
  1475. if (buf[0] == '\033' && buf[1] == '[') {
  1476. auto parts = StringView(buf + 2, length - 3).split_view(';');
  1477. auto row_opt = parts[0].to_int();
  1478. if (!row_opt.has_value()) {
  1479. dbgln("Terminal DSR issue; received garbage row");
  1480. } else {
  1481. row = row_opt.value();
  1482. }
  1483. auto col_opt = parts[1].to_int();
  1484. if (!col_opt.has_value()) {
  1485. dbgln("Terminal DSR issue; received garbage col");
  1486. } else {
  1487. col = col_opt.value();
  1488. }
  1489. }
  1490. return { row, col };
  1491. }
  1492. String Editor::line(size_t up_to_index) const
  1493. {
  1494. StringBuilder builder;
  1495. builder.append(Utf32View { m_buffer.data(), min(m_buffer.size(), up_to_index) });
  1496. return builder.build();
  1497. }
  1498. void Editor::remove_at_index(size_t index)
  1499. {
  1500. // See if we have any anchored styles, and reposition them if needed.
  1501. readjust_anchored_styles(index, ModificationKind::Removal);
  1502. auto cp = m_buffer[index];
  1503. m_buffer.remove(index);
  1504. if (cp == '\n')
  1505. ++m_extra_forward_lines;
  1506. ++m_chars_touched_in_the_middle;
  1507. }
  1508. void Editor::readjust_anchored_styles(size_t hint_index, ModificationKind modification)
  1509. {
  1510. struct Anchor {
  1511. Span old_span;
  1512. Span new_span;
  1513. Style style;
  1514. };
  1515. Vector<Anchor> anchors_to_relocate;
  1516. auto index_shift = modification == ModificationKind::Insertion ? 1 : -1;
  1517. auto forced_removal = modification == ModificationKind::ForcedOverlapRemoval;
  1518. for (auto& start_entry : m_current_spans.m_anchored_spans_starting) {
  1519. for (auto& end_entry : start_entry.value) {
  1520. if (forced_removal) {
  1521. if (start_entry.key <= hint_index && end_entry.key > hint_index) {
  1522. // Remove any overlapping regions.
  1523. continue;
  1524. }
  1525. }
  1526. if (start_entry.key >= hint_index) {
  1527. if (start_entry.key == hint_index && end_entry.key == hint_index + 1 && modification == ModificationKind::Removal) {
  1528. // Remove the anchor, as all its text was wiped.
  1529. continue;
  1530. }
  1531. // Shift everything.
  1532. 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 });
  1533. continue;
  1534. }
  1535. if (end_entry.key > hint_index) {
  1536. // Shift just the end.
  1537. 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 });
  1538. continue;
  1539. }
  1540. 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 });
  1541. }
  1542. }
  1543. m_current_spans.m_anchored_spans_ending.clear();
  1544. m_current_spans.m_anchored_spans_starting.clear();
  1545. // Pass over the relocations and update the stale entries.
  1546. for (auto& relocation : anchors_to_relocate) {
  1547. stylize(relocation.new_span, relocation.style);
  1548. }
  1549. }
  1550. size_t StringMetrics::lines_with_addition(const StringMetrics& offset, size_t column_width) const
  1551. {
  1552. size_t lines = 0;
  1553. for (size_t i = 0; i < line_metrics.size() - 1; ++i)
  1554. lines += (line_metrics[i].total_length() + column_width) / column_width;
  1555. auto last = line_metrics.last().total_length();
  1556. last += offset.line_metrics.first().total_length();
  1557. lines += (last + column_width) / column_width;
  1558. for (size_t i = 1; i < offset.line_metrics.size(); ++i)
  1559. lines += (offset.line_metrics[i].total_length() + column_width) / column_width;
  1560. return lines;
  1561. }
  1562. size_t StringMetrics::offset_with_addition(const StringMetrics& offset, size_t column_width) const
  1563. {
  1564. if (offset.line_metrics.size() > 1)
  1565. return offset.line_metrics.last().total_length() % column_width;
  1566. auto last = line_metrics.last().total_length();
  1567. last += offset.line_metrics.first().total_length();
  1568. return last % column_width;
  1569. }
  1570. bool Editor::Spans::contains_up_to_offset(const Spans& other, size_t offset) const
  1571. {
  1572. auto compare = [&]<typename K, typename V>(const HashMap<K, HashMap<K, V>>& left, const HashMap<K, HashMap<K, V>>& right) -> bool {
  1573. for (auto& entry : right) {
  1574. if (entry.key > offset + 1)
  1575. continue;
  1576. auto left_map = left.get(entry.key);
  1577. if (!left_map.has_value())
  1578. return false;
  1579. for (auto& left_entry : left_map.value()) {
  1580. if (auto value = entry.value.get(left_entry.key); !value.has_value()) {
  1581. // Might have the same thing with a longer span
  1582. bool found = false;
  1583. for (auto& possibly_longer_span_entry : entry.value) {
  1584. if (possibly_longer_span_entry.key > left_entry.key && possibly_longer_span_entry.key > offset && left_entry.value == possibly_longer_span_entry.value) {
  1585. found = true;
  1586. break;
  1587. }
  1588. }
  1589. if (found)
  1590. continue;
  1591. if constexpr (LINE_EDITOR_DEBUG) {
  1592. dbgln("Compare for {}-{} failed, no entry", entry.key, left_entry.key);
  1593. for (auto& x : entry.value)
  1594. dbgln("Have: {}-{} = {}", entry.key, x.key, x.value.to_string());
  1595. }
  1596. return false;
  1597. } else if (value.value() != left_entry.value) {
  1598. dbgln_if(LINE_EDITOR_DEBUG, "Compare for {}-{} failed, different values: {} != {}", entry.key, left_entry.key, value.value().to_string(), left_entry.value.to_string());
  1599. return false;
  1600. }
  1601. }
  1602. }
  1603. return true;
  1604. };
  1605. return compare(m_spans_starting, other.m_spans_starting)
  1606. && compare(m_anchored_spans_starting, other.m_anchored_spans_starting);
  1607. }
  1608. }