InternalFunctions.cpp 18 KB

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