InternalFunctions.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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/StringBuilder.h>
  27. #include <LibLine/Editor.h>
  28. #include <ctype.h>
  29. #include <stdio.h>
  30. namespace {
  31. constexpr u32 ctrl(char c) { return c & 0x3f; }
  32. }
  33. namespace Line {
  34. Function<bool(Editor&)> Editor::find_internal_function(const StringView& name)
  35. {
  36. #define __ENUMERATE(internal_name) \
  37. if (name == #internal_name) \
  38. return EDITOR_INTERNAL_FUNCTION(internal_name);
  39. ENUMERATE_EDITOR_INTERNAL_FUNCTIONS(__ENUMERATE)
  40. return {};
  41. }
  42. void Editor::search_forwards()
  43. {
  44. ScopedValueRollback inline_search_cursor_rollback { m_inline_search_cursor };
  45. StringBuilder builder;
  46. builder.append(Utf32View { m_buffer.data(), m_inline_search_cursor });
  47. String search_phrase = builder.to_string();
  48. if (m_search_offset_state == SearchOffsetState::Backwards)
  49. --m_search_offset;
  50. if (m_search_offset > 0) {
  51. ScopedValueRollback search_offset_rollback { m_search_offset };
  52. --m_search_offset;
  53. if (search(search_phrase, true)) {
  54. m_search_offset_state = SearchOffsetState::Forwards;
  55. search_offset_rollback.set_override_rollback_value(m_search_offset);
  56. } else {
  57. m_search_offset_state = SearchOffsetState::Unbiased;
  58. }
  59. } else {
  60. m_search_offset_state = SearchOffsetState::Unbiased;
  61. m_chars_touched_in_the_middle = buffer().size();
  62. m_cursor = 0;
  63. m_buffer.clear();
  64. insert(search_phrase);
  65. m_refresh_needed = true;
  66. }
  67. }
  68. void Editor::search_backwards()
  69. {
  70. ScopedValueRollback inline_search_cursor_rollback { m_inline_search_cursor };
  71. StringBuilder builder;
  72. builder.append(Utf32View { m_buffer.data(), m_inline_search_cursor });
  73. String search_phrase = builder.to_string();
  74. if (m_search_offset_state == SearchOffsetState::Forwards)
  75. ++m_search_offset;
  76. if (search(search_phrase, true)) {
  77. m_search_offset_state = SearchOffsetState::Backwards;
  78. ++m_search_offset;
  79. } else {
  80. m_search_offset_state = SearchOffsetState::Unbiased;
  81. --m_search_offset;
  82. }
  83. }
  84. void Editor::cursor_left_word()
  85. {
  86. if (m_cursor > 0) {
  87. auto skipped_at_least_one_character = false;
  88. for (;;) {
  89. if (m_cursor == 0)
  90. break;
  91. if (skipped_at_least_one_character && !isalnum(m_buffer[m_cursor - 1])) // stop *after* a non-alnum, but only if it changes the position
  92. break;
  93. skipped_at_least_one_character = true;
  94. --m_cursor;
  95. }
  96. }
  97. m_inline_search_cursor = m_cursor;
  98. }
  99. void Editor::cursor_left_character()
  100. {
  101. if (m_cursor > 0)
  102. --m_cursor;
  103. m_inline_search_cursor = m_cursor;
  104. }
  105. void Editor::cursor_right_word()
  106. {
  107. if (m_cursor < m_buffer.size()) {
  108. // Temporarily put a space at the end of our buffer,
  109. // doing this greatly simplifies the logic below.
  110. m_buffer.append(' ');
  111. for (;;) {
  112. if (m_cursor >= m_buffer.size())
  113. break;
  114. if (!isalnum(m_buffer[++m_cursor]))
  115. break;
  116. }
  117. m_buffer.take_last();
  118. }
  119. m_inline_search_cursor = m_cursor;
  120. m_search_offset = 0;
  121. }
  122. void Editor::cursor_right_character()
  123. {
  124. if (m_cursor < m_buffer.size()) {
  125. ++m_cursor;
  126. }
  127. m_inline_search_cursor = m_cursor;
  128. m_search_offset = 0;
  129. }
  130. void Editor::erase_character_backwards()
  131. {
  132. if (m_is_searching) {
  133. return;
  134. }
  135. if (m_cursor == 0) {
  136. fputc('\a', stderr);
  137. fflush(stderr);
  138. return;
  139. }
  140. remove_at_index(m_cursor - 1);
  141. --m_cursor;
  142. m_inline_search_cursor = m_cursor;
  143. // We will have to redraw :(
  144. m_refresh_needed = true;
  145. }
  146. void Editor::erase_character_forwards()
  147. {
  148. if (m_cursor == m_buffer.size()) {
  149. fputc('\a', stderr);
  150. fflush(stderr);
  151. return;
  152. }
  153. remove_at_index(m_cursor);
  154. m_refresh_needed = true;
  155. }
  156. void Editor::finish_edit()
  157. {
  158. fprintf(stderr, "<EOF>\n");
  159. if (!m_always_refresh) {
  160. m_input_error = Error::Eof;
  161. finish();
  162. really_quit_event_loop();
  163. }
  164. }
  165. void Editor::kill_line()
  166. {
  167. for (size_t i = 0; i < m_cursor; ++i)
  168. remove_at_index(0);
  169. m_cursor = 0;
  170. m_refresh_needed = true;
  171. }
  172. void Editor::erase_word_backwards()
  173. {
  174. // A word here is space-separated. `foo=bar baz` is two words.
  175. bool has_seen_nonspace = false;
  176. while (m_cursor > 0) {
  177. if (isspace(m_buffer[m_cursor - 1])) {
  178. if (has_seen_nonspace)
  179. break;
  180. } else {
  181. has_seen_nonspace = true;
  182. }
  183. erase_character_backwards();
  184. }
  185. }
  186. void Editor::erase_to_end()
  187. {
  188. while (m_cursor < m_buffer.size())
  189. erase_character_forwards();
  190. }
  191. void Editor::erase_to_beginning()
  192. {
  193. }
  194. void Editor::transpose_characters()
  195. {
  196. if (m_cursor > 0 && m_buffer.size() >= 2) {
  197. if (m_cursor < m_buffer.size())
  198. ++m_cursor;
  199. swap(m_buffer[m_cursor - 1], m_buffer[m_cursor - 2]);
  200. // FIXME: Update anchored styles too.
  201. m_refresh_needed = true;
  202. m_chars_touched_in_the_middle += 2;
  203. }
  204. }
  205. void Editor::enter_search()
  206. {
  207. if (m_is_searching) {
  208. // How did we get here?
  209. ASSERT_NOT_REACHED();
  210. } else {
  211. m_is_searching = true;
  212. m_search_offset = 0;
  213. m_pre_search_buffer.clear();
  214. for (auto code_point : m_buffer)
  215. m_pre_search_buffer.append(code_point);
  216. m_pre_search_cursor = m_cursor;
  217. // Disable our own notifier so as to avoid interfering with the search editor.
  218. m_notifier->set_enabled(false);
  219. m_search_editor = Editor::construct(Configuration { Configuration::Eager, Configuration::NoSignalHandlers }); // Has anyone seen 'Inception'?
  220. m_search_editor->initialize();
  221. add_child(*m_search_editor);
  222. m_search_editor->on_display_refresh = [this](Editor& search_editor) {
  223. StringBuilder builder;
  224. builder.append(Utf32View { search_editor.buffer().data(), search_editor.buffer().size() });
  225. if (!search(builder.build(), false, false)) {
  226. m_chars_touched_in_the_middle = m_buffer.size();
  227. m_refresh_needed = true;
  228. m_buffer.clear();
  229. m_cursor = 0;
  230. }
  231. refresh_display();
  232. };
  233. // Whenever the search editor gets a ^R, cycle between history entries.
  234. m_search_editor->register_key_input_callback(ctrl('R'), [this](Editor& search_editor) {
  235. ++m_search_offset;
  236. search_editor.m_refresh_needed = true;
  237. return false; // Do not process this key event
  238. });
  239. // ^C should cancel the search.
  240. m_search_editor->register_key_input_callback(ctrl('C'), [this](Editor& search_editor) {
  241. search_editor.finish();
  242. m_reset_buffer_on_search_end = true;
  243. search_editor.deferred_invoke([&search_editor](auto&) { search_editor.really_quit_event_loop(); });
  244. return false;
  245. });
  246. // Whenever the search editor gets a backspace, cycle back between history entries
  247. // unless we're at the zeroth entry, in which case, allow the deletion.
  248. m_search_editor->register_key_input_callback(m_termios.c_cc[VERASE], [this](Editor& search_editor) {
  249. if (m_search_offset > 0) {
  250. --m_search_offset;
  251. search_editor.m_refresh_needed = true;
  252. return false; // Do not process this key event
  253. }
  254. search_editor.erase_character_backwards();
  255. return false;
  256. });
  257. // ^L - This is a source of issues, as the search editor refreshes first,
  258. // and we end up with the wrong order of prompts, so we will first refresh
  259. // ourselves, then refresh the search editor, and then tell him not to process
  260. // this event.
  261. m_search_editor->register_key_input_callback(ctrl('L'), [this](auto& search_editor) {
  262. fprintf(stderr, "\033[3J\033[H\033[2J"); // Clear screen.
  263. // refresh our own prompt
  264. set_origin(1, 1);
  265. m_refresh_needed = true;
  266. refresh_display();
  267. // move the search prompt below ours
  268. // and tell it to redraw itself
  269. auto prompt_end_line = current_prompt_metrics().lines_with_addition(m_cached_buffer_metrics, m_num_columns);
  270. search_editor.set_origin(prompt_end_line + 1, 1);
  271. search_editor.m_refresh_needed = true;
  272. return false;
  273. });
  274. // quit without clearing the current buffer
  275. m_search_editor->register_key_input_callback('\t', [this](Editor& search_editor) {
  276. search_editor.finish();
  277. m_reset_buffer_on_search_end = false;
  278. return false;
  279. });
  280. fprintf(stderr, "\n");
  281. fflush(stderr);
  282. auto search_prompt = "\x1b[32msearch:\x1b[0m ";
  283. // While the search editor is active, we do not want editing events.
  284. m_is_editing = false;
  285. auto search_string_result = m_search_editor->get_line(search_prompt);
  286. // Grab where the search origin last was, anything up to this point will be cleared.
  287. auto search_end_row = m_search_editor->m_origin_row;
  288. remove_child(*m_search_editor);
  289. m_search_editor = nullptr;
  290. m_is_searching = false;
  291. m_is_editing = true;
  292. m_search_offset = 0;
  293. // Re-enable the notifier after discarding the search editor.
  294. m_notifier->set_enabled(true);
  295. if (search_string_result.is_error()) {
  296. // Somethine broke, fail
  297. m_input_error = search_string_result.error();
  298. finish();
  299. return;
  300. }
  301. auto& search_string = search_string_result.value();
  302. // Manually cleanup the search line.
  303. reposition_cursor();
  304. auto search_metrics = actual_rendered_string_metrics(search_string);
  305. auto metrics = actual_rendered_string_metrics(search_prompt);
  306. VT::clear_lines(0, metrics.lines_with_addition(search_metrics, m_num_columns) + search_end_row - m_origin_row - 1);
  307. reposition_cursor();
  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() && !isalnum(m_buffer[cursor]))
  328. ++cursor;
  329. while (cursor < m_buffer.size() && isalnum(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 && !isalnum(m_buffer[start - 1]))
  335. --start;
  336. while (start > 0 && isalnum(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 && !isalnum(m_buffer[start - 1]))
  341. --start;
  342. size_t start_gap = start;
  343. // Move left over first word.
  344. while (start > 0 && isalnum(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. fprintf(stderr, "\033[3J\033[H\033[2J"); // Clear screen.
  377. VT::move_absolute(1, 1);
  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 (!isalnum(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 (!isalnum(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() && !isalnum(m_buffer[m_cursor]))
  422. ++m_cursor;
  423. size_t start = m_cursor;
  424. while (m_cursor < m_buffer.size() && isalnum(m_buffer[m_cursor])) {
  425. if (change_op == CaseChangeOp::Uppercase || (change_op == CaseChangeOp::Capital && m_cursor == start)) {
  426. m_buffer[m_cursor] = toupper(m_buffer[m_cursor]);
  427. } else {
  428. ASSERT(change_op == CaseChangeOp::Lowercase || (change_op == CaseChangeOp::Capital && m_cursor > start));
  429. m_buffer[m_cursor] = tolower(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. }