Editor.cpp 45 KB

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