Editor.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  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. set_origin();
  475. strip_styles(true);
  476. m_history_cursor = m_history.size();
  477. refresh_display();
  478. Core::EventLoop loop;
  479. m_notifier = Core::Notifier::construct(STDIN_FILENO, Core::Notifier::Read);
  480. add_child(*m_notifier);
  481. m_notifier->on_ready_to_read = [&] { try_update_once(); };
  482. if (!m_incomplete_data.is_empty())
  483. deferred_invoke([&](auto&) { try_update_once(); });
  484. if (loop.exec() == Retry)
  485. return get_line(prompt);
  486. return m_input_error.has_value() ? Result<String, Editor::Error> { m_input_error.value() } : Result<String, Editor::Error> { m_returned_line };
  487. }
  488. void Editor::save_to(JsonObject& object)
  489. {
  490. Core::Object::save_to(object);
  491. object.set("is_searching", m_is_searching);
  492. object.set("is_editing", m_is_editing);
  493. object.set("cursor_offset", m_cursor);
  494. object.set("needs_refresh", m_refresh_needed);
  495. object.set("unprocessed_characters", m_incomplete_data.size());
  496. object.set("history_size", m_history.size());
  497. object.set("current_prompt", m_new_prompt);
  498. object.set("was_interrupted", m_was_interrupted);
  499. JsonObject display_area;
  500. display_area.set("top_left_row", m_origin_row);
  501. display_area.set("top_left_column", m_origin_column);
  502. display_area.set("line_count", num_lines());
  503. object.set("used_display_area", move(display_area));
  504. }
  505. void Editor::try_update_once()
  506. {
  507. if (m_was_interrupted) {
  508. handle_interrupt_event();
  509. }
  510. handle_read_event();
  511. if (m_always_refresh)
  512. m_refresh_needed = true;
  513. refresh_display();
  514. if (m_finish)
  515. really_quit_event_loop();
  516. }
  517. void Editor::handle_interrupt_event()
  518. {
  519. m_was_interrupted = false;
  520. m_callback_machine.interrupted(*this);
  521. if (!m_callback_machine.should_process_last_pressed_key())
  522. return;
  523. fprintf(stderr, "^C");
  524. fflush(stderr);
  525. if (on_interrupt_handled)
  526. on_interrupt_handled();
  527. m_buffer.clear();
  528. m_cursor = 0;
  529. finish();
  530. }
  531. void Editor::handle_read_event()
  532. {
  533. char keybuf[16];
  534. ssize_t nread = 0;
  535. if (!m_incomplete_data.size())
  536. nread = read(0, keybuf, sizeof(keybuf));
  537. if (nread < 0) {
  538. if (errno == EINTR) {
  539. if (!m_was_interrupted) {
  540. if (m_was_resized)
  541. return;
  542. finish();
  543. return;
  544. }
  545. handle_interrupt_event();
  546. return;
  547. }
  548. ScopedValueRollback errno_restorer(errno);
  549. perror("read failed");
  550. m_input_error = Error::ReadFailure;
  551. finish();
  552. return;
  553. }
  554. m_incomplete_data.append(keybuf, nread);
  555. nread = m_incomplete_data.size();
  556. if (nread == 0) {
  557. m_input_error = Error::Empty;
  558. finish();
  559. return;
  560. }
  561. auto reverse_tab = false;
  562. // Discard starting bytes until they make sense as utf-8.
  563. size_t valid_bytes = 0;
  564. while (nread) {
  565. Utf8View { StringView { m_incomplete_data.data(), (size_t)nread } }.validate(valid_bytes);
  566. if (valid_bytes)
  567. break;
  568. m_incomplete_data.take_first();
  569. --nread;
  570. }
  571. Utf8View input_view { StringView { m_incomplete_data.data(), valid_bytes } };
  572. size_t consumed_code_points = 0;
  573. Vector<u8, 4> csi_parameter_bytes;
  574. Vector<unsigned, 4> csi_parameters;
  575. Vector<u8> csi_intermediate_bytes;
  576. u8 csi_final;
  577. enum CSIMod {
  578. Shift = 1,
  579. Alt = 2,
  580. Ctrl = 4,
  581. };
  582. for (auto code_point : input_view) {
  583. if (m_finish)
  584. break;
  585. ++consumed_code_points;
  586. if (code_point == 0)
  587. continue;
  588. switch (m_state) {
  589. case InputState::GotEscape:
  590. switch (code_point) {
  591. case '[':
  592. m_state = InputState::CSIExpectParameter;
  593. continue;
  594. default: {
  595. m_state = InputState::Free;
  596. m_callback_machine.key_pressed(*this, { code_point, Key::Alt });
  597. cleanup_suggestions();
  598. continue;
  599. }
  600. }
  601. case InputState::CSIExpectParameter:
  602. if (code_point >= 0x30 && code_point <= 0x3f) { // '0123456789:;<=>?'
  603. csi_parameter_bytes.append(code_point);
  604. continue;
  605. }
  606. m_state = InputState::CSIExpectIntermediate;
  607. [[fallthrough]];
  608. case InputState::CSIExpectIntermediate:
  609. if (code_point >= 0x20 && code_point <= 0x2f) { // ' !"#$%&\'()*+,-./'
  610. csi_intermediate_bytes.append(code_point);
  611. continue;
  612. }
  613. m_state = InputState::CSIExpectFinal;
  614. [[fallthrough]];
  615. case InputState::CSIExpectFinal: {
  616. m_state = InputState::Free;
  617. if (!(code_point >= 0x40 && code_point <= 0x7f)) {
  618. dbgprintf("LibLine: Invalid CSI: %02x (%c)\r\n", code_point, code_point);
  619. continue;
  620. }
  621. csi_final = code_point;
  622. for (auto& parameter : String::copy(csi_parameter_bytes).split(';')) {
  623. if (auto value = parameter.to_uint(); value.has_value())
  624. csi_parameters.append(value.value());
  625. else
  626. csi_parameters.append(0);
  627. }
  628. unsigned param1 = 0, param2 = 0;
  629. if (csi_parameters.size() >= 1)
  630. param1 = csi_parameters[0];
  631. if (csi_parameters.size() >= 2)
  632. param2 = csi_parameters[1];
  633. unsigned modifiers = param2 ? param2 - 1 : 0;
  634. if (csi_final == 'Z') {
  635. // 'reverse tab'
  636. reverse_tab = true;
  637. break;
  638. }
  639. cleanup_suggestions();
  640. switch (csi_final) {
  641. case 'A': // ^[[A: arrow up
  642. search_backwards();
  643. continue;
  644. case 'B': // ^[[B: arrow down
  645. search_forwards();
  646. continue;
  647. case 'D': // ^[[D: arrow left
  648. if (modifiers == CSIMod::Alt || modifiers == CSIMod::Ctrl)
  649. cursor_left_word();
  650. else
  651. cursor_left_character();
  652. continue;
  653. case 'C': // ^[[C: arrow right
  654. if (modifiers == CSIMod::Alt || modifiers == CSIMod::Ctrl)
  655. cursor_right_word();
  656. else
  657. cursor_right_character();
  658. continue;
  659. case 'H': // ^[[H: home
  660. go_home();
  661. continue;
  662. case 'F': // ^[[F: end
  663. go_end();
  664. continue;
  665. case '~':
  666. if (param1 == 3) { // ^[[3~: delete
  667. if (modifiers == CSIMod::Ctrl)
  668. erase_alnum_word_forwards();
  669. else
  670. erase_character_forwards();
  671. m_search_offset = 0;
  672. continue;
  673. }
  674. // ^[[5~: page up
  675. // ^[[6~: page down
  676. dbgprintf("LibLine: Unhandled '~': %d\r\n", param1);
  677. continue;
  678. default:
  679. dbgprintf("LibLine: Unhandled final: %02x (%c)\r\n", code_point, code_point);
  680. continue;
  681. }
  682. break;
  683. }
  684. case InputState::Free:
  685. if (code_point == 27) {
  686. m_state = InputState::GotEscape;
  687. continue;
  688. }
  689. break;
  690. }
  691. // There are no sequences past this point, so short of 'tab', we will want to cleanup the suggestions.
  692. ArmedScopeGuard suggestion_cleanup { [this] { cleanup_suggestions(); } };
  693. // Normally ^D. `stty eof \^n` can change it to ^N (or something else), but Serenity doesn't have `stty` yet.
  694. // Process this here since the keybinds might override its behaviour.
  695. // This only applies when the buffer is empty. at any other time, the behaviour should be configurable.
  696. if (code_point == m_termios.c_cc[VEOF] && m_buffer.size() == 0) {
  697. finish_edit();
  698. continue;
  699. }
  700. m_callback_machine.key_pressed(*this, code_point);
  701. if (!m_callback_machine.should_process_last_pressed_key())
  702. continue;
  703. m_search_offset = 0; // reset search offset on any key
  704. if (code_point == '\t' || reverse_tab) {
  705. suggestion_cleanup.disarm();
  706. if (!on_tab_complete)
  707. continue;
  708. // Reverse tab can count as regular tab here.
  709. m_times_tab_pressed++;
  710. int token_start = m_cursor;
  711. // Ask for completions only on the first tab
  712. // and scan for the largest common prefix to display,
  713. // further tabs simply show the cached completions.
  714. if (m_times_tab_pressed == 1) {
  715. m_suggestion_manager.set_suggestions(on_tab_complete(*this));
  716. m_prompt_lines_at_suggestion_initiation = num_lines();
  717. if (m_suggestion_manager.count() == 0) {
  718. // There are no suggestions, beep.
  719. fputc('\a', stderr);
  720. fflush(stderr);
  721. }
  722. }
  723. // Adjust already incremented / decremented index when switching tab direction.
  724. if (reverse_tab && m_tab_direction != TabDirection::Backward) {
  725. m_suggestion_manager.previous();
  726. m_suggestion_manager.previous();
  727. m_tab_direction = TabDirection::Backward;
  728. }
  729. if (!reverse_tab && m_tab_direction != TabDirection::Forward) {
  730. m_suggestion_manager.next();
  731. m_suggestion_manager.next();
  732. m_tab_direction = TabDirection::Forward;
  733. }
  734. reverse_tab = false;
  735. auto completion_mode = m_times_tab_pressed == 1 ? SuggestionManager::CompletePrefix : m_times_tab_pressed == 2 ? SuggestionManager::ShowSuggestions : SuggestionManager::CycleSuggestions;
  736. auto completion_result = m_suggestion_manager.attempt_completion(completion_mode, token_start);
  737. auto new_cursor = m_cursor + completion_result.new_cursor_offset;
  738. for (size_t i = completion_result.offset_region_to_remove.start; i < completion_result.offset_region_to_remove.end; ++i)
  739. remove_at_index(new_cursor);
  740. m_cursor = new_cursor;
  741. m_inline_search_cursor = new_cursor;
  742. m_refresh_needed = true;
  743. for (auto& view : completion_result.insert)
  744. insert(view);
  745. if (completion_result.style_to_apply.has_value()) {
  746. // Apply the style of the last suggestion.
  747. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  748. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, completion_result.style_to_apply.value());
  749. }
  750. switch (completion_result.new_completion_mode) {
  751. case SuggestionManager::DontComplete:
  752. m_times_tab_pressed = 0;
  753. break;
  754. case SuggestionManager::CompletePrefix:
  755. break;
  756. default:
  757. ++m_times_tab_pressed;
  758. break;
  759. }
  760. if (m_times_tab_pressed > 1) {
  761. if (m_suggestion_manager.count() > 0) {
  762. if (m_suggestion_display->cleanup())
  763. reposition_cursor();
  764. m_suggestion_display->set_initial_prompt_lines(m_prompt_lines_at_suggestion_initiation);
  765. m_suggestion_display->display(m_suggestion_manager);
  766. m_origin_row = m_suggestion_display->origin_row();
  767. }
  768. }
  769. if (m_times_tab_pressed > 2) {
  770. if (m_tab_direction == TabDirection::Forward)
  771. m_suggestion_manager.next();
  772. else
  773. m_suggestion_manager.previous();
  774. }
  775. if (m_suggestion_manager.count() < 2) {
  776. // We have none, or just one suggestion,
  777. // we should just commit that and continue
  778. // after it, as if it were auto-completed.
  779. suggest(0, 0, Span::CodepointOriented);
  780. m_times_tab_pressed = 0;
  781. m_suggestion_manager.reset();
  782. m_suggestion_display->finish();
  783. }
  784. continue;
  785. }
  786. insert(code_point);
  787. }
  788. if (consumed_code_points == m_incomplete_data.size()) {
  789. m_incomplete_data.clear();
  790. } else {
  791. for (size_t i = 0; i < consumed_code_points; ++i)
  792. m_incomplete_data.take_first();
  793. }
  794. if (!m_incomplete_data.is_empty() && !m_finish)
  795. deferred_invoke([&](auto&) { try_update_once(); });
  796. }
  797. void Editor::cleanup_suggestions()
  798. {
  799. if (m_times_tab_pressed) {
  800. // Apply the style of the last suggestion.
  801. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  802. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, m_suggestion_manager.current_suggestion().style);
  803. // We probably have some suggestions drawn,
  804. // let's clean them up.
  805. if (m_suggestion_display->cleanup()) {
  806. reposition_cursor();
  807. m_refresh_needed = true;
  808. }
  809. m_suggestion_manager.reset();
  810. suggest(0, 0, Span::CodepointOriented);
  811. m_suggestion_display->finish();
  812. }
  813. m_times_tab_pressed = 0; // Safe to say if we get here, the user didn't press TAB
  814. }
  815. bool Editor::search(const StringView& phrase, bool allow_empty, bool from_beginning)
  816. {
  817. int last_matching_offset = -1;
  818. bool found = false;
  819. // Do not search for empty strings.
  820. if (allow_empty || phrase.length() > 0) {
  821. size_t search_offset = m_search_offset;
  822. for (size_t i = m_history_cursor; i > 0; --i) {
  823. auto& entry = m_history[i - 1];
  824. auto contains = from_beginning ? entry.starts_with(phrase) : entry.contains(phrase);
  825. if (contains) {
  826. last_matching_offset = i - 1;
  827. if (search_offset == 0) {
  828. found = true;
  829. break;
  830. }
  831. --search_offset;
  832. }
  833. }
  834. if (!found) {
  835. fputc('\a', stderr);
  836. fflush(stderr);
  837. }
  838. }
  839. if (found) {
  840. m_buffer.clear();
  841. m_cursor = 0;
  842. insert(m_history[last_matching_offset]);
  843. // Always needed, as we have cleared the buffer above.
  844. m_refresh_needed = true;
  845. }
  846. return found;
  847. }
  848. void Editor::recalculate_origin()
  849. {
  850. // Changing the columns can affect our origin if
  851. // the new size is smaller than our prompt, which would
  852. // cause said prompt to take up more space, so we should
  853. // compensate for that.
  854. if (m_cached_prompt_metrics.max_line_length >= m_num_columns) {
  855. auto added_lines = (m_cached_prompt_metrics.max_line_length + 1) / m_num_columns - 1;
  856. m_origin_row += added_lines;
  857. }
  858. // We also need to recalculate our cursor position,
  859. // but that will be calculated and applied at the next
  860. // refresh cycle.
  861. }
  862. void Editor::cleanup()
  863. {
  864. auto current_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  865. auto new_lines = current_prompt_metrics().lines_with_addition(current_buffer_metrics, m_num_columns);
  866. auto shown_lines = num_lines();
  867. if (new_lines < shown_lines)
  868. m_extra_forward_lines = max(shown_lines - new_lines, m_extra_forward_lines);
  869. VT::move_relative(-m_extra_forward_lines, m_pending_chars.size() - m_chars_inserted_in_the_middle);
  870. auto current_line = cursor_line();
  871. // There's a newline at the top, don't clear that line.
  872. if (current_prompt_metrics().line_lengths.first() == 0)
  873. --current_line;
  874. VT::clear_lines(current_line - 1, num_lines() - current_line + m_extra_forward_lines);
  875. m_extra_forward_lines = 0;
  876. reposition_cursor();
  877. };
  878. void Editor::refresh_display()
  879. {
  880. auto has_cleaned_up = false;
  881. // Someone changed the window size, figure it out
  882. // and react to it, we might need to redraw.
  883. if (m_was_resized) {
  884. if (m_previous_num_columns != m_num_columns) {
  885. // We need to cleanup and redo everything.
  886. m_cached_prompt_valid = false;
  887. m_refresh_needed = true;
  888. swap(m_previous_num_columns, m_num_columns);
  889. recalculate_origin();
  890. cleanup();
  891. swap(m_previous_num_columns, m_num_columns);
  892. has_cleaned_up = true;
  893. }
  894. m_was_resized = false;
  895. }
  896. // We might be at the last line, and have more than one line;
  897. // Refreshing the display will cause the terminal to scroll,
  898. // so note that fact and bring origin up.
  899. auto current_num_lines = num_lines();
  900. if (m_origin_row + current_num_lines > m_num_lines + 1) {
  901. if (current_num_lines > m_num_lines)
  902. m_origin_row = 0;
  903. else
  904. m_origin_row = m_num_lines - current_num_lines + 1;
  905. }
  906. // Do not call hook on pure cursor movement.
  907. if (m_cached_prompt_valid && !m_refresh_needed && m_pending_chars.size() == 0) {
  908. // Probably just moving around.
  909. reposition_cursor();
  910. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  911. return;
  912. }
  913. if (on_display_refresh)
  914. on_display_refresh(*this);
  915. if (m_cached_prompt_valid) {
  916. if (!m_refresh_needed && m_cursor == m_buffer.size()) {
  917. // Just write the characters out and continue,
  918. // no need to refresh the entire line.
  919. char null = 0;
  920. m_pending_chars.append(&null, 1);
  921. fputs((char*)m_pending_chars.data(), stderr);
  922. m_pending_chars.clear();
  923. m_drawn_cursor = m_cursor;
  924. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  925. fflush(stderr);
  926. return;
  927. }
  928. }
  929. // Ouch, reflow entire line.
  930. if (!has_cleaned_up) {
  931. cleanup();
  932. }
  933. VT::move_absolute(m_origin_row, m_origin_column);
  934. fputs(m_new_prompt.characters(), stderr);
  935. VT::clear_to_end_of_line();
  936. HashMap<u32, Style> empty_styles {};
  937. StringBuilder builder;
  938. for (size_t i = 0; i < m_buffer.size(); ++i) {
  939. auto ends = m_spans_ending.get(i).value_or(empty_styles);
  940. auto starts = m_spans_starting.get(i).value_or(empty_styles);
  941. auto anchored_ends = m_anchored_spans_ending.get(i).value_or(empty_styles);
  942. auto anchored_starts = m_anchored_spans_starting.get(i).value_or(empty_styles);
  943. if (ends.size() || anchored_ends.size()) {
  944. Style style;
  945. for (auto& applicable_style : ends)
  946. style.unify_with(applicable_style.value);
  947. for (auto& applicable_style : anchored_ends)
  948. style.unify_with(applicable_style.value);
  949. // Disable any style that should be turned off.
  950. VT::apply_style(style, false);
  951. // Reapply styles for overlapping spans that include this one.
  952. style = find_applicable_style(i);
  953. VT::apply_style(style, true);
  954. }
  955. if (starts.size() || anchored_starts.size()) {
  956. Style style;
  957. for (auto& applicable_style : starts)
  958. style.unify_with(applicable_style.value);
  959. for (auto& applicable_style : anchored_starts)
  960. style.unify_with(applicable_style.value);
  961. // Set new styles.
  962. VT::apply_style(style, true);
  963. }
  964. builder.clear();
  965. builder.append(Utf32View { &m_buffer[i], 1 });
  966. fputs(builder.to_string().characters(), stderr);
  967. }
  968. VT::apply_style(Style::reset_style()); // don't bleed to EOL
  969. m_pending_chars.clear();
  970. m_refresh_needed = false;
  971. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  972. m_chars_inserted_in_the_middle = 0;
  973. if (!m_cached_prompt_valid) {
  974. m_cached_prompt_valid = true;
  975. }
  976. reposition_cursor();
  977. fflush(stderr);
  978. }
  979. void Editor::strip_styles(bool strip_anchored)
  980. {
  981. m_spans_starting.clear();
  982. m_spans_ending.clear();
  983. if (strip_anchored) {
  984. m_anchored_spans_starting.clear();
  985. m_anchored_spans_ending.clear();
  986. }
  987. m_refresh_needed = true;
  988. }
  989. void Editor::reposition_cursor(bool to_end)
  990. {
  991. auto cursor = m_cursor;
  992. auto saved_cursor = m_cursor;
  993. if (to_end)
  994. cursor = m_buffer.size();
  995. m_cursor = cursor;
  996. m_drawn_cursor = cursor;
  997. auto line = cursor_line() - 1;
  998. auto column = offset_in_line();
  999. VT::move_absolute(line + m_origin_row, column + m_origin_column);
  1000. m_cursor = saved_cursor;
  1001. }
  1002. void VT::move_absolute(u32 row, u32 col)
  1003. {
  1004. fprintf(stderr, "\033[%d;%dH", row, col);
  1005. fflush(stderr);
  1006. }
  1007. void VT::move_relative(int row, int col)
  1008. {
  1009. char x_op = 'A', y_op = 'D';
  1010. if (row > 0)
  1011. x_op = 'B';
  1012. else
  1013. row = -row;
  1014. if (col > 0)
  1015. y_op = 'C';
  1016. else
  1017. col = -col;
  1018. if (row > 0)
  1019. fprintf(stderr, "\033[%d%c", row, x_op);
  1020. if (col > 0)
  1021. fprintf(stderr, "\033[%d%c", col, y_op);
  1022. }
  1023. Style Editor::find_applicable_style(size_t offset) const
  1024. {
  1025. // Walk through our styles and merge all that fit in the offset.
  1026. auto style = Style::reset_style();
  1027. auto unify = [&](auto& entry) {
  1028. if (entry.key >= offset)
  1029. return;
  1030. for (auto& style_value : entry.value) {
  1031. if (style_value.key <= offset)
  1032. return;
  1033. style.unify_with(style_value.value, true);
  1034. }
  1035. };
  1036. for (auto& entry : m_spans_starting) {
  1037. unify(entry);
  1038. }
  1039. for (auto& entry : m_anchored_spans_starting) {
  1040. unify(entry);
  1041. }
  1042. return style;
  1043. }
  1044. String Style::Background::to_vt_escape() const
  1045. {
  1046. if (is_default())
  1047. return "";
  1048. if (m_is_rgb) {
  1049. return String::format("\033[48;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1050. } else {
  1051. return String::format("\033[%dm", (u8)m_xterm_color + 40);
  1052. }
  1053. }
  1054. String Style::Foreground::to_vt_escape() const
  1055. {
  1056. if (is_default())
  1057. return "";
  1058. if (m_is_rgb) {
  1059. return String::format("\033[38;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1060. } else {
  1061. return String::format("\033[%dm", (u8)m_xterm_color + 30);
  1062. }
  1063. }
  1064. String Style::Hyperlink::to_vt_escape(bool starting) const
  1065. {
  1066. if (is_empty())
  1067. return "";
  1068. return String::format("\033]8;;%s\033\\", starting ? m_link.characters() : "");
  1069. }
  1070. void Style::unify_with(const Style& other, bool prefer_other)
  1071. {
  1072. // Unify colors.
  1073. if (prefer_other || m_background.is_default())
  1074. m_background = other.background();
  1075. if (prefer_other || m_foreground.is_default())
  1076. m_foreground = other.foreground();
  1077. // Unify graphic renditions.
  1078. if (other.bold())
  1079. set(Bold);
  1080. if (other.italic())
  1081. set(Italic);
  1082. if (other.underline())
  1083. set(Underline);
  1084. // Unify links.
  1085. if (prefer_other || m_hyperlink.is_empty())
  1086. m_hyperlink = other.hyperlink();
  1087. }
  1088. String Style::to_string() const
  1089. {
  1090. StringBuilder builder;
  1091. builder.append("Style { ");
  1092. if (!m_foreground.is_default()) {
  1093. builder.append("Foreground(");
  1094. if (m_foreground.m_is_rgb) {
  1095. builder.join(", ", m_foreground.m_rgb_color);
  1096. } else {
  1097. builder.appendf("(XtermColor) %d", m_foreground.m_xterm_color);
  1098. }
  1099. builder.append("), ");
  1100. }
  1101. if (!m_background.is_default()) {
  1102. builder.append("Background(");
  1103. if (m_background.m_is_rgb) {
  1104. builder.join(' ', m_background.m_rgb_color);
  1105. } else {
  1106. builder.appendf("(XtermColor) %d", m_background.m_xterm_color);
  1107. }
  1108. builder.append("), ");
  1109. }
  1110. if (bold())
  1111. builder.append("Bold, ");
  1112. if (underline())
  1113. builder.append("Underline, ");
  1114. if (italic())
  1115. builder.append("Italic, ");
  1116. if (!m_hyperlink.is_empty())
  1117. builder.appendf("Hyperlink(\"%s\"), ", m_hyperlink.m_link.characters());
  1118. builder.append("}");
  1119. return builder.build();
  1120. }
  1121. void VT::apply_style(const Style& style, bool is_starting)
  1122. {
  1123. if (is_starting) {
  1124. fprintf(stderr,
  1125. "\033[%d;%d;%dm%s%s%s",
  1126. style.bold() ? 1 : 22,
  1127. style.underline() ? 4 : 24,
  1128. style.italic() ? 3 : 23,
  1129. style.background().to_vt_escape().characters(),
  1130. style.foreground().to_vt_escape().characters(),
  1131. style.hyperlink().to_vt_escape(true).characters());
  1132. } else {
  1133. fprintf(stderr, "%s", style.hyperlink().to_vt_escape(false).characters());
  1134. }
  1135. }
  1136. void VT::clear_lines(size_t count_above, size_t count_below)
  1137. {
  1138. // Go down count_below lines.
  1139. if (count_below > 0)
  1140. fprintf(stderr, "\033[%dB", (int)count_below);
  1141. // Then clear lines going upwards.
  1142. for (size_t i = count_below + count_above; i > 0; --i)
  1143. fputs(i == 1 ? "\033[2K" : "\033[2K\033[A", stderr);
  1144. }
  1145. void VT::save_cursor()
  1146. {
  1147. fputs("\033[s", stderr);
  1148. fflush(stderr);
  1149. }
  1150. void VT::restore_cursor()
  1151. {
  1152. fputs("\033[u", stderr);
  1153. fflush(stderr);
  1154. }
  1155. void VT::clear_to_end_of_line()
  1156. {
  1157. fputs("\033[K", stderr);
  1158. fflush(stderr);
  1159. }
  1160. StringMetrics Editor::actual_rendered_string_metrics(const StringView& string)
  1161. {
  1162. size_t length { 0 };
  1163. StringMetrics metrics;
  1164. VTState state { Free };
  1165. Utf8View view { string };
  1166. auto it = view.begin();
  1167. for (; it != view.end(); ++it) {
  1168. auto c = *it;
  1169. auto it_copy = it;
  1170. ++it_copy;
  1171. auto next_c = it_copy == view.end() ? 0 : *it_copy;
  1172. state = actual_rendered_string_length_step(metrics, length, c, next_c, state);
  1173. }
  1174. metrics.line_lengths.append(length);
  1175. for (auto& line : metrics.line_lengths)
  1176. metrics.max_line_length = max(line, metrics.max_line_length);
  1177. return metrics;
  1178. }
  1179. StringMetrics Editor::actual_rendered_string_metrics(const Utf32View& view)
  1180. {
  1181. size_t length { 0 };
  1182. StringMetrics metrics;
  1183. VTState state { Free };
  1184. for (size_t i = 0; i < view.length(); ++i) {
  1185. auto c = view.code_points()[i];
  1186. auto next_c = i + 1 < view.length() ? view.code_points()[i + 1] : 0;
  1187. state = actual_rendered_string_length_step(metrics, length, c, next_c, state);
  1188. }
  1189. metrics.line_lengths.append(length);
  1190. for (auto& line : metrics.line_lengths)
  1191. metrics.max_line_length = max(line, metrics.max_line_length);
  1192. return metrics;
  1193. }
  1194. Editor::VTState Editor::actual_rendered_string_length_step(StringMetrics& metrics, size_t& length, u32 c, u32 next_c, VTState state)
  1195. {
  1196. switch (state) {
  1197. case Free:
  1198. if (c == '\x1b') { // escape
  1199. return Escape;
  1200. }
  1201. if (c == '\r') { // carriage return
  1202. length = 0;
  1203. if (!metrics.line_lengths.is_empty())
  1204. metrics.line_lengths.last() = 0;
  1205. return state;
  1206. }
  1207. if (c == '\n') { // return
  1208. metrics.line_lengths.append(length);
  1209. length = 0;
  1210. return state;
  1211. }
  1212. // FIXME: This will not support anything sophisticated
  1213. ++length;
  1214. ++metrics.total_length;
  1215. return state;
  1216. case Escape:
  1217. if (c == ']') {
  1218. if (next_c == '0')
  1219. state = Title;
  1220. return state;
  1221. }
  1222. if (c == '[') {
  1223. return Bracket;
  1224. }
  1225. // FIXME: This does not support non-VT (aside from set-title) escapes
  1226. return state;
  1227. case Bracket:
  1228. if (isdigit(c)) {
  1229. return BracketArgsSemi;
  1230. }
  1231. return state;
  1232. case BracketArgsSemi:
  1233. if (c == ';') {
  1234. return Bracket;
  1235. }
  1236. if (!isdigit(c))
  1237. state = Free;
  1238. return state;
  1239. case Title:
  1240. if (c == 7)
  1241. state = Free;
  1242. return state;
  1243. }
  1244. return state;
  1245. }
  1246. Vector<size_t, 2> Editor::vt_dsr()
  1247. {
  1248. char buf[16];
  1249. u32 length { 0 };
  1250. // Read whatever junk there is before talking to the terminal
  1251. // and insert them later when we're reading user input.
  1252. bool more_junk_to_read { false };
  1253. timeval timeout { 0, 0 };
  1254. fd_set readfds;
  1255. FD_ZERO(&readfds);
  1256. FD_SET(0, &readfds);
  1257. do {
  1258. more_junk_to_read = false;
  1259. (void)select(1, &readfds, nullptr, nullptr, &timeout);
  1260. if (FD_ISSET(0, &readfds)) {
  1261. auto nread = read(0, buf, 16);
  1262. if (nread < 0) {
  1263. m_input_error = Error::ReadFailure;
  1264. finish();
  1265. break;
  1266. }
  1267. if (nread == 0)
  1268. break;
  1269. m_incomplete_data.append(buf, nread);
  1270. more_junk_to_read = true;
  1271. }
  1272. } while (more_junk_to_read);
  1273. if (m_input_error.has_value())
  1274. return { 1, 1 };
  1275. fputs("\033[6n", stderr);
  1276. fflush(stderr);
  1277. do {
  1278. auto nread = read(0, buf + length, 16 - length);
  1279. if (nread < 0) {
  1280. if (errno == 0) {
  1281. // ????
  1282. continue;
  1283. }
  1284. dbg() << "Error while reading DSR: " << strerror(errno);
  1285. m_input_error = Error::ReadFailure;
  1286. finish();
  1287. return { 1, 1 };
  1288. }
  1289. if (nread == 0) {
  1290. m_input_error = Error::Empty;
  1291. finish();
  1292. dbg() << "Terminal DSR issue; received no response";
  1293. return { 1, 1 };
  1294. }
  1295. length += nread;
  1296. } while (buf[length - 1] != 'R' && length < 16);
  1297. size_t row { 1 }, col { 1 };
  1298. if (buf[0] == '\033' && buf[1] == '[') {
  1299. auto parts = StringView(buf + 2, length - 3).split_view(';');
  1300. auto row_opt = parts[0].to_int();
  1301. if (!row_opt.has_value()) {
  1302. dbg() << "Terminal DSR issue; received garbage row";
  1303. } else {
  1304. row = row_opt.value();
  1305. }
  1306. auto col_opt = parts[1].to_int();
  1307. if (!col_opt.has_value()) {
  1308. dbg() << "Terminal DSR issue; received garbage col";
  1309. } else {
  1310. col = col_opt.value();
  1311. }
  1312. }
  1313. return { row, col };
  1314. }
  1315. String Editor::line(size_t up_to_index) const
  1316. {
  1317. StringBuilder builder;
  1318. builder.append(Utf32View { m_buffer.data(), min(m_buffer.size(), up_to_index) });
  1319. return builder.build();
  1320. }
  1321. void Editor::remove_at_index(size_t index)
  1322. {
  1323. // See if we have any anchored styles, and reposition them if needed.
  1324. readjust_anchored_styles(index, ModificationKind::Removal);
  1325. auto cp = m_buffer[index];
  1326. m_buffer.remove(index);
  1327. if (cp == '\n')
  1328. ++m_extra_forward_lines;
  1329. }
  1330. void Editor::readjust_anchored_styles(size_t hint_index, ModificationKind modification)
  1331. {
  1332. struct Anchor {
  1333. Span old_span;
  1334. Span new_span;
  1335. Style style;
  1336. };
  1337. Vector<Anchor> anchors_to_relocate;
  1338. auto index_shift = modification == ModificationKind::Insertion ? 1 : -1;
  1339. auto forced_removal = modification == ModificationKind::ForcedOverlapRemoval;
  1340. for (auto& start_entry : m_anchored_spans_starting) {
  1341. for (auto& end_entry : start_entry.value) {
  1342. if (forced_removal) {
  1343. if (start_entry.key <= hint_index && end_entry.key > hint_index) {
  1344. // Remove any overlapping regions.
  1345. continue;
  1346. }
  1347. }
  1348. if (start_entry.key >= hint_index) {
  1349. if (start_entry.key == hint_index && end_entry.key == hint_index + 1 && modification == ModificationKind::Removal) {
  1350. // Remove the anchor, as all its text was wiped.
  1351. continue;
  1352. }
  1353. // Shift everything.
  1354. 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 });
  1355. continue;
  1356. }
  1357. if (end_entry.key > hint_index) {
  1358. // Shift just the end.
  1359. 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 });
  1360. continue;
  1361. }
  1362. 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 });
  1363. }
  1364. }
  1365. m_anchored_spans_ending.clear();
  1366. m_anchored_spans_starting.clear();
  1367. // Pass over the relocations and update the stale entries.
  1368. for (auto& relocation : anchors_to_relocate) {
  1369. stylize(relocation.new_span, relocation.style);
  1370. }
  1371. }
  1372. size_t StringMetrics::lines_with_addition(const StringMetrics& offset, size_t column_width) const
  1373. {
  1374. size_t lines = 0;
  1375. for (size_t i = 0; i < line_lengths.size() - 1; ++i)
  1376. lines += (line_lengths[i] + column_width) / column_width;
  1377. auto last = line_lengths.last();
  1378. last += offset.line_lengths.first();
  1379. lines += (last + column_width) / column_width;
  1380. for (size_t i = 1; i < offset.line_lengths.size(); ++i)
  1381. lines += (offset.line_lengths[i] + column_width) / column_width;
  1382. return lines;
  1383. }
  1384. }