Editor.cpp 66 KB

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