Editor.cpp 67 KB

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