Editor.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  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. Vector<u8, 4> csi_parameter_bytes;
  531. Vector<unsigned, 4> csi_parameters;
  532. Vector<u8> csi_intermediate_bytes;
  533. u8 csi_final;
  534. for (auto code_point : input_view) {
  535. if (m_finish)
  536. break;
  537. ++consumed_code_points;
  538. if (code_point == 0)
  539. continue;
  540. switch (m_state) {
  541. case InputState::GotEscape:
  542. switch (code_point) {
  543. case '[':
  544. m_state = InputState::CSIExpectParameter;
  545. continue;
  546. default: {
  547. m_state = InputState::Free;
  548. auto cb = m_key_callbacks.get({ code_point, Key::Alt });
  549. if (cb.has_value()) {
  550. if (!cb.value()->callback(*this)) {
  551. // There's nothing interesting to do here.
  552. }
  553. }
  554. cleanup_suggestions();
  555. continue;
  556. }
  557. }
  558. case InputState::CSIExpectParameter:
  559. if (code_point >= 0x30 && code_point <= 0x3f) { // '0123456789:;<=>?'
  560. csi_parameter_bytes.append(code_point);
  561. continue;
  562. }
  563. m_state = InputState::CSIExpectIntermediate;
  564. [[fallthrough]];
  565. case InputState::CSIExpectIntermediate:
  566. if (code_point >= 0x20 && code_point <= 0x2f) { // ' !"#$%&\'()*+,-./'
  567. csi_intermediate_bytes.append(code_point);
  568. continue;
  569. }
  570. m_state = InputState::CSIExpectFinal;
  571. [[fallthrough]];
  572. case InputState::CSIExpectFinal:
  573. m_state = InputState::Free;
  574. if (!(code_point >= 0x40 && code_point <= 0x7f)) {
  575. dbgprintf("LibLine: Invalid CSI: %02x (%c)\r\n", code_point, code_point);
  576. ctrl_held = false;
  577. continue;
  578. }
  579. csi_final = code_point;
  580. for (auto& parameter : String::copy(csi_parameter_bytes).split(';')) {
  581. if (auto value = parameter.to_uint(); value.has_value())
  582. csi_parameters.append(value.value());
  583. else
  584. csi_parameters.append(0);
  585. }
  586. if (csi_final == 'O') {
  587. // mod_ctrl
  588. ctrl_held = true;
  589. continue;
  590. }
  591. if (csi_final == 'Z') {
  592. // 'reverse tab'
  593. reverse_tab = true;
  594. ctrl_held = false;
  595. break;
  596. }
  597. cleanup_suggestions();
  598. switch (csi_final) {
  599. case 'A': // ^[[A: arrow up
  600. search_backwards();
  601. ctrl_held = false;
  602. continue;
  603. case 'B': // ^[[B: arrow down
  604. search_forwards();
  605. ctrl_held = false;
  606. continue;
  607. case 'D': // ^[[D: arrow left
  608. if (ctrl_held)
  609. cursor_left_word();
  610. else
  611. cursor_left_character();
  612. ctrl_held = false;
  613. continue;
  614. case 'C': // ^[[C: arrow right
  615. if (ctrl_held)
  616. cursor_right_word();
  617. else
  618. cursor_right_character();
  619. ctrl_held = false;
  620. continue;
  621. case 'H': // ^[[H: home
  622. go_home();
  623. ctrl_held = false;
  624. continue;
  625. case 'F': // ^[[F: end
  626. go_end();
  627. ctrl_held = false;
  628. continue;
  629. case '~':
  630. if (csi_parameters.size() == 1 && csi_parameters[0] == 3) { // ^[[3~: delete
  631. erase_character_forwards();
  632. m_search_offset = 0;
  633. ctrl_held = false;
  634. continue;
  635. }
  636. // ^[[5~: page up
  637. // ^[[6~: page down
  638. dbgprintf("LibLine: Unhandled '~'\r\n");
  639. ctrl_held = false;
  640. continue;
  641. default:
  642. dbgprintf("LibLine: Unhandled final: %02x (%c)\r\n", code_point, code_point);
  643. ctrl_held = false;
  644. continue;
  645. }
  646. break;
  647. case InputState::Free:
  648. if (code_point == 27) {
  649. m_state = InputState::GotEscape;
  650. continue;
  651. }
  652. break;
  653. }
  654. // There are no sequences past this point, so short of 'tab', we will want to cleanup the suggestions.
  655. ArmedScopeGuard suggestion_cleanup { [this] { cleanup_suggestions(); } };
  656. // Normally ^D. `stty eof \^n` can change it to ^N (or something else), but Serenity doesn't have `stty` yet.
  657. // Process this here since the keybinds might override its behaviour.
  658. // This only applies when the buffer is empty. at any other time, the behaviour should be configurable.
  659. if (code_point == m_termios.c_cc[VEOF] && m_buffer.size() == 0) {
  660. finish_edit();
  661. continue;
  662. }
  663. auto cb = m_key_callbacks.get(code_point);
  664. if (cb.has_value()) {
  665. if (!cb.value()->callback(*this)) {
  666. continue;
  667. }
  668. }
  669. m_search_offset = 0; // reset search offset on any key
  670. if (code_point == '\t' || reverse_tab) {
  671. suggestion_cleanup.disarm();
  672. if (!on_tab_complete)
  673. continue;
  674. // Reverse tab can count as regular tab here.
  675. m_times_tab_pressed++;
  676. int token_start = m_cursor;
  677. // Ask for completions only on the first tab
  678. // and scan for the largest common prefix to display,
  679. // further tabs simply show the cached completions.
  680. if (m_times_tab_pressed == 1) {
  681. m_suggestion_manager.set_suggestions(on_tab_complete(*this));
  682. m_prompt_lines_at_suggestion_initiation = num_lines();
  683. if (m_suggestion_manager.count() == 0) {
  684. // There are no suggestions, beep.
  685. fputc('\a', stderr);
  686. fflush(stderr);
  687. }
  688. }
  689. // Adjust already incremented / decremented index when switching tab direction.
  690. if (reverse_tab && m_tab_direction != TabDirection::Backward) {
  691. m_suggestion_manager.previous();
  692. m_suggestion_manager.previous();
  693. m_tab_direction = TabDirection::Backward;
  694. }
  695. if (!reverse_tab && m_tab_direction != TabDirection::Forward) {
  696. m_suggestion_manager.next();
  697. m_suggestion_manager.next();
  698. m_tab_direction = TabDirection::Forward;
  699. }
  700. reverse_tab = false;
  701. auto completion_mode = m_times_tab_pressed == 1 ? SuggestionManager::CompletePrefix : m_times_tab_pressed == 2 ? SuggestionManager::ShowSuggestions : SuggestionManager::CycleSuggestions;
  702. auto completion_result = m_suggestion_manager.attempt_completion(completion_mode, token_start);
  703. auto new_cursor = m_cursor + completion_result.new_cursor_offset;
  704. for (size_t i = completion_result.offset_region_to_remove.start; i < completion_result.offset_region_to_remove.end; ++i)
  705. remove_at_index(new_cursor);
  706. m_cursor = new_cursor;
  707. m_inline_search_cursor = new_cursor;
  708. m_refresh_needed = true;
  709. for (auto& view : completion_result.insert)
  710. insert(view);
  711. if (completion_result.style_to_apply.has_value()) {
  712. // Apply the style of the last suggestion.
  713. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  714. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, completion_result.style_to_apply.value());
  715. }
  716. switch (completion_result.new_completion_mode) {
  717. case SuggestionManager::DontComplete:
  718. m_times_tab_pressed = 0;
  719. break;
  720. case SuggestionManager::CompletePrefix:
  721. break;
  722. default:
  723. ++m_times_tab_pressed;
  724. break;
  725. }
  726. if (m_times_tab_pressed > 1) {
  727. if (m_suggestion_manager.count() > 0) {
  728. if (m_suggestion_display->cleanup())
  729. reposition_cursor();
  730. m_suggestion_display->set_initial_prompt_lines(m_prompt_lines_at_suggestion_initiation);
  731. m_suggestion_display->display(m_suggestion_manager);
  732. m_origin_row = m_suggestion_display->origin_row();
  733. }
  734. }
  735. if (m_times_tab_pressed > 2) {
  736. if (m_tab_direction == TabDirection::Forward)
  737. m_suggestion_manager.next();
  738. else
  739. m_suggestion_manager.previous();
  740. }
  741. if (m_suggestion_manager.count() < 2) {
  742. // We have none, or just one suggestion,
  743. // we should just commit that and continue
  744. // after it, as if it were auto-completed.
  745. suggest(0, 0, Span::CodepointOriented);
  746. m_times_tab_pressed = 0;
  747. m_suggestion_manager.reset();
  748. m_suggestion_display->finish();
  749. }
  750. continue;
  751. }
  752. insert(code_point);
  753. }
  754. if (consumed_code_points == m_incomplete_data.size()) {
  755. m_incomplete_data.clear();
  756. } else {
  757. for (size_t i = 0; i < consumed_code_points; ++i)
  758. m_incomplete_data.take_first();
  759. }
  760. }
  761. void Editor::cleanup_suggestions()
  762. {
  763. if (m_times_tab_pressed) {
  764. // Apply the style of the last suggestion.
  765. readjust_anchored_styles(m_suggestion_manager.current_suggestion().start_index, ModificationKind::ForcedOverlapRemoval);
  766. stylize({ m_suggestion_manager.current_suggestion().start_index, m_cursor, Span::Mode::CodepointOriented }, m_suggestion_manager.current_suggestion().style);
  767. // We probably have some suggestions drawn,
  768. // let's clean them up.
  769. if (m_suggestion_display->cleanup()) {
  770. reposition_cursor();
  771. m_refresh_needed = true;
  772. }
  773. m_suggestion_manager.reset();
  774. suggest(0, 0, Span::CodepointOriented);
  775. m_suggestion_display->finish();
  776. }
  777. m_times_tab_pressed = 0; // Safe to say if we get here, the user didn't press TAB
  778. }
  779. bool Editor::search(const StringView& phrase, bool allow_empty, bool from_beginning)
  780. {
  781. int last_matching_offset = -1;
  782. bool found = false;
  783. // Do not search for empty strings.
  784. if (allow_empty || phrase.length() > 0) {
  785. size_t search_offset = m_search_offset;
  786. for (size_t i = m_history_cursor; i > 0; --i) {
  787. auto& entry = m_history[i - 1];
  788. auto contains = from_beginning ? entry.starts_with(phrase) : entry.contains(phrase);
  789. if (contains) {
  790. last_matching_offset = i - 1;
  791. if (search_offset == 0) {
  792. found = true;
  793. break;
  794. }
  795. --search_offset;
  796. }
  797. }
  798. if (!found) {
  799. fputc('\a', stderr);
  800. fflush(stderr);
  801. }
  802. }
  803. if (found) {
  804. m_buffer.clear();
  805. m_cursor = 0;
  806. insert(m_history[last_matching_offset]);
  807. // Always needed, as we have cleared the buffer above.
  808. m_refresh_needed = true;
  809. }
  810. return found;
  811. }
  812. void Editor::recalculate_origin()
  813. {
  814. // Changing the columns can affect our origin if
  815. // the new size is smaller than our prompt, which would
  816. // cause said prompt to take up more space, so we should
  817. // compensate for that.
  818. if (m_cached_prompt_metrics.max_line_length >= m_num_columns) {
  819. auto added_lines = (m_cached_prompt_metrics.max_line_length + 1) / m_num_columns - 1;
  820. m_origin_row += added_lines;
  821. }
  822. // We also need to recalculate our cursor position,
  823. // but that will be calculated and applied at the next
  824. // refresh cycle.
  825. }
  826. void Editor::cleanup()
  827. {
  828. auto current_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  829. auto new_lines = current_prompt_metrics().lines_with_addition(current_buffer_metrics, m_num_columns);
  830. auto shown_lines = num_lines();
  831. if (new_lines < shown_lines)
  832. m_extra_forward_lines = max(shown_lines - new_lines, m_extra_forward_lines);
  833. VT::move_relative(-m_extra_forward_lines, m_pending_chars.size() - m_chars_inserted_in_the_middle);
  834. auto current_line = cursor_line();
  835. // There's a newline at the top, don't clear that line.
  836. if (current_prompt_metrics().line_lengths.first() == 0)
  837. --current_line;
  838. VT::clear_lines(current_line - 1, num_lines() - current_line + m_extra_forward_lines);
  839. m_extra_forward_lines = 0;
  840. reposition_cursor();
  841. };
  842. void Editor::refresh_display()
  843. {
  844. auto has_cleaned_up = false;
  845. // Someone changed the window size, figure it out
  846. // and react to it, we might need to redraw.
  847. if (m_was_resized) {
  848. if (m_previous_num_columns != m_num_columns) {
  849. // We need to cleanup and redo everything.
  850. m_cached_prompt_valid = false;
  851. m_refresh_needed = true;
  852. swap(m_previous_num_columns, m_num_columns);
  853. recalculate_origin();
  854. cleanup();
  855. swap(m_previous_num_columns, m_num_columns);
  856. has_cleaned_up = true;
  857. }
  858. m_was_resized = false;
  859. }
  860. // Do not call hook on pure cursor movement.
  861. if (m_cached_prompt_valid && !m_refresh_needed && m_pending_chars.size() == 0) {
  862. // Probably just moving around.
  863. reposition_cursor();
  864. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  865. return;
  866. }
  867. // We might be at the last line, and have more than one line;
  868. // Refreshing the display will cause the terminal to scroll,
  869. // so note that fact and bring origin up.
  870. auto current_num_lines = num_lines();
  871. if (m_origin_row + current_num_lines > m_num_lines + 1) {
  872. if (current_num_lines > m_num_lines)
  873. m_origin_row = 0;
  874. else
  875. m_origin_row = m_num_lines - current_num_lines + 1;
  876. }
  877. if (on_display_refresh)
  878. on_display_refresh(*this);
  879. if (m_cached_prompt_valid) {
  880. if (!m_refresh_needed && m_cursor == m_buffer.size()) {
  881. // Just write the characters out and continue,
  882. // no need to refresh the entire line.
  883. char null = 0;
  884. m_pending_chars.append(&null, 1);
  885. fputs((char*)m_pending_chars.data(), stderr);
  886. m_pending_chars.clear();
  887. m_drawn_cursor = m_cursor;
  888. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  889. fflush(stderr);
  890. return;
  891. }
  892. }
  893. // Ouch, reflow entire line.
  894. if (!has_cleaned_up) {
  895. cleanup();
  896. }
  897. VT::move_absolute(m_origin_row, m_origin_column);
  898. fputs(m_new_prompt.characters(), stderr);
  899. VT::clear_to_end_of_line();
  900. HashMap<u32, Style> empty_styles {};
  901. StringBuilder builder;
  902. for (size_t i = 0; i < m_buffer.size(); ++i) {
  903. auto ends = m_spans_ending.get(i).value_or(empty_styles);
  904. auto starts = m_spans_starting.get(i).value_or(empty_styles);
  905. auto anchored_ends = m_anchored_spans_ending.get(i).value_or(empty_styles);
  906. auto anchored_starts = m_anchored_spans_starting.get(i).value_or(empty_styles);
  907. if (ends.size() || anchored_ends.size()) {
  908. Style style;
  909. for (auto& applicable_style : ends)
  910. style.unify_with(applicable_style.value);
  911. for (auto& applicable_style : anchored_ends)
  912. style.unify_with(applicable_style.value);
  913. // Disable any style that should be turned off.
  914. VT::apply_style(style, false);
  915. // Reapply styles for overlapping spans that include this one.
  916. style = find_applicable_style(i);
  917. VT::apply_style(style, true);
  918. }
  919. if (starts.size() || anchored_starts.size()) {
  920. Style style;
  921. for (auto& applicable_style : starts)
  922. style.unify_with(applicable_style.value);
  923. for (auto& applicable_style : anchored_starts)
  924. style.unify_with(applicable_style.value);
  925. // Set new styles.
  926. VT::apply_style(style, true);
  927. }
  928. builder.clear();
  929. builder.append(Utf32View { &m_buffer[i], 1 });
  930. fputs(builder.to_string().characters(), stderr);
  931. }
  932. VT::apply_style(Style::reset_style()); // don't bleed to EOL
  933. m_pending_chars.clear();
  934. m_refresh_needed = false;
  935. m_cached_buffer_metrics = actual_rendered_string_metrics(buffer_view());
  936. m_chars_inserted_in_the_middle = 0;
  937. if (!m_cached_prompt_valid) {
  938. m_cached_prompt_valid = true;
  939. }
  940. reposition_cursor();
  941. fflush(stderr);
  942. }
  943. void Editor::strip_styles(bool strip_anchored)
  944. {
  945. m_spans_starting.clear();
  946. m_spans_ending.clear();
  947. if (strip_anchored) {
  948. m_anchored_spans_starting.clear();
  949. m_anchored_spans_ending.clear();
  950. }
  951. m_refresh_needed = true;
  952. }
  953. void Editor::reposition_cursor(bool to_end)
  954. {
  955. auto cursor = m_cursor;
  956. auto saved_cursor = m_cursor;
  957. if (to_end)
  958. cursor = m_buffer.size();
  959. m_cursor = cursor;
  960. m_drawn_cursor = cursor;
  961. auto line = cursor_line() - 1;
  962. auto column = offset_in_line();
  963. VT::move_absolute(line + m_origin_row, column + m_origin_column);
  964. m_cursor = saved_cursor;
  965. }
  966. void VT::move_absolute(u32 row, u32 col)
  967. {
  968. fprintf(stderr, "\033[%d;%dH", row, col);
  969. fflush(stderr);
  970. }
  971. void VT::move_relative(int row, int col)
  972. {
  973. char x_op = 'A', y_op = 'D';
  974. if (row > 0)
  975. x_op = 'B';
  976. else
  977. row = -row;
  978. if (col > 0)
  979. y_op = 'C';
  980. else
  981. col = -col;
  982. if (row > 0)
  983. fprintf(stderr, "\033[%d%c", row, x_op);
  984. if (col > 0)
  985. fprintf(stderr, "\033[%d%c", col, y_op);
  986. }
  987. Style Editor::find_applicable_style(size_t offset) const
  988. {
  989. // Walk through our styles and merge all that fit in the offset.
  990. auto style = Style::reset_style();
  991. auto unify = [&](auto& entry) {
  992. if (entry.key >= offset)
  993. return;
  994. for (auto& style_value : entry.value) {
  995. if (style_value.key <= offset)
  996. return;
  997. style.unify_with(style_value.value, true);
  998. }
  999. };
  1000. for (auto& entry : m_spans_starting) {
  1001. unify(entry);
  1002. }
  1003. for (auto& entry : m_anchored_spans_starting) {
  1004. unify(entry);
  1005. }
  1006. return style;
  1007. }
  1008. String Style::Background::to_vt_escape() const
  1009. {
  1010. if (is_default())
  1011. return "";
  1012. if (m_is_rgb) {
  1013. return String::format("\033[48;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1014. } else {
  1015. return String::format("\033[%dm", (u8)m_xterm_color + 40);
  1016. }
  1017. }
  1018. String Style::Foreground::to_vt_escape() const
  1019. {
  1020. if (is_default())
  1021. return "";
  1022. if (m_is_rgb) {
  1023. return String::format("\033[38;2;%d;%d;%dm", m_rgb_color[0], m_rgb_color[1], m_rgb_color[2]);
  1024. } else {
  1025. return String::format("\033[%dm", (u8)m_xterm_color + 30);
  1026. }
  1027. }
  1028. String Style::Hyperlink::to_vt_escape(bool starting) const
  1029. {
  1030. if (is_empty())
  1031. return "";
  1032. return String::format("\033]8;;%s\033\\", starting ? m_link.characters() : "");
  1033. }
  1034. void Style::unify_with(const Style& other, bool prefer_other)
  1035. {
  1036. // Unify colors.
  1037. if (prefer_other || m_background.is_default())
  1038. m_background = other.background();
  1039. if (prefer_other || m_foreground.is_default())
  1040. m_foreground = other.foreground();
  1041. // Unify graphic renditions.
  1042. if (other.bold())
  1043. set(Bold);
  1044. if (other.italic())
  1045. set(Italic);
  1046. if (other.underline())
  1047. set(Underline);
  1048. // Unify links.
  1049. if (prefer_other || m_hyperlink.is_empty())
  1050. m_hyperlink = other.hyperlink();
  1051. }
  1052. String Style::to_string() const
  1053. {
  1054. StringBuilder builder;
  1055. builder.append("Style { ");
  1056. if (!m_foreground.is_default()) {
  1057. builder.append("Foreground(");
  1058. if (m_foreground.m_is_rgb) {
  1059. builder.join(", ", m_foreground.m_rgb_color);
  1060. } else {
  1061. builder.appendf("(XtermColor) %d", m_foreground.m_xterm_color);
  1062. }
  1063. builder.append("), ");
  1064. }
  1065. if (!m_background.is_default()) {
  1066. builder.append("Background(");
  1067. if (m_background.m_is_rgb) {
  1068. builder.join(' ', m_background.m_rgb_color);
  1069. } else {
  1070. builder.appendf("(XtermColor) %d", m_background.m_xterm_color);
  1071. }
  1072. builder.append("), ");
  1073. }
  1074. if (bold())
  1075. builder.append("Bold, ");
  1076. if (underline())
  1077. builder.append("Underline, ");
  1078. if (italic())
  1079. builder.append("Italic, ");
  1080. if (!m_hyperlink.is_empty())
  1081. builder.appendf("Hyperlink(\"%s\"), ", m_hyperlink.m_link.characters());
  1082. builder.append("}");
  1083. return builder.build();
  1084. }
  1085. void VT::apply_style(const Style& style, bool is_starting)
  1086. {
  1087. if (is_starting) {
  1088. fprintf(stderr,
  1089. "\033[%d;%d;%dm%s%s%s",
  1090. style.bold() ? 1 : 22,
  1091. style.underline() ? 4 : 24,
  1092. style.italic() ? 3 : 23,
  1093. style.background().to_vt_escape().characters(),
  1094. style.foreground().to_vt_escape().characters(),
  1095. style.hyperlink().to_vt_escape(true).characters());
  1096. } else {
  1097. fprintf(stderr, "%s", style.hyperlink().to_vt_escape(false).characters());
  1098. }
  1099. }
  1100. void VT::clear_lines(size_t count_above, size_t count_below)
  1101. {
  1102. // Go down count_below lines.
  1103. if (count_below > 0)
  1104. fprintf(stderr, "\033[%dB", (int)count_below);
  1105. // Then clear lines going upwards.
  1106. for (size_t i = count_below + count_above; i > 0; --i)
  1107. fputs(i == 1 ? "\033[2K" : "\033[2K\033[A", stderr);
  1108. }
  1109. void VT::save_cursor()
  1110. {
  1111. fputs("\033[s", stderr);
  1112. fflush(stderr);
  1113. }
  1114. void VT::restore_cursor()
  1115. {
  1116. fputs("\033[u", stderr);
  1117. fflush(stderr);
  1118. }
  1119. void VT::clear_to_end_of_line()
  1120. {
  1121. fputs("\033[K", stderr);
  1122. fflush(stderr);
  1123. }
  1124. StringMetrics Editor::actual_rendered_string_metrics(const StringView& string)
  1125. {
  1126. size_t length { 0 };
  1127. StringMetrics metrics;
  1128. VTState state { Free };
  1129. Utf8View view { string };
  1130. auto it = view.begin();
  1131. for (; it != view.end(); ++it) {
  1132. auto c = *it;
  1133. auto it_copy = it;
  1134. ++it_copy;
  1135. auto next_c = it_copy == view.end() ? 0 : *it_copy;
  1136. state = actual_rendered_string_length_step(metrics, length, c, next_c, state);
  1137. }
  1138. metrics.line_lengths.append(length);
  1139. for (auto& line : metrics.line_lengths)
  1140. metrics.max_line_length = max(line, metrics.max_line_length);
  1141. return metrics;
  1142. }
  1143. StringMetrics Editor::actual_rendered_string_metrics(const Utf32View& view)
  1144. {
  1145. size_t length { 0 };
  1146. StringMetrics metrics;
  1147. VTState state { Free };
  1148. for (size_t i = 0; i < view.length(); ++i) {
  1149. auto c = view.code_points()[i];
  1150. auto next_c = i + 1 < view.length() ? view.code_points()[i + 1] : 0;
  1151. state = actual_rendered_string_length_step(metrics, length, c, next_c, state);
  1152. }
  1153. metrics.line_lengths.append(length);
  1154. for (auto& line : metrics.line_lengths)
  1155. metrics.max_line_length = max(line, metrics.max_line_length);
  1156. return metrics;
  1157. }
  1158. Editor::VTState Editor::actual_rendered_string_length_step(StringMetrics& metrics, size_t& length, u32 c, u32 next_c, VTState state)
  1159. {
  1160. switch (state) {
  1161. case Free:
  1162. if (c == '\x1b') { // escape
  1163. return Escape;
  1164. }
  1165. if (c == '\r') { // carriage return
  1166. length = 0;
  1167. if (!metrics.line_lengths.is_empty())
  1168. metrics.line_lengths.last() = 0;
  1169. return state;
  1170. }
  1171. if (c == '\n') { // return
  1172. metrics.line_lengths.append(length);
  1173. length = 0;
  1174. return state;
  1175. }
  1176. // FIXME: This will not support anything sophisticated
  1177. ++length;
  1178. ++metrics.total_length;
  1179. return state;
  1180. case Escape:
  1181. if (c == ']') {
  1182. if (next_c == '0')
  1183. state = Title;
  1184. return state;
  1185. }
  1186. if (c == '[') {
  1187. return Bracket;
  1188. }
  1189. // FIXME: This does not support non-VT (aside from set-title) escapes
  1190. return state;
  1191. case Bracket:
  1192. if (isdigit(c)) {
  1193. return BracketArgsSemi;
  1194. }
  1195. return state;
  1196. case BracketArgsSemi:
  1197. if (c == ';') {
  1198. return Bracket;
  1199. }
  1200. if (!isdigit(c))
  1201. state = Free;
  1202. return state;
  1203. case Title:
  1204. if (c == 7)
  1205. state = Free;
  1206. return state;
  1207. }
  1208. return state;
  1209. }
  1210. Vector<size_t, 2> Editor::vt_dsr()
  1211. {
  1212. char buf[16];
  1213. u32 length { 0 };
  1214. // Read whatever junk there is before talking to the terminal
  1215. // and insert them later when we're reading user input.
  1216. bool more_junk_to_read { false };
  1217. timeval timeout { 0, 0 };
  1218. fd_set readfds;
  1219. FD_ZERO(&readfds);
  1220. FD_SET(0, &readfds);
  1221. do {
  1222. more_junk_to_read = false;
  1223. (void)select(1, &readfds, nullptr, nullptr, &timeout);
  1224. if (FD_ISSET(0, &readfds)) {
  1225. auto nread = read(0, buf, 16);
  1226. if (nread < 0) {
  1227. m_input_error = Error::ReadFailure;
  1228. finish();
  1229. break;
  1230. }
  1231. if (nread == 0)
  1232. break;
  1233. m_incomplete_data.append(buf, nread);
  1234. more_junk_to_read = true;
  1235. }
  1236. } while (more_junk_to_read);
  1237. if (m_input_error.has_value())
  1238. return { 1, 1 };
  1239. fputs("\033[6n", stderr);
  1240. fflush(stderr);
  1241. do {
  1242. auto nread = read(0, buf + length, 16 - length);
  1243. if (nread < 0) {
  1244. if (errno == 0) {
  1245. // ????
  1246. continue;
  1247. }
  1248. dbg() << "Error while reading DSR: " << strerror(errno);
  1249. m_input_error = Error::ReadFailure;
  1250. finish();
  1251. return { 1, 1 };
  1252. }
  1253. if (nread == 0) {
  1254. m_input_error = Error::Empty;
  1255. finish();
  1256. dbg() << "Terminal DSR issue; received no response";
  1257. return { 1, 1 };
  1258. }
  1259. length += nread;
  1260. } while (buf[length - 1] != 'R' && length < 16);
  1261. size_t row { 1 }, col { 1 };
  1262. if (buf[0] == '\033' && buf[1] == '[') {
  1263. auto parts = StringView(buf + 2, length - 3).split_view(';');
  1264. auto row_opt = parts[0].to_int();
  1265. if (!row_opt.has_value()) {
  1266. dbg() << "Terminal DSR issue; received garbage row";
  1267. } else {
  1268. row = row_opt.value();
  1269. }
  1270. auto col_opt = parts[1].to_int();
  1271. if (!col_opt.has_value()) {
  1272. dbg() << "Terminal DSR issue; received garbage col";
  1273. } else {
  1274. col = col_opt.value();
  1275. }
  1276. }
  1277. return { row, col };
  1278. }
  1279. String Editor::line(size_t up_to_index) const
  1280. {
  1281. StringBuilder builder;
  1282. builder.append(Utf32View { m_buffer.data(), min(m_buffer.size(), up_to_index) });
  1283. return builder.build();
  1284. }
  1285. void Editor::remove_at_index(size_t index)
  1286. {
  1287. // See if we have any anchored styles, and reposition them if needed.
  1288. readjust_anchored_styles(index, ModificationKind::Removal);
  1289. auto cp = m_buffer[index];
  1290. m_buffer.remove(index);
  1291. if (cp == '\n')
  1292. ++m_extra_forward_lines;
  1293. }
  1294. void Editor::readjust_anchored_styles(size_t hint_index, ModificationKind modification)
  1295. {
  1296. struct Anchor {
  1297. Span old_span;
  1298. Span new_span;
  1299. Style style;
  1300. };
  1301. Vector<Anchor> anchors_to_relocate;
  1302. auto index_shift = modification == ModificationKind::Insertion ? 1 : -1;
  1303. auto forced_removal = modification == ModificationKind::ForcedOverlapRemoval;
  1304. for (auto& start_entry : m_anchored_spans_starting) {
  1305. for (auto& end_entry : start_entry.value) {
  1306. if (forced_removal) {
  1307. if (start_entry.key <= hint_index && end_entry.key > hint_index) {
  1308. // Remove any overlapping regions.
  1309. continue;
  1310. }
  1311. }
  1312. if (start_entry.key >= hint_index) {
  1313. if (start_entry.key == hint_index && end_entry.key == hint_index + 1 && modification == ModificationKind::Removal) {
  1314. // Remove the anchor, as all its text was wiped.
  1315. continue;
  1316. }
  1317. // Shift everything.
  1318. 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 });
  1319. continue;
  1320. }
  1321. if (end_entry.key > hint_index) {
  1322. // Shift just the end.
  1323. 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 });
  1324. continue;
  1325. }
  1326. 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 });
  1327. }
  1328. }
  1329. m_anchored_spans_ending.clear();
  1330. m_anchored_spans_starting.clear();
  1331. // Pass over the relocations and update the stale entries.
  1332. for (auto& relocation : anchors_to_relocate) {
  1333. stylize(relocation.new_span, relocation.style);
  1334. }
  1335. }
  1336. size_t StringMetrics::lines_with_addition(const StringMetrics& offset, size_t column_width) const
  1337. {
  1338. size_t lines = 0;
  1339. for (size_t i = 0; i < line_lengths.size() - 1; ++i)
  1340. lines += (line_lengths[i] + column_width) / column_width;
  1341. auto last = line_lengths.last();
  1342. last += offset.line_lengths.first();
  1343. lines += (last + column_width) / column_width;
  1344. for (size_t i = 1; i < offset.line_lengths.size(); ++i)
  1345. lines += (offset.line_lengths[i] + column_width) / column_width;
  1346. return lines;
  1347. }
  1348. }