InternalFunctions.cpp 19 KB

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