Editor.cpp 51 KB

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