Editor.cpp 69 KB

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