Editor.cpp 50 KB

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