Editor.cpp 52 KB

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