Editor.cpp 76 KB

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