Editor.cpp 69 KB

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