InternalFunctions.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/CharacterTypes.h>
  7. #include <AK/ScopeGuard.h>
  8. #include <AK/ScopedValueRollback.h>
  9. #include <AK/StringBuilder.h>
  10. #include <AK/TemporaryChange.h>
  11. #include <LibCore/File.h>
  12. #include <LibLine/Editor.h>
  13. #include <stdio.h>
  14. #include <sys/wait.h>
  15. #include <unistd.h>
  16. namespace {
  17. constexpr u32 ctrl(char c) { return c & 0x3f; }
  18. }
  19. namespace Line {
  20. Function<bool(Editor&)> Editor::find_internal_function(StringView name)
  21. {
  22. #define __ENUMERATE(internal_name) \
  23. if (name == #internal_name) \
  24. return EDITOR_INTERNAL_FUNCTION(internal_name);
  25. ENUMERATE_EDITOR_INTERNAL_FUNCTIONS(__ENUMERATE)
  26. return {};
  27. }
  28. void Editor::search_forwards()
  29. {
  30. ScopedValueRollback inline_search_cursor_rollback { m_inline_search_cursor };
  31. StringBuilder builder;
  32. builder.append(Utf32View { m_buffer.data(), m_inline_search_cursor });
  33. auto search_phrase = builder.to_byte_string();
  34. if (m_search_offset_state == SearchOffsetState::Backwards)
  35. --m_search_offset;
  36. if (m_search_offset > 0) {
  37. ScopedValueRollback search_offset_rollback { m_search_offset };
  38. --m_search_offset;
  39. if (search(search_phrase, true)) {
  40. m_search_offset_state = SearchOffsetState::Forwards;
  41. search_offset_rollback.set_override_rollback_value(m_search_offset);
  42. } else {
  43. m_search_offset_state = SearchOffsetState::Unbiased;
  44. }
  45. } else {
  46. m_search_offset_state = SearchOffsetState::Unbiased;
  47. m_chars_touched_in_the_middle = buffer().size();
  48. m_cursor = 0;
  49. m_buffer.clear();
  50. insert(search_phrase);
  51. m_refresh_needed = true;
  52. }
  53. }
  54. void Editor::search_backwards()
  55. {
  56. ScopedValueRollback inline_search_cursor_rollback { m_inline_search_cursor };
  57. StringBuilder builder;
  58. builder.append(Utf32View { m_buffer.data(), m_inline_search_cursor });
  59. auto search_phrase = builder.to_byte_string();
  60. if (m_search_offset_state == SearchOffsetState::Forwards)
  61. ++m_search_offset;
  62. if (search(search_phrase, true)) {
  63. m_search_offset_state = SearchOffsetState::Backwards;
  64. ++m_search_offset;
  65. } else {
  66. m_search_offset_state = SearchOffsetState::Unbiased;
  67. --m_search_offset;
  68. }
  69. }
  70. void Editor::cursor_left_word()
  71. {
  72. auto has_seen_alnum = false;
  73. while (m_cursor) {
  74. // after seeing at least one alnum, stop just before a non-alnum
  75. if (not is_ascii_alphanumeric(m_buffer[m_cursor - 1])) {
  76. if (has_seen_alnum)
  77. break;
  78. } else {
  79. has_seen_alnum = true;
  80. }
  81. --m_cursor;
  82. }
  83. m_inline_search_cursor = m_cursor;
  84. }
  85. void Editor::cursor_left_character()
  86. {
  87. if (m_cursor > 0) {
  88. size_t closest_cursor_left_offset;
  89. binary_search(m_cached_buffer_metrics.grapheme_breaks, m_cursor - 1, &closest_cursor_left_offset);
  90. m_cursor = m_cached_buffer_metrics.grapheme_breaks[closest_cursor_left_offset];
  91. }
  92. m_inline_search_cursor = m_cursor;
  93. }
  94. void Editor::cursor_right_word()
  95. {
  96. if (m_cursor < m_buffer.size()) {
  97. // Temporarily put a space at the end of our buffer,
  98. // doing this greatly simplifies the logic below.
  99. m_buffer.append(' ');
  100. for (;;) {
  101. if (m_cursor >= m_buffer.size())
  102. break;
  103. if (!is_ascii_alphanumeric(m_buffer[++m_cursor]))
  104. break;
  105. }
  106. m_buffer.take_last();
  107. }
  108. m_inline_search_cursor = m_cursor;
  109. m_search_offset = 0;
  110. }
  111. void Editor::cursor_right_character()
  112. {
  113. if (m_cursor < m_buffer.size()) {
  114. size_t closest_cursor_left_offset;
  115. binary_search(m_cached_buffer_metrics.grapheme_breaks, m_cursor, &closest_cursor_left_offset);
  116. m_cursor = closest_cursor_left_offset + 1 >= m_cached_buffer_metrics.grapheme_breaks.size()
  117. ? m_buffer.size()
  118. : m_cached_buffer_metrics.grapheme_breaks[closest_cursor_left_offset + 1];
  119. }
  120. m_inline_search_cursor = m_cursor;
  121. m_search_offset = 0;
  122. }
  123. void Editor::erase_character_backwards()
  124. {
  125. if (m_is_searching) {
  126. return;
  127. }
  128. if (m_cursor == 0) {
  129. fputc('\a', stderr);
  130. fflush(stderr);
  131. return;
  132. }
  133. size_t closest_cursor_left_offset;
  134. binary_search(m_cached_buffer_metrics.grapheme_breaks, m_cursor - 1, &closest_cursor_left_offset);
  135. auto start_of_previous_grapheme = m_cached_buffer_metrics.grapheme_breaks[closest_cursor_left_offset];
  136. for (; m_cursor > start_of_previous_grapheme; --m_cursor)
  137. remove_at_index(m_cursor - 1);
  138. m_inline_search_cursor = m_cursor;
  139. // We will have to redraw :(
  140. m_refresh_needed = true;
  141. }
  142. void Editor::erase_character_forwards()
  143. {
  144. if (m_cursor == m_buffer.size()) {
  145. fputc('\a', stderr);
  146. fflush(stderr);
  147. return;
  148. }
  149. size_t closest_cursor_left_offset;
  150. binary_search(m_cached_buffer_metrics.grapheme_breaks, m_cursor, &closest_cursor_left_offset);
  151. auto end_of_next_grapheme = closest_cursor_left_offset + 1 >= m_cached_buffer_metrics.grapheme_breaks.size()
  152. ? m_buffer.size()
  153. : m_cached_buffer_metrics.grapheme_breaks[closest_cursor_left_offset + 1];
  154. for (auto cursor = m_cursor; cursor < end_of_next_grapheme; ++cursor)
  155. remove_at_index(m_cursor);
  156. m_refresh_needed = true;
  157. }
  158. void Editor::finish_edit()
  159. {
  160. fprintf(stderr, "<EOF>\n");
  161. if (!m_always_refresh) {
  162. m_input_error = Error::Eof;
  163. finish();
  164. really_quit_event_loop().release_value_but_fixme_should_propagate_errors();
  165. }
  166. }
  167. void Editor::kill_line()
  168. {
  169. for (size_t i = 0; i < m_cursor; ++i)
  170. remove_at_index(0);
  171. m_cursor = 0;
  172. m_inline_search_cursor = m_cursor;
  173. m_refresh_needed = true;
  174. }
  175. void Editor::erase_word_backwards()
  176. {
  177. // A word here is space-separated. `foo=bar baz` is two words.
  178. bool has_seen_nonspace = false;
  179. while (m_cursor > 0) {
  180. if (is_ascii_space(m_buffer[m_cursor - 1])) {
  181. if (has_seen_nonspace)
  182. break;
  183. } else {
  184. has_seen_nonspace = true;
  185. }
  186. erase_character_backwards();
  187. }
  188. }
  189. void Editor::erase_to_end()
  190. {
  191. while (m_cursor < m_buffer.size())
  192. erase_character_forwards();
  193. }
  194. void Editor::erase_to_beginning()
  195. {
  196. }
  197. void Editor::transpose_characters()
  198. {
  199. if (m_cursor > 0 && m_buffer.size() >= 2) {
  200. if (m_cursor < m_buffer.size())
  201. ++m_cursor;
  202. swap(m_buffer[m_cursor - 1], m_buffer[m_cursor - 2]);
  203. // FIXME: Update anchored styles too.
  204. m_refresh_needed = true;
  205. m_chars_touched_in_the_middle += 2;
  206. }
  207. }
  208. void Editor::enter_search()
  209. {
  210. if (m_is_searching) {
  211. // How did we get here?
  212. VERIFY_NOT_REACHED();
  213. } else {
  214. m_is_searching = true;
  215. m_search_offset = 0;
  216. m_pre_search_buffer.clear();
  217. for (auto code_point : m_buffer)
  218. m_pre_search_buffer.append(code_point);
  219. m_pre_search_cursor = m_cursor;
  220. ensure_free_lines_from_origin(1 + num_lines());
  221. // Disable our own notifier so as to avoid interfering with the search editor.
  222. m_notifier->set_enabled(false);
  223. m_search_editor = Editor::construct(Configuration { Configuration::Eager, Configuration::NoSignalHandlers }); // Has anyone seen 'Inception'?
  224. m_search_editor->initialize();
  225. add_child(*m_search_editor);
  226. m_search_editor->on_display_refresh = [this](Editor& search_editor) {
  227. // Remove the search editor prompt before updating ourselves (this avoids artifacts when we move the search editor around).
  228. search_editor.cleanup().release_value_but_fixme_should_propagate_errors();
  229. StringBuilder builder;
  230. builder.append(Utf32View { search_editor.buffer().data(), search_editor.buffer().size() });
  231. if (!search(builder.to_byte_string(), false, false)) {
  232. m_chars_touched_in_the_middle = m_buffer.size();
  233. m_refresh_needed = true;
  234. m_buffer.clear();
  235. m_cursor = 0;
  236. }
  237. refresh_display().release_value_but_fixme_should_propagate_errors();
  238. // Move the search prompt below ours and tell it to redraw itself.
  239. auto prompt_end_line = current_prompt_metrics().lines_with_addition(m_cached_buffer_metrics, m_num_columns);
  240. search_editor.set_origin(prompt_end_line + m_origin_row, 1);
  241. search_editor.m_refresh_needed = true;
  242. };
  243. // Whenever the search editor gets a ^R, cycle between history entries.
  244. m_search_editor->register_key_input_callback(ctrl('R'), [this](Editor& search_editor) {
  245. ++m_search_offset;
  246. search_editor.m_refresh_needed = true;
  247. return false; // Do not process this key event
  248. });
  249. // ^C should cancel the search.
  250. m_search_editor->register_key_input_callback(ctrl('C'), [this](Editor& search_editor) {
  251. search_editor.finish();
  252. m_reset_buffer_on_search_end = true;
  253. search_editor.end_search();
  254. search_editor.deferred_invoke([&search_editor] { search_editor.really_quit_event_loop().release_value_but_fixme_should_propagate_errors(); });
  255. return false;
  256. });
  257. // Whenever the search editor gets a backspace, cycle back between history entries
  258. // unless we're at the zeroth entry, in which case, allow the deletion.
  259. m_search_editor->register_key_input_callback(m_termios.c_cc[VERASE], [this](Editor& search_editor) {
  260. if (m_search_offset > 0) {
  261. --m_search_offset;
  262. search_editor.m_refresh_needed = true;
  263. return false; // Do not process this key event
  264. }
  265. search_editor.erase_character_backwards();
  266. return false;
  267. });
  268. // ^L - This is a source of issues, as the search editor refreshes first,
  269. // and we end up with the wrong order of prompts, so we will first refresh
  270. // ourselves, then refresh the search editor, and then tell him not to process
  271. // this event.
  272. m_search_editor->register_key_input_callback(ctrl('L'), [this](auto& search_editor) {
  273. fprintf(stderr, "\033[3J\033[H\033[2J"); // Clear screen.
  274. // refresh our own prompt
  275. {
  276. TemporaryChange refresh_change { m_always_refresh, true };
  277. set_origin(1, 1);
  278. m_refresh_needed = true;
  279. refresh_display().release_value_but_fixme_should_propagate_errors();
  280. }
  281. // move the search prompt below ours
  282. // and tell it to redraw itself
  283. auto prompt_end_line = current_prompt_metrics().lines_with_addition(m_cached_buffer_metrics, m_num_columns);
  284. search_editor.set_origin(prompt_end_line + 1, 1);
  285. search_editor.m_refresh_needed = true;
  286. return false;
  287. });
  288. // quit without clearing the current buffer
  289. m_search_editor->register_key_input_callback('\t', [this](Editor& search_editor) {
  290. search_editor.finish();
  291. m_reset_buffer_on_search_end = false;
  292. return false;
  293. });
  294. auto search_prompt = "\x1b[32msearch:\x1b[0m "sv;
  295. // While the search editor is active, we do not want editing events.
  296. m_is_editing = false;
  297. auto search_string_result = m_search_editor->get_line(search_prompt);
  298. // Grab where the search origin last was, anything up to this point will be cleared.
  299. auto search_end_row = m_search_editor->m_origin_row;
  300. remove_child(*m_search_editor);
  301. m_search_editor = nullptr;
  302. m_is_searching = false;
  303. m_is_editing = true;
  304. m_search_offset = 0;
  305. // Re-enable the notifier after discarding the search editor.
  306. m_notifier->set_enabled(true);
  307. if (search_string_result.is_error()) {
  308. // Somethine broke, fail
  309. m_input_error = search_string_result.error();
  310. finish();
  311. return;
  312. }
  313. auto& search_string = search_string_result.value();
  314. // Manually cleanup the search line.
  315. auto stderr_stream = Core::File::standard_error().release_value_but_fixme_should_propagate_errors();
  316. reposition_cursor(*stderr_stream).release_value_but_fixme_should_propagate_errors();
  317. auto search_metrics = actual_rendered_string_metrics(search_string, {});
  318. auto metrics = actual_rendered_string_metrics(search_prompt, {});
  319. VT::clear_lines(0, metrics.lines_with_addition(search_metrics, m_num_columns) + search_end_row - m_origin_row - 1, *stderr_stream).release_value_but_fixme_should_propagate_errors();
  320. reposition_cursor(*stderr_stream).release_value_but_fixme_should_propagate_errors();
  321. m_refresh_needed = true;
  322. m_cached_prompt_valid = false;
  323. m_chars_touched_in_the_middle = 1;
  324. if (!m_reset_buffer_on_search_end || search_metrics.total_length == 0) {
  325. // If the entry was empty, or we purposely quit without a newline,
  326. // do not return anything; instead, just end the search.
  327. end_search();
  328. return;
  329. }
  330. // Return the string,
  331. finish();
  332. }
  333. }
  334. void Editor::transpose_words()
  335. {
  336. // A word here is contiguous alnums. `foo=bar baz` is three words.
  337. // 'abcd,.:efg...' should become 'efg...,.:abcd' if caret is after
  338. // 'efg...'. If it's in 'efg', it should become 'efg,.:abcd...'
  339. // with the caret after it, which then becomes 'abcd...,.:efg'
  340. // when alt-t is pressed a second time.
  341. // Move to end of word under (or after) caret.
  342. size_t cursor = m_cursor;
  343. while (cursor < m_buffer.size() && !is_ascii_alphanumeric(m_buffer[cursor]))
  344. ++cursor;
  345. while (cursor < m_buffer.size() && is_ascii_alphanumeric(m_buffer[cursor]))
  346. ++cursor;
  347. // Move left over second word and the space to its right.
  348. size_t end = cursor;
  349. size_t start = cursor;
  350. while (start > 0 && !is_ascii_alphanumeric(m_buffer[start - 1]))
  351. --start;
  352. while (start > 0 && is_ascii_alphanumeric(m_buffer[start - 1]))
  353. --start;
  354. size_t start_second_word = start;
  355. // Move left over space between the two words.
  356. while (start > 0 && !is_ascii_alphanumeric(m_buffer[start - 1]))
  357. --start;
  358. size_t start_gap = start;
  359. // Move left over first word.
  360. while (start > 0 && is_ascii_alphanumeric(m_buffer[start - 1]))
  361. --start;
  362. if (start != start_gap) {
  363. // To swap the two words, swap each word (and the gap) individually, and then swap the whole range.
  364. auto swap_range = [this](auto from, auto to) {
  365. for (size_t i = 0; i < (to - from) / 2; ++i)
  366. swap(m_buffer[from + i], m_buffer[to - 1 - i]);
  367. };
  368. swap_range(start, start_gap);
  369. swap_range(start_gap, start_second_word);
  370. swap_range(start_second_word, end);
  371. swap_range(start, end);
  372. m_cursor = cursor;
  373. // FIXME: Update anchored styles too.
  374. m_refresh_needed = true;
  375. m_chars_touched_in_the_middle += end - start;
  376. }
  377. }
  378. void Editor::go_home()
  379. {
  380. m_cursor = 0;
  381. m_inline_search_cursor = m_cursor;
  382. m_search_offset = 0;
  383. }
  384. void Editor::go_end()
  385. {
  386. m_cursor = m_buffer.size();
  387. m_inline_search_cursor = m_cursor;
  388. m_search_offset = 0;
  389. }
  390. void Editor::clear_screen()
  391. {
  392. warn("\033[3J\033[H\033[2J");
  393. auto stream = Core::File::standard_error().release_value_but_fixme_should_propagate_errors();
  394. VT::move_absolute(1, 1, *stream).release_value_but_fixme_should_propagate_errors();
  395. set_origin(1, 1);
  396. m_refresh_needed = true;
  397. m_cached_prompt_valid = false;
  398. }
  399. void Editor::insert_last_words()
  400. {
  401. if (!m_history.is_empty()) {
  402. // FIXME: This isn't quite right: if the last arg was `"foo bar"` or `foo\ bar` (but not `foo\\ bar`), we should insert that whole arg as last token.
  403. if (auto last_words = m_history.last().entry.split_view(' '); !last_words.is_empty())
  404. insert(last_words.last());
  405. }
  406. }
  407. void Editor::erase_alnum_word_backwards()
  408. {
  409. // A word here is contiguous alnums. `foo=bar baz` is three words.
  410. bool has_seen_alnum = false;
  411. while (m_cursor > 0) {
  412. if (!is_ascii_alphanumeric(m_buffer[m_cursor - 1])) {
  413. if (has_seen_alnum)
  414. break;
  415. } else {
  416. has_seen_alnum = true;
  417. }
  418. erase_character_backwards();
  419. }
  420. }
  421. void Editor::erase_alnum_word_forwards()
  422. {
  423. // A word here is contiguous alnums. `foo=bar baz` is three words.
  424. bool has_seen_alnum = false;
  425. while (m_cursor < m_buffer.size()) {
  426. if (!is_ascii_alphanumeric(m_buffer[m_cursor])) {
  427. if (has_seen_alnum)
  428. break;
  429. } else {
  430. has_seen_alnum = true;
  431. }
  432. erase_character_forwards();
  433. }
  434. }
  435. void Editor::case_change_word(Editor::CaseChangeOp change_op)
  436. {
  437. // A word here is contiguous alnums. `foo=bar baz` is three words.
  438. while (m_cursor < m_buffer.size() && !is_ascii_alphanumeric(m_buffer[m_cursor]))
  439. ++m_cursor;
  440. size_t start = m_cursor;
  441. while (m_cursor < m_buffer.size() && is_ascii_alphanumeric(m_buffer[m_cursor])) {
  442. if (change_op == CaseChangeOp::Uppercase || (change_op == CaseChangeOp::Capital && m_cursor == start)) {
  443. m_buffer[m_cursor] = to_ascii_uppercase(m_buffer[m_cursor]);
  444. } else {
  445. VERIFY(change_op == CaseChangeOp::Lowercase || (change_op == CaseChangeOp::Capital && m_cursor > start));
  446. m_buffer[m_cursor] = to_ascii_lowercase(m_buffer[m_cursor]);
  447. }
  448. ++m_cursor;
  449. }
  450. m_refresh_needed = true;
  451. m_chars_touched_in_the_middle = 1;
  452. }
  453. void Editor::capitalize_word()
  454. {
  455. case_change_word(CaseChangeOp::Capital);
  456. }
  457. void Editor::lowercase_word()
  458. {
  459. case_change_word(CaseChangeOp::Lowercase);
  460. }
  461. void Editor::uppercase_word()
  462. {
  463. case_change_word(CaseChangeOp::Uppercase);
  464. }
  465. void Editor::edit_in_external_editor()
  466. {
  467. auto const* editor_command = getenv("EDITOR");
  468. if (!editor_command)
  469. editor_command = m_configuration.m_default_text_editor.characters();
  470. char file_path[] = "/tmp/line-XXXXXX";
  471. auto fd = mkstemp(file_path);
  472. if (fd < 0) {
  473. perror("mktemp");
  474. return;
  475. }
  476. {
  477. auto write_fd = dup(fd);
  478. auto stream = Core::File::adopt_fd(write_fd, Core::File::OpenMode::Write).release_value_but_fixme_should_propagate_errors();
  479. StringBuilder builder;
  480. builder.append(Utf32View { m_buffer.data(), m_buffer.size() });
  481. auto bytes = builder.string_view().bytes();
  482. while (!bytes.is_empty()) {
  483. auto nwritten = stream->write_some(bytes).release_value_but_fixme_should_propagate_errors();
  484. bytes = bytes.slice(nwritten);
  485. }
  486. lseek(fd, 0, SEEK_SET);
  487. }
  488. ScopeGuard remove_temp_file_guard {
  489. [fd, file_path] {
  490. close(fd);
  491. unlink(file_path);
  492. }
  493. };
  494. Vector<char const*> args { editor_command, file_path, nullptr };
  495. auto pid = fork();
  496. if (pid == -1) {
  497. perror("fork");
  498. return;
  499. }
  500. if (pid == 0) {
  501. execvp(editor_command, const_cast<char* const*>(args.data()));
  502. perror("execv");
  503. _exit(126);
  504. } else {
  505. int wstatus = 0;
  506. do {
  507. waitpid(pid, &wstatus, 0);
  508. } while (errno == EINTR);
  509. if (!(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0))
  510. return;
  511. }
  512. {
  513. auto file = Core::File::open({ file_path, strlen(file_path) }, Core::File::OpenMode::Read).release_value_but_fixme_should_propagate_errors();
  514. auto contents = file->read_until_eof().release_value_but_fixme_should_propagate_errors();
  515. StringView data { contents };
  516. while (data.ends_with('\n'))
  517. data = data.substring_view(0, data.length() - 1);
  518. m_cursor = 0;
  519. m_chars_touched_in_the_middle = m_buffer.size();
  520. m_buffer.clear_with_capacity();
  521. m_refresh_needed = true;
  522. Utf8View view { data };
  523. if (view.validate()) {
  524. for (auto cp : view)
  525. insert(cp);
  526. } else {
  527. for (auto ch : data)
  528. insert(ch);
  529. }
  530. }
  531. }
  532. }