VimEditingEngine.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/String.h>
  8. #include <LibGUI/Event.h>
  9. #include <LibGUI/TextEditor.h>
  10. #include <LibGUI/VimEditingEngine.h>
  11. #include <string.h>
  12. namespace GUI {
  13. void VimCursor::move()
  14. {
  15. if (m_forwards)
  16. move_forwards();
  17. else
  18. move_backwards();
  19. }
  20. void VimCursor::move_reverse()
  21. {
  22. if (m_forwards)
  23. move_backwards();
  24. else
  25. move_forwards();
  26. }
  27. u32 VimCursor::peek()
  28. {
  29. TextPosition saved_position = m_position;
  30. move();
  31. u32 peeked = current_char();
  32. m_position = saved_position;
  33. return peeked;
  34. }
  35. u32 VimCursor::peek_reverse()
  36. {
  37. TextPosition saved_position = m_position;
  38. move_reverse();
  39. u32 peeked = current_char();
  40. m_position = saved_position;
  41. return peeked;
  42. }
  43. TextDocumentLine& VimCursor::current_line()
  44. {
  45. return m_editor.line(m_position.line());
  46. }
  47. u32 VimCursor::current_char()
  48. {
  49. if (on_empty_line()) {
  50. // Fails all of isspace, ispunct, isalnum so should be good.
  51. return 0;
  52. } else {
  53. return current_line().view().code_points()[m_position.column()];
  54. }
  55. }
  56. bool VimCursor::on_empty_line()
  57. {
  58. return current_line().length() == 0;
  59. }
  60. bool VimCursor::will_cross_line_boundary()
  61. {
  62. if (on_empty_line())
  63. return true;
  64. else if (m_forwards && m_position.column() == current_line().length() - 1)
  65. return true;
  66. else if (!m_forwards && m_position.column() == 0)
  67. return true;
  68. else
  69. return false;
  70. }
  71. void VimCursor::move_forwards()
  72. {
  73. if (on_empty_line() || m_position.column() == current_line().length() - 1) {
  74. if (m_position.line() == m_editor.line_count() - 1) {
  75. // We have reached the end of the document, so any other
  76. // forward movements are no-ops.
  77. m_hit_edge = true;
  78. } else {
  79. m_position.set_column(0);
  80. m_position.set_line(m_position.line() + 1);
  81. m_crossed_line_boundary = true;
  82. }
  83. } else {
  84. m_position.set_column(m_position.column() + 1);
  85. m_crossed_line_boundary = false;
  86. }
  87. }
  88. void VimCursor::move_backwards()
  89. {
  90. if (m_position.column() == 0) {
  91. if (m_position.line() == 0) {
  92. // We have reached the start of the document, so any other
  93. // backward movements are no-ops.
  94. m_hit_edge = true;
  95. } else {
  96. m_position.set_line(m_position.line() - 1);
  97. if (!on_empty_line())
  98. m_position.set_column(current_line().length() - 1);
  99. else
  100. m_position.set_column(0);
  101. m_crossed_line_boundary = true;
  102. }
  103. } else {
  104. m_position.set_column(m_position.column() - 1);
  105. m_crossed_line_boundary = false;
  106. }
  107. }
  108. void VimMotion::add_key_code(KeyCode key, [[maybe_unused]] bool ctrl, bool shift, [[maybe_unused]] bool alt)
  109. {
  110. if (is_complete())
  111. return;
  112. if (m_find_mode != FindMode::None) {
  113. // We need to consume the next character because we are going to find
  114. // until that character.
  115. // HACK: there is no good way to obtain whether a character is alphanumeric
  116. // from the keycode itself.
  117. char const* keycode_str = key_code_to_string(key);
  118. if (strlen(keycode_str) == 1 && (isalpha(keycode_str[0]) || isspace(keycode_str[0]))) {
  119. m_next_character = tolower(keycode_str[0]);
  120. m_unit = Unit::Find;
  121. } else {
  122. m_unit = Unit::Unknown;
  123. }
  124. m_is_complete = true;
  125. m_should_consume_next_character = false;
  126. return;
  127. }
  128. bool should_use_guirky = m_guirky_mode;
  129. switch (key) {
  130. #define DIGIT(n) \
  131. case KeyCode::Key_##n: \
  132. m_amount = (m_amount * 10) + n; \
  133. break
  134. // Digits add digits to the amount.
  135. DIGIT(1);
  136. DIGIT(2);
  137. DIGIT(3);
  138. DIGIT(4);
  139. DIGIT(5);
  140. DIGIT(6);
  141. DIGIT(7);
  142. DIGIT(8);
  143. DIGIT(9);
  144. #undef DIGIT
  145. // Home means to the beginning of the line.
  146. case KeyCode::Key_Home:
  147. m_unit = Unit::Character;
  148. m_amount = START_OF_LINE;
  149. m_is_complete = true;
  150. break;
  151. // If 0 appears while amount is 0, then it means beginning of line.
  152. // Otherwise, it adds 0 to the amount.
  153. case KeyCode::Key_0:
  154. if (m_amount == 0) {
  155. m_unit = Unit::Character;
  156. m_amount = START_OF_LINE;
  157. m_is_complete = true;
  158. } else {
  159. m_amount = m_amount * 10;
  160. }
  161. break;
  162. // End or $ means end of line.
  163. // TODO: d2$ in vim deletes to the end of the line and then the next line.
  164. case KeyCode::Key_End:
  165. case KeyCode::Key_Dollar:
  166. m_unit = Unit::Character;
  167. m_amount = END_OF_LINE;
  168. m_is_complete = true;
  169. break;
  170. // ^ means the first non-whitespace character for this line.
  171. // It deletes backwards if you're in front of it, and forwards if you're behind.
  172. case KeyCode::Key_Circumflex:
  173. m_unit = Unit::Character;
  174. m_amount = START_OF_NON_WHITESPACE;
  175. m_is_complete = true;
  176. break;
  177. // j, down or + operates on this line and amount line(s) after.
  178. case KeyCode::Key_J:
  179. case KeyCode::Key_Down:
  180. case KeyCode::Key_Plus:
  181. m_unit = Unit::Line;
  182. if (m_amount == 0)
  183. m_amount = 1;
  184. m_is_complete = true;
  185. break;
  186. // k, up or - operates on this line and amount line(s) before.
  187. case KeyCode::Key_K:
  188. case KeyCode::Key_Up:
  189. case KeyCode::Key_Minus:
  190. m_unit = Unit::Line;
  191. if (m_amount == 0)
  192. m_amount = -1;
  193. else
  194. m_amount = -m_amount;
  195. m_is_complete = true;
  196. break;
  197. // BS, h or left operates on this character and amount character(s) before.
  198. case KeyCode::Key_Backspace:
  199. case KeyCode::Key_H:
  200. case KeyCode::Key_Left:
  201. m_unit = Unit::Character;
  202. if (m_amount == 0)
  203. m_amount = -1;
  204. else
  205. m_amount = -m_amount;
  206. m_is_complete = true;
  207. break;
  208. // l or right operates on this character and amount character(s) after.
  209. case KeyCode::Key_L:
  210. case KeyCode::Key_Right:
  211. m_unit = Unit::Character;
  212. if (m_amount > 0)
  213. m_amount--;
  214. m_is_complete = true;
  215. break;
  216. // w operates on amount word(s) after.
  217. // W operates on amount WORD(s) after.
  218. case KeyCode::Key_W:
  219. if (shift)
  220. m_unit = Unit::WORD;
  221. else
  222. m_unit = Unit::Word;
  223. if (m_amount == 0)
  224. m_amount = 1;
  225. m_is_complete = true;
  226. break;
  227. // b operates on amount word(s) before.
  228. // B operates on amount WORD(s) before.
  229. case KeyCode::Key_B:
  230. if (shift)
  231. m_unit = Unit::WORD;
  232. else
  233. m_unit = Unit::Word;
  234. if (m_amount == 0)
  235. m_amount = -1;
  236. else
  237. m_amount = -m_amount;
  238. m_is_complete = true;
  239. break;
  240. // e operates on amount of word(s) after, till the end of the last word.
  241. // E operates on amount of WORD(s) after, till the end of the last WORD.
  242. // ge operates on amount of word(s) before, till the end of the last word.
  243. // gE operates on amount of WORD(s) before, till the end of the last WORD.
  244. case KeyCode::Key_E:
  245. if (shift)
  246. m_unit = Unit::EndOfWORD;
  247. else
  248. m_unit = Unit::EndOfWord;
  249. if (m_guirky_mode) {
  250. if (m_amount == 0)
  251. m_amount = -1;
  252. else
  253. m_amount = -m_amount;
  254. m_guirky_mode = false;
  255. } else {
  256. if (m_amount == 0)
  257. m_amount = 1;
  258. }
  259. m_is_complete = true;
  260. break;
  261. // g enables guirky (g-prefix commands) mode.
  262. // gg operates from the start of the document to the cursor.
  263. // G operates from the cursor to the end of the document.
  264. case KeyCode::Key_G:
  265. if (m_guirky_mode) {
  266. if (shift) {
  267. // gG is not a valid command in vim.
  268. m_guirky_mode = false;
  269. m_unit = Unit::Unknown;
  270. m_is_complete = true;
  271. } else {
  272. m_guirky_mode = false;
  273. m_unit = Unit::Document;
  274. m_amount = -1;
  275. m_is_complete = true;
  276. }
  277. } else {
  278. if (shift) {
  279. m_unit = Unit::Document;
  280. m_amount = 1;
  281. m_is_complete = true;
  282. } else {
  283. m_guirky_mode = true;
  284. }
  285. }
  286. break;
  287. // t operates until the given character.
  288. case KeyCode::Key_T:
  289. m_find_mode = FindMode::To;
  290. m_should_consume_next_character = true;
  291. if (m_amount == 0)
  292. m_amount = 1;
  293. break;
  294. // f operates through the given character.
  295. case KeyCode::Key_F:
  296. m_find_mode = FindMode::Find;
  297. m_should_consume_next_character = true;
  298. if (m_amount == 0)
  299. m_amount = 1;
  300. break;
  301. default:
  302. m_unit = Unit::Unknown;
  303. m_is_complete = true;
  304. break;
  305. }
  306. if (should_use_guirky && m_guirky_mode) {
  307. // If we didn't use the g then we cancel the motion.
  308. m_guirky_mode = false;
  309. m_unit = Unit::Unknown;
  310. m_is_complete = true;
  311. }
  312. }
  313. Optional<TextRange> VimMotion::get_range(VimEditingEngine& engine, bool normalize_for_position)
  314. {
  315. if (!is_complete() || is_cancelled())
  316. return {};
  317. TextEditor& editor = engine.editor();
  318. auto position = editor.cursor();
  319. int amount = abs(m_amount);
  320. bool forwards = m_amount >= 0;
  321. VimCursor cursor { editor, position, forwards };
  322. m_start_line = m_end_line = position.line();
  323. m_start_column = m_end_column = position.column();
  324. switch (m_unit) {
  325. case Unit::Unknown:
  326. VERIFY_NOT_REACHED();
  327. case Unit::Document: {
  328. calculate_document_range(editor);
  329. break;
  330. }
  331. case Unit::Line: {
  332. calculate_line_range(editor, normalize_for_position);
  333. break;
  334. }
  335. case Unit::EndOfWord:
  336. case Unit::Word:
  337. case Unit::EndOfWORD:
  338. case Unit::WORD: {
  339. calculate_word_range(cursor, amount, normalize_for_position);
  340. break;
  341. }
  342. case Unit::Character: {
  343. calculate_character_range(cursor, amount, normalize_for_position);
  344. break;
  345. }
  346. case Unit::Find: {
  347. calculate_find_range(cursor, amount);
  348. break;
  349. }
  350. }
  351. return { TextRange { { m_start_line, m_start_column }, { m_end_line, m_end_column } } };
  352. }
  353. void VimMotion::calculate_document_range(TextEditor& editor)
  354. {
  355. if (m_amount >= 0) {
  356. m_end_line = editor.line_count() - 1;
  357. auto& last_line = editor.line(m_end_line);
  358. m_end_column = last_line.length();
  359. } else {
  360. m_start_line = 0;
  361. m_start_column = 0;
  362. }
  363. }
  364. void VimMotion::calculate_line_range(TextEditor& editor, bool normalize_for_position)
  365. {
  366. // Use this line +/- m_amount lines.
  367. m_start_column = 0;
  368. m_end_column = 0;
  369. if (m_amount >= 0) {
  370. m_end_line = min(m_end_line + !normalize_for_position + m_amount, editor.line_count());
  371. // We can't delete to "last line + 1", so if we're on the last line,
  372. // delete until the end.
  373. if (m_end_line == editor.line_count()) {
  374. m_end_line--;
  375. m_end_column = editor.line(m_end_line).length();
  376. }
  377. } else {
  378. // Can't write it as max(start_line + m_amount, 0) because of unsigned
  379. // shenanigans.
  380. if (m_start_line <= (unsigned)-m_amount)
  381. m_start_line = 0;
  382. else
  383. m_start_line += m_amount;
  384. if (m_end_line == editor.line_count() - 1)
  385. m_end_column = editor.line(m_end_line).length();
  386. else
  387. m_end_line++;
  388. }
  389. }
  390. void VimMotion::calculate_word_range(VimCursor& cursor, int amount, bool normalize_for_position)
  391. {
  392. enum {
  393. Whitespace,
  394. Word,
  395. Punctuation,
  396. Unknown
  397. };
  398. // Word is defined as a-zA-Z0-9_.
  399. auto part_of_word = [](u32 ch) { return ch == '_' || isalnum(ch); };
  400. auto part_of_punctuation = [](u32 ch) { return ch != '_' && ispunct(ch); };
  401. auto classify = [&](u32 ch) {
  402. if (isspace(ch))
  403. return Whitespace;
  404. else if (part_of_word(ch))
  405. return Word;
  406. else if (part_of_punctuation(ch))
  407. return Punctuation;
  408. else
  409. return Unknown;
  410. };
  411. // A small explanation for the code below: Because the direction of the
  412. // movement for this motion determines what the "start" and "end" of a word
  413. // is, the code below treats the motions like so:
  414. // - Start of word: w/W/ge/gE
  415. // - End of word: e/E/b/B
  416. while (amount > 0) {
  417. if (cursor.hit_edge())
  418. break;
  419. if ((!cursor.forwards() && (m_unit == Unit::Word || m_unit == Unit::WORD))
  420. || (cursor.forwards() && (m_unit == Unit::EndOfWord || m_unit == Unit::EndOfWORD))) {
  421. // End-of-word motions peek at the "next" character and if its class
  422. // is not the same as ours, they move over one character (to end up
  423. // at the new character class). This is required because we don't
  424. // want to exit the word with end-of-word motions.
  425. if (m_unit == Unit::Word || m_unit == Unit::EndOfWord) {
  426. // Word-style peeking
  427. int current_class = classify(cursor.current_char());
  428. int peeked_class = classify(cursor.peek());
  429. if (current_class != peeked_class) {
  430. cursor.move();
  431. }
  432. } else {
  433. // WORD-style peeking, much simpler
  434. if (isspace(cursor.peek())) {
  435. cursor.move();
  436. }
  437. }
  438. } else {
  439. // Start-of-word motions want to exit the word no matter which part
  440. // of it we're in.
  441. if (m_unit == Unit::Word || m_unit == Unit::EndOfWord) {
  442. // Word-style consumption
  443. if (part_of_word(cursor.current_char())) {
  444. do {
  445. cursor.move();
  446. if (cursor.hit_edge() || cursor.crossed_line_boundary())
  447. break;
  448. } while (part_of_word(cursor.current_char()));
  449. } else if (part_of_punctuation(cursor.current_char())) {
  450. do {
  451. cursor.move();
  452. if (cursor.hit_edge() || cursor.crossed_line_boundary())
  453. break;
  454. } while (part_of_punctuation(cursor.current_char()));
  455. } else if (cursor.on_empty_line()) {
  456. cursor.move();
  457. }
  458. } else {
  459. // WORD-style consumption
  460. if (!isspace(cursor.current_char())) {
  461. do {
  462. cursor.move();
  463. if (cursor.hit_edge() || cursor.crossed_line_boundary())
  464. break;
  465. } while (!isspace(cursor.current_char()));
  466. } else if (cursor.on_empty_line()) {
  467. cursor.move();
  468. }
  469. }
  470. }
  471. // Now consume any space if it exists.
  472. if (isspace(cursor.current_char())) {
  473. do {
  474. cursor.move();
  475. if (cursor.hit_edge())
  476. break;
  477. } while (isspace(cursor.current_char()));
  478. }
  479. if ((!cursor.forwards() && (m_unit == Unit::Word || m_unit == Unit::WORD))
  480. || (cursor.forwards() && (m_unit == Unit::EndOfWord || m_unit == Unit::EndOfWORD))) {
  481. // End-of-word motions consume until the class doesn't match.
  482. if (m_unit == Unit::Word || m_unit == Unit::EndOfWord) {
  483. // Word-style consumption
  484. int current_class = classify(cursor.current_char());
  485. while (classify(cursor.current_char()) == current_class) {
  486. cursor.move();
  487. if (cursor.hit_edge() || cursor.crossed_line_boundary())
  488. break;
  489. }
  490. } else {
  491. // WORD-style consumption
  492. while (!isspace(cursor.current_char())) {
  493. cursor.move();
  494. if (cursor.hit_edge() || cursor.crossed_line_boundary())
  495. break;
  496. }
  497. }
  498. }
  499. amount--;
  500. }
  501. // If we need to normalize for position then we do a move_reverse for
  502. // end-of-word motions, because vim acts on end-of-word ranges through the
  503. // character your cursor is placed on but acts on start-of-words *until* the
  504. // character your cursor is placed on.
  505. if (normalize_for_position) {
  506. if ((!cursor.forwards() && (m_unit == Unit::Word || m_unit == Unit::WORD))
  507. || (cursor.forwards() && (m_unit == Unit::EndOfWord || m_unit == Unit::EndOfWORD))) {
  508. if (!cursor.hit_edge())
  509. cursor.move_reverse();
  510. }
  511. }
  512. if (cursor.forwards()) {
  513. m_end_line = cursor.current_position().line();
  514. m_end_column = cursor.current_position().column() + normalize_for_position;
  515. } else {
  516. m_start_line = cursor.current_position().line();
  517. m_start_column = cursor.current_position().column();
  518. }
  519. }
  520. void VimMotion::calculate_character_range(VimCursor& cursor, int amount, bool normalize_for_position)
  521. {
  522. if (m_amount == START_OF_LINE) {
  523. m_start_column = 0;
  524. } else if (m_amount == END_OF_LINE) {
  525. m_end_column = cursor.current_line().length();
  526. } else if (m_amount == START_OF_NON_WHITESPACE) {
  527. // Find the first non-whitespace character and set the range from current
  528. // position to it.
  529. TextPosition cursor_copy = cursor.current_position();
  530. cursor.current_position().set_column(0);
  531. while (isspace(cursor.current_char())) {
  532. if (cursor.will_cross_line_boundary())
  533. break;
  534. cursor.move_forwards();
  535. }
  536. if (cursor_copy < cursor.current_position())
  537. m_end_column = cursor.current_position().column() + 1;
  538. else
  539. m_start_column = cursor.current_position().column();
  540. } else {
  541. while (amount > 0) {
  542. if (cursor.hit_edge() || cursor.will_cross_line_boundary())
  543. break;
  544. cursor.move();
  545. amount--;
  546. }
  547. if (cursor.forwards()) {
  548. m_end_column = cursor.current_position().column() + 1 + normalize_for_position;
  549. } else {
  550. m_start_column = cursor.current_position().column();
  551. }
  552. }
  553. }
  554. void VimMotion::calculate_find_range(VimCursor& cursor, int amount)
  555. {
  556. // Find the searched character (case-insensitive).
  557. while (amount > 0) {
  558. cursor.move_forwards();
  559. while ((unsigned)tolower(cursor.current_char()) != m_next_character) {
  560. if (cursor.will_cross_line_boundary())
  561. break;
  562. cursor.move_forwards();
  563. }
  564. amount--;
  565. }
  566. // If we didn't find our character before reaching the end of the line, then
  567. // we want the range to be invalid so no operation is performed.
  568. if ((unsigned)tolower(cursor.current_char()) == m_next_character) {
  569. // We found our character.
  570. bool in_find_mode = m_find_mode == FindMode::Find;
  571. m_end_column = cursor.current_position().column() + in_find_mode;
  572. }
  573. m_find_mode = FindMode::None;
  574. }
  575. Optional<TextPosition> VimMotion::get_position(VimEditingEngine& engine)
  576. {
  577. auto range_optional = get_range(engine, true);
  578. if (!range_optional.has_value())
  579. return {};
  580. auto range = range_optional.value();
  581. if (!range.is_valid())
  582. return {};
  583. TextEditor& editor = engine.editor();
  584. auto cursor_position = editor.cursor();
  585. switch (m_unit) {
  586. case Unit::Document: {
  587. if (range.start().line() < cursor_position.line()) {
  588. cursor_position.set_line(range.start().line());
  589. } else {
  590. cursor_position.set_line(range.end().line());
  591. }
  592. cursor_position.set_column(0);
  593. return { cursor_position };
  594. }
  595. case Unit::Line: {
  596. size_t line_number;
  597. // Because we select lines from start to end, we can't use that
  598. // to get the new position, so we do some correction here.
  599. if (range.start().line() < cursor_position.line() || m_amount < 0) {
  600. line_number = range.start().line();
  601. } else {
  602. line_number = range.end().line();
  603. }
  604. auto& line = editor.line(line_number);
  605. cursor_position.set_line(line_number);
  606. if (line.length() <= cursor_position.column()) {
  607. cursor_position.set_column(line.length() - 1);
  608. }
  609. return { cursor_position };
  610. }
  611. default: {
  612. if (range.start() < cursor_position) {
  613. return { range.start() };
  614. } else {
  615. // Ranges are end-exclusive. The normalize_for_position argument we pass
  616. // above in get_range normalizes some values which shouldn't be
  617. // end-exclusive during normal operations.
  618. bool is_at_start = range.end().column() == 0;
  619. size_t column = is_at_start ? 0 : range.end().column() - 1;
  620. // Need to not go beyond the last character, as standard in vim.
  621. auto& line = editor.line(range.end().line());
  622. return { TextPosition { range.end().line(), min(column, line.length() - 1) } };
  623. }
  624. }
  625. }
  626. }
  627. void VimMotion::reset()
  628. {
  629. m_unit = Unit::Unknown;
  630. m_amount = 0;
  631. m_is_complete = false;
  632. }
  633. CursorWidth VimEditingEngine::cursor_width() const
  634. {
  635. return m_vim_mode == VimMode::Insert ? CursorWidth::NARROW : CursorWidth::WIDE;
  636. }
  637. bool VimEditingEngine::on_key(const KeyEvent& event)
  638. {
  639. switch (m_vim_mode) {
  640. case (VimMode::Insert):
  641. return on_key_in_insert_mode(event);
  642. case (VimMode::Visual):
  643. return on_key_in_visual_mode(event);
  644. case (VimMode::Normal):
  645. return on_key_in_normal_mode(event);
  646. default:
  647. VERIFY_NOT_REACHED();
  648. }
  649. return false;
  650. }
  651. bool VimEditingEngine::on_key_in_insert_mode(const KeyEvent& event)
  652. {
  653. if (EditingEngine::on_key(event))
  654. return true;
  655. if (event.key() == KeyCode::Key_Escape || (event.ctrl() && event.key() == KeyCode::Key_LeftBracket) || (event.ctrl() && event.key() == KeyCode::Key_C)) {
  656. if (m_editor->cursor().column() > 0)
  657. move_one_left();
  658. switch_to_normal_mode();
  659. return true;
  660. }
  661. return false;
  662. }
  663. bool VimEditingEngine::on_key_in_normal_mode(const KeyEvent& event)
  664. {
  665. // Ignore auxiliary keypress events.
  666. if (event.key() == KeyCode::Key_LeftShift
  667. || event.key() == KeyCode::Key_RightShift
  668. || event.key() == KeyCode::Key_Control
  669. || event.key() == KeyCode::Key_Alt) {
  670. return false;
  671. }
  672. if (m_previous_key == KeyCode::Key_D) {
  673. if (event.key() == KeyCode::Key_D && !m_motion.should_consume_next_character()) {
  674. yank(Line);
  675. delete_line();
  676. m_motion.reset();
  677. m_previous_key = {};
  678. } else {
  679. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  680. if (m_motion.is_complete()) {
  681. if (!m_motion.is_cancelled()) {
  682. auto range = m_motion.get_range(*this);
  683. VERIFY(range.has_value());
  684. if (range->is_valid()) {
  685. m_editor->delete_text_range(*range);
  686. }
  687. }
  688. m_motion.reset();
  689. m_previous_key = {};
  690. }
  691. }
  692. } else if (m_previous_key == KeyCode::Key_Y) {
  693. if (event.key() == KeyCode::Key_Y && !m_motion.should_consume_next_character()) {
  694. yank(Line);
  695. m_motion.reset();
  696. m_previous_key = {};
  697. } else {
  698. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  699. if (m_motion.is_complete()) {
  700. if (!m_motion.is_cancelled()) {
  701. auto range = m_motion.get_range(*this);
  702. VERIFY(range.has_value());
  703. if (range->is_valid()) {
  704. m_editor->set_selection(*range);
  705. yank(Selection);
  706. m_editor->clear_selection();
  707. }
  708. }
  709. m_motion.reset();
  710. m_previous_key = {};
  711. }
  712. }
  713. } else if (m_previous_key == KeyCode::Key_C) {
  714. if (event.key() == KeyCode::Key_C && !m_motion.should_consume_next_character()) {
  715. // Needed because the code to replace the deleted line is called after delete_line() so
  716. // what was the second last line before the delete, is now the last line.
  717. bool was_second_last_line = m_editor->cursor().line() == m_editor->line_count() - 2;
  718. yank(Line);
  719. delete_line();
  720. if (was_second_last_line || (m_editor->cursor().line() != 0 && m_editor->cursor().line() != m_editor->line_count() - 1)) {
  721. move_one_up(event);
  722. move_to_line_end();
  723. m_editor->add_code_point(0x0A);
  724. } else if (m_editor->cursor().line() == 0) {
  725. move_to_line_beginning();
  726. m_editor->add_code_point(0x0A);
  727. move_one_up(event);
  728. } else if (m_editor->cursor().line() == m_editor->line_count() - 1) {
  729. m_editor->add_code_point(0x0A);
  730. }
  731. switch_to_insert_mode();
  732. } else {
  733. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  734. if (m_motion.is_complete()) {
  735. if (!m_motion.is_cancelled()) {
  736. auto range = m_motion.get_range(*this);
  737. VERIFY(range.has_value());
  738. if (range->is_valid()) {
  739. m_editor->set_selection(*range);
  740. yank(Selection);
  741. m_editor->delete_text_range(*range);
  742. switch_to_insert_mode();
  743. }
  744. }
  745. m_motion.reset();
  746. m_previous_key = {};
  747. }
  748. }
  749. } else {
  750. if (m_motion.should_consume_next_character()) {
  751. // We must consume the next character.
  752. // FIXME: deduplicate with code below.
  753. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  754. if (m_motion.is_complete()) {
  755. if (!m_motion.is_cancelled()) {
  756. auto maybe_new_position = m_motion.get_position(*this);
  757. if (maybe_new_position.has_value()) {
  758. auto new_position = maybe_new_position.value();
  759. m_editor->set_cursor(new_position);
  760. }
  761. }
  762. m_motion.reset();
  763. }
  764. return true;
  765. }
  766. // Handle first any key codes that are to be applied regardless of modifiers.
  767. switch (event.key()) {
  768. case (KeyCode::Key_Escape):
  769. if (m_editor->on_escape_pressed)
  770. m_editor->on_escape_pressed();
  771. return true;
  772. default:
  773. break;
  774. }
  775. // SHIFT is pressed.
  776. if (event.shift() && !event.ctrl() && !event.alt()) {
  777. switch (event.key()) {
  778. case (KeyCode::Key_A):
  779. move_to_line_end();
  780. switch_to_insert_mode();
  781. return true;
  782. case (KeyCode::Key_I):
  783. move_to_line_beginning();
  784. switch_to_insert_mode();
  785. return true;
  786. case (KeyCode::Key_O):
  787. move_to_line_beginning();
  788. m_editor->add_code_point(0x0A);
  789. move_one_up(event);
  790. switch_to_insert_mode();
  791. return true;
  792. // FIXME: Integrate these into vim motions too.
  793. case (KeyCode::Key_LeftBrace):
  794. move_to_previous_empty_lines_block();
  795. return true;
  796. case (KeyCode::Key_RightBrace):
  797. move_to_next_empty_lines_block();
  798. return true;
  799. default:
  800. break;
  801. }
  802. }
  803. // CTRL is pressed.
  804. if (event.ctrl() && !event.shift() && !event.alt()) {
  805. switch (event.key()) {
  806. case (KeyCode::Key_D):
  807. move_half_page_down();
  808. return true;
  809. case (KeyCode::Key_R):
  810. m_editor->redo();
  811. return true;
  812. case (KeyCode::Key_U):
  813. move_half_page_up();
  814. return true;
  815. default:
  816. break;
  817. }
  818. }
  819. // FIXME: H and L movement keys will move to the previous or next line when reaching the beginning or end
  820. // of the line and pressed again.
  821. // No modifier is pressed.
  822. if (!event.ctrl() && !event.shift() && !event.alt()) {
  823. switch (event.key()) {
  824. case (KeyCode::Key_A):
  825. move_one_right();
  826. switch_to_insert_mode();
  827. return true;
  828. case (KeyCode::Key_C):
  829. m_previous_key = event.key();
  830. return true;
  831. case (KeyCode::Key_D):
  832. m_previous_key = event.key();
  833. return true;
  834. case (KeyCode::Key_I):
  835. switch_to_insert_mode();
  836. return true;
  837. case (KeyCode::Key_O):
  838. move_to_line_end();
  839. m_editor->add_code_point(0x0A);
  840. switch_to_insert_mode();
  841. return true;
  842. case (KeyCode::Key_U):
  843. m_editor->undo();
  844. return true;
  845. case (KeyCode::Key_X):
  846. yank({ m_editor->cursor(), { m_editor->cursor().line(), m_editor->cursor().column() + 1 } });
  847. delete_char();
  848. return true;
  849. case (KeyCode::Key_V):
  850. switch_to_visual_mode();
  851. return true;
  852. case (KeyCode::Key_Y):
  853. m_previous_key = event.key();
  854. return true;
  855. case (KeyCode::Key_P):
  856. put();
  857. return true;
  858. case (KeyCode::Key_PageUp):
  859. move_page_up();
  860. return true;
  861. case (KeyCode::Key_PageDown):
  862. move_page_down();
  863. return true;
  864. default:
  865. break;
  866. }
  867. }
  868. // If nothing else handled the key, we'll be feeding the motion state
  869. // machine instead.
  870. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  871. if (m_motion.is_complete()) {
  872. if (!m_motion.is_cancelled()) {
  873. auto maybe_new_position = m_motion.get_position(*this);
  874. if (maybe_new_position.has_value()) {
  875. auto new_position = maybe_new_position.value();
  876. m_editor->set_cursor(new_position);
  877. }
  878. }
  879. m_motion.reset();
  880. }
  881. }
  882. return true;
  883. }
  884. bool VimEditingEngine::on_key_in_visual_mode(const KeyEvent& event)
  885. {
  886. // If the motion state machine requires the next character, feed it.
  887. if (m_motion.should_consume_next_character()) {
  888. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  889. if (m_motion.is_complete()) {
  890. if (!m_motion.is_cancelled()) {
  891. auto maybe_new_position = m_motion.get_position(*this);
  892. if (maybe_new_position.has_value()) {
  893. auto new_position = maybe_new_position.value();
  894. m_editor->set_cursor(new_position);
  895. update_selection_on_cursor_move();
  896. }
  897. }
  898. m_motion.reset();
  899. }
  900. return true;
  901. }
  902. // Handle first any key codes that are to be applied regardless of modifiers.
  903. switch (event.key()) {
  904. case (KeyCode::Key_Escape):
  905. switch_to_normal_mode();
  906. if (m_editor->on_escape_pressed)
  907. m_editor->on_escape_pressed();
  908. return true;
  909. default:
  910. break;
  911. }
  912. // SHIFT is pressed.
  913. if (event.shift() && !event.ctrl() && !event.alt()) {
  914. switch (event.key()) {
  915. case (KeyCode::Key_A):
  916. move_to_line_end();
  917. switch_to_insert_mode();
  918. return true;
  919. case (KeyCode::Key_I):
  920. move_to_line_beginning();
  921. switch_to_insert_mode();
  922. return true;
  923. default:
  924. break;
  925. }
  926. }
  927. // CTRL is pressed.
  928. if (event.ctrl() && !event.shift() && !event.alt()) {
  929. switch (event.key()) {
  930. case (KeyCode::Key_D):
  931. move_half_page_down();
  932. update_selection_on_cursor_move();
  933. return true;
  934. case (KeyCode::Key_U):
  935. move_half_page_up();
  936. update_selection_on_cursor_move();
  937. return true;
  938. default:
  939. break;
  940. }
  941. }
  942. // No modifier is pressed.
  943. if (!event.ctrl() && !event.shift() && !event.alt()) {
  944. switch (event.key()) {
  945. case (KeyCode::Key_D):
  946. yank(Selection);
  947. m_editor->do_delete();
  948. switch_to_normal_mode();
  949. return true;
  950. case (KeyCode::Key_U):
  951. // FIXME: Set selection to uppercase.
  952. return true;
  953. case (KeyCode::Key_X):
  954. yank(Selection);
  955. m_editor->do_delete();
  956. switch_to_normal_mode();
  957. return true;
  958. case (KeyCode::Key_V):
  959. switch_to_normal_mode();
  960. return true;
  961. case (KeyCode::Key_C):
  962. yank(Selection);
  963. m_editor->do_delete();
  964. switch_to_insert_mode();
  965. return true;
  966. case (KeyCode::Key_Y):
  967. yank(Selection);
  968. switch_to_normal_mode();
  969. return true;
  970. case (KeyCode::Key_PageUp):
  971. move_page_up();
  972. update_selection_on_cursor_move();
  973. return true;
  974. case (KeyCode::Key_PageDown):
  975. move_page_down();
  976. update_selection_on_cursor_move();
  977. return true;
  978. default:
  979. break;
  980. }
  981. }
  982. // By default, we feed the motion state machine.
  983. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  984. if (m_motion.is_complete()) {
  985. if (!m_motion.is_cancelled()) {
  986. auto maybe_new_position = m_motion.get_position(*this);
  987. if (maybe_new_position.has_value()) {
  988. auto new_position = maybe_new_position.value();
  989. m_editor->set_cursor(new_position);
  990. update_selection_on_cursor_move();
  991. }
  992. }
  993. m_motion.reset();
  994. }
  995. return true;
  996. }
  997. void VimEditingEngine::switch_to_normal_mode()
  998. {
  999. m_vim_mode = VimMode::Normal;
  1000. m_editor->reset_cursor_blink();
  1001. m_previous_key = {};
  1002. clear_visual_mode_data();
  1003. m_motion.reset();
  1004. };
  1005. void VimEditingEngine::switch_to_insert_mode()
  1006. {
  1007. m_vim_mode = VimMode::Insert;
  1008. m_editor->reset_cursor_blink();
  1009. m_previous_key = {};
  1010. clear_visual_mode_data();
  1011. m_motion.reset();
  1012. };
  1013. void VimEditingEngine::switch_to_visual_mode()
  1014. {
  1015. m_vim_mode = VimMode::Visual;
  1016. m_editor->reset_cursor_blink();
  1017. m_previous_key = {};
  1018. m_editor->selection()->set(m_editor->cursor(), { m_editor->cursor().line(), m_editor->cursor().column() + 1 });
  1019. m_editor->did_update_selection();
  1020. m_motion.reset();
  1021. }
  1022. void VimEditingEngine::update_selection_on_cursor_move()
  1023. {
  1024. auto cursor = m_editor->cursor();
  1025. auto& line = m_editor->current_line();
  1026. cursor.set_column(min(cursor.column() + 1, line.length()));
  1027. m_editor->selection()->set_end(cursor);
  1028. m_editor->did_update_selection();
  1029. }
  1030. void VimEditingEngine::clear_visual_mode_data()
  1031. {
  1032. if (m_editor->has_selection()) {
  1033. m_editor->selection()->clear();
  1034. m_editor->did_update_selection();
  1035. }
  1036. }
  1037. void VimEditingEngine::move_half_page_up()
  1038. {
  1039. move_up(0.5);
  1040. };
  1041. void VimEditingEngine::move_half_page_down()
  1042. {
  1043. move_down(0.5);
  1044. };
  1045. void VimEditingEngine::yank(YankType type)
  1046. {
  1047. m_yank_type = type;
  1048. if (type == YankType::Line) {
  1049. m_yank_buffer = m_editor->current_line().to_utf8();
  1050. } else {
  1051. m_yank_buffer = m_editor->selected_text();
  1052. }
  1053. // When putting this, auto indentation (if enabled) will indent as far as
  1054. // is necessary, then any whitespace captured before the yanked text will be placed
  1055. // after the indentation, doubling the indentation.
  1056. if (m_editor->is_automatic_indentation_enabled())
  1057. m_yank_buffer = m_yank_buffer.trim_whitespace(TrimMode::Left);
  1058. }
  1059. void VimEditingEngine::yank(TextRange range)
  1060. {
  1061. m_yank_type = YankType::Selection;
  1062. m_yank_buffer = m_editor->document().text_in_range(range);
  1063. }
  1064. void VimEditingEngine::put()
  1065. {
  1066. if (m_yank_type == YankType::Line) {
  1067. move_to_line_end();
  1068. StringBuilder sb = StringBuilder(m_yank_buffer.length() + 1);
  1069. sb.append_code_point(0x0A);
  1070. sb.append(m_yank_buffer);
  1071. m_editor->insert_at_cursor_or_replace_selection(sb.to_string());
  1072. m_editor->set_cursor({ m_editor->cursor().line(), m_editor->current_line().first_non_whitespace_column() });
  1073. } else {
  1074. // FIXME: If attempting to put on the last column a line,
  1075. // the buffer will bne placed on the next line due to the move_one_left/right behaviour.
  1076. move_one_right();
  1077. m_editor->insert_at_cursor_or_replace_selection(m_yank_buffer);
  1078. move_one_left();
  1079. }
  1080. }
  1081. void VimEditingEngine::move_to_previous_empty_lines_block()
  1082. {
  1083. VERIFY(!m_editor.is_null());
  1084. size_t line_idx = m_editor->cursor().line();
  1085. bool skipping_initial_empty_lines = true;
  1086. while (line_idx > 0) {
  1087. if (m_editor->document().line(line_idx).is_empty()) {
  1088. if (!skipping_initial_empty_lines)
  1089. break;
  1090. } else {
  1091. skipping_initial_empty_lines = false;
  1092. }
  1093. line_idx--;
  1094. }
  1095. TextPosition new_cursor = { line_idx, 0 };
  1096. m_editor->set_cursor(new_cursor);
  1097. };
  1098. void VimEditingEngine::move_to_next_empty_lines_block()
  1099. {
  1100. VERIFY(!m_editor.is_null());
  1101. size_t line_idx = m_editor->cursor().line();
  1102. bool skipping_initial_empty_lines = true;
  1103. while (line_idx < m_editor->line_count() - 1) {
  1104. if (m_editor->document().line(line_idx).is_empty()) {
  1105. if (!skipping_initial_empty_lines)
  1106. break;
  1107. } else {
  1108. skipping_initial_empty_lines = false;
  1109. }
  1110. line_idx++;
  1111. }
  1112. TextPosition new_cursor = { line_idx, 0 };
  1113. m_editor->set_cursor(new_cursor);
  1114. };
  1115. }