Editor.cpp 81 KB

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