Editor.cpp 83 KB

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