Editor.cpp 81 KB

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