InternalFunctions.cpp 24 KB

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