InternalFunctions.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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(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_inline_search_cursor = m_cursor;
  158. m_refresh_needed = true;
  159. }
  160. void Editor::erase_word_backwards()
  161. {
  162. // A word here is space-separated. `foo=bar baz` is two words.
  163. bool has_seen_nonspace = false;
  164. while (m_cursor > 0) {
  165. if (is_ascii_space(m_buffer[m_cursor - 1])) {
  166. if (has_seen_nonspace)
  167. break;
  168. } else {
  169. has_seen_nonspace = true;
  170. }
  171. erase_character_backwards();
  172. }
  173. }
  174. void Editor::erase_to_end()
  175. {
  176. while (m_cursor < m_buffer.size())
  177. erase_character_forwards();
  178. }
  179. void Editor::erase_to_beginning()
  180. {
  181. }
  182. void Editor::transpose_characters()
  183. {
  184. if (m_cursor > 0 && m_buffer.size() >= 2) {
  185. if (m_cursor < m_buffer.size())
  186. ++m_cursor;
  187. swap(m_buffer[m_cursor - 1], m_buffer[m_cursor - 2]);
  188. // FIXME: Update anchored styles too.
  189. m_refresh_needed = true;
  190. m_chars_touched_in_the_middle += 2;
  191. }
  192. }
  193. void Editor::enter_search()
  194. {
  195. if (m_is_searching) {
  196. // How did we get here?
  197. VERIFY_NOT_REACHED();
  198. } else {
  199. m_is_searching = true;
  200. m_search_offset = 0;
  201. m_pre_search_buffer.clear();
  202. for (auto code_point : m_buffer)
  203. m_pre_search_buffer.append(code_point);
  204. m_pre_search_cursor = m_cursor;
  205. ensure_free_lines_from_origin(1 + num_lines());
  206. // Disable our own notifier so as to avoid interfering with the search editor.
  207. m_notifier->set_enabled(false);
  208. m_search_editor = Editor::construct(Configuration { Configuration::Eager, Configuration::NoSignalHandlers }); // Has anyone seen 'Inception'?
  209. m_search_editor->initialize();
  210. add_child(*m_search_editor);
  211. m_search_editor->on_display_refresh = [this](Editor& search_editor) {
  212. // Remove the search editor prompt before updating ourselves (this avoids artifacts when we move the search editor around).
  213. search_editor.cleanup();
  214. StringBuilder builder;
  215. builder.append(Utf32View { search_editor.buffer().data(), search_editor.buffer().size() });
  216. if (!search(builder.build(), false, false)) {
  217. m_chars_touched_in_the_middle = m_buffer.size();
  218. m_refresh_needed = true;
  219. m_buffer.clear();
  220. m_cursor = 0;
  221. }
  222. refresh_display();
  223. // Move the search prompt below ours and tell it to redraw itself.
  224. auto prompt_end_line = current_prompt_metrics().lines_with_addition(m_cached_buffer_metrics, m_num_columns);
  225. search_editor.set_origin(prompt_end_line + m_origin_row, 1);
  226. search_editor.m_refresh_needed = true;
  227. };
  228. // Whenever the search editor gets a ^R, cycle between history entries.
  229. m_search_editor->register_key_input_callback(ctrl('R'), [this](Editor& search_editor) {
  230. ++m_search_offset;
  231. search_editor.m_refresh_needed = true;
  232. return false; // Do not process this key event
  233. });
  234. // ^C should cancel the search.
  235. m_search_editor->register_key_input_callback(ctrl('C'), [this](Editor& search_editor) {
  236. search_editor.finish();
  237. m_reset_buffer_on_search_end = true;
  238. search_editor.end_search();
  239. search_editor.deferred_invoke([&search_editor] { search_editor.really_quit_event_loop(); });
  240. return false;
  241. });
  242. // Whenever the search editor gets a backspace, cycle back between history entries
  243. // unless we're at the zeroth entry, in which case, allow the deletion.
  244. m_search_editor->register_key_input_callback(m_termios.c_cc[VERASE], [this](Editor& search_editor) {
  245. if (m_search_offset > 0) {
  246. --m_search_offset;
  247. search_editor.m_refresh_needed = true;
  248. return false; // Do not process this key event
  249. }
  250. search_editor.erase_character_backwards();
  251. return false;
  252. });
  253. // ^L - This is a source of issues, as the search editor refreshes first,
  254. // and we end up with the wrong order of prompts, so we will first refresh
  255. // ourselves, then refresh the search editor, and then tell him not to process
  256. // this event.
  257. m_search_editor->register_key_input_callback(ctrl('L'), [this](auto& search_editor) {
  258. fprintf(stderr, "\033[3J\033[H\033[2J"); // Clear screen.
  259. // refresh our own prompt
  260. {
  261. TemporaryChange refresh_change { m_always_refresh, true };
  262. set_origin(1, 1);
  263. m_refresh_needed = true;
  264. refresh_display();
  265. }
  266. // move the search prompt below ours
  267. // and tell it to redraw itself
  268. auto prompt_end_line = current_prompt_metrics().lines_with_addition(m_cached_buffer_metrics, m_num_columns);
  269. search_editor.set_origin(prompt_end_line + 1, 1);
  270. search_editor.m_refresh_needed = true;
  271. return false;
  272. });
  273. // quit without clearing the current buffer
  274. m_search_editor->register_key_input_callback('\t', [this](Editor& search_editor) {
  275. search_editor.finish();
  276. m_reset_buffer_on_search_end = false;
  277. return false;
  278. });
  279. auto search_prompt = "\x1b[32msearch:\x1b[0m ";
  280. // While the search editor is active, we do not want editing events.
  281. m_is_editing = false;
  282. auto search_string_result = m_search_editor->get_line(search_prompt);
  283. // Grab where the search origin last was, anything up to this point will be cleared.
  284. auto search_end_row = m_search_editor->m_origin_row;
  285. remove_child(*m_search_editor);
  286. m_search_editor = nullptr;
  287. m_is_searching = false;
  288. m_is_editing = true;
  289. m_search_offset = 0;
  290. // Re-enable the notifier after discarding the search editor.
  291. m_notifier->set_enabled(true);
  292. if (search_string_result.is_error()) {
  293. // Somethine broke, fail
  294. m_input_error = search_string_result.error();
  295. finish();
  296. return;
  297. }
  298. auto& search_string = search_string_result.value();
  299. // Manually cleanup the search line.
  300. OutputFileStream stderr_stream { stderr };
  301. reposition_cursor(stderr_stream);
  302. auto search_metrics = actual_rendered_string_metrics(search_string);
  303. auto metrics = actual_rendered_string_metrics(search_prompt);
  304. VT::clear_lines(0, metrics.lines_with_addition(search_metrics, m_num_columns) + search_end_row - m_origin_row - 1, stderr_stream);
  305. reposition_cursor(stderr_stream);
  306. m_refresh_needed = true;
  307. m_cached_prompt_valid = false;
  308. m_chars_touched_in_the_middle = 1;
  309. if (!m_reset_buffer_on_search_end || search_metrics.total_length == 0) {
  310. // If the entry was empty, or we purposely quit without a newline,
  311. // do not return anything; instead, just end the search.
  312. end_search();
  313. return;
  314. }
  315. // Return the string,
  316. finish();
  317. }
  318. }
  319. void Editor::transpose_words()
  320. {
  321. // A word here is contiguous alnums. `foo=bar baz` is three words.
  322. // 'abcd,.:efg...' should become 'efg...,.:abcd' if caret is after
  323. // 'efg...'. If it's in 'efg', it should become 'efg,.:abcd...'
  324. // with the caret after it, which then becomes 'abcd...,.:efg'
  325. // when alt-t is pressed a second time.
  326. // Move to end of word under (or after) caret.
  327. size_t cursor = m_cursor;
  328. while (cursor < m_buffer.size() && !is_ascii_alphanumeric(m_buffer[cursor]))
  329. ++cursor;
  330. while (cursor < m_buffer.size() && is_ascii_alphanumeric(m_buffer[cursor]))
  331. ++cursor;
  332. // Move left over second word and the space to its right.
  333. size_t end = cursor;
  334. size_t start = cursor;
  335. while (start > 0 && !is_ascii_alphanumeric(m_buffer[start - 1]))
  336. --start;
  337. while (start > 0 && is_ascii_alphanumeric(m_buffer[start - 1]))
  338. --start;
  339. size_t start_second_word = start;
  340. // Move left over space between the two words.
  341. while (start > 0 && !is_ascii_alphanumeric(m_buffer[start - 1]))
  342. --start;
  343. size_t start_gap = start;
  344. // Move left over first word.
  345. while (start > 0 && is_ascii_alphanumeric(m_buffer[start - 1]))
  346. --start;
  347. if (start != start_gap) {
  348. // To swap the two words, swap each word (and the gap) individually, and then swap the whole range.
  349. auto swap_range = [this](auto from, auto to) {
  350. for (size_t i = 0; i < (to - from) / 2; ++i)
  351. swap(m_buffer[from + i], m_buffer[to - 1 - i]);
  352. };
  353. swap_range(start, start_gap);
  354. swap_range(start_gap, start_second_word);
  355. swap_range(start_second_word, end);
  356. swap_range(start, end);
  357. m_cursor = cursor;
  358. // FIXME: Update anchored styles too.
  359. m_refresh_needed = true;
  360. m_chars_touched_in_the_middle += end - start;
  361. }
  362. }
  363. void Editor::go_home()
  364. {
  365. m_cursor = 0;
  366. m_inline_search_cursor = m_cursor;
  367. m_search_offset = 0;
  368. }
  369. void Editor::go_end()
  370. {
  371. m_cursor = m_buffer.size();
  372. m_inline_search_cursor = m_cursor;
  373. m_search_offset = 0;
  374. }
  375. void Editor::clear_screen()
  376. {
  377. warn("\033[3J\033[H\033[2J");
  378. OutputFileStream stream { stderr };
  379. VT::move_absolute(1, 1, stream);
  380. set_origin(1, 1);
  381. m_refresh_needed = true;
  382. m_cached_prompt_valid = false;
  383. }
  384. void Editor::insert_last_words()
  385. {
  386. if (!m_history.is_empty()) {
  387. // 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.
  388. if (auto last_words = m_history.last().entry.split_view(' '); !last_words.is_empty())
  389. insert(last_words.last());
  390. }
  391. }
  392. void Editor::erase_alnum_word_backwards()
  393. {
  394. // A word here is contiguous alnums. `foo=bar baz` is three words.
  395. bool has_seen_alnum = false;
  396. while (m_cursor > 0) {
  397. if (!is_ascii_alphanumeric(m_buffer[m_cursor - 1])) {
  398. if (has_seen_alnum)
  399. break;
  400. } else {
  401. has_seen_alnum = true;
  402. }
  403. erase_character_backwards();
  404. }
  405. }
  406. void Editor::erase_alnum_word_forwards()
  407. {
  408. // A word here is contiguous alnums. `foo=bar baz` is three words.
  409. bool has_seen_alnum = false;
  410. while (m_cursor < m_buffer.size()) {
  411. if (!is_ascii_alphanumeric(m_buffer[m_cursor])) {
  412. if (has_seen_alnum)
  413. break;
  414. } else {
  415. has_seen_alnum = true;
  416. }
  417. erase_character_forwards();
  418. }
  419. }
  420. void Editor::case_change_word(Editor::CaseChangeOp change_op)
  421. {
  422. // A word here is contiguous alnums. `foo=bar baz` is three words.
  423. while (m_cursor < m_buffer.size() && !is_ascii_alphanumeric(m_buffer[m_cursor]))
  424. ++m_cursor;
  425. size_t start = m_cursor;
  426. while (m_cursor < m_buffer.size() && is_ascii_alphanumeric(m_buffer[m_cursor])) {
  427. if (change_op == CaseChangeOp::Uppercase || (change_op == CaseChangeOp::Capital && m_cursor == start)) {
  428. m_buffer[m_cursor] = to_ascii_uppercase(m_buffer[m_cursor]);
  429. } else {
  430. VERIFY(change_op == CaseChangeOp::Lowercase || (change_op == CaseChangeOp::Capital && m_cursor > start));
  431. m_buffer[m_cursor] = to_ascii_lowercase(m_buffer[m_cursor]);
  432. }
  433. ++m_cursor;
  434. m_refresh_needed = true;
  435. }
  436. }
  437. void Editor::capitalize_word()
  438. {
  439. case_change_word(CaseChangeOp::Capital);
  440. }
  441. void Editor::lowercase_word()
  442. {
  443. case_change_word(CaseChangeOp::Lowercase);
  444. }
  445. void Editor::uppercase_word()
  446. {
  447. case_change_word(CaseChangeOp::Uppercase);
  448. }
  449. void Editor::edit_in_external_editor()
  450. {
  451. auto const* editor_command = getenv("EDITOR");
  452. if (!editor_command)
  453. editor_command = m_configuration.m_default_text_editor.characters();
  454. char file_path[] = "/tmp/line-XXXXXX";
  455. auto fd = mkstemp(file_path);
  456. if (fd < 0) {
  457. perror("mktemp");
  458. return;
  459. }
  460. {
  461. auto write_fd = dup(fd);
  462. OutputFileStream stream { write_fd };
  463. StringBuilder builder;
  464. builder.append(Utf32View { m_buffer.data(), m_buffer.size() });
  465. auto bytes = builder.string_view().bytes();
  466. while (!bytes.is_empty()) {
  467. auto nwritten = stream.write(bytes);
  468. bytes = bytes.slice(nwritten);
  469. }
  470. lseek(fd, 0, SEEK_SET);
  471. }
  472. ScopeGuard remove_temp_file_guard {
  473. [fd, file_path] {
  474. close(fd);
  475. unlink(file_path);
  476. }
  477. };
  478. Vector<char const*> args { editor_command, file_path, nullptr };
  479. auto pid = fork();
  480. if (pid == -1) {
  481. perror("fork");
  482. return;
  483. }
  484. if (pid == 0) {
  485. execvp(editor_command, const_cast<char* const*>(args.data()));
  486. perror("execv");
  487. _exit(126);
  488. } else {
  489. int wstatus = 0;
  490. do {
  491. waitpid(pid, &wstatus, 0);
  492. } while (errno == EINTR);
  493. if (!(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0))
  494. return;
  495. }
  496. {
  497. auto file_or_error = Core::File::open(file_path, Core::OpenMode::ReadOnly);
  498. if (file_or_error.is_error())
  499. return;
  500. auto file = file_or_error.release_value();
  501. auto contents = file->read_all();
  502. StringView data { contents };
  503. while (data.ends_with('\n'))
  504. data = data.substring_view(0, data.length() - 1);
  505. m_cursor = 0;
  506. m_chars_touched_in_the_middle = m_buffer.size();
  507. m_buffer.clear_with_capacity();
  508. m_refresh_needed = true;
  509. Utf8View view { data };
  510. if (view.validate()) {
  511. for (auto cp : view)
  512. insert(cp);
  513. } else {
  514. for (auto ch : data)
  515. insert(ch);
  516. }
  517. }
  518. }
  519. }