Editor.cpp 50 KB

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