Editor.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  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(const StringView& libname)
  36. {
  37. Configuration configuration;
  38. auto config_file = Core::ConfigFile::open_for_lib(libname);
  39. // Read behaviour options.
  40. auto refresh = config_file->read_entry("behaviour", "refresh", "lazy");
  41. auto operation = config_file->read_entry("behaviour", "operation_mode");
  42. auto bracketed_paste = config_file->read_bool_entry("behaviour", "bracketed_paste", true);
  43. auto default_text_editor = config_file->read_entry("behaviour", "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_behaviour == Configuration::RefreshBehaviour::Eager;
  167. m_pending_chars = ByteBuffer::create_uninitialized(0);
  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(const String& 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(const String& 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, const It0& end0, It1&& begin1, const It1& 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(const String& 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. [](const HistoryEntry& left, const HistoryEntry& 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 (const auto& 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(const Utf32View& string)
  313. {
  314. for (size_t i = 0; i < string.length(); ++i)
  315. insert(string.code_points()[i]);
  316. }
  317. void Editor::insert(const String& string)
  318. {
  319. for (auto ch : Utf8View { string })
  320. insert(ch);
  321. }
  322. void Editor::insert(const 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. m_pending_chars.append(str.characters(), str.length());
  333. readjust_anchored_styles(m_cursor, ModificationKind::Insertion);
  334. if (m_cursor == m_buffer.size()) {
  335. m_buffer.append(cp);
  336. m_cursor = m_buffer.size();
  337. m_inline_search_cursor = m_cursor;
  338. return;
  339. }
  340. m_buffer.insert(m_cursor, cp);
  341. ++m_chars_touched_in_the_middle;
  342. ++m_cursor;
  343. m_inline_search_cursor = m_cursor;
  344. }
  345. void Editor::register_key_input_callback(const KeyBinding& binding)
  346. {
  347. if (binding.kind == KeyBinding::Kind::InternalFunction) {
  348. auto internal_function = find_internal_function(binding.binding);
  349. if (!internal_function) {
  350. dbgln("LibLine: Unknown internal function '{}'", binding.binding);
  351. return;
  352. }
  353. return register_key_input_callback(binding.keys, move(internal_function));
  354. }
  355. return register_key_input_callback(binding.keys, [binding = String(binding.binding)](auto& editor) {
  356. editor.insert(binding);
  357. return false;
  358. });
  359. }
  360. static size_t code_point_length_in_utf8(u32 code_point)
  361. {
  362. if (code_point <= 0x7f)
  363. return 1;
  364. if (code_point <= 0x07ff)
  365. return 2;
  366. if (code_point <= 0xffff)
  367. return 3;
  368. if (code_point <= 0x10ffff)
  369. return 4;
  370. return 3;
  371. }
  372. // buffer [ 0 1 2 3 . . . A . . . B . . . M . . . N ]
  373. // ^ ^ ^ ^
  374. // | | | +- end of buffer
  375. // | | +- scan offset = M
  376. // | +- range end = M - B
  377. // +- range start = M - A
  378. // 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.
  379. // If `reverse' is true, A and B are before M, if not, A and B are after M.
  380. 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
  381. {
  382. size_t byte_offset = 0;
  383. size_t code_point_offset = scan_code_point_offset + (reverse ? 1 : 0);
  384. CodepointRange range;
  385. for (;;) {
  386. if (!reverse) {
  387. if (code_point_offset >= m_buffer.size())
  388. break;
  389. } else {
  390. if (code_point_offset == 0)
  391. break;
  392. }
  393. if (byte_offset > end_byte_offset)
  394. break;
  395. if (byte_offset < start_byte_offset)
  396. ++range.start;
  397. if (byte_offset < end_byte_offset)
  398. ++range.end;
  399. byte_offset += code_point_length_in_utf8(m_buffer[reverse ? --code_point_offset : code_point_offset++]);
  400. }
  401. return range;
  402. }
  403. void Editor::stylize(const Span& span, const Style& style)
  404. {
  405. if (style.is_empty())
  406. return;
  407. auto start = span.beginning();
  408. auto end = span.end();
  409. if (span.mode() == Span::ByteOriented) {
  410. auto offsets = byte_offset_range_to_code_point_offset_range(start, end, 0);
  411. start = offsets.start;
  412. end = offsets.end;
  413. }
  414. auto& spans_starting = style.is_anchored() ? m_current_spans.m_anchored_spans_starting : m_current_spans.m_spans_starting;
  415. auto& spans_ending = style.is_anchored() ? m_current_spans.m_anchored_spans_ending : m_current_spans.m_spans_ending;
  416. auto starting_map = spans_starting.get(start).value_or({});
  417. if (!starting_map.contains(end))
  418. m_refresh_needed = true;
  419. starting_map.set(end, style);
  420. spans_starting.set(start, starting_map);
  421. auto ending_map = spans_ending.get(end).value_or({});
  422. if (!ending_map.contains(start))
  423. m_refresh_needed = true;
  424. ending_map.set(start, style);
  425. spans_ending.set(end, ending_map);
  426. }
  427. void Editor::suggest(size_t invariant_offset, size_t static_offset, Span::Mode offset_mode) const
  428. {
  429. auto internal_static_offset = static_offset;
  430. auto internal_invariant_offset = invariant_offset;
  431. if (offset_mode == Span::Mode::ByteOriented) {
  432. // FIXME: We're assuming that invariant_offset points to the end of the available data
  433. // this is not necessarily true, but is true in most cases.
  434. auto offsets = byte_offset_range_to_code_point_offset_range(internal_static_offset, internal_invariant_offset + internal_static_offset, m_cursor - 1, true);
  435. internal_static_offset = offsets.start;
  436. internal_invariant_offset = offsets.end - offsets.start;
  437. }
  438. m_suggestion_manager.set_suggestion_variants(internal_static_offset, internal_invariant_offset, 0);
  439. }
  440. void Editor::initialize()
  441. {
  442. if (m_initialized)
  443. return;
  444. struct termios termios;
  445. tcgetattr(0, &termios);
  446. m_default_termios = termios; // grab a copy to restore
  447. get_terminal_size();
  448. if (m_configuration.operation_mode == Configuration::Unset) {
  449. auto istty = isatty(STDIN_FILENO) && isatty(STDERR_FILENO);
  450. if (!istty) {
  451. m_configuration.set(Configuration::NonInteractive);
  452. } else {
  453. auto* term = getenv("TERM");
  454. if (StringView { term }.starts_with("xterm"))
  455. m_configuration.set(Configuration::Full);
  456. else
  457. m_configuration.set(Configuration::NoEscapeSequences);
  458. }
  459. }
  460. // Because we use our own line discipline which includes echoing,
  461. // we disable ICANON and ECHO.
  462. if (m_configuration.operation_mode == Configuration::Full) {
  463. termios.c_lflag &= ~(ECHO | ICANON);
  464. tcsetattr(0, TCSANOW, &termios);
  465. }
  466. m_termios = termios;
  467. set_default_keybinds();
  468. for (auto& keybind : m_configuration.keybindings)
  469. register_key_input_callback(keybind);
  470. if (m_configuration.m_signal_mode == Configuration::WithSignalHandlers) {
  471. m_signal_handlers.append(Core::EventLoop::register_signal(SIGINT, [this](int) {
  472. interrupted();
  473. }));
  474. m_signal_handlers.append(Core::EventLoop::register_signal(SIGWINCH, [this](int) {
  475. resized();
  476. }));
  477. }
  478. m_initialized = true;
  479. }
  480. void Editor::refetch_default_termios()
  481. {
  482. struct termios termios;
  483. tcgetattr(0, &termios);
  484. m_default_termios = termios;
  485. if (m_configuration.operation_mode == Configuration::Full)
  486. termios.c_lflag &= ~(ECHO | ICANON);
  487. m_termios = termios;
  488. }
  489. void Editor::interrupted()
  490. {
  491. if (m_is_searching)
  492. return m_search_editor->interrupted();
  493. if (!m_is_editing)
  494. return;
  495. m_was_interrupted = true;
  496. handle_interrupt_event();
  497. if (!m_finish || !m_previous_interrupt_was_handled_as_interrupt)
  498. return;
  499. m_finish = false;
  500. {
  501. OutputFileStream stderr_stream { stderr };
  502. reposition_cursor(stderr_stream, true);
  503. if (m_suggestion_display->cleanup())
  504. reposition_cursor(stderr_stream, true);
  505. stderr_stream.write("\n"sv.bytes());
  506. }
  507. m_buffer.clear();
  508. m_chars_touched_in_the_middle = buffer().size();
  509. m_is_editing = false;
  510. restore();
  511. m_notifier->set_enabled(false);
  512. m_notifier = nullptr;
  513. Core::EventLoop::current().quit(Retry);
  514. }
  515. void Editor::resized()
  516. {
  517. m_was_resized = true;
  518. m_previous_num_columns = m_num_columns;
  519. get_terminal_size();
  520. if (!m_has_origin_reset_scheduled) {
  521. // Reset the origin, but make sure it doesn't blow up if we can't read it
  522. if (set_origin(false)) {
  523. handle_resize_event(false);
  524. } else {
  525. deferred_invoke([this] { handle_resize_event(true); });
  526. m_has_origin_reset_scheduled = true;
  527. }
  528. }
  529. }
  530. void Editor::handle_resize_event(bool reset_origin)
  531. {
  532. m_has_origin_reset_scheduled = false;
  533. if (reset_origin && !set_origin(false)) {
  534. m_has_origin_reset_scheduled = true;
  535. return deferred_invoke([this] { handle_resize_event(true); });
  536. }
  537. set_origin(m_origin_row, 1);
  538. OutputFileStream stderr_stream { stderr };
  539. reposition_cursor(stderr_stream, true);
  540. m_suggestion_display->redisplay(m_suggestion_manager, m_num_lines, m_num_columns);
  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(const String& 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. break;
  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 behaviour.
  881. // This only applies when the buffer is empty. at any other time, the behaviour 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) {
  961. if (m_suggestion_manager.count() > 0) {
  962. if (m_suggestion_display->cleanup())
  963. reposition_cursor(stderr_stream);
  964. m_suggestion_display->set_initial_prompt_lines(m_prompt_lines_at_suggestion_initiation);
  965. m_suggestion_display->display(m_suggestion_manager);
  966. m_origin_row = m_suggestion_display->origin_row();
  967. }
  968. }
  969. if (m_times_tab_pressed > 2) {
  970. if (m_tab_direction == TabDirection::Forward)
  971. m_suggestion_manager.next();
  972. else
  973. m_suggestion_manager.previous();
  974. }
  975. if (m_suggestion_manager.count() < 2) {
  976. // We have none, or just one suggestion,
  977. // we should just commit that and continue
  978. // after it, as if it were auto-completed.
  979. suggest(0, 0, Span::CodepointOriented);
  980. m_times_tab_pressed = 0;
  981. m_suggestion_manager.reset();
  982. m_suggestion_display->finish();
  983. }
  984. continue;
  985. }
  986. // If we got here, manually cleanup the suggestions and then insert the new code point.
  987. suggestion_cleanup.disarm();
  988. cleanup_suggestions();
  989. insert(code_point);
  990. }
  991. if (consumed_code_points == m_incomplete_data.size()) {
  992. m_incomplete_data.clear();
  993. } else {
  994. for (size_t i = 0; i < consumed_code_points; ++i)
  995. m_incomplete_data.take_first();
  996. }
  997. if (!m_incomplete_data.is_empty() && !m_finish)
  998. deferred_invoke([&] { try_update_once(); });
  999. }
  1000. void Editor::cleanup_suggestions()
  1001. {
  1002. if (m_times_tab_pressed) {
  1003. // Apply the style of the last suggestion.
  1004. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  1005. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, m_suggestion_manager.current_suggestion().style);
  1006. // We probably have some suggestions drawn,
  1007. // let's clean them up.
  1008. if (m_suggestion_display->cleanup()) {
  1009. OutputFileStream stderr_stream { stderr };
  1010. reposition_cursor(stderr_stream);
  1011. m_refresh_needed = true;
  1012. }
  1013. m_suggestion_manager.reset();
  1014. suggest(0, 0, Span::CodepointOriented);
  1015. m_suggestion_display->finish();
  1016. }
  1017. m_times_tab_pressed = 0; // Safe to say if we get here, the user didn't press TAB
  1018. }
  1019. bool Editor::search(const StringView& phrase, bool allow_empty, bool from_beginning)
  1020. {
  1021. int last_matching_offset = -1;
  1022. bool found = false;
  1023. // Do not search for empty strings.
  1024. if (allow_empty || phrase.length() > 0) {
  1025. size_t search_offset = m_search_offset;
  1026. for (size_t i = m_history_cursor; i > 0; --i) {
  1027. auto& entry = m_history[i - 1];
  1028. auto contains = from_beginning ? entry.entry.starts_with(phrase) : entry.entry.contains(phrase);
  1029. if (contains) {
  1030. last_matching_offset = i - 1;
  1031. if (search_offset == 0) {
  1032. found = true;
  1033. break;
  1034. }
  1035. --search_offset;
  1036. }
  1037. }
  1038. if (!found) {
  1039. fputc('\a', stderr);
  1040. fflush(stderr);
  1041. }
  1042. }
  1043. if (found) {
  1044. // We plan to clear the buffer, so mark the entire thing touched.
  1045. m_chars_touched_in_the_middle = m_buffer.size();
  1046. m_buffer.clear();
  1047. m_cursor = 0;
  1048. insert(m_history[last_matching_offset].entry);
  1049. // Always needed, as we have cleared the buffer above.
  1050. m_refresh_needed = true;
  1051. }
  1052. return found;
  1053. }
  1054. void Editor::recalculate_origin()
  1055. {
  1056. // Changing the columns can affect our origin if
  1057. // the new size is smaller than our prompt, which would
  1058. // cause said prompt to take up more space, so we should
  1059. // compensate for that.
  1060. if (m_cached_prompt_metrics.max_line_length >= m_num_columns) {
  1061. auto added_lines = (m_cached_prompt_metrics.max_line_length + 1) / m_num_columns - 1;
  1062. m_origin_row += added_lines;
  1063. }
  1064. // We also need to recalculate our cursor position,
  1065. // but that will be calculated and applied at the next
  1066. // refresh cycle.
  1067. }
  1068. void Editor::cleanup()
  1069. {
  1070. auto current_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1071. auto new_lines = current_prompt_metrics().lines_with_addition(current_buffer_metrics, m_num_columns);
  1072. auto shown_lines = num_lines();
  1073. if (new_lines < shown_lines)
  1074. m_extra_forward_lines = max(shown_lines - new_lines, m_extra_forward_lines);
  1075. OutputFileStream stderr_stream { stderr };
  1076. reposition_cursor(stderr_stream, true);
  1077. auto current_line = num_lines() - 1;
  1078. VT::clear_lines(current_line, m_extra_forward_lines, stderr_stream);
  1079. m_extra_forward_lines = 0;
  1080. reposition_cursor(stderr_stream);
  1081. };
  1082. void Editor::refresh_display()
  1083. {
  1084. DuplexMemoryStream output_stream;
  1085. ScopeGuard flush_stream {
  1086. [&] {
  1087. auto buffer = output_stream.copy_into_contiguous_buffer();
  1088. if (buffer.is_empty())
  1089. return;
  1090. fwrite(buffer.data(), sizeof(char), buffer.size(), stderr);
  1091. }
  1092. };
  1093. auto has_cleaned_up = false;
  1094. // Someone changed the window size, figure it out
  1095. // and react to it, we might need to redraw.
  1096. if (m_was_resized) {
  1097. if (m_previous_num_columns != m_num_columns) {
  1098. // We need to cleanup and redo everything.
  1099. m_cached_prompt_valid = false;
  1100. m_refresh_needed = true;
  1101. swap(m_previous_num_columns, m_num_columns);
  1102. recalculate_origin();
  1103. cleanup();
  1104. swap(m_previous_num_columns, m_num_columns);
  1105. has_cleaned_up = true;
  1106. }
  1107. m_was_resized = false;
  1108. }
  1109. // We might be at the last line, and have more than one line;
  1110. // Refreshing the display will cause the terminal to scroll,
  1111. // so note that fact and bring origin up, making sure to
  1112. // reserve the space for however many lines we move it up.
  1113. auto current_num_lines = num_lines();
  1114. if (m_origin_row + current_num_lines > m_num_lines) {
  1115. if (current_num_lines > m_num_lines) {
  1116. for (size_t i = 0; i < m_num_lines; ++i)
  1117. output_stream.write("\n"sv.bytes());
  1118. m_origin_row = 0;
  1119. } else {
  1120. auto old_origin_row = m_origin_row;
  1121. m_origin_row = m_num_lines - current_num_lines + 1;
  1122. for (size_t i = 0; i < old_origin_row - m_origin_row; ++i)
  1123. output_stream.write("\n"sv.bytes());
  1124. }
  1125. }
  1126. // Do not call hook on pure cursor movement.
  1127. if (m_cached_prompt_valid && !m_refresh_needed && m_pending_chars.size() == 0) {
  1128. // Probably just moving around.
  1129. reposition_cursor(output_stream);
  1130. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1131. m_drawn_end_of_line_offset = m_buffer.size();
  1132. return;
  1133. }
  1134. if (on_display_refresh)
  1135. on_display_refresh(*this);
  1136. if (m_cached_prompt_valid) {
  1137. if (!m_refresh_needed && m_cursor == m_buffer.size()) {
  1138. // Just write the characters out and continue,
  1139. // no need to refresh the entire line.
  1140. output_stream.write(m_pending_chars);
  1141. m_pending_chars.clear();
  1142. m_drawn_cursor = m_cursor;
  1143. m_drawn_end_of_line_offset = m_buffer.size();
  1144. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1145. m_drawn_spans = m_current_spans;
  1146. return;
  1147. }
  1148. }
  1149. auto apply_styles = [&, empty_styles = HashMap<u32, Style> {}](size_t i) {
  1150. auto ends = m_current_spans.m_spans_ending.get(i).value_or(empty_styles);
  1151. auto starts = m_current_spans.m_spans_starting.get(i).value_or(empty_styles);
  1152. auto anchored_ends = m_current_spans.m_anchored_spans_ending.get(i).value_or(empty_styles);
  1153. auto anchored_starts = m_current_spans.m_anchored_spans_starting.get(i).value_or(empty_styles);
  1154. if (ends.size() || anchored_ends.size()) {
  1155. Style style;
  1156. for (auto& applicable_style : ends)
  1157. style.unify_with(applicable_style.value);
  1158. for (auto& applicable_style : anchored_ends)
  1159. style.unify_with(applicable_style.value);
  1160. // Disable any style that should be turned off.
  1161. VT::apply_style(style, output_stream, false);
  1162. // Reapply styles for overlapping spans that include this one.
  1163. style = find_applicable_style(i);
  1164. VT::apply_style(style, output_stream, true);
  1165. }
  1166. if (starts.size() || anchored_starts.size()) {
  1167. Style style;
  1168. for (auto& applicable_style : starts)
  1169. style.unify_with(applicable_style.value);
  1170. for (auto& applicable_style : anchored_starts)
  1171. style.unify_with(applicable_style.value);
  1172. // Set new styles.
  1173. VT::apply_style(style, output_stream, true);
  1174. }
  1175. };
  1176. auto print_character_at = [&](size_t i) {
  1177. StringBuilder builder;
  1178. auto c = m_buffer[i];
  1179. bool should_print_masked = is_ascii_control(c) && c != '\n';
  1180. bool should_print_caret = c < 64 && should_print_masked;
  1181. if (should_print_caret)
  1182. builder.appendff("^{:c}", c + 64);
  1183. else if (should_print_masked)
  1184. builder.appendff("\\x{:0>2x}", c);
  1185. else
  1186. builder.append(Utf32View { &c, 1 });
  1187. if (should_print_masked)
  1188. output_stream.write("\033[7m"sv.bytes());
  1189. output_stream.write(builder.string_view().bytes());
  1190. if (should_print_masked)
  1191. output_stream.write("\033[27m"sv.bytes());
  1192. };
  1193. // If there have been no changes to previous sections of the line (style or text)
  1194. // just append the new text with the appropriate styles.
  1195. 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)) {
  1196. auto initial_style = find_applicable_style(m_drawn_end_of_line_offset);
  1197. VT::apply_style(initial_style, output_stream);
  1198. for (size_t i = m_drawn_end_of_line_offset; i < m_buffer.size(); ++i) {
  1199. apply_styles(i);
  1200. print_character_at(i);
  1201. }
  1202. VT::apply_style(Style::reset_style(), output_stream);
  1203. m_pending_chars.clear();
  1204. m_refresh_needed = false;
  1205. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1206. m_chars_touched_in_the_middle = 0;
  1207. m_drawn_cursor = m_cursor;
  1208. m_drawn_end_of_line_offset = m_buffer.size();
  1209. // No need to reposition the cursor, the cursor is already where it needs to be.
  1210. return;
  1211. }
  1212. if constexpr (LINE_EDITOR_DEBUG) {
  1213. if (m_cached_prompt_valid && m_chars_touched_in_the_middle == 0) {
  1214. auto x = m_drawn_spans.contains_up_to_offset(m_current_spans, m_drawn_cursor);
  1215. dbgln("Contains: {} At offset: {}", x, m_drawn_cursor);
  1216. dbgln("Drawn Spans:");
  1217. for (auto& sentry : m_drawn_spans.m_spans_starting) {
  1218. for (auto& entry : sentry.value) {
  1219. dbgln("{}-{}: {}", sentry.key, entry.key, entry.value.to_string());
  1220. }
  1221. }
  1222. dbgln("==========================================================================");
  1223. dbgln("Current Spans:");
  1224. for (auto& sentry : m_current_spans.m_spans_starting) {
  1225. for (auto& entry : sentry.value) {
  1226. dbgln("{}-{}: {}", sentry.key, entry.key, entry.value.to_string());
  1227. }
  1228. }
  1229. }
  1230. }
  1231. // Ouch, reflow entire line.
  1232. if (!has_cleaned_up) {
  1233. cleanup();
  1234. }
  1235. VT::move_absolute(m_origin_row, m_origin_column, output_stream);
  1236. output_stream.write(m_new_prompt.bytes());
  1237. VT::clear_to_end_of_line(output_stream);
  1238. StringBuilder builder;
  1239. for (size_t i = 0; i < m_buffer.size(); ++i) {
  1240. apply_styles(i);
  1241. print_character_at(i);
  1242. }
  1243. VT::apply_style(Style::reset_style(), output_stream); // don't bleed to EOL
  1244. m_pending_chars.clear();
  1245. m_refresh_needed = false;
  1246. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  1247. m_chars_touched_in_the_middle = 0;
  1248. m_drawn_spans = m_current_spans;
  1249. m_drawn_end_of_line_offset = m_buffer.size();
  1250. m_cached_prompt_valid = true;
  1251. reposition_cursor(output_stream);
  1252. }
  1253. void Editor::strip_styles(bool strip_anchored)
  1254. {
  1255. m_current_spans.m_spans_starting.clear();
  1256. m_current_spans.m_spans_ending.clear();
  1257. if (strip_anchored) {
  1258. m_current_spans.m_anchored_spans_starting.clear();
  1259. m_current_spans.m_anchored_spans_ending.clear();
  1260. }
  1261. m_refresh_needed = true;
  1262. }
  1263. void Editor::reposition_cursor(OutputStream& stream, bool to_end)
  1264. {
  1265. auto cursor = m_cursor;
  1266. auto saved_cursor = m_cursor;
  1267. if (to_end)
  1268. cursor = m_buffer.size();
  1269. m_cursor = cursor;
  1270. m_drawn_cursor = cursor;
  1271. auto line = cursor_line() - 1;
  1272. auto column = offset_in_line();
  1273. ensure_free_lines_from_origin(line);
  1274. VERIFY(column + m_origin_column <= m_num_columns);
  1275. VT::move_absolute(line + m_origin_row, column + m_origin_column, stream);
  1276. m_cursor = saved_cursor;
  1277. }
  1278. void VT::move_absolute(u32 row, u32 col, OutputStream& stream)
  1279. {
  1280. stream.write(String::formatted("\033[{};{}H", row, col).bytes());
  1281. }
  1282. void VT::move_relative(int row, int col, OutputStream& stream)
  1283. {
  1284. char x_op = 'A', y_op = 'D';
  1285. if (row > 0)
  1286. x_op = 'B';
  1287. else
  1288. row = -row;
  1289. if (col > 0)
  1290. y_op = 'C';
  1291. else
  1292. col = -col;
  1293. if (row > 0)
  1294. stream.write(String::formatted("\033[{}{}", row, x_op).bytes());
  1295. if (col > 0)
  1296. stream.write(String::formatted("\033[{}{}", col, y_op).bytes());
  1297. }
  1298. Style Editor::find_applicable_style(size_t offset) const
  1299. {
  1300. // Walk through our styles and merge all that fit in the offset.
  1301. auto style = Style::reset_style();
  1302. auto unify = [&](auto& entry) {
  1303. if (entry.key >= offset)
  1304. return;
  1305. for (auto& style_value : entry.value) {
  1306. if (style_value.key <= offset)
  1307. return;
  1308. style.unify_with(style_value.value, true);
  1309. }
  1310. };
  1311. for (auto& entry : m_current_spans.m_spans_starting) {
  1312. unify(entry);
  1313. }
  1314. for (auto& entry : m_current_spans.m_anchored_spans_starting) {
  1315. unify(entry);
  1316. }
  1317. return style;
  1318. }
  1319. String Style::Background::to_vt_escape() const
  1320. {
  1321. if (is_default())
  1322. return "";
  1323. if (m_is_rgb) {
  1324. return String::formatted("\e[48;2;{};{};{}m", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1325. } else {
  1326. return String::formatted("\e[{}m", (u8)m_xterm_color + 40);
  1327. }
  1328. }
  1329. String Style::Foreground::to_vt_escape() const
  1330. {
  1331. if (is_default())
  1332. return "";
  1333. if (m_is_rgb) {
  1334. return String::formatted("\e[38;2;{};{};{}m", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1335. } else {
  1336. return String::formatted("\e[{}m", (u8)m_xterm_color + 30);
  1337. }
  1338. }
  1339. String Style::Hyperlink::to_vt_escape(bool starting) const
  1340. {
  1341. if (is_empty())
  1342. return "";
  1343. return String::formatted("\e]8;;{}\e\\", starting ? m_link : String::empty());
  1344. }
  1345. void Style::unify_with(const Style& other, bool prefer_other)
  1346. {
  1347. // Unify colors.
  1348. if (prefer_other || m_background.is_default())
  1349. m_background = other.background();
  1350. if (prefer_other || m_foreground.is_default())
  1351. m_foreground = other.foreground();
  1352. // Unify graphic renditions.
  1353. if (other.bold())
  1354. set(Bold);
  1355. if (other.italic())
  1356. set(Italic);
  1357. if (other.underline())
  1358. set(Underline);
  1359. // Unify links.
  1360. if (prefer_other || m_hyperlink.is_empty())
  1361. m_hyperlink = other.hyperlink();
  1362. }
  1363. String Style::to_string() const
  1364. {
  1365. StringBuilder builder;
  1366. builder.append("Style { ");
  1367. if (!m_foreground.is_default()) {
  1368. builder.append("Foreground(");
  1369. if (m_foreground.m_is_rgb) {
  1370. builder.join(", ", m_foreground.m_rgb_color);
  1371. } else {
  1372. builder.appendff("(XtermColor) {}", (int)m_foreground.m_xterm_color);
  1373. }
  1374. builder.append("), ");
  1375. }
  1376. if (!m_background.is_default()) {
  1377. builder.append("Background(");
  1378. if (m_background.m_is_rgb) {
  1379. builder.join(' ', m_background.m_rgb_color);
  1380. } else {
  1381. builder.appendff("(XtermColor) {}", (int)m_background.m_xterm_color);
  1382. }
  1383. builder.append("), ");
  1384. }
  1385. if (bold())
  1386. builder.append("Bold, ");
  1387. if (underline())
  1388. builder.append("Underline, ");
  1389. if (italic())
  1390. builder.append("Italic, ");
  1391. if (!m_hyperlink.is_empty())
  1392. builder.appendff("Hyperlink(\"{}\"), ", m_hyperlink.m_link);
  1393. builder.append("}");
  1394. return builder.build();
  1395. }
  1396. void VT::apply_style(const Style& style, OutputStream& stream, bool is_starting)
  1397. {
  1398. if (is_starting) {
  1399. stream.write(String::formatted("\033[{};{};{}m{}{}{}",
  1400. style.bold() ? 1 : 22,
  1401. style.underline() ? 4 : 24,
  1402. style.italic() ? 3 : 23,
  1403. style.background().to_vt_escape(),
  1404. style.foreground().to_vt_escape(),
  1405. style.hyperlink().to_vt_escape(true))
  1406. .bytes());
  1407. } else {
  1408. stream.write(style.hyperlink().to_vt_escape(false).bytes());
  1409. }
  1410. }
  1411. void VT::clear_lines(size_t count_above, size_t count_below, OutputStream& stream)
  1412. {
  1413. if (count_below + count_above == 0) {
  1414. stream.write("\033[2K"sv.bytes());
  1415. } else {
  1416. // Go down count_below lines.
  1417. if (count_below > 0)
  1418. stream.write(String::formatted("\033[{}B", count_below).bytes());
  1419. // Then clear lines going upwards.
  1420. for (size_t i = count_below + count_above; i > 0; --i) {
  1421. stream.write("\033[2K"sv.bytes());
  1422. if (i != 1)
  1423. stream.write("\033[A"sv.bytes());
  1424. }
  1425. }
  1426. }
  1427. void VT::save_cursor(OutputStream& stream)
  1428. {
  1429. stream.write("\033[s"sv.bytes());
  1430. }
  1431. void VT::restore_cursor(OutputStream& stream)
  1432. {
  1433. stream.write("\033[u"sv.bytes());
  1434. }
  1435. void VT::clear_to_end_of_line(OutputStream& stream)
  1436. {
  1437. stream.write("\033[K"sv.bytes());
  1438. }
  1439. StringMetrics Editor::actual_rendered_string_metrics(const StringView& string)
  1440. {
  1441. StringMetrics metrics;
  1442. StringMetrics::LineMetrics current_line;
  1443. VTState state { Free };
  1444. Utf8View view { string };
  1445. auto it = view.begin();
  1446. for (; it != view.end(); ++it) {
  1447. auto c = *it;
  1448. auto it_copy = it;
  1449. ++it_copy;
  1450. auto next_c = it_copy == view.end() ? 0 : *it_copy;
  1451. state = actual_rendered_string_length_step(metrics, view.iterator_offset(it), current_line, c, next_c, state);
  1452. }
  1453. metrics.line_metrics.append(current_line);
  1454. for (auto& line : metrics.line_metrics)
  1455. metrics.max_line_length = max(line.total_length(), metrics.max_line_length);
  1456. return metrics;
  1457. }
  1458. StringMetrics Editor::actual_rendered_string_metrics(const Utf32View& view)
  1459. {
  1460. StringMetrics metrics;
  1461. StringMetrics::LineMetrics current_line;
  1462. VTState state { Free };
  1463. for (size_t i = 0; i < view.length(); ++i) {
  1464. auto c = view.code_points()[i];
  1465. auto next_c = i + 1 < view.length() ? view.code_points()[i + 1] : 0;
  1466. state = actual_rendered_string_length_step(metrics, i, current_line, c, next_c, state);
  1467. }
  1468. metrics.line_metrics.append(current_line);
  1469. for (auto& line : metrics.line_metrics)
  1470. metrics.max_line_length = max(line.total_length(), metrics.max_line_length);
  1471. return metrics;
  1472. }
  1473. Editor::VTState Editor::actual_rendered_string_length_step(StringMetrics& metrics, size_t index, StringMetrics::LineMetrics& current_line, u32 c, u32 next_c, VTState state)
  1474. {
  1475. switch (state) {
  1476. case Free:
  1477. if (c == '\x1b') { // escape
  1478. return Escape;
  1479. }
  1480. if (c == '\r') { // carriage return
  1481. current_line.masked_chars = {};
  1482. current_line.length = 0;
  1483. if (!metrics.line_metrics.is_empty())
  1484. metrics.line_metrics.last() = { {}, 0 };
  1485. return state;
  1486. }
  1487. if (c == '\n') { // return
  1488. metrics.line_metrics.append(current_line);
  1489. current_line.masked_chars = {};
  1490. current_line.length = 0;
  1491. return state;
  1492. }
  1493. if (is_ascii_control(c) && c != '\n')
  1494. current_line.masked_chars.append({ index, 1, c < 64 ? 2u : 4u }); // if the character cannot be represented as ^c, represent it as \xbb.
  1495. // FIXME: This will not support anything sophisticated
  1496. ++current_line.length;
  1497. ++metrics.total_length;
  1498. return state;
  1499. case Escape:
  1500. if (c == ']') {
  1501. if (next_c == '0')
  1502. state = Title;
  1503. return state;
  1504. }
  1505. if (c == '[') {
  1506. return Bracket;
  1507. }
  1508. // FIXME: This does not support non-VT (aside from set-title) escapes
  1509. return state;
  1510. case Bracket:
  1511. if (is_ascii_digit(c)) {
  1512. return BracketArgsSemi;
  1513. }
  1514. return state;
  1515. case BracketArgsSemi:
  1516. if (c == ';') {
  1517. return Bracket;
  1518. }
  1519. if (!is_ascii_digit(c))
  1520. state = Free;
  1521. return state;
  1522. case Title:
  1523. if (c == 7)
  1524. state = Free;
  1525. return state;
  1526. }
  1527. return state;
  1528. }
  1529. Result<Vector<size_t, 2>, Editor::Error> Editor::vt_dsr()
  1530. {
  1531. char buf[16];
  1532. // Read whatever junk there is before talking to the terminal
  1533. // and insert them later when we're reading user input.
  1534. bool more_junk_to_read { false };
  1535. timeval timeout { 0, 0 };
  1536. fd_set readfds;
  1537. FD_ZERO(&readfds);
  1538. FD_SET(0, &readfds);
  1539. do {
  1540. more_junk_to_read = false;
  1541. [[maybe_unused]] auto rc = select(1, &readfds, nullptr, nullptr, &timeout);
  1542. if (FD_ISSET(0, &readfds)) {
  1543. auto nread = read(0, buf, 16);
  1544. if (nread < 0) {
  1545. m_input_error = Error::ReadFailure;
  1546. finish();
  1547. break;
  1548. }
  1549. if (nread == 0)
  1550. break;
  1551. m_incomplete_data.append(buf, nread);
  1552. more_junk_to_read = true;
  1553. }
  1554. } while (more_junk_to_read);
  1555. if (m_input_error.has_value())
  1556. return m_input_error.value();
  1557. fputs("\033[6n", stderr);
  1558. fflush(stderr);
  1559. // Parse the DSR response
  1560. // it should be of the form .*\e[\d+;\d+R.*
  1561. // Anything not part of the response is just added to the incomplete data.
  1562. enum {
  1563. Free,
  1564. SawEsc,
  1565. SawBracket,
  1566. InFirstCoordinate,
  1567. SawSemicolon,
  1568. InSecondCoordinate,
  1569. SawR,
  1570. } state { Free };
  1571. auto has_error = false;
  1572. Vector<char, 4> coordinate_buffer;
  1573. size_t row { 1 }, col { 1 };
  1574. do {
  1575. char c;
  1576. auto nread = read(0, &c, 1);
  1577. if (nread < 0) {
  1578. if (errno == 0 || errno == EINTR) {
  1579. // ????
  1580. continue;
  1581. }
  1582. dbgln("Error while reading DSR: {}", strerror(errno));
  1583. return Error::ReadFailure;
  1584. }
  1585. if (nread == 0) {
  1586. dbgln("Terminal DSR issue; received no response");
  1587. return Error::Empty;
  1588. }
  1589. switch (state) {
  1590. case Free:
  1591. if (c == '\x1b') {
  1592. state = SawEsc;
  1593. continue;
  1594. }
  1595. m_incomplete_data.append(c);
  1596. continue;
  1597. case SawEsc:
  1598. if (c == '[') {
  1599. state = SawBracket;
  1600. continue;
  1601. }
  1602. m_incomplete_data.append(c);
  1603. continue;
  1604. case SawBracket:
  1605. if (is_ascii_digit(c)) {
  1606. state = InFirstCoordinate;
  1607. coordinate_buffer.append(c);
  1608. continue;
  1609. }
  1610. m_incomplete_data.append(c);
  1611. continue;
  1612. case InFirstCoordinate:
  1613. if (is_ascii_digit(c)) {
  1614. coordinate_buffer.append(c);
  1615. continue;
  1616. }
  1617. if (c == ';') {
  1618. auto maybe_row = StringView { coordinate_buffer.data(), coordinate_buffer.size() }.to_uint();
  1619. if (!maybe_row.has_value())
  1620. has_error = true;
  1621. row = maybe_row.value_or(1u);
  1622. coordinate_buffer.clear_with_capacity();
  1623. state = SawSemicolon;
  1624. continue;
  1625. }
  1626. m_incomplete_data.append(c);
  1627. continue;
  1628. case SawSemicolon:
  1629. if (is_ascii_digit(c)) {
  1630. state = InSecondCoordinate;
  1631. coordinate_buffer.append(c);
  1632. continue;
  1633. }
  1634. m_incomplete_data.append(c);
  1635. continue;
  1636. case InSecondCoordinate:
  1637. if (is_ascii_digit(c)) {
  1638. coordinate_buffer.append(c);
  1639. continue;
  1640. }
  1641. if (c == 'R') {
  1642. auto maybe_column = StringView { coordinate_buffer.data(), coordinate_buffer.size() }.to_uint();
  1643. if (!maybe_column.has_value())
  1644. has_error = true;
  1645. col = maybe_column.value_or(1u);
  1646. coordinate_buffer.clear_with_capacity();
  1647. state = SawR;
  1648. continue;
  1649. }
  1650. m_incomplete_data.append(c);
  1651. continue;
  1652. case SawR:
  1653. m_incomplete_data.append(c);
  1654. continue;
  1655. default:
  1656. VERIFY_NOT_REACHED();
  1657. }
  1658. } while (state != SawR);
  1659. if (has_error)
  1660. dbgln("Terminal DSR issue, couldn't parse DSR response");
  1661. return Vector<size_t, 2> { row, col };
  1662. }
  1663. String Editor::line(size_t up_to_index) const
  1664. {
  1665. StringBuilder builder;
  1666. builder.append(Utf32View { m_buffer.data(), min(m_buffer.size(), up_to_index) });
  1667. return builder.build();
  1668. }
  1669. void Editor::remove_at_index(size_t index)
  1670. {
  1671. // See if we have any anchored styles, and reposition them if needed.
  1672. readjust_anchored_styles(index, ModificationKind::Removal);
  1673. auto cp = m_buffer[index];
  1674. m_buffer.remove(index);
  1675. if (cp == '\n')
  1676. ++m_extra_forward_lines;
  1677. ++m_chars_touched_in_the_middle;
  1678. }
  1679. void Editor::readjust_anchored_styles(size_t hint_index, ModificationKind modification)
  1680. {
  1681. struct Anchor {
  1682. Span old_span;
  1683. Span new_span;
  1684. Style style;
  1685. };
  1686. Vector<Anchor> anchors_to_relocate;
  1687. auto index_shift = modification == ModificationKind::Insertion ? 1 : -1;
  1688. auto forced_removal = modification == ModificationKind::ForcedOverlapRemoval;
  1689. for (auto& start_entry : m_current_spans.m_anchored_spans_starting) {
  1690. for (auto& end_entry : start_entry.value) {
  1691. if (forced_removal) {
  1692. if (start_entry.key <= hint_index && end_entry.key > hint_index) {
  1693. // Remove any overlapping regions.
  1694. continue;
  1695. }
  1696. }
  1697. if (start_entry.key >= hint_index) {
  1698. if (start_entry.key == hint_index && end_entry.key == hint_index + 1 && modification == ModificationKind::Removal) {
  1699. // Remove the anchor, as all its text was wiped.
  1700. continue;
  1701. }
  1702. // Shift everything.
  1703. 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 });
  1704. continue;
  1705. }
  1706. if (end_entry.key > hint_index) {
  1707. // Shift just the end.
  1708. 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 });
  1709. continue;
  1710. }
  1711. 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 });
  1712. }
  1713. }
  1714. m_current_spans.m_anchored_spans_ending.clear();
  1715. m_current_spans.m_anchored_spans_starting.clear();
  1716. // Pass over the relocations and update the stale entries.
  1717. for (auto& relocation : anchors_to_relocate) {
  1718. stylize(relocation.new_span, relocation.style);
  1719. }
  1720. }
  1721. size_t StringMetrics::lines_with_addition(const StringMetrics& offset, size_t column_width) const
  1722. {
  1723. size_t lines = 0;
  1724. for (size_t i = 0; i < line_metrics.size() - 1; ++i)
  1725. lines += (line_metrics[i].total_length() + column_width) / column_width;
  1726. auto last = line_metrics.last().total_length();
  1727. last += offset.line_metrics.first().total_length();
  1728. lines += (last + column_width) / column_width;
  1729. for (size_t i = 1; i < offset.line_metrics.size(); ++i)
  1730. lines += (offset.line_metrics[i].total_length() + column_width) / column_width;
  1731. return lines;
  1732. }
  1733. size_t StringMetrics::offset_with_addition(const StringMetrics& offset, size_t column_width) const
  1734. {
  1735. if (offset.line_metrics.size() > 1)
  1736. return offset.line_metrics.last().total_length() % column_width;
  1737. auto last = line_metrics.last().total_length();
  1738. last += offset.line_metrics.first().total_length();
  1739. return last % column_width;
  1740. }
  1741. bool Editor::Spans::contains_up_to_offset(const Spans& other, size_t offset) const
  1742. {
  1743. auto compare = [&]<typename K, typename V>(const HashMap<K, HashMap<K, V>>& left, const HashMap<K, HashMap<K, V>>& right) -> bool {
  1744. for (auto& entry : right) {
  1745. if (entry.key > offset + 1)
  1746. continue;
  1747. auto left_map = left.get(entry.key);
  1748. if (!left_map.has_value())
  1749. return false;
  1750. for (auto& left_entry : left_map.value()) {
  1751. if (auto value = entry.value.get(left_entry.key); !value.has_value()) {
  1752. // Might have the same thing with a longer span
  1753. bool found = false;
  1754. for (auto& possibly_longer_span_entry : entry.value) {
  1755. if (possibly_longer_span_entry.key > left_entry.key && possibly_longer_span_entry.key > offset && left_entry.value == possibly_longer_span_entry.value) {
  1756. found = true;
  1757. break;
  1758. }
  1759. }
  1760. if (found)
  1761. continue;
  1762. if constexpr (LINE_EDITOR_DEBUG) {
  1763. dbgln("Compare for {}-{} failed, no entry", entry.key, left_entry.key);
  1764. for (auto& x : entry.value)
  1765. dbgln("Have: {}-{} = {}", entry.key, x.key, x.value.to_string());
  1766. }
  1767. return false;
  1768. } else if (value.value() != left_entry.value) {
  1769. dbgln_if(LINE_EDITOR_DEBUG, "Compare for {}-{} failed, different values: {} != {}", entry.key, left_entry.key, value.value().to_string(), left_entry.value.to_string());
  1770. return false;
  1771. }
  1772. }
  1773. }
  1774. return true;
  1775. };
  1776. return compare(m_spans_starting, other.m_spans_starting)
  1777. && compare(m_anchored_spans_starting, other.m_anchored_spans_starting);
  1778. }
  1779. }