Editor.cpp 49 KB

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