Editor.cpp 82 KB

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