Editor.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  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/StringBuilder.h>
  28. #include <AK/Utf32View.h>
  29. #include <AK/Utf8View.h>
  30. #include <ctype.h>
  31. #include <stdio.h>
  32. #include <sys/ioctl.h>
  33. #include <sys/select.h>
  34. #include <sys/time.h>
  35. #include <unistd.h>
  36. namespace Line {
  37. Editor::Editor(Configuration configuration)
  38. : m_configuration(move(configuration))
  39. {
  40. m_always_refresh = configuration.refresh_behaviour == Configuration::RefreshBehaviour::Eager;
  41. m_pending_chars = ByteBuffer::create_uninitialized(0);
  42. struct winsize ws;
  43. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0) {
  44. m_num_columns = 80;
  45. m_num_lines = 25;
  46. } else {
  47. m_num_columns = ws.ws_col;
  48. m_num_lines = ws.ws_row;
  49. }
  50. }
  51. Editor::~Editor()
  52. {
  53. if (m_initialized)
  54. restore();
  55. }
  56. void Editor::add_to_history(const String& line)
  57. {
  58. if ((m_history.size() + 1) > m_history_capacity)
  59. m_history.take_first();
  60. m_history.append(line);
  61. }
  62. void Editor::clear_line()
  63. {
  64. for (size_t i = 0; i < m_cursor; ++i)
  65. fputc(0x8, stdout);
  66. fputs("\033[K", stdout);
  67. fflush(stdout);
  68. m_buffer.clear();
  69. m_cursor = 0;
  70. m_inline_search_cursor = m_cursor;
  71. }
  72. void Editor::insert(const String& string)
  73. {
  74. for (auto ch : Utf8View { string })
  75. insert(ch);
  76. }
  77. void Editor::insert(const u32 cp)
  78. {
  79. StringBuilder builder;
  80. builder.append(Utf32View(&cp, 1));
  81. auto str = builder.build();
  82. m_pending_chars.append(str.characters(), str.length());
  83. if (m_cursor == m_buffer.size()) {
  84. m_buffer.append(cp);
  85. m_cursor = m_buffer.size();
  86. m_inline_search_cursor = m_cursor;
  87. return;
  88. }
  89. m_buffer.insert(m_cursor, cp);
  90. ++m_chars_inserted_in_the_middle;
  91. ++m_cursor;
  92. m_inline_search_cursor = m_cursor;
  93. }
  94. void Editor::register_character_input_callback(char ch, Function<bool(Editor&)> callback)
  95. {
  96. if (m_key_callbacks.contains(ch)) {
  97. dbg() << "Key callback registered twice for " << ch;
  98. ASSERT_NOT_REACHED();
  99. }
  100. m_key_callbacks.set(ch, make<KeyCallback>(move(callback)));
  101. }
  102. static size_t codepoint_length_in_utf8(u32 codepoint)
  103. {
  104. if (codepoint <= 0x7f)
  105. return 1;
  106. if (codepoint <= 0x07ff)
  107. return 2;
  108. if (codepoint <= 0xffff)
  109. return 3;
  110. if (codepoint <= 0x10ffff)
  111. return 4;
  112. return 3;
  113. }
  114. void Editor::stylize(const Span& span, const Style& style)
  115. {
  116. auto start = span.beginning();
  117. auto end = span.end();
  118. if (span.mode() == Span::ByteOriented) {
  119. size_t byte_offset = 0;
  120. size_t codepoint_offset = 0;
  121. size_t start_codepoint_offset = 0, end_codepoint_offset = 0;
  122. for (;;) {
  123. if (codepoint_offset >= m_buffer.size())
  124. break;
  125. if (byte_offset > end)
  126. break;
  127. if (byte_offset < start)
  128. ++start_codepoint_offset;
  129. ++end_codepoint_offset;
  130. byte_offset += codepoint_length_in_utf8(m_buffer[codepoint_offset++]);
  131. }
  132. start = start_codepoint_offset;
  133. end = end_codepoint_offset;
  134. }
  135. auto starting_map = m_spans_starting.get(start).value_or({});
  136. if (!starting_map.contains(end))
  137. m_refresh_needed = true;
  138. starting_map.set(end, style);
  139. m_spans_starting.set(start, starting_map);
  140. auto ending_map = m_spans_ending.get(end).value_or({});
  141. if (!ending_map.contains(start))
  142. m_refresh_needed = true;
  143. ending_map.set(start, style);
  144. m_spans_ending.set(end, ending_map);
  145. }
  146. String Editor::get_line(const String& prompt)
  147. {
  148. initialize();
  149. m_is_editing = true;
  150. set_prompt(prompt);
  151. reset();
  152. set_origin();
  153. m_history_cursor = m_history.size();
  154. for (;;) {
  155. if (m_always_refresh)
  156. m_refresh_needed = true;
  157. refresh_display();
  158. if (m_finish) {
  159. m_finish = false;
  160. printf("\n");
  161. fflush(stdout);
  162. auto string = line();
  163. m_buffer.clear();
  164. m_is_editing = false;
  165. restore();
  166. return string;
  167. }
  168. char keybuf[16];
  169. ssize_t nread = 0;
  170. if (!m_incomplete_data.size())
  171. nread = read(0, keybuf, sizeof(keybuf));
  172. if (nread < 0) {
  173. if (errno == EINTR) {
  174. if (!m_was_interrupted) {
  175. if (m_was_resized)
  176. continue;
  177. finish();
  178. continue;
  179. }
  180. m_was_interrupted = false;
  181. if (!m_buffer.is_empty())
  182. printf("^C");
  183. m_buffer.clear();
  184. m_cursor = 0;
  185. if (on_interrupt_handled)
  186. on_interrupt_handled();
  187. m_refresh_needed = true;
  188. continue;
  189. }
  190. perror("read failed");
  191. // FIXME: exit()ing here is a bit off. Should communicate failure to caller somehow instead.
  192. exit(2);
  193. }
  194. m_incomplete_data.append(keybuf, nread);
  195. nread = m_incomplete_data.size();
  196. // FIXME: exit()ing here is a bit off. Should communicate failure to caller somehow instead.
  197. if (nread == 0)
  198. exit(0);
  199. auto reverse_tab = false;
  200. auto increment_suggestion_index = [&] {
  201. if (m_suggestions.size())
  202. m_next_suggestion_index = (m_next_suggestion_index + 1) % m_suggestions.size();
  203. else
  204. m_next_suggestion_index = 0;
  205. };
  206. auto decrement_suggestion_index = [&] {
  207. if (m_next_suggestion_index == 0)
  208. m_next_suggestion_index = m_suggestions.size();
  209. m_next_suggestion_index--;
  210. };
  211. auto ctrl_held = false;
  212. // discard starting bytes until they make sense as utf-8
  213. size_t valid_bytes = 0;
  214. while (nread) {
  215. Utf8View { StringView { m_incomplete_data.data(), (size_t)nread } }.validate(valid_bytes);
  216. if (valid_bytes)
  217. break;
  218. m_incomplete_data.take_first();
  219. --nread;
  220. }
  221. Utf8View input_view { StringView { m_incomplete_data.data(), valid_bytes } };
  222. size_t consumed_codepoints = 0;
  223. for (auto codepoint : input_view) {
  224. if (m_finish)
  225. break;
  226. ++consumed_codepoints;
  227. if (codepoint == 0)
  228. continue;
  229. switch (m_state) {
  230. case InputState::ExpectBracket:
  231. if (codepoint == '[') {
  232. m_state = InputState::ExpectFinal;
  233. continue;
  234. } else {
  235. m_state = InputState::Free;
  236. break;
  237. }
  238. case InputState::ExpectFinal:
  239. switch (codepoint) {
  240. case 'O': // mod_ctrl
  241. ctrl_held = true;
  242. continue;
  243. case 'A': // up
  244. {
  245. m_searching_backwards = true;
  246. auto inline_search_cursor = m_inline_search_cursor;
  247. StringBuilder builder;
  248. builder.append(Utf32View { m_buffer.data(), inline_search_cursor });
  249. String search_phrase = builder.to_string();
  250. if (search(search_phrase, true, true)) {
  251. ++m_search_offset;
  252. } else {
  253. insert(search_phrase);
  254. }
  255. m_inline_search_cursor = inline_search_cursor;
  256. m_state = InputState::Free;
  257. ctrl_held = false;
  258. continue;
  259. }
  260. case 'B': // down
  261. {
  262. auto inline_search_cursor = m_inline_search_cursor;
  263. StringBuilder builder;
  264. builder.append(Utf32View { m_buffer.data(), inline_search_cursor });
  265. String search_phrase = builder.to_string();
  266. auto search_changed_directions = m_searching_backwards;
  267. m_searching_backwards = false;
  268. if (m_search_offset > 0) {
  269. m_search_offset -= 1 + search_changed_directions;
  270. if (!search(search_phrase, true, true)) {
  271. insert(search_phrase);
  272. }
  273. } else {
  274. m_search_offset = 0;
  275. m_cursor = 0;
  276. m_buffer.clear();
  277. insert(search_phrase);
  278. m_refresh_needed = true;
  279. }
  280. m_inline_search_cursor = inline_search_cursor;
  281. m_state = InputState::Free;
  282. ctrl_held = false;
  283. continue;
  284. }
  285. case 'D': // left
  286. if (m_cursor > 0) {
  287. if (ctrl_held) {
  288. auto skipped_at_least_one_character = false;
  289. for (;;) {
  290. if (m_cursor == 0)
  291. break;
  292. if (skipped_at_least_one_character && isspace(m_buffer[m_cursor - 1])) // stop *after* a space, but only if it changes the position
  293. break;
  294. skipped_at_least_one_character = true;
  295. --m_cursor;
  296. }
  297. } else {
  298. --m_cursor;
  299. }
  300. }
  301. m_inline_search_cursor = m_cursor;
  302. m_state = InputState::Free;
  303. ctrl_held = false;
  304. continue;
  305. case 'C': // right
  306. if (m_cursor < m_buffer.size()) {
  307. if (ctrl_held) {
  308. // temporarily put a space at the end of our buffer
  309. // this greatly simplifies the logic below
  310. m_buffer.append(' ');
  311. for (;;) {
  312. if (m_cursor >= m_buffer.size())
  313. break;
  314. if (isspace(m_buffer[++m_cursor]))
  315. break;
  316. }
  317. m_buffer.take_last();
  318. } else {
  319. ++m_cursor;
  320. }
  321. }
  322. m_inline_search_cursor = m_cursor;
  323. m_search_offset = 0;
  324. m_state = InputState::Free;
  325. ctrl_held = false;
  326. continue;
  327. case 'H':
  328. m_cursor = 0;
  329. m_inline_search_cursor = m_cursor;
  330. m_search_offset = 0;
  331. m_state = InputState::Free;
  332. ctrl_held = false;
  333. continue;
  334. case 'F':
  335. m_cursor = m_buffer.size();
  336. m_state = InputState::Free;
  337. m_inline_search_cursor = m_cursor;
  338. m_search_offset = 0;
  339. ctrl_held = false;
  340. continue;
  341. case 'Z': // shift+tab
  342. reverse_tab = true;
  343. m_state = InputState::Free;
  344. ctrl_held = false;
  345. break;
  346. case '3':
  347. if (m_cursor == m_buffer.size()) {
  348. fputc('\a', stdout);
  349. fflush(stdout);
  350. continue;
  351. }
  352. m_buffer.remove(m_cursor);
  353. m_refresh_needed = true;
  354. m_search_offset = 0;
  355. m_state = InputState::ExpectTerminator;
  356. ctrl_held = false;
  357. continue;
  358. default:
  359. dbgprintf("Shell: Unhandled final: %02x (%c)\r\n", codepoint, codepoint);
  360. m_state = InputState::Free;
  361. ctrl_held = false;
  362. continue;
  363. }
  364. break;
  365. case InputState::ExpectTerminator:
  366. m_state = InputState::Free;
  367. continue;
  368. case InputState::Free:
  369. if (codepoint == 27) {
  370. m_state = InputState::ExpectBracket;
  371. continue;
  372. }
  373. break;
  374. }
  375. auto cb = m_key_callbacks.get(codepoint);
  376. if (cb.has_value()) {
  377. if (!cb.value()->callback(*this)) {
  378. continue;
  379. }
  380. }
  381. m_search_offset = 0; // reset search offset on any key
  382. if (codepoint == '\t' || reverse_tab) {
  383. if (!on_tab_complete)
  384. continue;
  385. // reverse tab can count as regular tab here
  386. m_times_tab_pressed++;
  387. // ask for completions only on the first tab
  388. // and scan for the largest common prefix to display
  389. // further tabs simply show the cached completions
  390. if (m_times_tab_pressed == 1) {
  391. m_suggestions = on_tab_complete(*this);
  392. size_t common_suggestion_prefix { 0 };
  393. if (m_suggestions.size() == 1) {
  394. m_largest_common_suggestion_prefix_length = m_suggestions[0].text.length();
  395. } else if (m_suggestions.size()) {
  396. char last_valid_suggestion_char;
  397. for (;; ++common_suggestion_prefix) {
  398. if (m_suggestions[0].text.length() <= common_suggestion_prefix)
  399. goto no_more_commons;
  400. last_valid_suggestion_char = m_suggestions[0].text[common_suggestion_prefix];
  401. for (const auto& suggestion : m_suggestions) {
  402. if (suggestion.text.length() <= common_suggestion_prefix || suggestion.text[common_suggestion_prefix] != last_valid_suggestion_char) {
  403. goto no_more_commons;
  404. }
  405. }
  406. }
  407. no_more_commons:;
  408. m_largest_common_suggestion_prefix_length = common_suggestion_prefix;
  409. } else {
  410. m_largest_common_suggestion_prefix_length = 0;
  411. // there are no suggestions, beep~
  412. putchar('\a');
  413. fflush(stdout);
  414. }
  415. m_prompt_lines_at_suggestion_initiation = num_lines();
  416. }
  417. // Adjust already incremented / decremented index when switching tab direction
  418. if (reverse_tab && m_tab_direction != TabDirection::Backward) {
  419. decrement_suggestion_index();
  420. decrement_suggestion_index();
  421. m_tab_direction = TabDirection::Backward;
  422. }
  423. if (!reverse_tab && m_tab_direction != TabDirection::Forward) {
  424. increment_suggestion_index();
  425. increment_suggestion_index();
  426. m_tab_direction = TabDirection::Forward;
  427. }
  428. reverse_tab = false;
  429. auto current_suggestion_index = m_next_suggestion_index;
  430. if (m_next_suggestion_index < m_suggestions.size()) {
  431. auto can_complete = m_next_suggestion_invariant_offset <= m_largest_common_suggestion_prefix_length;
  432. if (!m_last_shown_suggestion.text.is_null()) {
  433. size_t actual_offset;
  434. size_t shown_length = m_last_shown_suggestion_display_length;
  435. switch (m_times_tab_pressed) {
  436. case 1:
  437. actual_offset = m_cursor;
  438. break;
  439. case 2:
  440. actual_offset = m_cursor - m_largest_common_suggestion_prefix_length + m_next_suggestion_invariant_offset;
  441. if (can_complete)
  442. shown_length = m_largest_common_suggestion_prefix_length + m_last_shown_suggestion.trailing_trivia.length();
  443. break;
  444. default:
  445. if (m_last_shown_suggestion_display_length == 0)
  446. actual_offset = m_cursor;
  447. else
  448. actual_offset = m_cursor - m_last_shown_suggestion_display_length + m_next_suggestion_invariant_offset;
  449. break;
  450. }
  451. for (size_t i = m_next_suggestion_invariant_offset; i < shown_length; ++i)
  452. m_buffer.remove(actual_offset);
  453. m_cursor = actual_offset;
  454. m_inline_search_cursor = m_cursor;
  455. m_refresh_needed = true;
  456. }
  457. m_last_shown_suggestion = m_suggestions[m_next_suggestion_index];
  458. m_last_shown_suggestion_display_length = m_last_shown_suggestion.text.length();
  459. m_last_shown_suggestion_was_complete = true;
  460. if (m_times_tab_pressed == 1) {
  461. // This is the first time, so only auto-complete *if possible*
  462. if (can_complete) {
  463. insert(m_last_shown_suggestion.text.substring_view(m_next_suggestion_invariant_offset, m_largest_common_suggestion_prefix_length - m_next_suggestion_invariant_offset));
  464. m_last_shown_suggestion_display_length = m_largest_common_suggestion_prefix_length;
  465. // do not increment the suggestion index, as the first tab should only be a *peek*
  466. if (m_suggestions.size() == 1) {
  467. // if there's one suggestion, commit and forget
  468. m_times_tab_pressed = 0;
  469. // add in the trivia of the last selected suggestion
  470. insert(m_last_shown_suggestion.trailing_trivia);
  471. m_last_shown_suggestion_display_length += m_last_shown_suggestion.trailing_trivia.length();
  472. }
  473. } else {
  474. m_last_shown_suggestion_display_length = 0;
  475. }
  476. ++m_times_tab_pressed;
  477. m_last_shown_suggestion_was_complete = false;
  478. } else {
  479. insert(m_last_shown_suggestion.text.substring_view(m_next_suggestion_invariant_offset, m_last_shown_suggestion.text.length() - m_next_suggestion_invariant_offset));
  480. // add in the trivia of the last selected suggestion
  481. insert(m_last_shown_suggestion.trailing_trivia);
  482. m_last_shown_suggestion_display_length += m_last_shown_suggestion.trailing_trivia.length();
  483. if (m_tab_direction == TabDirection::Forward)
  484. increment_suggestion_index();
  485. else
  486. decrement_suggestion_index();
  487. }
  488. } else {
  489. m_next_suggestion_index = 0;
  490. }
  491. if (m_times_tab_pressed > 1 && !m_suggestions.is_empty()) {
  492. size_t longest_suggestion_length = 0;
  493. size_t start_index = 0;
  494. for (auto& suggestion : m_suggestions) {
  495. if (start_index++ < m_last_displayed_suggestion_index)
  496. continue;
  497. longest_suggestion_length = max(longest_suggestion_length, suggestion.text.length());
  498. }
  499. size_t num_printed = 0;
  500. size_t lines_used { 1 };
  501. size_t index { 0 };
  502. vt_save_cursor();
  503. vt_clear_lines(0, m_lines_used_for_last_suggestions);
  504. vt_restore_cursor();
  505. auto spans_entire_line { false };
  506. auto max_line_count = (m_cached_prompt_length + longest_suggestion_length + m_num_columns - 1) / m_num_columns;
  507. if (longest_suggestion_length >= m_num_columns - 2) {
  508. spans_entire_line = true;
  509. // we should make enough space for the biggest entry in
  510. // the suggestion list to fit in the prompt line
  511. auto start = max_line_count - m_prompt_lines_at_suggestion_initiation;
  512. for (size_t i = start; i < max_line_count; ++i) {
  513. putchar('\n');
  514. }
  515. lines_used += max_line_count;
  516. longest_suggestion_length = 0;
  517. }
  518. vt_move_absolute(max_line_count + m_origin_x, 1);
  519. for (auto& suggestion : m_suggestions) {
  520. if (index < m_last_displayed_suggestion_index) {
  521. ++index;
  522. continue;
  523. }
  524. size_t next_column = num_printed + suggestion.text.length() + longest_suggestion_length + 2;
  525. if (next_column > m_num_columns) {
  526. auto lines = (suggestion.text.length() + m_num_columns - 1) / m_num_columns;
  527. lines_used += lines;
  528. putchar('\n');
  529. num_printed = 0;
  530. }
  531. // show just enough suggestions to fill up the screen
  532. // without moving the prompt out of view
  533. if (lines_used + m_prompt_lines_at_suggestion_initiation >= m_num_lines)
  534. break;
  535. // only apply colour to the selection if something is *actually* added to the buffer
  536. if (m_last_shown_suggestion_was_complete && index == current_suggestion_index) {
  537. vt_apply_style({ Style::Foreground(Style::XtermColor::Blue) });
  538. fflush(stdout);
  539. }
  540. if (spans_entire_line) {
  541. num_printed += m_num_columns;
  542. fprintf(stderr, "%s", suggestion.text.characters());
  543. } else {
  544. num_printed += fprintf(stderr, "%-*s", static_cast<int>(longest_suggestion_length) + 2, suggestion.text.characters());
  545. }
  546. if (m_last_shown_suggestion_was_complete && index == current_suggestion_index) {
  547. vt_apply_style({});
  548. fflush(stdout);
  549. }
  550. ++index;
  551. }
  552. m_lines_used_for_last_suggestions = lines_used;
  553. // if we filled the screen, move back the origin
  554. if (m_origin_x + lines_used >= m_num_lines) {
  555. m_origin_x = m_num_lines - lines_used;
  556. }
  557. --index;
  558. // cycle pages of suggestions
  559. if (index == current_suggestion_index)
  560. m_last_displayed_suggestion_index = index;
  561. if (m_last_displayed_suggestion_index >= m_suggestions.size() - 1)
  562. m_last_displayed_suggestion_index = 0;
  563. }
  564. if (m_suggestions.size() < 2) {
  565. // we have none, or just one suggestion
  566. // we should just commit that and continue
  567. // after it, as if it were auto-completed
  568. suggest(0, 0);
  569. m_last_shown_suggestion = String::empty();
  570. m_last_shown_suggestion_display_length = 0;
  571. m_suggestions.clear();
  572. m_times_tab_pressed = 0;
  573. m_last_displayed_suggestion_index = 0;
  574. }
  575. continue;
  576. }
  577. if (m_times_tab_pressed) {
  578. // we probably have some suggestions drawn
  579. // let's clean them up
  580. if (m_lines_used_for_last_suggestions) {
  581. vt_clear_lines(0, m_lines_used_for_last_suggestions);
  582. reposition_cursor();
  583. m_refresh_needed = true;
  584. m_lines_used_for_last_suggestions = 0;
  585. }
  586. m_last_shown_suggestion_display_length = 0;
  587. m_last_shown_suggestion = String::empty();
  588. m_last_displayed_suggestion_index = 0;
  589. m_suggestions.clear();
  590. suggest(0, 0);
  591. }
  592. m_times_tab_pressed = 0; // Safe to say if we get here, the user didn't press TAB
  593. auto do_backspace = [&] {
  594. if (m_is_searching) {
  595. return;
  596. }
  597. if (m_cursor == 0) {
  598. fputc('\a', stdout);
  599. fflush(stdout);
  600. return;
  601. }
  602. m_buffer.remove(m_cursor - 1);
  603. --m_cursor;
  604. m_inline_search_cursor = m_cursor;
  605. // we will have to redraw :(
  606. m_refresh_needed = true;
  607. };
  608. if (codepoint == 8 || codepoint == m_termios.c_cc[VERASE]) {
  609. do_backspace();
  610. continue;
  611. }
  612. if (codepoint == m_termios.c_cc[VWERASE]) {
  613. bool has_seen_nonspace = false;
  614. while (m_cursor > 0) {
  615. if (isspace(m_buffer[m_cursor - 1])) {
  616. if (has_seen_nonspace)
  617. break;
  618. } else {
  619. has_seen_nonspace = true;
  620. }
  621. do_backspace();
  622. }
  623. continue;
  624. }
  625. if (codepoint == m_termios.c_cc[VKILL]) {
  626. for (size_t i = 0; i < m_cursor; ++i)
  627. m_buffer.remove(0);
  628. m_cursor = 0;
  629. m_refresh_needed = true;
  630. continue;
  631. }
  632. // ^L
  633. if (codepoint == 0xc) {
  634. printf("\033[3J\033[H\033[2J"); // Clear screen.
  635. vt_move_absolute(1, 1);
  636. m_origin_x = 1;
  637. m_origin_y = 1;
  638. m_refresh_needed = true;
  639. continue;
  640. }
  641. // ^A
  642. if (codepoint == 0x01) {
  643. m_cursor = 0;
  644. continue;
  645. }
  646. // ^R
  647. if (codepoint == 0x12) {
  648. if (m_is_searching) {
  649. // how did we get here?
  650. ASSERT_NOT_REACHED();
  651. } else {
  652. m_is_searching = true;
  653. m_search_offset = 0;
  654. m_pre_search_buffer.clear();
  655. for (auto codepoint : m_buffer)
  656. m_pre_search_buffer.append(codepoint);
  657. m_pre_search_cursor = m_cursor;
  658. m_search_editor = make<Editor>(Configuration { Configuration::Eager, m_configuration.split_mechanism }); // Has anyone seen 'Inception'?
  659. m_search_editor->on_display_refresh = [this](Editor& search_editor) {
  660. StringBuilder builder;
  661. builder.append(Utf32View { search_editor.buffer().data(), search_editor.buffer().size() });
  662. search(builder.build());
  663. refresh_display();
  664. return;
  665. };
  666. // whenever the search editor gets a ^R, cycle between history entries
  667. m_search_editor->register_character_input_callback(0x12, [this](Editor& search_editor) {
  668. ++m_search_offset;
  669. search_editor.m_refresh_needed = true;
  670. return false; // Do not process this key event
  671. });
  672. // whenever the search editor gets a backspace, cycle back between history entries
  673. // unless we're at the zeroth entry, in which case, allow the deletion
  674. m_search_editor->register_character_input_callback(m_termios.c_cc[VERASE], [this](Editor& search_editor) {
  675. if (m_search_offset > 0) {
  676. --m_search_offset;
  677. search_editor.m_refresh_needed = true;
  678. return false; // Do not process this key event
  679. }
  680. return true;
  681. });
  682. // ^L - This is a source of issues, as the search editor refreshes first,
  683. // and we end up with the wrong order of prompts, so we will first refresh
  684. // ourselves, then refresh the search editor, and then tell him not to process
  685. // this event
  686. m_search_editor->register_character_input_callback(0x0c, [this](auto& search_editor) {
  687. printf("\033[3J\033[H\033[2J"); // Clear screen.
  688. // refresh our own prompt
  689. m_origin_x = 1;
  690. m_origin_y = 1;
  691. m_refresh_needed = true;
  692. refresh_display();
  693. // move the search prompt below ours
  694. // and tell it to redraw itself
  695. search_editor.m_origin_x = 2;
  696. search_editor.m_origin_y = 1;
  697. search_editor.m_refresh_needed = true;
  698. return false;
  699. });
  700. // quit without clearing the current buffer
  701. m_search_editor->register_character_input_callback('\t', [this](Editor& search_editor) {
  702. search_editor.finish();
  703. m_reset_buffer_on_search_end = false;
  704. return false;
  705. });
  706. printf("\n");
  707. fflush(stdout);
  708. auto search_prompt = "\x1b[32msearch:\x1b[0m ";
  709. auto search_string = m_search_editor->get_line(search_prompt);
  710. m_search_editor = nullptr;
  711. m_is_searching = false;
  712. m_search_offset = 0;
  713. // manually cleanup the search line
  714. reposition_cursor();
  715. vt_clear_lines(0, (search_string.length() + actual_rendered_string_length(search_prompt) + m_num_columns - 1) / m_num_columns);
  716. reposition_cursor();
  717. if (!m_reset_buffer_on_search_end || search_string.length() == 0) {
  718. // if the entry was empty, or we purposely quit without a newline,
  719. // do not return anything
  720. // instead, just end the search
  721. end_search();
  722. continue;
  723. }
  724. // return the string
  725. finish();
  726. continue;
  727. }
  728. continue;
  729. }
  730. // Normally ^D
  731. if (codepoint == m_termios.c_cc[VEOF]) {
  732. if (m_buffer.is_empty()) {
  733. printf("<EOF>\n");
  734. if (!m_always_refresh) // this is a little off, but it'll do for now
  735. exit(0);
  736. }
  737. continue;
  738. }
  739. // ^E
  740. if (codepoint == 0x05) {
  741. m_cursor = m_buffer.size();
  742. continue;
  743. }
  744. if (codepoint == '\n') {
  745. finish();
  746. continue;
  747. }
  748. insert(codepoint);
  749. }
  750. if (consumed_codepoints == m_incomplete_data.size()) {
  751. m_incomplete_data.clear();
  752. } else {
  753. for (size_t i = 0; i < consumed_codepoints; ++i)
  754. m_incomplete_data.take_first();
  755. }
  756. }
  757. }
  758. bool Editor::search(const StringView& phrase, bool allow_empty, bool from_beginning)
  759. {
  760. int last_matching_offset = -1;
  761. // do not search for empty strings
  762. if (allow_empty || phrase.length() > 0) {
  763. size_t search_offset = m_search_offset;
  764. for (size_t i = m_history_cursor; i > 0; --i) {
  765. auto contains = from_beginning ? m_history[i - 1].starts_with(phrase) : m_history[i - 1].contains(phrase);
  766. if (contains) {
  767. last_matching_offset = i - 1;
  768. if (search_offset == 0)
  769. break;
  770. --search_offset;
  771. }
  772. }
  773. if (last_matching_offset == -1) {
  774. fputc('\a', stdout);
  775. fflush(stdout);
  776. }
  777. }
  778. m_buffer.clear();
  779. m_cursor = 0;
  780. if (last_matching_offset >= 0) {
  781. insert(m_history[last_matching_offset]);
  782. }
  783. // always needed
  784. m_refresh_needed = true;
  785. return last_matching_offset >= 0;
  786. }
  787. void Editor::recalculate_origin()
  788. {
  789. // changing the columns can affect our origin if
  790. // the new size is smaller than our prompt, which would
  791. // cause said prompt to take up more space, so we should
  792. // compensate for that
  793. if (m_cached_prompt_length >= m_num_columns) {
  794. auto added_lines = (m_cached_prompt_length + 1) / m_num_columns - 1;
  795. m_origin_x += added_lines;
  796. }
  797. // we also need to recalculate our cursor position
  798. // but that will be calculated and applied at the next
  799. // refresh cycle
  800. }
  801. void Editor::cleanup()
  802. {
  803. vt_move_relative(0, m_pending_chars.size() - m_chars_inserted_in_the_middle);
  804. auto current_line = cursor_line();
  805. vt_clear_lines(current_line - 1, num_lines() - current_line);
  806. vt_move_relative(-num_lines() + 1, -offset_in_line() - m_old_prompt_length - m_pending_chars.size() + m_chars_inserted_in_the_middle);
  807. };
  808. void Editor::refresh_display()
  809. {
  810. auto has_cleaned_up = false;
  811. // someone changed the window size, figure it out
  812. // and react to it, we might need to redraw
  813. if (m_was_resized) {
  814. auto previous_num_columns = m_num_columns;
  815. struct winsize ws;
  816. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0) {
  817. m_num_columns = 80;
  818. m_num_lines = 25;
  819. } else {
  820. m_num_columns = ws.ws_col;
  821. m_num_lines = ws.ws_row;
  822. }
  823. if (previous_num_columns != m_num_columns) {
  824. // we need to cleanup and redo everything
  825. m_cached_prompt_valid = false;
  826. m_refresh_needed = true;
  827. swap(previous_num_columns, m_num_columns);
  828. recalculate_origin();
  829. cleanup();
  830. swap(previous_num_columns, m_num_columns);
  831. has_cleaned_up = true;
  832. }
  833. }
  834. // do not call hook on pure cursor movement
  835. if (m_cached_prompt_valid && !m_refresh_needed && m_pending_chars.size() == 0) {
  836. // probably just moving around
  837. reposition_cursor();
  838. m_cached_buffer_size = m_buffer.size();
  839. return;
  840. }
  841. if (on_display_refresh)
  842. on_display_refresh(*this);
  843. if (m_cached_prompt_valid) {
  844. if (!m_refresh_needed && m_cursor == m_buffer.size()) {
  845. // just write the characters out and continue
  846. // no need to refresh the entire line
  847. char null = 0;
  848. m_pending_chars.append(&null, 1);
  849. fputs((char*)m_pending_chars.data(), stdout);
  850. m_pending_chars.clear();
  851. m_drawn_cursor = m_cursor;
  852. m_cached_buffer_size = m_buffer.size();
  853. fflush(stdout);
  854. return;
  855. }
  856. }
  857. // ouch, reflow entire line
  858. // FIXME: handle multiline stuff
  859. if (!has_cleaned_up) {
  860. cleanup();
  861. }
  862. vt_move_absolute(m_origin_x, m_origin_y);
  863. fputs(m_new_prompt.characters(), stdout);
  864. vt_clear_to_end_of_line();
  865. HashMap<u32, Style> empty_styles {};
  866. StringBuilder builder;
  867. for (size_t i = 0; i < m_buffer.size(); ++i) {
  868. auto ends = m_spans_ending.get(i).value_or(empty_styles);
  869. auto starts = m_spans_starting.get(i).value_or(empty_styles);
  870. if (ends.size()) {
  871. // go back to defaults
  872. vt_apply_style(find_applicable_style(i));
  873. }
  874. if (starts.size()) {
  875. // set new options
  876. vt_apply_style(starts.begin()->value); // apply some random style that starts here
  877. }
  878. builder.clear();
  879. builder.append(Utf32View { &m_buffer[i], 1 });
  880. fputs(builder.to_string().characters(), stdout);
  881. }
  882. vt_apply_style({}); // don't bleed to EOL
  883. m_pending_chars.clear();
  884. m_refresh_needed = false;
  885. m_cached_buffer_size = m_buffer.size();
  886. m_chars_inserted_in_the_middle = 0;
  887. if (!m_cached_prompt_valid) {
  888. m_cached_prompt_valid = true;
  889. }
  890. reposition_cursor();
  891. fflush(stdout);
  892. }
  893. void Editor::reposition_cursor()
  894. {
  895. m_drawn_cursor = m_cursor;
  896. auto line = cursor_line() - 1;
  897. auto column = offset_in_line();
  898. vt_move_absolute(line + m_origin_x, column + m_origin_y);
  899. }
  900. void Editor::vt_move_absolute(u32 x, u32 y)
  901. {
  902. printf("\033[%d;%dH", x, y);
  903. fflush(stdout);
  904. }
  905. void Editor::vt_move_relative(int x, int y)
  906. {
  907. char x_op = 'A', y_op = 'D';
  908. if (x > 0)
  909. x_op = 'B';
  910. else
  911. x = -x;
  912. if (y > 0)
  913. y_op = 'C';
  914. else
  915. y = -y;
  916. if (x > 0)
  917. printf("\033[%d%c", x, x_op);
  918. if (y > 0)
  919. printf("\033[%d%c", y, y_op);
  920. }
  921. Style Editor::find_applicable_style(size_t offset) const
  922. {
  923. // walk through our styles and find one that fits in the offset
  924. for (auto& entry : m_spans_starting) {
  925. if (entry.key > offset)
  926. continue;
  927. for (auto& style_value : entry.value) {
  928. if (style_value.key <= offset)
  929. continue;
  930. return style_value.value;
  931. }
  932. }
  933. return {};
  934. }
  935. String Style::Background::to_vt_escape() const
  936. {
  937. if (m_is_rgb) {
  938. return String::format("\033[48;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  939. } else {
  940. return String::format("\033[%dm", (u8)m_xterm_color + 40);
  941. }
  942. }
  943. String Style::Foreground::to_vt_escape() const
  944. {
  945. if (m_is_rgb) {
  946. return String::format("\033[38;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  947. } else {
  948. return String::format("\033[%dm", (u8)m_xterm_color + 30);
  949. }
  950. }
  951. void Editor::vt_apply_style(const Style& style)
  952. {
  953. printf(
  954. "\033[%d;%d;%dm%s%s",
  955. style.bold() ? 1 : 22,
  956. style.underline() ? 4 : 24,
  957. style.italic() ? 3 : 23,
  958. style.background().to_vt_escape().characters(),
  959. style.foreground().to_vt_escape().characters());
  960. }
  961. void Editor::vt_clear_lines(size_t count_above, size_t count_below)
  962. {
  963. // go down count_below lines
  964. if (count_below > 0)
  965. printf("\033[%dB", (int)count_below);
  966. // then clear lines going upwards
  967. for (size_t i = count_below + count_above; i > 0; --i)
  968. fputs(i == 1 ? "\033[2K" : "\033[2K\033[A", stdout);
  969. }
  970. void Editor::vt_save_cursor()
  971. {
  972. fputs("\033[s", stdout);
  973. fflush(stdout);
  974. }
  975. void Editor::vt_restore_cursor()
  976. {
  977. fputs("\033[u", stdout);
  978. fflush(stdout);
  979. }
  980. void Editor::vt_clear_to_end_of_line()
  981. {
  982. fputs("\033[K", stdout);
  983. fflush(stdout);
  984. }
  985. size_t Editor::actual_rendered_string_length(const StringView& string) const
  986. {
  987. size_t length { 0 };
  988. enum VTState {
  989. Free = 1,
  990. Escape = 3,
  991. Bracket = 5,
  992. BracketArgsSemi = 7,
  993. Title = 9,
  994. } state { Free };
  995. Utf8View view { string };
  996. auto it = view.begin();
  997. for (size_t i = 0; i < view.length_in_codepoints(); ++i, ++it) {
  998. auto c = *it;
  999. switch (state) {
  1000. case Free:
  1001. if (c == '\x1b') {
  1002. // escape
  1003. state = Escape;
  1004. continue;
  1005. }
  1006. if (c == '\r' || c == '\n') {
  1007. // reset length to 0, since we either overwrite, or are on a newline
  1008. length = 0;
  1009. continue;
  1010. }
  1011. // FIXME: This will not support anything sophisticated
  1012. ++length;
  1013. break;
  1014. case Escape:
  1015. if (c == ']') {
  1016. ++i;
  1017. ++it;
  1018. if (*it == '0')
  1019. state = Title;
  1020. continue;
  1021. }
  1022. if (c == '[') {
  1023. state = Bracket;
  1024. continue;
  1025. }
  1026. // FIXME: This does not support non-VT (aside from set-title) escapes
  1027. break;
  1028. case Bracket:
  1029. if (isdigit(c)) {
  1030. state = BracketArgsSemi;
  1031. continue;
  1032. }
  1033. break;
  1034. case BracketArgsSemi:
  1035. if (c == ';') {
  1036. state = Bracket;
  1037. continue;
  1038. }
  1039. if (!isdigit(c))
  1040. state = Free;
  1041. break;
  1042. case Title:
  1043. if (c == 7)
  1044. state = Free;
  1045. break;
  1046. }
  1047. }
  1048. return length;
  1049. }
  1050. Vector<size_t, 2> Editor::vt_dsr()
  1051. {
  1052. char buf[16];
  1053. u32 length { 0 };
  1054. // read whatever junk there is before talking to the terminal
  1055. // and insert them later when we're reading user input
  1056. bool more_junk_to_read { false };
  1057. timeval timeout { 0, 0 };
  1058. fd_set readfds;
  1059. FD_ZERO(&readfds);
  1060. FD_SET(0, &readfds);
  1061. do {
  1062. more_junk_to_read = false;
  1063. (void)select(1, &readfds, nullptr, nullptr, &timeout);
  1064. if (FD_ISSET(0, &readfds)) {
  1065. auto nread = read(0, buf, 16);
  1066. m_incomplete_data.append(buf, nread);
  1067. more_junk_to_read = true;
  1068. }
  1069. } while (more_junk_to_read);
  1070. fputs("\033[6n", stdout);
  1071. fflush(stdout);
  1072. do {
  1073. auto nread = read(0, buf + length, 16 - length);
  1074. if (nread < 0) {
  1075. if (errno == 0) {
  1076. // ????
  1077. continue;
  1078. }
  1079. dbg() << "Error while reading DSR: " << strerror(errno);
  1080. return { 1, 1 };
  1081. }
  1082. if (nread == 0) {
  1083. dbg() << "Terminal DSR issue; received no response";
  1084. return { 1, 1 };
  1085. }
  1086. length += nread;
  1087. } while (buf[length - 1] != 'R' && length < 16);
  1088. size_t x { 1 }, y { 1 };
  1089. if (buf[0] == '\033' && buf[1] == '[') {
  1090. auto parts = StringView(buf + 2, length - 3).split_view(';');
  1091. bool ok;
  1092. x = parts[0].to_int(ok);
  1093. if (!ok) {
  1094. dbg() << "Terminal DSR issue; received garbage x";
  1095. }
  1096. y = parts[1].to_int(ok);
  1097. if (!ok) {
  1098. dbg() << "Terminal DSR issue; received garbage y";
  1099. }
  1100. }
  1101. return { x, y };
  1102. }
  1103. String Editor::line(size_t up_to_index) const
  1104. {
  1105. StringBuilder builder;
  1106. builder.append(Utf32View { m_buffer.data(), min(m_buffer.size(), up_to_index) });
  1107. return builder.build();
  1108. }
  1109. bool Editor::should_break_token(Vector<u32, 1024>& buffer, size_t index)
  1110. {
  1111. switch (m_configuration.split_mechanism) {
  1112. case Configuration::TokenSplitMechanism::Spaces:
  1113. return buffer[index] == ' ';
  1114. case Configuration::TokenSplitMechanism::UnescapedSpaces:
  1115. return buffer[index] == ' ' && (index == 0 || buffer[index - 1] != '\\');
  1116. }
  1117. ASSERT_NOT_REACHED();
  1118. return true;
  1119. };
  1120. }