Editor.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053
  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/CharacterTypes.h>
  9. #include <AK/Debug.h>
  10. #include <AK/GenericLexer.h>
  11. #include <AK/JsonObject.h>
  12. #include <AK/ScopeGuard.h>
  13. #include <AK/ScopedValueRollback.h>
  14. #include <AK/StringBuilder.h>
  15. #include <AK/Utf32View.h>
  16. #include <AK/Utf8View.h>
  17. #include <LibCore/ConfigFile.h>
  18. #include <LibCore/Event.h>
  19. #include <LibCore/EventLoop.h>
  20. #include <LibCore/File.h>
  21. #include <LibCore/Notifier.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. m_notifier = nullptr;
  509. Core::EventLoop::current().quit(Retry);
  510. }
  511. void Editor::resized()
  512. {
  513. m_was_resized = true;
  514. m_previous_num_columns = m_num_columns;
  515. get_terminal_size();
  516. if (!m_has_origin_reset_scheduled) {
  517. // Reset the origin, but make sure it doesn't blow up if we can't read it
  518. if (set_origin(false)) {
  519. handle_resize_event(false);
  520. } else {
  521. deferred_invoke([this](auto&) { handle_resize_event(true); });
  522. m_has_origin_reset_scheduled = true;
  523. }
  524. }
  525. }
  526. void Editor::handle_resize_event(bool reset_origin)
  527. {
  528. m_has_origin_reset_scheduled = false;
  529. if (reset_origin && !set_origin(false)) {
  530. m_has_origin_reset_scheduled = true;
  531. return deferred_invoke([this](auto&) { handle_resize_event(true); });
  532. }
  533. set_origin(m_origin_row, 1);
  534. reposition_cursor(true);
  535. m_suggestion_display->redisplay(m_suggestion_manager, m_num_lines, m_num_columns);
  536. reposition_cursor();
  537. if (m_is_searching)
  538. m_search_editor->resized();
  539. }
  540. void Editor::really_quit_event_loop()
  541. {
  542. m_finish = false;
  543. reposition_cursor(true);
  544. fprintf(stderr, "\n");
  545. fflush(stderr);
  546. auto string = line();
  547. m_buffer.clear();
  548. m_chars_touched_in_the_middle = buffer().size();
  549. m_is_editing = false;
  550. if (m_initialized)
  551. restore();
  552. m_returned_line = string;
  553. m_notifier->set_enabled(false);
  554. m_notifier = nullptr;
  555. Core::EventLoop::current().quit(Exit);
  556. }
  557. auto Editor::get_line(const String& prompt) -> Result<String, Editor::Error>
  558. {
  559. initialize();
  560. m_is_editing = true;
  561. if (m_configuration.operation_mode == Configuration::NoEscapeSequences || m_configuration.operation_mode == Configuration::NonInteractive) {
  562. // Do not use escape sequences, instead, use LibC's getline.
  563. size_t size = 0;
  564. char* line = nullptr;
  565. // Show the prompt only on interactive mode (NoEscapeSequences in this case).
  566. if (m_configuration.operation_mode != Configuration::NonInteractive)
  567. fputs(prompt.characters(), stderr);
  568. auto line_length = getline(&line, &size, stdin);
  569. // getline() returns -1 and sets errno=0 on EOF.
  570. if (line_length == -1) {
  571. if (line)
  572. free(line);
  573. if (errno == 0)
  574. return Error::Eof;
  575. return Error::ReadFailure;
  576. }
  577. restore();
  578. if (line) {
  579. String result { line, (size_t)line_length, Chomp };
  580. free(line);
  581. return result;
  582. }
  583. return Error::ReadFailure;
  584. }
  585. auto old_cols = m_num_columns;
  586. auto old_lines = m_num_lines;
  587. get_terminal_size();
  588. if (m_configuration.enable_bracketed_paste)
  589. fprintf(stderr, "\x1b[?2004h");
  590. if (m_num_columns != old_cols || m_num_lines != old_lines)
  591. m_refresh_needed = true;
  592. set_prompt(prompt);
  593. reset();
  594. strip_styles(true);
  595. auto prompt_lines = max(current_prompt_metrics().line_metrics.size(), 1ul) - 1;
  596. for (size_t i = 0; i < prompt_lines; ++i)
  597. putc('\n', stderr);
  598. VT::move_relative(-prompt_lines, 0);
  599. set_origin();
  600. m_history_cursor = m_history.size();
  601. refresh_display();
  602. Core::EventLoop loop;
  603. m_notifier = Core::Notifier::construct(STDIN_FILENO, Core::Notifier::Read);
  604. m_notifier->on_ready_to_read = [&] { try_update_once(); };
  605. if (!m_incomplete_data.is_empty())
  606. deferred_invoke([&](auto&) { try_update_once(); });
  607. if (loop.exec() == Retry)
  608. return get_line(prompt);
  609. return m_input_error.has_value() ? Result<String, Editor::Error> { m_input_error.value() } : Result<String, Editor::Error> { m_returned_line };
  610. }
  611. void Editor::save_to(JsonObject& object)
  612. {
  613. Core::Object::save_to(object);
  614. object.set("is_searching", m_is_searching);
  615. object.set("is_editing", m_is_editing);
  616. object.set("cursor_offset", m_cursor);
  617. object.set("needs_refresh", m_refresh_needed);
  618. object.set("unprocessed_characters", m_incomplete_data.size());
  619. object.set("history_size", m_history.size());
  620. object.set("current_prompt", m_new_prompt);
  621. object.set("was_interrupted", m_was_interrupted);
  622. JsonObject display_area;
  623. display_area.set("top_left_row", m_origin_row);
  624. display_area.set("top_left_column", m_origin_column);
  625. display_area.set("line_count", num_lines());
  626. object.set("used_display_area", move(display_area));
  627. }
  628. void Editor::try_update_once()
  629. {
  630. if (m_was_interrupted) {
  631. handle_interrupt_event();
  632. }
  633. handle_read_event();
  634. if (m_always_refresh)
  635. m_refresh_needed = true;
  636. refresh_display();
  637. if (m_finish)
  638. really_quit_event_loop();
  639. }
  640. void Editor::handle_interrupt_event()
  641. {
  642. m_was_interrupted = false;
  643. m_previous_interrupt_was_handled_as_interrupt = false;
  644. m_callback_machine.interrupted(*this);
  645. if (!m_callback_machine.should_process_last_pressed_key())
  646. return;
  647. m_previous_interrupt_was_handled_as_interrupt = true;
  648. fprintf(stderr, "^C");
  649. fflush(stderr);
  650. if (on_interrupt_handled)
  651. on_interrupt_handled();
  652. m_buffer.clear();
  653. m_chars_touched_in_the_middle = buffer().size();
  654. m_cursor = 0;
  655. finish();
  656. }
  657. void Editor::handle_read_event()
  658. {
  659. char keybuf[16];
  660. ssize_t nread = 0;
  661. if (!m_incomplete_data.size())
  662. nread = read(0, keybuf, sizeof(keybuf));
  663. if (nread < 0) {
  664. if (errno == EINTR) {
  665. if (!m_was_interrupted) {
  666. if (m_was_resized)
  667. return;
  668. finish();
  669. return;
  670. }
  671. handle_interrupt_event();
  672. return;
  673. }
  674. ScopedValueRollback errno_restorer(errno);
  675. perror("read failed");
  676. m_input_error = Error::ReadFailure;
  677. finish();
  678. return;
  679. }
  680. m_incomplete_data.append(keybuf, nread);
  681. nread = m_incomplete_data.size();
  682. if (nread == 0) {
  683. m_input_error = Error::Empty;
  684. finish();
  685. return;
  686. }
  687. auto reverse_tab = false;
  688. // Discard starting bytes until they make sense as utf-8.
  689. size_t valid_bytes = 0;
  690. while (nread) {
  691. Utf8View { StringView { m_incomplete_data.data(), (size_t)nread } }.validate(valid_bytes);
  692. if (valid_bytes)
  693. break;
  694. m_incomplete_data.take_first();
  695. --nread;
  696. }
  697. Utf8View input_view { StringView { m_incomplete_data.data(), valid_bytes } };
  698. size_t consumed_code_points = 0;
  699. static Vector<u8, 4> csi_parameter_bytes;
  700. static Vector<u8> csi_intermediate_bytes;
  701. Vector<unsigned, 4> csi_parameters;
  702. u8 csi_final;
  703. enum CSIMod {
  704. Shift = 1,
  705. Alt = 2,
  706. Ctrl = 4,
  707. };
  708. for (auto code_point : input_view) {
  709. if (m_finish)
  710. break;
  711. ++consumed_code_points;
  712. if (code_point == 0)
  713. continue;
  714. switch (m_state) {
  715. case InputState::GotEscape:
  716. switch (code_point) {
  717. case '[':
  718. m_state = InputState::CSIExpectParameter;
  719. continue;
  720. default: {
  721. m_callback_machine.key_pressed(*this, { code_point, Key::Alt });
  722. m_state = InputState::Free;
  723. cleanup_suggestions();
  724. continue;
  725. }
  726. }
  727. case InputState::CSIExpectParameter:
  728. if (code_point >= 0x30 && code_point <= 0x3f) { // '0123456789:;<=>?'
  729. csi_parameter_bytes.append(code_point);
  730. continue;
  731. }
  732. m_state = InputState::CSIExpectIntermediate;
  733. [[fallthrough]];
  734. case InputState::CSIExpectIntermediate:
  735. if (code_point >= 0x20 && code_point <= 0x2f) { // ' !"#$%&\'()*+,-./'
  736. csi_intermediate_bytes.append(code_point);
  737. continue;
  738. }
  739. m_state = InputState::CSIExpectFinal;
  740. [[fallthrough]];
  741. case InputState::CSIExpectFinal: {
  742. m_state = m_previous_free_state;
  743. auto is_in_paste = m_state == InputState::Paste;
  744. for (auto& parameter : String::copy(csi_parameter_bytes).split(';')) {
  745. if (auto value = parameter.to_uint(); value.has_value())
  746. csi_parameters.append(value.value());
  747. else
  748. csi_parameters.append(0);
  749. }
  750. unsigned param1 = 0, param2 = 0;
  751. if (csi_parameters.size() >= 1)
  752. param1 = csi_parameters[0];
  753. if (csi_parameters.size() >= 2)
  754. param2 = csi_parameters[1];
  755. unsigned modifiers = param2 ? param2 - 1 : 0;
  756. if (is_in_paste && code_point != '~' && param1 != 201) {
  757. // The only valid escape to process in paste mode is the stop-paste sequence.
  758. // so treat everything else as part of the pasted data.
  759. insert('\x1b');
  760. insert('[');
  761. insert(StringView { csi_parameter_bytes.data(), csi_parameter_bytes.size() });
  762. insert(StringView { csi_intermediate_bytes.data(), csi_intermediate_bytes.size() });
  763. insert(code_point);
  764. continue;
  765. }
  766. if (!(code_point >= 0x40 && code_point <= 0x7f)) {
  767. dbgln("LibLine: Invalid CSI: {:02x} ({:c})", code_point, code_point);
  768. continue;
  769. }
  770. csi_final = code_point;
  771. csi_parameters.clear();
  772. csi_parameter_bytes.clear();
  773. csi_intermediate_bytes.clear();
  774. if (csi_final == 'Z') {
  775. // 'reverse tab'
  776. reverse_tab = true;
  777. break;
  778. }
  779. cleanup_suggestions();
  780. switch (csi_final) {
  781. case 'A': // ^[[A: arrow up
  782. search_backwards();
  783. continue;
  784. case 'B': // ^[[B: arrow down
  785. search_forwards();
  786. continue;
  787. case 'D': // ^[[D: arrow left
  788. if (modifiers == CSIMod::Alt || modifiers == CSIMod::Ctrl)
  789. cursor_left_word();
  790. else
  791. cursor_left_character();
  792. continue;
  793. case 'C': // ^[[C: arrow right
  794. if (modifiers == CSIMod::Alt || modifiers == CSIMod::Ctrl)
  795. cursor_right_word();
  796. else
  797. cursor_right_character();
  798. continue;
  799. case 'H': // ^[[H: home
  800. go_home();
  801. continue;
  802. case 'F': // ^[[F: end
  803. go_end();
  804. continue;
  805. case '~':
  806. if (param1 == 3) { // ^[[3~: delete
  807. if (modifiers == CSIMod::Ctrl)
  808. erase_alnum_word_forwards();
  809. else
  810. erase_character_forwards();
  811. m_search_offset = 0;
  812. continue;
  813. }
  814. if (m_configuration.enable_bracketed_paste) {
  815. // ^[[200~: start bracketed paste
  816. // ^[[201~: end bracketed paste
  817. if (!is_in_paste && param1 == 200) {
  818. m_state = InputState::Paste;
  819. continue;
  820. }
  821. if (is_in_paste && param1 == 201) {
  822. m_state = InputState::Free;
  823. continue;
  824. }
  825. }
  826. // ^[[5~: page up
  827. // ^[[6~: page down
  828. dbgln("LibLine: Unhandled '~': {}", param1);
  829. continue;
  830. default:
  831. dbgln("LibLine: Unhandled final: {:02x} ({:c})", code_point, code_point);
  832. continue;
  833. }
  834. break;
  835. }
  836. case InputState::Verbatim:
  837. m_state = InputState::Free;
  838. // Verbatim mode will bypass all mechanisms and just insert the code point.
  839. insert(code_point);
  840. continue;
  841. case InputState::Paste:
  842. if (code_point == 27) {
  843. m_previous_free_state = InputState::Paste;
  844. m_state = InputState::GotEscape;
  845. continue;
  846. }
  847. insert(code_point);
  848. continue;
  849. case InputState::Free:
  850. m_previous_free_state = InputState::Free;
  851. if (code_point == 27) {
  852. m_callback_machine.key_pressed(*this, code_point);
  853. // Note that this should also deal with explicitly registered keys
  854. // that would otherwise be interpreted as escapes.
  855. if (m_callback_machine.should_process_last_pressed_key())
  856. m_state = InputState::GotEscape;
  857. continue;
  858. }
  859. if (code_point == 22) { // ^v
  860. m_callback_machine.key_pressed(*this, code_point);
  861. if (m_callback_machine.should_process_last_pressed_key())
  862. m_state = InputState::Verbatim;
  863. continue;
  864. }
  865. break;
  866. }
  867. // There are no sequences past this point, so short of 'tab', we will want to cleanup the suggestions.
  868. ArmedScopeGuard suggestion_cleanup { [this] { cleanup_suggestions(); } };
  869. // Normally ^D. `stty eof \^n` can change it to ^N (or something else), but Serenity doesn't have `stty` yet.
  870. // Process this here since the keybinds might override its behaviour.
  871. // This only applies when the buffer is empty. at any other time, the behaviour should be configurable.
  872. if (code_point == m_termios.c_cc[VEOF] && m_buffer.size() == 0) {
  873. finish_edit();
  874. continue;
  875. }
  876. m_callback_machine.key_pressed(*this, code_point);
  877. if (!m_callback_machine.should_process_last_pressed_key())
  878. continue;
  879. m_search_offset = 0; // reset search offset on any key
  880. if (code_point == '\t' || reverse_tab) {
  881. suggestion_cleanup.disarm();
  882. if (!on_tab_complete)
  883. continue;
  884. // Reverse tab can count as regular tab here.
  885. m_times_tab_pressed++;
  886. int token_start = m_cursor;
  887. // Ask for completions only on the first tab
  888. // and scan for the largest common prefix to display,
  889. // further tabs simply show the cached completions.
  890. if (m_times_tab_pressed == 1) {
  891. m_suggestion_manager.set_suggestions(on_tab_complete(*this));
  892. m_prompt_lines_at_suggestion_initiation = num_lines();
  893. if (m_suggestion_manager.count() == 0) {
  894. // There are no suggestions, beep.
  895. fputc('\a', stderr);
  896. fflush(stderr);
  897. }
  898. }
  899. // Adjust already incremented / decremented index when switching tab direction.
  900. if (reverse_tab && m_tab_direction != TabDirection::Backward) {
  901. m_suggestion_manager.previous();
  902. m_suggestion_manager.previous();
  903. m_tab_direction = TabDirection::Backward;
  904. }
  905. if (!reverse_tab && m_tab_direction != TabDirection::Forward) {
  906. m_suggestion_manager.next();
  907. m_suggestion_manager.next();
  908. m_tab_direction = TabDirection::Forward;
  909. }
  910. reverse_tab = false;
  911. SuggestionManager::CompletionMode completion_mode;
  912. switch (m_times_tab_pressed) {
  913. case 1:
  914. completion_mode = SuggestionManager::CompletePrefix;
  915. break;
  916. case 2:
  917. completion_mode = SuggestionManager::ShowSuggestions;
  918. break;
  919. default:
  920. completion_mode = SuggestionManager::CycleSuggestions;
  921. break;
  922. }
  923. auto completion_result = m_suggestion_manager.attempt_completion(completion_mode, token_start);
  924. auto new_cursor = m_cursor + completion_result.new_cursor_offset;
  925. for (size_t i = completion_result.offset_region_to_remove.start; i < completion_result.offset_region_to_remove.end; ++i)
  926. remove_at_index(new_cursor);
  927. m_cursor = new_cursor;
  928. m_inline_search_cursor = new_cursor;
  929. m_refresh_needed = true;
  930. m_chars_touched_in_the_middle++;
  931. for (auto& view : completion_result.insert)
  932. insert(view);
  933. reposition_cursor();
  934. if (completion_result.style_to_apply.has_value()) {
  935. // Apply the style of the last suggestion.
  936. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  937. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, completion_result.style_to_apply.value());
  938. }
  939. switch (completion_result.new_completion_mode) {
  940. case SuggestionManager::DontComplete:
  941. m_times_tab_pressed = 0;
  942. break;
  943. case SuggestionManager::CompletePrefix:
  944. break;
  945. default:
  946. ++m_times_tab_pressed;
  947. break;
  948. }
  949. if (m_times_tab_pressed > 1) {
  950. if (m_suggestion_manager.count() > 0) {
  951. if (m_suggestion_display->cleanup())
  952. reposition_cursor();
  953. m_suggestion_display->set_initial_prompt_lines(m_prompt_lines_at_suggestion_initiation);
  954. m_suggestion_display->display(m_suggestion_manager);
  955. m_origin_row = m_suggestion_display->origin_row();
  956. }
  957. }
  958. if (m_times_tab_pressed > 2) {
  959. if (m_tab_direction == TabDirection::Forward)
  960. m_suggestion_manager.next();
  961. else
  962. m_suggestion_manager.previous();
  963. }
  964. if (m_suggestion_manager.count() < 2) {
  965. // We have none, or just one suggestion,
  966. // we should just commit that and continue
  967. // after it, as if it were auto-completed.
  968. suggest(0, 0, Span::CodepointOriented);
  969. m_times_tab_pressed = 0;
  970. m_suggestion_manager.reset();
  971. m_suggestion_display->finish();
  972. }
  973. continue;
  974. }
  975. // If we got here, manually cleanup the suggestions and then insert the new code point.
  976. suggestion_cleanup.disarm();
  977. cleanup_suggestions();
  978. insert(code_point);
  979. }
  980. if (consumed_code_points == m_incomplete_data.size()) {
  981. m_incomplete_data.clear();
  982. } else {
  983. for (size_t i = 0; i < consumed_code_points; ++i)
  984. m_incomplete_data.take_first();
  985. }
  986. if (!m_incomplete_data.is_empty() && !m_finish)
  987. deferred_invoke([&](auto&) { try_update_once(); });
  988. }
  989. void Editor::cleanup_suggestions()
  990. {
  991. if (m_times_tab_pressed) {
  992. // Apply the style of the last suggestion.
  993. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  994. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, m_suggestion_manager.current_suggestion().style);
  995. // We probably have some suggestions drawn,
  996. // let's clean them up.
  997. if (m_suggestion_display->cleanup()) {
  998. reposition_cursor();
  999. m_refresh_needed = true;
  1000. }
  1001. m_suggestion_manager.reset();
  1002. suggest(0, 0, Span::CodepointOriented);
  1003. m_suggestion_display->finish();
  1004. }
  1005. m_times_tab_pressed = 0; // Safe to say if we get here, the user didn't press TAB
  1006. }
  1007. bool Editor::search(const StringView& phrase, bool allow_empty, bool from_beginning)
  1008. {
  1009. int last_matching_offset = -1;
  1010. bool found = false;
  1011. // Do not search for empty strings.
  1012. if (allow_empty || phrase.length() > 0) {
  1013. size_t search_offset = m_search_offset;
  1014. for (size_t i = m_history_cursor; i > 0; --i) {
  1015. auto& entry = m_history[i - 1];
  1016. auto contains = from_beginning ? entry.entry.starts_with(phrase) : entry.entry.contains(phrase);
  1017. if (contains) {
  1018. last_matching_offset = i - 1;
  1019. if (search_offset == 0) {
  1020. found = true;
  1021. break;
  1022. }
  1023. --search_offset;
  1024. }
  1025. }
  1026. if (!found) {
  1027. fputc('\a', stderr);
  1028. fflush(stderr);
  1029. }
  1030. }
  1031. if (found) {
  1032. // We plan to clear the buffer, so mark the entire thing touched.
  1033. m_chars_touched_in_the_middle = m_buffer.size();
  1034. m_buffer.clear();
  1035. m_cursor = 0;
  1036. insert(m_history[last_matching_offset].entry);
  1037. // Always needed, as we have cleared the buffer above.
  1038. m_refresh_needed = true;
  1039. }
  1040. return found;
  1041. }
  1042. void Editor::recalculate_origin()
  1043. {
  1044. // Changing the columns can affect our origin if
  1045. // the new size is smaller than our prompt, which would
  1046. // cause said prompt to take up more space, so we should
  1047. // compensate for that.
  1048. if (m_cached_prompt_metrics.max_line_length >= m_num_columns) {
  1049. auto added_lines = (m_cached_prompt_metrics.max_line_length + 1) / m_num_columns - 1;
  1050. m_origin_row += added_lines;
  1051. }
  1052. // We also need to recalculate our cursor position,
  1053. // but that will be calculated and applied at the next
  1054. // refresh cycle.
  1055. }
  1056. void Editor::cleanup()
  1057. {
  1058. auto current_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1059. auto new_lines = current_prompt_metrics().lines_with_addition(current_buffer_metrics, m_num_columns);
  1060. auto shown_lines = num_lines();
  1061. if (new_lines < shown_lines)
  1062. m_extra_forward_lines = max(shown_lines - new_lines, m_extra_forward_lines);
  1063. reposition_cursor(true);
  1064. auto current_line = num_lines() - 1;
  1065. VT::clear_lines(current_line, m_extra_forward_lines);
  1066. m_extra_forward_lines = 0;
  1067. reposition_cursor();
  1068. };
  1069. void Editor::refresh_display()
  1070. {
  1071. auto has_cleaned_up = false;
  1072. // Someone changed the window size, figure it out
  1073. // and react to it, we might need to redraw.
  1074. if (m_was_resized) {
  1075. if (m_previous_num_columns != m_num_columns) {
  1076. // We need to cleanup and redo everything.
  1077. m_cached_prompt_valid = false;
  1078. m_refresh_needed = true;
  1079. swap(m_previous_num_columns, m_num_columns);
  1080. recalculate_origin();
  1081. cleanup();
  1082. swap(m_previous_num_columns, m_num_columns);
  1083. has_cleaned_up = true;
  1084. }
  1085. m_was_resized = false;
  1086. }
  1087. // We might be at the last line, and have more than one line;
  1088. // Refreshing the display will cause the terminal to scroll,
  1089. // so note that fact and bring origin up, making sure to
  1090. // reserve the space for however many lines we move it up.
  1091. auto current_num_lines = num_lines();
  1092. if (m_origin_row + current_num_lines > m_num_lines) {
  1093. if (current_num_lines > m_num_lines) {
  1094. for (size_t i = 0; i < m_num_lines; ++i)
  1095. putc('\n', stderr);
  1096. m_origin_row = 0;
  1097. } else {
  1098. auto old_origin_row = m_origin_row;
  1099. m_origin_row = m_num_lines - current_num_lines + 1;
  1100. for (size_t i = 0; i < old_origin_row - m_origin_row; ++i)
  1101. putc('\n', stderr);
  1102. }
  1103. fflush(stderr);
  1104. }
  1105. // Do not call hook on pure cursor movement.
  1106. if (m_cached_prompt_valid && !m_refresh_needed && m_pending_chars.size() == 0) {
  1107. // Probably just moving around.
  1108. reposition_cursor();
  1109. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1110. m_drawn_end_of_line_offset = m_buffer.size();
  1111. return;
  1112. }
  1113. if (on_display_refresh)
  1114. on_display_refresh(*this);
  1115. if (m_cached_prompt_valid) {
  1116. if (!m_refresh_needed && m_cursor == m_buffer.size()) {
  1117. // Just write the characters out and continue,
  1118. // no need to refresh the entire line.
  1119. char null = 0;
  1120. m_pending_chars.append(&null, 1);
  1121. fputs((char*)m_pending_chars.data(), stderr);
  1122. m_pending_chars.clear();
  1123. m_drawn_cursor = m_cursor;
  1124. m_drawn_end_of_line_offset = m_buffer.size();
  1125. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1126. m_drawn_spans = m_current_spans;
  1127. fflush(stderr);
  1128. return;
  1129. }
  1130. }
  1131. auto apply_styles = [&, empty_styles = HashMap<u32, Style> {}](size_t i) {
  1132. auto ends = m_current_spans.m_spans_ending.get(i).value_or(empty_styles);
  1133. auto starts = m_current_spans.m_spans_starting.get(i).value_or(empty_styles);
  1134. auto anchored_ends = m_current_spans.m_anchored_spans_ending.get(i).value_or(empty_styles);
  1135. auto anchored_starts = m_current_spans.m_anchored_spans_starting.get(i).value_or(empty_styles);
  1136. if (ends.size() || anchored_ends.size()) {
  1137. Style style;
  1138. for (auto& applicable_style : ends)
  1139. style.unify_with(applicable_style.value);
  1140. for (auto& applicable_style : anchored_ends)
  1141. style.unify_with(applicable_style.value);
  1142. // Disable any style that should be turned off.
  1143. VT::apply_style(style, false);
  1144. // Reapply styles for overlapping spans that include this one.
  1145. style = find_applicable_style(i);
  1146. VT::apply_style(style, true);
  1147. }
  1148. if (starts.size() || anchored_starts.size()) {
  1149. Style style;
  1150. for (auto& applicable_style : starts)
  1151. style.unify_with(applicable_style.value);
  1152. for (auto& applicable_style : anchored_starts)
  1153. style.unify_with(applicable_style.value);
  1154. // Set new styles.
  1155. VT::apply_style(style, true);
  1156. }
  1157. };
  1158. auto print_character_at = [this](size_t i) {
  1159. StringBuilder builder;
  1160. auto c = m_buffer[i];
  1161. bool should_print_masked = is_ascii_control(c) && c != '\n';
  1162. bool should_print_caret = c < 64 && should_print_masked;
  1163. if (should_print_caret)
  1164. builder.appendff("^{:c}", c + 64);
  1165. else if (should_print_masked)
  1166. builder.appendff("\\x{:0>2x}", c);
  1167. else
  1168. builder.append(Utf32View { &c, 1 });
  1169. if (should_print_masked)
  1170. fputs("\033[7m", stderr);
  1171. fputs(builder.to_string().characters(), stderr);
  1172. if (should_print_masked)
  1173. fputs("\033[27m", stderr);
  1174. };
  1175. // If there have been no changes to previous sections of the line (style or text)
  1176. // just append the new text with the appropriate styles.
  1177. 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)) {
  1178. auto initial_style = find_applicable_style(m_drawn_end_of_line_offset);
  1179. VT::apply_style(initial_style);
  1180. for (size_t i = m_drawn_end_of_line_offset; i < m_buffer.size(); ++i) {
  1181. apply_styles(i);
  1182. print_character_at(i);
  1183. }
  1184. VT::apply_style(Style::reset_style());
  1185. m_pending_chars.clear();
  1186. m_refresh_needed = false;
  1187. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1188. m_chars_touched_in_the_middle = 0;
  1189. m_drawn_cursor = m_cursor;
  1190. m_drawn_end_of_line_offset = m_buffer.size();
  1191. // No need to reposition the cursor, the cursor is already where it needs to be.
  1192. return;
  1193. }
  1194. if constexpr (LINE_EDITOR_DEBUG) {
  1195. if (m_cached_prompt_valid && m_chars_touched_in_the_middle == 0) {
  1196. auto x = m_drawn_spans.contains_up_to_offset(m_current_spans, m_drawn_cursor);
  1197. dbgln("Contains: {} At offset: {}", x, m_drawn_cursor);
  1198. dbgln("Drawn Spans:");
  1199. for (auto& sentry : m_drawn_spans.m_spans_starting) {
  1200. for (auto& entry : sentry.value) {
  1201. dbgln("{}-{}: {}", sentry.key, entry.key, entry.value.to_string());
  1202. }
  1203. }
  1204. dbgln("==========================================================================");
  1205. dbgln("Current Spans:");
  1206. for (auto& sentry : m_current_spans.m_spans_starting) {
  1207. for (auto& entry : sentry.value) {
  1208. dbgln("{}-{}: {}", sentry.key, entry.key, entry.value.to_string());
  1209. }
  1210. }
  1211. }
  1212. }
  1213. // Ouch, reflow entire line.
  1214. if (!has_cleaned_up) {
  1215. cleanup();
  1216. }
  1217. VT::move_absolute(m_origin_row, m_origin_column);
  1218. fputs(m_new_prompt.characters(), stderr);
  1219. VT::clear_to_end_of_line();
  1220. StringBuilder builder;
  1221. for (size_t i = 0; i < m_buffer.size(); ++i) {
  1222. apply_styles(i);
  1223. print_character_at(i);
  1224. }
  1225. VT::apply_style(Style::reset_style()); // don't bleed to EOL
  1226. m_pending_chars.clear();
  1227. m_refresh_needed = false;
  1228. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1229. m_chars_touched_in_the_middle = 0;
  1230. m_drawn_spans = m_current_spans;
  1231. m_drawn_end_of_line_offset = m_buffer.size();
  1232. m_cached_prompt_valid = true;
  1233. reposition_cursor();
  1234. fflush(stderr);
  1235. }
  1236. void Editor::strip_styles(bool strip_anchored)
  1237. {
  1238. m_current_spans.m_spans_starting.clear();
  1239. m_current_spans.m_spans_ending.clear();
  1240. if (strip_anchored) {
  1241. m_current_spans.m_anchored_spans_starting.clear();
  1242. m_current_spans.m_anchored_spans_ending.clear();
  1243. }
  1244. m_refresh_needed = true;
  1245. }
  1246. void Editor::reposition_cursor(bool to_end)
  1247. {
  1248. auto cursor = m_cursor;
  1249. auto saved_cursor = m_cursor;
  1250. if (to_end)
  1251. cursor = m_buffer.size();
  1252. m_cursor = cursor;
  1253. m_drawn_cursor = cursor;
  1254. auto line = cursor_line() - 1;
  1255. auto column = offset_in_line();
  1256. ensure_free_lines_from_origin(line);
  1257. VERIFY(column + m_origin_column <= m_num_columns);
  1258. VT::move_absolute(line + m_origin_row, column + m_origin_column);
  1259. m_cursor = saved_cursor;
  1260. }
  1261. void VT::move_absolute(u32 row, u32 col)
  1262. {
  1263. fprintf(stderr, "\033[%d;%dH", row, col);
  1264. fflush(stderr);
  1265. }
  1266. void VT::move_relative(int row, int col)
  1267. {
  1268. char x_op = 'A', y_op = 'D';
  1269. if (row > 0)
  1270. x_op = 'B';
  1271. else
  1272. row = -row;
  1273. if (col > 0)
  1274. y_op = 'C';
  1275. else
  1276. col = -col;
  1277. if (row > 0)
  1278. fprintf(stderr, "\033[%d%c", row, x_op);
  1279. if (col > 0)
  1280. fprintf(stderr, "\033[%d%c", col, y_op);
  1281. }
  1282. Style Editor::find_applicable_style(size_t offset) const
  1283. {
  1284. // Walk through our styles and merge all that fit in the offset.
  1285. auto style = Style::reset_style();
  1286. auto unify = [&](auto& entry) {
  1287. if (entry.key >= offset)
  1288. return;
  1289. for (auto& style_value : entry.value) {
  1290. if (style_value.key <= offset)
  1291. return;
  1292. style.unify_with(style_value.value, true);
  1293. }
  1294. };
  1295. for (auto& entry : m_current_spans.m_spans_starting) {
  1296. unify(entry);
  1297. }
  1298. for (auto& entry : m_current_spans.m_anchored_spans_starting) {
  1299. unify(entry);
  1300. }
  1301. return style;
  1302. }
  1303. String Style::Background::to_vt_escape() const
  1304. {
  1305. if (is_default())
  1306. return "";
  1307. if (m_is_rgb) {
  1308. return String::formatted("\e[48;2;{};{};{}m", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1309. } else {
  1310. return String::formatted("\e[{}m", (u8)m_xterm_color + 40);
  1311. }
  1312. }
  1313. String Style::Foreground::to_vt_escape() const
  1314. {
  1315. if (is_default())
  1316. return "";
  1317. if (m_is_rgb) {
  1318. return String::formatted("\e[38;2;{};{};{}m", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1319. } else {
  1320. return String::formatted("\e[{}m", (u8)m_xterm_color + 30);
  1321. }
  1322. }
  1323. String Style::Hyperlink::to_vt_escape(bool starting) const
  1324. {
  1325. if (is_empty())
  1326. return "";
  1327. return String::formatted("\e]8;;{}\e\\", starting ? m_link : String::empty());
  1328. }
  1329. void Style::unify_with(const Style& other, bool prefer_other)
  1330. {
  1331. // Unify colors.
  1332. if (prefer_other || m_background.is_default())
  1333. m_background = other.background();
  1334. if (prefer_other || m_foreground.is_default())
  1335. m_foreground = other.foreground();
  1336. // Unify graphic renditions.
  1337. if (other.bold())
  1338. set(Bold);
  1339. if (other.italic())
  1340. set(Italic);
  1341. if (other.underline())
  1342. set(Underline);
  1343. // Unify links.
  1344. if (prefer_other || m_hyperlink.is_empty())
  1345. m_hyperlink = other.hyperlink();
  1346. }
  1347. String Style::to_string() const
  1348. {
  1349. StringBuilder builder;
  1350. builder.append("Style { ");
  1351. if (!m_foreground.is_default()) {
  1352. builder.append("Foreground(");
  1353. if (m_foreground.m_is_rgb) {
  1354. builder.join(", ", m_foreground.m_rgb_color);
  1355. } else {
  1356. builder.appendff("(XtermColor) {}", (int)m_foreground.m_xterm_color);
  1357. }
  1358. builder.append("), ");
  1359. }
  1360. if (!m_background.is_default()) {
  1361. builder.append("Background(");
  1362. if (m_background.m_is_rgb) {
  1363. builder.join(' ', m_background.m_rgb_color);
  1364. } else {
  1365. builder.appendff("(XtermColor) {}", (int)m_background.m_xterm_color);
  1366. }
  1367. builder.append("), ");
  1368. }
  1369. if (bold())
  1370. builder.append("Bold, ");
  1371. if (underline())
  1372. builder.append("Underline, ");
  1373. if (italic())
  1374. builder.append("Italic, ");
  1375. if (!m_hyperlink.is_empty())
  1376. builder.appendff("Hyperlink(\"{}\"), ", m_hyperlink.m_link);
  1377. builder.append("}");
  1378. return builder.build();
  1379. }
  1380. void VT::apply_style(const Style& style, bool is_starting)
  1381. {
  1382. if (is_starting) {
  1383. fprintf(stderr,
  1384. "\033[%d;%d;%dm%s%s%s",
  1385. style.bold() ? 1 : 22,
  1386. style.underline() ? 4 : 24,
  1387. style.italic() ? 3 : 23,
  1388. style.background().to_vt_escape().characters(),
  1389. style.foreground().to_vt_escape().characters(),
  1390. style.hyperlink().to_vt_escape(true).characters());
  1391. } else {
  1392. fprintf(stderr, "%s", style.hyperlink().to_vt_escape(false).characters());
  1393. }
  1394. }
  1395. void VT::clear_lines(size_t count_above, size_t count_below)
  1396. {
  1397. if (count_below + count_above == 0) {
  1398. fputs("\033[2K", stderr);
  1399. } else {
  1400. // Go down count_below lines.
  1401. if (count_below > 0)
  1402. fprintf(stderr, "\033[%dB", (int)count_below);
  1403. // Then clear lines going upwards.
  1404. for (size_t i = count_below + count_above; i > 0; --i)
  1405. fputs(i == 1 ? "\033[2K" : "\033[2K\033[A", stderr);
  1406. }
  1407. }
  1408. void VT::save_cursor()
  1409. {
  1410. fputs("\033[s", stderr);
  1411. fflush(stderr);
  1412. }
  1413. void VT::restore_cursor()
  1414. {
  1415. fputs("\033[u", stderr);
  1416. fflush(stderr);
  1417. }
  1418. void VT::clear_to_end_of_line()
  1419. {
  1420. fputs("\033[K", stderr);
  1421. fflush(stderr);
  1422. }
  1423. StringMetrics Editor::actual_rendered_string_metrics(const StringView& string)
  1424. {
  1425. StringMetrics metrics;
  1426. StringMetrics::LineMetrics current_line;
  1427. VTState state { Free };
  1428. Utf8View view { string };
  1429. auto it = view.begin();
  1430. for (; it != view.end(); ++it) {
  1431. auto c = *it;
  1432. auto it_copy = it;
  1433. ++it_copy;
  1434. auto next_c = it_copy == view.end() ? 0 : *it_copy;
  1435. state = actual_rendered_string_length_step(metrics, view.iterator_offset(it), current_line, c, next_c, state);
  1436. }
  1437. metrics.line_metrics.append(current_line);
  1438. for (auto& line : metrics.line_metrics)
  1439. metrics.max_line_length = max(line.total_length(), metrics.max_line_length);
  1440. return metrics;
  1441. }
  1442. StringMetrics Editor::actual_rendered_string_metrics(const Utf32View& view)
  1443. {
  1444. StringMetrics metrics;
  1445. StringMetrics::LineMetrics current_line;
  1446. VTState state { Free };
  1447. for (size_t i = 0; i < view.length(); ++i) {
  1448. auto c = view.code_points()[i];
  1449. auto next_c = i + 1 < view.length() ? view.code_points()[i + 1] : 0;
  1450. state = actual_rendered_string_length_step(metrics, i, current_line, c, next_c, state);
  1451. }
  1452. metrics.line_metrics.append(current_line);
  1453. for (auto& line : metrics.line_metrics)
  1454. metrics.max_line_length = max(line.total_length(), metrics.max_line_length);
  1455. return metrics;
  1456. }
  1457. Editor::VTState Editor::actual_rendered_string_length_step(StringMetrics& metrics, size_t index, StringMetrics::LineMetrics& current_line, u32 c, u32 next_c, VTState state)
  1458. {
  1459. switch (state) {
  1460. case Free:
  1461. if (c == '\x1b') { // escape
  1462. return Escape;
  1463. }
  1464. if (c == '\r') { // carriage return
  1465. current_line.masked_chars = {};
  1466. current_line.length = 0;
  1467. if (!metrics.line_metrics.is_empty())
  1468. metrics.line_metrics.last() = { {}, 0 };
  1469. return state;
  1470. }
  1471. if (c == '\n') { // return
  1472. metrics.line_metrics.append(current_line);
  1473. current_line.masked_chars = {};
  1474. current_line.length = 0;
  1475. return state;
  1476. }
  1477. if (is_ascii_control(c) && c != '\n')
  1478. current_line.masked_chars.append({ index, 1, c < 64 ? 2u : 4u }); // if the character cannot be represented as ^c, represent it as \xbb.
  1479. // FIXME: This will not support anything sophisticated
  1480. ++current_line.length;
  1481. ++metrics.total_length;
  1482. return state;
  1483. case Escape:
  1484. if (c == ']') {
  1485. if (next_c == '0')
  1486. state = Title;
  1487. return state;
  1488. }
  1489. if (c == '[') {
  1490. return Bracket;
  1491. }
  1492. // FIXME: This does not support non-VT (aside from set-title) escapes
  1493. return state;
  1494. case Bracket:
  1495. if (is_ascii_digit(c)) {
  1496. return BracketArgsSemi;
  1497. }
  1498. return state;
  1499. case BracketArgsSemi:
  1500. if (c == ';') {
  1501. return Bracket;
  1502. }
  1503. if (!is_ascii_digit(c))
  1504. state = Free;
  1505. return state;
  1506. case Title:
  1507. if (c == 7)
  1508. state = Free;
  1509. return state;
  1510. }
  1511. return state;
  1512. }
  1513. Result<Vector<size_t, 2>, Editor::Error> Editor::vt_dsr()
  1514. {
  1515. char buf[16];
  1516. // Read whatever junk there is before talking to the terminal
  1517. // and insert them later when we're reading user input.
  1518. bool more_junk_to_read { false };
  1519. timeval timeout { 0, 0 };
  1520. fd_set readfds;
  1521. FD_ZERO(&readfds);
  1522. FD_SET(0, &readfds);
  1523. do {
  1524. more_junk_to_read = false;
  1525. [[maybe_unused]] auto rc = select(1, &readfds, nullptr, nullptr, &timeout);
  1526. if (FD_ISSET(0, &readfds)) {
  1527. auto nread = read(0, buf, 16);
  1528. if (nread < 0) {
  1529. m_input_error = Error::ReadFailure;
  1530. finish();
  1531. break;
  1532. }
  1533. if (nread == 0)
  1534. break;
  1535. m_incomplete_data.append(buf, nread);
  1536. more_junk_to_read = true;
  1537. }
  1538. } while (more_junk_to_read);
  1539. if (m_input_error.has_value())
  1540. return m_input_error.value();
  1541. fputs("\033[6n", stderr);
  1542. fflush(stderr);
  1543. // Parse the DSR response
  1544. // it should be of the form .*\e[\d+;\d+R.*
  1545. // Anything not part of the response is just added to the incomplete data.
  1546. enum {
  1547. Free,
  1548. SawEsc,
  1549. SawBracket,
  1550. InFirstCoordinate,
  1551. SawSemicolon,
  1552. InSecondCoordinate,
  1553. SawR,
  1554. } state { Free };
  1555. auto has_error = false;
  1556. Vector<char, 4> coordinate_buffer;
  1557. size_t row { 1 }, col { 1 };
  1558. do {
  1559. char c;
  1560. auto nread = read(0, &c, 1);
  1561. if (nread < 0) {
  1562. if (errno == 0 || errno == EINTR) {
  1563. // ????
  1564. continue;
  1565. }
  1566. dbgln("Error while reading DSR: {}", strerror(errno));
  1567. return Error::ReadFailure;
  1568. }
  1569. if (nread == 0) {
  1570. dbgln("Terminal DSR issue; received no response");
  1571. return Error::Empty;
  1572. }
  1573. switch (state) {
  1574. case Free:
  1575. if (c == '\x1b') {
  1576. state = SawEsc;
  1577. continue;
  1578. }
  1579. m_incomplete_data.append(c);
  1580. continue;
  1581. case SawEsc:
  1582. if (c == '[') {
  1583. state = SawBracket;
  1584. continue;
  1585. }
  1586. m_incomplete_data.append(c);
  1587. continue;
  1588. case SawBracket:
  1589. if (is_ascii_digit(c)) {
  1590. state = InFirstCoordinate;
  1591. coordinate_buffer.append(c);
  1592. continue;
  1593. }
  1594. m_incomplete_data.append(c);
  1595. continue;
  1596. case InFirstCoordinate:
  1597. if (is_ascii_digit(c)) {
  1598. coordinate_buffer.append(c);
  1599. continue;
  1600. }
  1601. if (c == ';') {
  1602. auto maybe_row = StringView { coordinate_buffer.data(), coordinate_buffer.size() }.to_uint();
  1603. if (!maybe_row.has_value())
  1604. has_error = true;
  1605. row = maybe_row.value_or(1u);
  1606. coordinate_buffer.clear_with_capacity();
  1607. state = SawSemicolon;
  1608. continue;
  1609. }
  1610. m_incomplete_data.append(c);
  1611. continue;
  1612. case SawSemicolon:
  1613. if (is_ascii_digit(c)) {
  1614. state = InSecondCoordinate;
  1615. coordinate_buffer.append(c);
  1616. continue;
  1617. }
  1618. m_incomplete_data.append(c);
  1619. continue;
  1620. case InSecondCoordinate:
  1621. if (is_ascii_digit(c)) {
  1622. coordinate_buffer.append(c);
  1623. continue;
  1624. }
  1625. if (c == 'R') {
  1626. auto maybe_column = StringView { coordinate_buffer.data(), coordinate_buffer.size() }.to_uint();
  1627. if (!maybe_column.has_value())
  1628. has_error = true;
  1629. col = maybe_column.value_or(1u);
  1630. coordinate_buffer.clear_with_capacity();
  1631. state = SawR;
  1632. continue;
  1633. }
  1634. m_incomplete_data.append(c);
  1635. continue;
  1636. case SawR:
  1637. m_incomplete_data.append(c);
  1638. continue;
  1639. default:
  1640. VERIFY_NOT_REACHED();
  1641. }
  1642. } while (state != SawR);
  1643. if (has_error)
  1644. dbgln("Terminal DSR issue, couldn't parse DSR response");
  1645. return Vector<size_t, 2> { row, col };
  1646. }
  1647. String Editor::line(size_t up_to_index) const
  1648. {
  1649. StringBuilder builder;
  1650. builder.append(Utf32View { m_buffer.data(), min(m_buffer.size(), up_to_index) });
  1651. return builder.build();
  1652. }
  1653. void Editor::remove_at_index(size_t index)
  1654. {
  1655. // See if we have any anchored styles, and reposition them if needed.
  1656. readjust_anchored_styles(index, ModificationKind::Removal);
  1657. auto cp = m_buffer[index];
  1658. m_buffer.remove(index);
  1659. if (cp == '\n')
  1660. ++m_extra_forward_lines;
  1661. ++m_chars_touched_in_the_middle;
  1662. }
  1663. void Editor::readjust_anchored_styles(size_t hint_index, ModificationKind modification)
  1664. {
  1665. struct Anchor {
  1666. Span old_span;
  1667. Span new_span;
  1668. Style style;
  1669. };
  1670. Vector<Anchor> anchors_to_relocate;
  1671. auto index_shift = modification == ModificationKind::Insertion ? 1 : -1;
  1672. auto forced_removal = modification == ModificationKind::ForcedOverlapRemoval;
  1673. for (auto& start_entry : m_current_spans.m_anchored_spans_starting) {
  1674. for (auto& end_entry : start_entry.value) {
  1675. if (forced_removal) {
  1676. if (start_entry.key <= hint_index && end_entry.key > hint_index) {
  1677. // Remove any overlapping regions.
  1678. continue;
  1679. }
  1680. }
  1681. if (start_entry.key >= hint_index) {
  1682. if (start_entry.key == hint_index && end_entry.key == hint_index + 1 && modification == ModificationKind::Removal) {
  1683. // Remove the anchor, as all its text was wiped.
  1684. continue;
  1685. }
  1686. // Shift everything.
  1687. 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 });
  1688. continue;
  1689. }
  1690. if (end_entry.key > hint_index) {
  1691. // Shift just the end.
  1692. 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 });
  1693. continue;
  1694. }
  1695. 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 });
  1696. }
  1697. }
  1698. m_current_spans.m_anchored_spans_ending.clear();
  1699. m_current_spans.m_anchored_spans_starting.clear();
  1700. // Pass over the relocations and update the stale entries.
  1701. for (auto& relocation : anchors_to_relocate) {
  1702. stylize(relocation.new_span, relocation.style);
  1703. }
  1704. }
  1705. size_t StringMetrics::lines_with_addition(const StringMetrics& offset, size_t column_width) const
  1706. {
  1707. size_t lines = 0;
  1708. for (size_t i = 0; i < line_metrics.size() - 1; ++i)
  1709. lines += (line_metrics[i].total_length() + column_width) / column_width;
  1710. auto last = line_metrics.last().total_length();
  1711. last += offset.line_metrics.first().total_length();
  1712. lines += (last + column_width) / column_width;
  1713. for (size_t i = 1; i < offset.line_metrics.size(); ++i)
  1714. lines += (offset.line_metrics[i].total_length() + column_width) / column_width;
  1715. return lines;
  1716. }
  1717. size_t StringMetrics::offset_with_addition(const StringMetrics& offset, size_t column_width) const
  1718. {
  1719. if (offset.line_metrics.size() > 1)
  1720. return offset.line_metrics.last().total_length() % column_width;
  1721. auto last = line_metrics.last().total_length();
  1722. last += offset.line_metrics.first().total_length();
  1723. return last % column_width;
  1724. }
  1725. bool Editor::Spans::contains_up_to_offset(const Spans& other, size_t offset) const
  1726. {
  1727. auto compare = [&]<typename K, typename V>(const HashMap<K, HashMap<K, V>>& left, const HashMap<K, HashMap<K, V>>& right) -> bool {
  1728. for (auto& entry : right) {
  1729. if (entry.key > offset + 1)
  1730. continue;
  1731. auto left_map = left.get(entry.key);
  1732. if (!left_map.has_value())
  1733. return false;
  1734. for (auto& left_entry : left_map.value()) {
  1735. if (auto value = entry.value.get(left_entry.key); !value.has_value()) {
  1736. // Might have the same thing with a longer span
  1737. bool found = false;
  1738. for (auto& possibly_longer_span_entry : entry.value) {
  1739. if (possibly_longer_span_entry.key > left_entry.key && possibly_longer_span_entry.key > offset && left_entry.value == possibly_longer_span_entry.value) {
  1740. found = true;
  1741. break;
  1742. }
  1743. }
  1744. if (found)
  1745. continue;
  1746. if constexpr (LINE_EDITOR_DEBUG) {
  1747. dbgln("Compare for {}-{} failed, no entry", entry.key, left_entry.key);
  1748. for (auto& x : entry.value)
  1749. dbgln("Have: {}-{} = {}", entry.key, x.key, x.value.to_string());
  1750. }
  1751. return false;
  1752. } else if (value.value() != left_entry.value) {
  1753. dbgln_if(LINE_EDITOR_DEBUG, "Compare for {}-{} failed, different values: {} != {}", entry.key, left_entry.key, value.value().to_string(), left_entry.value.to_string());
  1754. return false;
  1755. }
  1756. }
  1757. }
  1758. return true;
  1759. };
  1760. return compare(m_spans_starting, other.m_spans_starting)
  1761. && compare(m_anchored_spans_starting, other.m_anchored_spans_starting);
  1762. }
  1763. }