Editor.cpp 67 KB

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