Editor.cpp 65 KB

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