Editor.cpp 57 KB

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