Editor.cpp 53 KB

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