Editor.cpp 53 KB

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