Editor.cpp 68 KB

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