Editor.cpp 67 KB

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