InternalFunctions.cpp 19 KB

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