Editor.cpp 80 KB

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