Editor.cpp 68 KB

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