Editor.cpp 52 KB

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