VimEditingEngine.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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, bool in_visual_mode)
  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. auto& line = editor.line(range.end().line());
  620. size_t column = is_at_start ? 0 : range.end().column() - 1;
  621. column = min(column, line.length() - (in_visual_mode ? 0 : 1));
  622. // Need to not go beyond the last character, as standard in vim.
  623. return { TextPosition { range.end().line(), column } };
  624. }
  625. }
  626. }
  627. }
  628. void VimMotion::reset()
  629. {
  630. m_unit = Unit::Unknown;
  631. m_amount = 0;
  632. m_is_complete = false;
  633. }
  634. CursorWidth VimEditingEngine::cursor_width() const
  635. {
  636. return m_vim_mode == VimMode::Insert ? CursorWidth::NARROW : CursorWidth::WIDE;
  637. }
  638. bool VimEditingEngine::on_key(const KeyEvent& event)
  639. {
  640. switch (m_vim_mode) {
  641. case (VimMode::Insert):
  642. return on_key_in_insert_mode(event);
  643. case (VimMode::Visual):
  644. return on_key_in_visual_mode(event);
  645. case (VimMode::Normal):
  646. return on_key_in_normal_mode(event);
  647. default:
  648. VERIFY_NOT_REACHED();
  649. }
  650. return false;
  651. }
  652. bool VimEditingEngine::on_key_in_insert_mode(const KeyEvent& event)
  653. {
  654. if (EditingEngine::on_key(event))
  655. return true;
  656. if (event.key() == KeyCode::Key_Escape || (event.ctrl() && event.key() == KeyCode::Key_LeftBracket) || (event.ctrl() && event.key() == KeyCode::Key_C)) {
  657. if (m_editor->cursor().column() > 0)
  658. move_one_left();
  659. switch_to_normal_mode();
  660. return true;
  661. }
  662. return false;
  663. }
  664. bool VimEditingEngine::on_key_in_normal_mode(const KeyEvent& event)
  665. {
  666. // Ignore auxiliary keypress events.
  667. if (event.key() == KeyCode::Key_LeftShift
  668. || event.key() == KeyCode::Key_RightShift
  669. || event.key() == KeyCode::Key_Control
  670. || event.key() == KeyCode::Key_Alt) {
  671. return false;
  672. }
  673. if (m_previous_key == KeyCode::Key_D) {
  674. if (event.key() == KeyCode::Key_D && !m_motion.should_consume_next_character()) {
  675. yank(Line);
  676. delete_line();
  677. m_motion.reset();
  678. m_previous_key = {};
  679. } else {
  680. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  681. if (m_motion.is_complete()) {
  682. if (!m_motion.is_cancelled()) {
  683. auto range = m_motion.get_range(*this);
  684. VERIFY(range.has_value());
  685. if (range->is_valid()) {
  686. m_editor->delete_text_range(*range);
  687. }
  688. }
  689. m_motion.reset();
  690. m_previous_key = {};
  691. }
  692. }
  693. } else if (m_previous_key == KeyCode::Key_Y) {
  694. if (event.key() == KeyCode::Key_Y && !m_motion.should_consume_next_character()) {
  695. yank(Line);
  696. m_motion.reset();
  697. m_previous_key = {};
  698. } else {
  699. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  700. if (m_motion.is_complete()) {
  701. if (!m_motion.is_cancelled()) {
  702. auto range = m_motion.get_range(*this);
  703. VERIFY(range.has_value());
  704. if (range->is_valid()) {
  705. m_editor->set_selection(*range);
  706. yank(Selection);
  707. m_editor->clear_selection();
  708. }
  709. }
  710. m_motion.reset();
  711. m_previous_key = {};
  712. }
  713. }
  714. } else if (m_previous_key == KeyCode::Key_C) {
  715. if (event.key() == KeyCode::Key_C && !m_motion.should_consume_next_character()) {
  716. // Needed because the code to replace the deleted line is called after delete_line() so
  717. // what was the second last line before the delete, is now the last line.
  718. bool was_second_last_line = m_editor->cursor().line() == m_editor->line_count() - 2;
  719. yank(Line);
  720. delete_line();
  721. if (was_second_last_line || (m_editor->cursor().line() != 0 && m_editor->cursor().line() != m_editor->line_count() - 1)) {
  722. move_one_up(event);
  723. move_to_line_end();
  724. m_editor->add_code_point(0x0A);
  725. } else if (m_editor->cursor().line() == 0) {
  726. move_to_line_beginning();
  727. m_editor->add_code_point(0x0A);
  728. move_one_up(event);
  729. } else if (m_editor->cursor().line() == m_editor->line_count() - 1) {
  730. m_editor->add_code_point(0x0A);
  731. }
  732. switch_to_insert_mode();
  733. } else {
  734. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  735. if (m_motion.is_complete()) {
  736. if (!m_motion.is_cancelled()) {
  737. auto range = m_motion.get_range(*this);
  738. VERIFY(range.has_value());
  739. if (range->is_valid()) {
  740. m_editor->set_selection(*range);
  741. yank(Selection);
  742. m_editor->delete_text_range(*range);
  743. switch_to_insert_mode();
  744. }
  745. }
  746. m_motion.reset();
  747. m_previous_key = {};
  748. }
  749. }
  750. } else {
  751. if (m_motion.should_consume_next_character()) {
  752. // We must consume the next character.
  753. // FIXME: deduplicate with code below.
  754. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  755. if (m_motion.is_complete()) {
  756. if (!m_motion.is_cancelled()) {
  757. auto maybe_new_position = m_motion.get_position(*this);
  758. if (maybe_new_position.has_value()) {
  759. auto new_position = maybe_new_position.value();
  760. m_editor->set_cursor(new_position);
  761. }
  762. }
  763. m_motion.reset();
  764. }
  765. return true;
  766. }
  767. // Handle first any key codes that are to be applied regardless of modifiers.
  768. switch (event.key()) {
  769. case (KeyCode::Key_Escape):
  770. if (m_editor->on_escape_pressed)
  771. m_editor->on_escape_pressed();
  772. return true;
  773. default:
  774. break;
  775. }
  776. // SHIFT is pressed.
  777. if (event.shift() && !event.ctrl() && !event.alt()) {
  778. switch (event.key()) {
  779. case (KeyCode::Key_A):
  780. move_to_line_end();
  781. switch_to_insert_mode();
  782. return true;
  783. case (KeyCode::Key_I):
  784. move_to_line_beginning();
  785. switch_to_insert_mode();
  786. return true;
  787. case (KeyCode::Key_O):
  788. move_to_line_beginning();
  789. m_editor->add_code_point(0x0A);
  790. move_one_up(event);
  791. switch_to_insert_mode();
  792. return true;
  793. // FIXME: Integrate these into vim motions too.
  794. case (KeyCode::Key_LeftBrace):
  795. move_to_previous_empty_lines_block();
  796. return true;
  797. case (KeyCode::Key_RightBrace):
  798. move_to_next_empty_lines_block();
  799. return true;
  800. default:
  801. break;
  802. }
  803. }
  804. // CTRL is pressed.
  805. if (event.ctrl() && !event.shift() && !event.alt()) {
  806. switch (event.key()) {
  807. case (KeyCode::Key_D):
  808. move_half_page_down();
  809. return true;
  810. case (KeyCode::Key_R):
  811. m_editor->redo();
  812. return true;
  813. case (KeyCode::Key_U):
  814. move_half_page_up();
  815. return true;
  816. default:
  817. break;
  818. }
  819. }
  820. // FIXME: H and L movement keys will move to the previous or next line when reaching the beginning or end
  821. // of the line and pressed again.
  822. // No modifier is pressed.
  823. if (!event.ctrl() && !event.shift() && !event.alt()) {
  824. switch (event.key()) {
  825. case (KeyCode::Key_A):
  826. move_one_right();
  827. switch_to_insert_mode();
  828. return true;
  829. case (KeyCode::Key_C):
  830. m_previous_key = event.key();
  831. return true;
  832. case (KeyCode::Key_D):
  833. m_previous_key = event.key();
  834. return true;
  835. case (KeyCode::Key_I):
  836. switch_to_insert_mode();
  837. return true;
  838. case (KeyCode::Key_O):
  839. move_to_line_end();
  840. m_editor->add_code_point(0x0A);
  841. switch_to_insert_mode();
  842. return true;
  843. case (KeyCode::Key_U):
  844. m_editor->undo();
  845. return true;
  846. case (KeyCode::Key_X):
  847. yank({ m_editor->cursor(), { m_editor->cursor().line(), m_editor->cursor().column() + 1 } });
  848. delete_char();
  849. return true;
  850. case (KeyCode::Key_V):
  851. switch_to_visual_mode();
  852. return true;
  853. case (KeyCode::Key_Y):
  854. m_previous_key = event.key();
  855. return true;
  856. case (KeyCode::Key_P):
  857. put();
  858. return true;
  859. case (KeyCode::Key_PageUp):
  860. move_page_up();
  861. return true;
  862. case (KeyCode::Key_PageDown):
  863. move_page_down();
  864. return true;
  865. default:
  866. break;
  867. }
  868. }
  869. // If nothing else handled the key, we'll be feeding the motion state
  870. // machine instead.
  871. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  872. if (m_motion.is_complete()) {
  873. if (!m_motion.is_cancelled()) {
  874. auto maybe_new_position = m_motion.get_position(*this);
  875. if (maybe_new_position.has_value()) {
  876. auto new_position = maybe_new_position.value();
  877. m_editor->set_cursor(new_position);
  878. }
  879. }
  880. m_motion.reset();
  881. }
  882. }
  883. return true;
  884. }
  885. bool VimEditingEngine::on_key_in_visual_mode(const KeyEvent& event)
  886. {
  887. // If the motion state machine requires the next character, feed it.
  888. if (m_motion.should_consume_next_character()) {
  889. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  890. if (m_motion.is_complete()) {
  891. if (!m_motion.is_cancelled()) {
  892. auto maybe_new_position = m_motion.get_position(*this, true);
  893. if (maybe_new_position.has_value()) {
  894. auto new_position = maybe_new_position.value();
  895. m_editor->set_cursor(new_position);
  896. update_selection_on_cursor_move();
  897. }
  898. }
  899. m_motion.reset();
  900. }
  901. return true;
  902. }
  903. // Handle first any key codes that are to be applied regardless of modifiers.
  904. switch (event.key()) {
  905. case (KeyCode::Key_Escape):
  906. switch_to_normal_mode();
  907. if (m_editor->on_escape_pressed)
  908. m_editor->on_escape_pressed();
  909. return true;
  910. default:
  911. break;
  912. }
  913. // SHIFT is pressed.
  914. if (event.shift() && !event.ctrl() && !event.alt()) {
  915. switch (event.key()) {
  916. case (KeyCode::Key_A):
  917. move_to_line_end();
  918. switch_to_insert_mode();
  919. return true;
  920. case (KeyCode::Key_I):
  921. move_to_line_beginning();
  922. switch_to_insert_mode();
  923. return true;
  924. default:
  925. break;
  926. }
  927. }
  928. // CTRL is pressed.
  929. if (event.ctrl() && !event.shift() && !event.alt()) {
  930. switch (event.key()) {
  931. case (KeyCode::Key_D):
  932. move_half_page_down();
  933. update_selection_on_cursor_move();
  934. return true;
  935. case (KeyCode::Key_U):
  936. move_half_page_up();
  937. update_selection_on_cursor_move();
  938. return true;
  939. default:
  940. break;
  941. }
  942. }
  943. // No modifier is pressed.
  944. if (!event.ctrl() && !event.shift() && !event.alt()) {
  945. switch (event.key()) {
  946. case (KeyCode::Key_D):
  947. yank(Selection);
  948. m_editor->do_delete();
  949. switch_to_normal_mode();
  950. return true;
  951. case (KeyCode::Key_U):
  952. // FIXME: Set selection to uppercase.
  953. return true;
  954. case (KeyCode::Key_X):
  955. yank(Selection);
  956. m_editor->do_delete();
  957. switch_to_normal_mode();
  958. return true;
  959. case (KeyCode::Key_V):
  960. switch_to_normal_mode();
  961. return true;
  962. case (KeyCode::Key_C):
  963. yank(Selection);
  964. m_editor->do_delete();
  965. switch_to_insert_mode();
  966. return true;
  967. case (KeyCode::Key_Y):
  968. yank(Selection);
  969. switch_to_normal_mode();
  970. return true;
  971. case (KeyCode::Key_PageUp):
  972. move_page_up();
  973. update_selection_on_cursor_move();
  974. return true;
  975. case (KeyCode::Key_PageDown):
  976. move_page_down();
  977. update_selection_on_cursor_move();
  978. return true;
  979. default:
  980. break;
  981. }
  982. }
  983. // By default, we feed the motion state machine.
  984. m_motion.add_key_code(event.key(), event.ctrl(), event.shift(), event.alt());
  985. if (m_motion.is_complete()) {
  986. if (!m_motion.is_cancelled()) {
  987. auto maybe_new_position = m_motion.get_position(*this, true);
  988. if (maybe_new_position.has_value()) {
  989. auto new_position = maybe_new_position.value();
  990. m_editor->set_cursor(new_position);
  991. update_selection_on_cursor_move();
  992. }
  993. }
  994. m_motion.reset();
  995. }
  996. return true;
  997. }
  998. void VimEditingEngine::switch_to_normal_mode()
  999. {
  1000. m_vim_mode = VimMode::Normal;
  1001. m_editor->reset_cursor_blink();
  1002. m_previous_key = {};
  1003. clear_visual_mode_data();
  1004. m_motion.reset();
  1005. };
  1006. void VimEditingEngine::switch_to_insert_mode()
  1007. {
  1008. m_vim_mode = VimMode::Insert;
  1009. m_editor->reset_cursor_blink();
  1010. m_previous_key = {};
  1011. clear_visual_mode_data();
  1012. m_motion.reset();
  1013. };
  1014. void VimEditingEngine::switch_to_visual_mode()
  1015. {
  1016. m_vim_mode = VimMode::Visual;
  1017. m_editor->reset_cursor_blink();
  1018. m_previous_key = {};
  1019. m_selection_start_position = m_editor->cursor();
  1020. m_editor->selection()->set(m_editor->cursor(), { m_editor->cursor().line(), m_editor->cursor().column() + 1 });
  1021. m_editor->did_update_selection();
  1022. m_motion.reset();
  1023. }
  1024. void VimEditingEngine::update_selection_on_cursor_move()
  1025. {
  1026. auto cursor = m_editor->cursor();
  1027. auto start = m_selection_start_position < cursor ? m_selection_start_position : cursor;
  1028. auto end = m_selection_start_position < cursor ? cursor : m_selection_start_position;
  1029. if (end.column() >= m_editor->current_line().length()) {
  1030. if (end.line() != m_editor->line_count() - 1)
  1031. end = { end.line() + 1, 0 };
  1032. } else {
  1033. end.set_column(end.column() + 1);
  1034. }
  1035. m_editor->selection()->set(start, end);
  1036. m_editor->did_update_selection();
  1037. }
  1038. void VimEditingEngine::clamp_cursor_position()
  1039. {
  1040. auto cursor = m_editor->cursor();
  1041. if (cursor.column() >= m_editor->current_line().length()) {
  1042. cursor.set_column(m_editor->current_line().length() - 1);
  1043. m_editor->set_cursor(cursor);
  1044. }
  1045. }
  1046. void VimEditingEngine::clear_visual_mode_data()
  1047. {
  1048. if (m_editor->has_selection()) {
  1049. m_editor->selection()->clear();
  1050. m_editor->did_update_selection();
  1051. clamp_cursor_position();
  1052. }
  1053. m_selection_start_position = {};
  1054. }
  1055. void VimEditingEngine::move_half_page_up()
  1056. {
  1057. move_up(0.5);
  1058. };
  1059. void VimEditingEngine::move_half_page_down()
  1060. {
  1061. move_down(0.5);
  1062. };
  1063. void VimEditingEngine::yank(YankType type)
  1064. {
  1065. m_yank_type = type;
  1066. if (type == YankType::Line) {
  1067. m_yank_buffer = m_editor->current_line().to_utf8();
  1068. } else {
  1069. m_yank_buffer = m_editor->selected_text();
  1070. }
  1071. // When putting this, auto indentation (if enabled) will indent as far as
  1072. // is necessary, then any whitespace captured before the yanked text will be placed
  1073. // after the indentation, doubling the indentation.
  1074. if (m_editor->is_automatic_indentation_enabled())
  1075. m_yank_buffer = m_yank_buffer.trim_whitespace(TrimMode::Left);
  1076. }
  1077. void VimEditingEngine::yank(TextRange range)
  1078. {
  1079. m_yank_type = YankType::Selection;
  1080. m_yank_buffer = m_editor->document().text_in_range(range);
  1081. }
  1082. void VimEditingEngine::put()
  1083. {
  1084. if (m_yank_type == YankType::Line) {
  1085. move_to_line_end();
  1086. StringBuilder sb = StringBuilder(m_yank_buffer.length() + 1);
  1087. sb.append_code_point(0x0A);
  1088. sb.append(m_yank_buffer);
  1089. m_editor->insert_at_cursor_or_replace_selection(sb.to_string());
  1090. m_editor->set_cursor({ m_editor->cursor().line(), m_editor->current_line().first_non_whitespace_column() });
  1091. } else {
  1092. // FIXME: If attempting to put on the last column a line,
  1093. // the buffer will bne placed on the next line due to the move_one_left/right behaviour.
  1094. move_one_right();
  1095. m_editor->insert_at_cursor_or_replace_selection(m_yank_buffer);
  1096. move_one_left();
  1097. }
  1098. }
  1099. void VimEditingEngine::move_to_previous_empty_lines_block()
  1100. {
  1101. VERIFY(!m_editor.is_null());
  1102. size_t line_idx = m_editor->cursor().line();
  1103. bool skipping_initial_empty_lines = true;
  1104. while (line_idx > 0) {
  1105. if (m_editor->document().line(line_idx).is_empty()) {
  1106. if (!skipping_initial_empty_lines)
  1107. break;
  1108. } else {
  1109. skipping_initial_empty_lines = false;
  1110. }
  1111. line_idx--;
  1112. }
  1113. TextPosition new_cursor = { line_idx, 0 };
  1114. m_editor->set_cursor(new_cursor);
  1115. };
  1116. void VimEditingEngine::move_to_next_empty_lines_block()
  1117. {
  1118. VERIFY(!m_editor.is_null());
  1119. size_t line_idx = m_editor->cursor().line();
  1120. bool skipping_initial_empty_lines = true;
  1121. while (line_idx < m_editor->line_count() - 1) {
  1122. if (m_editor->document().line(line_idx).is_empty()) {
  1123. if (!skipping_initial_empty_lines)
  1124. break;
  1125. } else {
  1126. skipping_initial_empty_lines = false;
  1127. }
  1128. line_idx++;
  1129. }
  1130. TextPosition new_cursor = { line_idx, 0 };
  1131. m_editor->set_cursor(new_cursor);
  1132. };
  1133. }