Editor.cpp 57 KB

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