Editor.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  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_end_of_line_offset = m_buffer.size();
  1095. // No need to reposition the cursor, the cursor is already where it needs to be.
  1096. return;
  1097. }
  1098. if constexpr (LINE_EDITOR_DEBUG) {
  1099. if (m_cached_prompt_valid && m_chars_touched_in_the_middle == 0) {
  1100. auto x = m_drawn_spans.contains_up_to_offset(m_current_spans, m_drawn_cursor);
  1101. dbgln("Contains: {} At offset: {}", x, m_drawn_cursor);
  1102. dbgln("Drawn Spans:");
  1103. for (auto& sentry : m_drawn_spans.m_spans_starting) {
  1104. for (auto& entry : sentry.value) {
  1105. dbgln("{}-{}: {}", sentry.key, entry.key, entry.value.to_string());
  1106. }
  1107. }
  1108. dbgln("==========================================================================");
  1109. dbgln("Current Spans:");
  1110. for (auto& sentry : m_current_spans.m_spans_starting) {
  1111. for (auto& entry : sentry.value) {
  1112. dbgln("{}-{}: {}", sentry.key, entry.key, entry.value.to_string());
  1113. }
  1114. }
  1115. }
  1116. }
  1117. // Ouch, reflow entire line.
  1118. if (!has_cleaned_up) {
  1119. cleanup();
  1120. }
  1121. VT::move_absolute(m_origin_row, m_origin_column);
  1122. fputs(m_new_prompt.characters(), stderr);
  1123. VT::clear_to_end_of_line();
  1124. StringBuilder builder;
  1125. for (size_t i = 0; i < m_buffer.size(); ++i) {
  1126. apply_styles(i);
  1127. print_character_at(i);
  1128. }
  1129. VT::apply_style(Style::reset_style()); // don't bleed to EOL
  1130. m_pending_chars.clear();
  1131. m_refresh_needed = false;
  1132. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1133. m_chars_touched_in_the_middle = 0;
  1134. m_drawn_spans = m_current_spans;
  1135. m_drawn_end_of_line_offset = m_buffer.size();
  1136. m_cached_prompt_valid = true;
  1137. reposition_cursor();
  1138. fflush(stderr);
  1139. }
  1140. void Editor::strip_styles(bool strip_anchored)
  1141. {
  1142. m_current_spans.m_spans_starting.clear();
  1143. m_current_spans.m_spans_ending.clear();
  1144. if (strip_anchored) {
  1145. m_current_spans.m_anchored_spans_starting.clear();
  1146. m_current_spans.m_anchored_spans_ending.clear();
  1147. }
  1148. m_refresh_needed = true;
  1149. }
  1150. void Editor::reposition_cursor(bool to_end)
  1151. {
  1152. auto cursor = m_cursor;
  1153. auto saved_cursor = m_cursor;
  1154. if (to_end)
  1155. cursor = m_buffer.size();
  1156. m_cursor = cursor;
  1157. m_drawn_cursor = cursor;
  1158. auto line = cursor_line() - 1;
  1159. auto column = offset_in_line();
  1160. ASSERT(column + m_origin_column <= m_num_columns);
  1161. VT::move_absolute(line + m_origin_row, column + m_origin_column);
  1162. if (line + m_origin_row > m_num_lines) {
  1163. for (size_t i = m_num_lines; i < line + m_origin_row; ++i)
  1164. fputc('\n', stderr);
  1165. m_origin_row -= line + m_origin_row - m_num_lines;
  1166. VT::move_relative(0, column + m_origin_column);
  1167. }
  1168. m_cursor = saved_cursor;
  1169. }
  1170. void VT::move_absolute(u32 row, u32 col)
  1171. {
  1172. fprintf(stderr, "\033[%d;%dH", row, col);
  1173. fflush(stderr);
  1174. }
  1175. void VT::move_relative(int row, int col)
  1176. {
  1177. char x_op = 'A', y_op = 'D';
  1178. if (row > 0)
  1179. x_op = 'B';
  1180. else
  1181. row = -row;
  1182. if (col > 0)
  1183. y_op = 'C';
  1184. else
  1185. col = -col;
  1186. if (row > 0)
  1187. fprintf(stderr, "\033[%d%c", row, x_op);
  1188. if (col > 0)
  1189. fprintf(stderr, "\033[%d%c", col, y_op);
  1190. }
  1191. Style Editor::find_applicable_style(size_t offset) const
  1192. {
  1193. // Walk through our styles and merge all that fit in the offset.
  1194. auto style = Style::reset_style();
  1195. auto unify = [&](auto& entry) {
  1196. if (entry.key >= offset)
  1197. return;
  1198. for (auto& style_value : entry.value) {
  1199. if (style_value.key <= offset)
  1200. return;
  1201. style.unify_with(style_value.value, true);
  1202. }
  1203. };
  1204. for (auto& entry : m_current_spans.m_spans_starting) {
  1205. unify(entry);
  1206. }
  1207. for (auto& entry : m_current_spans.m_anchored_spans_starting) {
  1208. unify(entry);
  1209. }
  1210. return style;
  1211. }
  1212. String Style::Background::to_vt_escape() const
  1213. {
  1214. if (is_default())
  1215. return "";
  1216. if (m_is_rgb) {
  1217. return String::format("\033[48;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1218. } else {
  1219. return String::format("\033[%dm", (u8)m_xterm_color + 40);
  1220. }
  1221. }
  1222. String Style::Foreground::to_vt_escape() const
  1223. {
  1224. if (is_default())
  1225. return "";
  1226. if (m_is_rgb) {
  1227. return String::format("\033[38;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1228. } else {
  1229. return String::format("\033[%dm", (u8)m_xterm_color + 30);
  1230. }
  1231. }
  1232. String Style::Hyperlink::to_vt_escape(bool starting) const
  1233. {
  1234. if (is_empty())
  1235. return "";
  1236. return String::format("\033]8;;%s\033\\", starting ? m_link.characters() : "");
  1237. }
  1238. void Style::unify_with(const Style& other, bool prefer_other)
  1239. {
  1240. // Unify colors.
  1241. if (prefer_other || m_background.is_default())
  1242. m_background = other.background();
  1243. if (prefer_other || m_foreground.is_default())
  1244. m_foreground = other.foreground();
  1245. // Unify graphic renditions.
  1246. if (other.bold())
  1247. set(Bold);
  1248. if (other.italic())
  1249. set(Italic);
  1250. if (other.underline())
  1251. set(Underline);
  1252. // Unify links.
  1253. if (prefer_other || m_hyperlink.is_empty())
  1254. m_hyperlink = other.hyperlink();
  1255. }
  1256. String Style::to_string() const
  1257. {
  1258. StringBuilder builder;
  1259. builder.append("Style { ");
  1260. if (!m_foreground.is_default()) {
  1261. builder.append("Foreground(");
  1262. if (m_foreground.m_is_rgb) {
  1263. builder.join(", ", m_foreground.m_rgb_color);
  1264. } else {
  1265. builder.appendf("(XtermColor) %d", (int)m_foreground.m_xterm_color);
  1266. }
  1267. builder.append("), ");
  1268. }
  1269. if (!m_background.is_default()) {
  1270. builder.append("Background(");
  1271. if (m_background.m_is_rgb) {
  1272. builder.join(' ', m_background.m_rgb_color);
  1273. } else {
  1274. builder.appendf("(XtermColor) %d", (int)m_background.m_xterm_color);
  1275. }
  1276. builder.append("), ");
  1277. }
  1278. if (bold())
  1279. builder.append("Bold, ");
  1280. if (underline())
  1281. builder.append("Underline, ");
  1282. if (italic())
  1283. builder.append("Italic, ");
  1284. if (!m_hyperlink.is_empty())
  1285. builder.appendf("Hyperlink(\"%s\"), ", m_hyperlink.m_link.characters());
  1286. builder.append("}");
  1287. return builder.build();
  1288. }
  1289. void VT::apply_style(const Style& style, bool is_starting)
  1290. {
  1291. if (is_starting) {
  1292. fprintf(stderr,
  1293. "\033[%d;%d;%dm%s%s%s",
  1294. style.bold() ? 1 : 22,
  1295. style.underline() ? 4 : 24,
  1296. style.italic() ? 3 : 23,
  1297. style.background().to_vt_escape().characters(),
  1298. style.foreground().to_vt_escape().characters(),
  1299. style.hyperlink().to_vt_escape(true).characters());
  1300. } else {
  1301. fprintf(stderr, "%s", style.hyperlink().to_vt_escape(false).characters());
  1302. }
  1303. }
  1304. void VT::clear_lines(size_t count_above, size_t count_below)
  1305. {
  1306. // Go down count_below lines.
  1307. if (count_below > 0)
  1308. fprintf(stderr, "\033[%dB", (int)count_below);
  1309. // Then clear lines going upwards.
  1310. for (size_t i = count_below + count_above; i > 0; --i)
  1311. fputs(i == 1 ? "\033[2K" : "\033[2K\033[A", stderr);
  1312. }
  1313. void VT::save_cursor()
  1314. {
  1315. fputs("\033[s", stderr);
  1316. fflush(stderr);
  1317. }
  1318. void VT::restore_cursor()
  1319. {
  1320. fputs("\033[u", stderr);
  1321. fflush(stderr);
  1322. }
  1323. void VT::clear_to_end_of_line()
  1324. {
  1325. fputs("\033[K", stderr);
  1326. fflush(stderr);
  1327. }
  1328. StringMetrics Editor::actual_rendered_string_metrics(const StringView& string)
  1329. {
  1330. StringMetrics metrics;
  1331. StringMetrics::LineMetrics current_line;
  1332. VTState state { Free };
  1333. Utf8View view { string };
  1334. auto it = view.begin();
  1335. for (; it != view.end(); ++it) {
  1336. auto c = *it;
  1337. auto it_copy = it;
  1338. ++it_copy;
  1339. auto next_c = it_copy == view.end() ? 0 : *it_copy;
  1340. state = actual_rendered_string_length_step(metrics, view.iterator_offset(it), current_line, c, next_c, state);
  1341. }
  1342. metrics.line_metrics.append(current_line);
  1343. for (auto& line : metrics.line_metrics)
  1344. metrics.max_line_length = max(line.total_length(), metrics.max_line_length);
  1345. return metrics;
  1346. }
  1347. StringMetrics Editor::actual_rendered_string_metrics(const Utf32View& view)
  1348. {
  1349. StringMetrics metrics;
  1350. StringMetrics::LineMetrics current_line;
  1351. VTState state { Free };
  1352. for (size_t i = 0; i < view.length(); ++i) {
  1353. auto c = view.code_points()[i];
  1354. auto next_c = i + 1 < view.length() ? view.code_points()[i + 1] : 0;
  1355. state = actual_rendered_string_length_step(metrics, i, current_line, c, next_c, state);
  1356. }
  1357. metrics.line_metrics.append(current_line);
  1358. for (auto& line : metrics.line_metrics)
  1359. metrics.max_line_length = max(line.total_length(), metrics.max_line_length);
  1360. return metrics;
  1361. }
  1362. Editor::VTState Editor::actual_rendered_string_length_step(StringMetrics& metrics, size_t index, StringMetrics::LineMetrics& current_line, u32 c, u32 next_c, VTState state)
  1363. {
  1364. switch (state) {
  1365. case Free:
  1366. if (c == '\x1b') { // escape
  1367. return Escape;
  1368. }
  1369. if (c == '\r') { // carriage return
  1370. current_line.masked_chars = {};
  1371. current_line.length = 0;
  1372. if (!metrics.line_metrics.is_empty())
  1373. metrics.line_metrics.last() = { {}, 0 };
  1374. return state;
  1375. }
  1376. if (c == '\n') { // return
  1377. metrics.line_metrics.append(current_line);
  1378. current_line.masked_chars = {};
  1379. current_line.length = 0;
  1380. return state;
  1381. }
  1382. if (isascii(c) && iscntrl(c) && c != '\n')
  1383. current_line.masked_chars.append({ index, 1, 2 });
  1384. // FIXME: This will not support anything sophisticated
  1385. ++current_line.length;
  1386. ++metrics.total_length;
  1387. return state;
  1388. case Escape:
  1389. if (c == ']') {
  1390. if (next_c == '0')
  1391. state = Title;
  1392. return state;
  1393. }
  1394. if (c == '[') {
  1395. return Bracket;
  1396. }
  1397. // FIXME: This does not support non-VT (aside from set-title) escapes
  1398. return state;
  1399. case Bracket:
  1400. if (isdigit(c)) {
  1401. return BracketArgsSemi;
  1402. }
  1403. return state;
  1404. case BracketArgsSemi:
  1405. if (c == ';') {
  1406. return Bracket;
  1407. }
  1408. if (!isdigit(c))
  1409. state = Free;
  1410. return state;
  1411. case Title:
  1412. if (c == 7)
  1413. state = Free;
  1414. return state;
  1415. }
  1416. return state;
  1417. }
  1418. Vector<size_t, 2> Editor::vt_dsr()
  1419. {
  1420. char buf[16];
  1421. u32 length { 0 };
  1422. // Read whatever junk there is before talking to the terminal
  1423. // and insert them later when we're reading user input.
  1424. bool more_junk_to_read { false };
  1425. timeval timeout { 0, 0 };
  1426. fd_set readfds;
  1427. FD_ZERO(&readfds);
  1428. FD_SET(0, &readfds);
  1429. do {
  1430. more_junk_to_read = false;
  1431. [[maybe_unused]] auto rc = select(1, &readfds, nullptr, nullptr, &timeout);
  1432. if (FD_ISSET(0, &readfds)) {
  1433. auto nread = read(0, buf, 16);
  1434. if (nread < 0) {
  1435. m_input_error = Error::ReadFailure;
  1436. finish();
  1437. break;
  1438. }
  1439. if (nread == 0)
  1440. break;
  1441. m_incomplete_data.append(buf, nread);
  1442. more_junk_to_read = true;
  1443. }
  1444. } while (more_junk_to_read);
  1445. if (m_input_error.has_value())
  1446. return { 1, 1 };
  1447. fputs("\033[6n", stderr);
  1448. fflush(stderr);
  1449. do {
  1450. auto nread = read(0, buf + length, 16 - length);
  1451. if (nread < 0) {
  1452. if (errno == 0 || errno == EINTR) {
  1453. // ????
  1454. continue;
  1455. }
  1456. dbgln("Error while reading DSR: {}", strerror(errno));
  1457. m_input_error = Error::ReadFailure;
  1458. finish();
  1459. return { 1, 1 };
  1460. }
  1461. if (nread == 0) {
  1462. m_input_error = Error::Empty;
  1463. finish();
  1464. dbgln("Terminal DSR issue; received no response");
  1465. return { 1, 1 };
  1466. }
  1467. length += nread;
  1468. } while (buf[length - 1] != 'R' && length < 16);
  1469. size_t row { 1 }, col { 1 };
  1470. if (buf[0] == '\033' && buf[1] == '[') {
  1471. auto parts = StringView(buf + 2, length - 3).split_view(';');
  1472. auto row_opt = parts[0].to_int();
  1473. if (!row_opt.has_value()) {
  1474. dbgln("Terminal DSR issue; received garbage row");
  1475. } else {
  1476. row = row_opt.value();
  1477. }
  1478. auto col_opt = parts[1].to_int();
  1479. if (!col_opt.has_value()) {
  1480. dbgln("Terminal DSR issue; received garbage col");
  1481. } else {
  1482. col = col_opt.value();
  1483. }
  1484. }
  1485. return { row, col };
  1486. }
  1487. String Editor::line(size_t up_to_index) const
  1488. {
  1489. StringBuilder builder;
  1490. builder.append(Utf32View { m_buffer.data(), min(m_buffer.size(), up_to_index) });
  1491. return builder.build();
  1492. }
  1493. void Editor::remove_at_index(size_t index)
  1494. {
  1495. // See if we have any anchored styles, and reposition them if needed.
  1496. readjust_anchored_styles(index, ModificationKind::Removal);
  1497. auto cp = m_buffer[index];
  1498. m_buffer.remove(index);
  1499. if (cp == '\n')
  1500. ++m_extra_forward_lines;
  1501. ++m_chars_touched_in_the_middle;
  1502. }
  1503. void Editor::readjust_anchored_styles(size_t hint_index, ModificationKind modification)
  1504. {
  1505. struct Anchor {
  1506. Span old_span;
  1507. Span new_span;
  1508. Style style;
  1509. };
  1510. Vector<Anchor> anchors_to_relocate;
  1511. auto index_shift = modification == ModificationKind::Insertion ? 1 : -1;
  1512. auto forced_removal = modification == ModificationKind::ForcedOverlapRemoval;
  1513. for (auto& start_entry : m_current_spans.m_anchored_spans_starting) {
  1514. for (auto& end_entry : start_entry.value) {
  1515. if (forced_removal) {
  1516. if (start_entry.key <= hint_index && end_entry.key > hint_index) {
  1517. // Remove any overlapping regions.
  1518. continue;
  1519. }
  1520. }
  1521. if (start_entry.key >= hint_index) {
  1522. if (start_entry.key == hint_index && end_entry.key == hint_index + 1 && modification == ModificationKind::Removal) {
  1523. // Remove the anchor, as all its text was wiped.
  1524. continue;
  1525. }
  1526. // Shift everything.
  1527. 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 });
  1528. continue;
  1529. }
  1530. if (end_entry.key > hint_index) {
  1531. // Shift just the end.
  1532. 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 });
  1533. continue;
  1534. }
  1535. 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 });
  1536. }
  1537. }
  1538. m_current_spans.m_anchored_spans_ending.clear();
  1539. m_current_spans.m_anchored_spans_starting.clear();
  1540. // Pass over the relocations and update the stale entries.
  1541. for (auto& relocation : anchors_to_relocate) {
  1542. stylize(relocation.new_span, relocation.style);
  1543. }
  1544. }
  1545. size_t StringMetrics::lines_with_addition(const StringMetrics& offset, size_t column_width) const
  1546. {
  1547. size_t lines = 0;
  1548. for (size_t i = 0; i < line_metrics.size() - 1; ++i)
  1549. lines += (line_metrics[i].total_length() + column_width) / column_width;
  1550. auto last = line_metrics.last().total_length();
  1551. last += offset.line_metrics.first().total_length();
  1552. lines += (last + column_width) / column_width;
  1553. for (size_t i = 1; i < offset.line_metrics.size(); ++i)
  1554. lines += (offset.line_metrics[i].total_length() + column_width) / column_width;
  1555. return lines;
  1556. }
  1557. size_t StringMetrics::offset_with_addition(const StringMetrics& offset, size_t column_width) const
  1558. {
  1559. if (offset.line_metrics.size() > 1)
  1560. return offset.line_metrics.last().total_length() % column_width;
  1561. auto last = line_metrics.last().total_length();
  1562. last += offset.line_metrics.first().total_length();
  1563. return last % column_width;
  1564. }
  1565. bool Editor::Spans::contains_up_to_offset(const Spans& other, size_t offset) const
  1566. {
  1567. auto compare = [&]<typename K, typename V>(const HashMap<K, HashMap<K, V>>& left, const HashMap<K, HashMap<K, V>>& right) -> bool {
  1568. for (auto& entry : right) {
  1569. if (entry.key > offset + 1)
  1570. continue;
  1571. auto left_map = left.get(entry.key);
  1572. if (!left_map.has_value())
  1573. return false;
  1574. for (auto& left_entry : left_map.value()) {
  1575. if (auto value = entry.value.get(left_entry.key); !value.has_value()) {
  1576. // Might have the same thing with a longer span
  1577. bool found = false;
  1578. for (auto& possibly_longer_span_entry : entry.value) {
  1579. if (possibly_longer_span_entry.key > left_entry.key && possibly_longer_span_entry.key > offset && left_entry.value == possibly_longer_span_entry.value) {
  1580. found = true;
  1581. break;
  1582. }
  1583. }
  1584. if (found)
  1585. continue;
  1586. if constexpr (LINE_EDITOR_DEBUG) {
  1587. dbgln("Compare for {}-{} failed, no entry", entry.key, left_entry.key);
  1588. for (auto& x : entry.value)
  1589. dbgln("Have: {}-{} = {}", entry.key, x.key, x.value.to_string());
  1590. }
  1591. return false;
  1592. } else if (value.value() != left_entry.value) {
  1593. dbgln_if(LINE_EDITOR_DEBUG, "Compare for {}-{} failed, different values: {} != {}", entry.key, left_entry.key, value.value().to_string(), left_entry.value.to_string());
  1594. return false;
  1595. }
  1596. }
  1597. }
  1598. return true;
  1599. };
  1600. return compare(m_spans_starting, other.m_spans_starting)
  1601. && compare(m_anchored_spans_starting, other.m_anchored_spans_starting);
  1602. }
  1603. }