Editor.cpp 59 KB

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