Editor.cpp 47 KB

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