TextDocument.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Badge.h>
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/Debug.h>
  11. #include <AK/QuickSort.h>
  12. #include <AK/ScopeGuard.h>
  13. #include <AK/StdLibExtras.h>
  14. #include <AK/StringBuilder.h>
  15. #include <AK/Utf8View.h>
  16. #include <LibCore/Timer.h>
  17. #include <LibGUI/TextDocument.h>
  18. #include <LibRegex/Regex.h>
  19. #include <LibUnicode/CharacterTypes.h>
  20. #include <LibUnicode/Segmentation.h>
  21. namespace GUI {
  22. NonnullRefPtr<TextDocument> TextDocument::create(Client* client)
  23. {
  24. return adopt_ref(*new TextDocument(client));
  25. }
  26. TextDocument::TextDocument(Client* client)
  27. {
  28. if (client)
  29. m_clients.set(client);
  30. append_line(make<TextDocumentLine>(*this));
  31. set_unmodified();
  32. m_undo_stack.on_state_change = [this] {
  33. if (m_client_notifications_enabled) {
  34. for (auto* client : m_clients)
  35. client->document_did_update_undo_stack();
  36. }
  37. };
  38. }
  39. bool TextDocument::set_text(StringView text, AllowCallback allow_callback, IsNewDocument is_new_document)
  40. {
  41. m_client_notifications_enabled = false;
  42. if (is_new_document == IsNewDocument::Yes)
  43. m_undo_stack.clear();
  44. m_spans.clear();
  45. m_folding_regions.clear();
  46. remove_all_lines();
  47. ArmedScopeGuard clear_text_guard([this]() {
  48. set_text({});
  49. });
  50. size_t start_of_current_line = 0;
  51. auto add_line = [&](size_t current_position) -> bool {
  52. size_t line_length = current_position - start_of_current_line;
  53. auto line = make<TextDocumentLine>(*this);
  54. bool success = true;
  55. if (line_length)
  56. success = line->set_text(*this, text.substring_view(start_of_current_line, current_position - start_of_current_line));
  57. if (!success)
  58. return false;
  59. append_line(move(line));
  60. start_of_current_line = current_position + 1;
  61. return true;
  62. };
  63. size_t i = 0;
  64. for (i = 0; i < text.length(); ++i) {
  65. if (text[i] != '\n')
  66. continue;
  67. auto success = add_line(i);
  68. if (!success)
  69. return false;
  70. }
  71. auto success = add_line(i);
  72. if (!success)
  73. return false;
  74. // Don't show the file's trailing newline as an actual new line.
  75. if (line_count() > 1 && line(line_count() - 1).is_empty())
  76. (void)m_lines.take_last();
  77. m_client_notifications_enabled = true;
  78. for (auto* client : m_clients)
  79. client->document_did_set_text(allow_callback);
  80. clear_text_guard.disarm();
  81. // FIXME: Should the modified state be cleared on some of the earlier returns as well?
  82. if (is_new_document == IsNewDocument::Yes)
  83. set_unmodified();
  84. return true;
  85. }
  86. void TextDocument::append_line(NonnullOwnPtr<TextDocumentLine> line)
  87. {
  88. lines().append(move(line));
  89. if (m_client_notifications_enabled) {
  90. for (auto* client : m_clients)
  91. client->document_did_append_line();
  92. }
  93. }
  94. void TextDocument::insert_line(size_t line_index, NonnullOwnPtr<TextDocumentLine> line)
  95. {
  96. lines().insert(line_index, move(line));
  97. if (m_client_notifications_enabled) {
  98. for (auto* client : m_clients)
  99. client->document_did_insert_line(line_index);
  100. }
  101. }
  102. NonnullOwnPtr<TextDocumentLine> TextDocument::take_line(size_t line_index)
  103. {
  104. auto line = lines().take(line_index);
  105. if (m_client_notifications_enabled) {
  106. for (auto* client : m_clients)
  107. client->document_did_remove_line(line_index);
  108. }
  109. return line;
  110. }
  111. void TextDocument::remove_line(size_t line_index)
  112. {
  113. lines().remove(line_index);
  114. if (m_client_notifications_enabled) {
  115. for (auto* client : m_clients)
  116. client->document_did_remove_line(line_index);
  117. }
  118. }
  119. void TextDocument::remove_all_lines()
  120. {
  121. lines().clear();
  122. if (m_client_notifications_enabled) {
  123. for (auto* client : m_clients)
  124. client->document_did_remove_all_lines();
  125. }
  126. }
  127. void TextDocument::register_client(Client& client)
  128. {
  129. m_clients.set(&client);
  130. }
  131. void TextDocument::unregister_client(Client& client)
  132. {
  133. m_clients.remove(&client);
  134. }
  135. void TextDocument::update_views(Badge<TextDocumentLine>)
  136. {
  137. notify_did_change();
  138. }
  139. void TextDocument::notify_did_change()
  140. {
  141. if (m_client_notifications_enabled) {
  142. for (auto* client : m_clients)
  143. client->document_did_change();
  144. }
  145. m_regex_needs_update = true;
  146. }
  147. void TextDocument::set_all_cursors(TextPosition const& position)
  148. {
  149. if (m_client_notifications_enabled) {
  150. for (auto* client : m_clients)
  151. client->document_did_set_cursor(position);
  152. }
  153. }
  154. DeprecatedString TextDocument::text() const
  155. {
  156. StringBuilder builder;
  157. for (size_t i = 0; i < line_count(); ++i) {
  158. auto& line = this->line(i);
  159. builder.append(line.view());
  160. if (i != line_count() - 1)
  161. builder.append('\n');
  162. }
  163. return builder.to_deprecated_string();
  164. }
  165. DeprecatedString TextDocument::text_in_range(TextRange const& a_range) const
  166. {
  167. auto range = a_range.normalized();
  168. if (is_empty() || line_count() < range.end().line() - range.start().line())
  169. return DeprecatedString("");
  170. StringBuilder builder;
  171. for (size_t i = range.start().line(); i <= range.end().line(); ++i) {
  172. auto& line = this->line(i);
  173. size_t selection_start_column_on_line = range.start().line() == i ? range.start().column() : 0;
  174. size_t selection_end_column_on_line = range.end().line() == i ? range.end().column() : line.length();
  175. if (!line.is_empty()) {
  176. builder.append(
  177. Utf32View(
  178. line.code_points() + selection_start_column_on_line,
  179. selection_end_column_on_line - selection_start_column_on_line));
  180. }
  181. if (i != range.end().line())
  182. builder.append('\n');
  183. }
  184. return builder.to_deprecated_string();
  185. }
  186. // This function will return the position of the previous grapheme cluster
  187. // break, relative to the cursor, for "correct looking" parsing of unicode based
  188. // on grapheme cluster boundary algorithm.
  189. size_t TextDocument::get_previous_grapheme_cluster_boundary(TextPosition const& cursor) const
  190. {
  191. if (!cursor.is_valid())
  192. return 0;
  193. auto const& line = this->line(cursor.line());
  194. auto index = Unicode::previous_grapheme_segmentation_boundary(line.view(), cursor.column());
  195. return index.value_or(cursor.column() - 1);
  196. }
  197. // This function will return the position of the next grapheme cluster break,
  198. // relative to the cursor, for "correct looking" parsing of unicode based on
  199. // grapheme cluster boundary algorithm.
  200. size_t TextDocument::get_next_grapheme_cluster_boundary(TextPosition const& cursor) const
  201. {
  202. if (!cursor.is_valid())
  203. return 0;
  204. auto const& line = this->line(cursor.line());
  205. auto index = Unicode::next_grapheme_segmentation_boundary(line.view(), cursor.column());
  206. return index.value_or(cursor.column() + 1);
  207. }
  208. u32 TextDocument::code_point_at(TextPosition const& position) const
  209. {
  210. VERIFY(position.line() < line_count());
  211. auto& line = this->line(position.line());
  212. if (position.column() == line.length())
  213. return '\n';
  214. return line.code_points()[position.column()];
  215. }
  216. TextPosition TextDocument::next_position_after(TextPosition const& position, SearchShouldWrap should_wrap) const
  217. {
  218. auto& line = this->line(position.line());
  219. if (position.column() == line.length()) {
  220. if (position.line() == line_count() - 1) {
  221. if (should_wrap == SearchShouldWrap::Yes)
  222. return { 0, 0 };
  223. return {};
  224. }
  225. return { position.line() + 1, 0 };
  226. }
  227. return { position.line(), position.column() + 1 };
  228. }
  229. TextPosition TextDocument::previous_position_before(TextPosition const& position, SearchShouldWrap should_wrap) const
  230. {
  231. if (position.column() == 0) {
  232. if (position.line() == 0) {
  233. if (should_wrap == SearchShouldWrap::Yes) {
  234. auto& last_line = this->line(line_count() - 1);
  235. return { line_count() - 1, last_line.length() };
  236. }
  237. return {};
  238. }
  239. auto& prev_line = this->line(position.line() - 1);
  240. return { position.line() - 1, prev_line.length() };
  241. }
  242. return { position.line(), position.column() - 1 };
  243. }
  244. void TextDocument::update_regex_matches(StringView needle)
  245. {
  246. if (m_regex_needs_update || needle != m_regex_needle) {
  247. Regex<PosixExtended> re(needle);
  248. Vector<RegexStringView> views;
  249. for (size_t line = 0; line < m_lines.size(); ++line) {
  250. views.append(m_lines[line]->view());
  251. }
  252. re.search(views, m_regex_result);
  253. m_regex_needs_update = false;
  254. m_regex_needle = DeprecatedString { needle };
  255. m_regex_result_match_index = -1;
  256. m_regex_result_match_capture_group_index = -1;
  257. }
  258. }
  259. TextRange TextDocument::find_next(StringView needle, TextPosition const& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case)
  260. {
  261. if (needle.is_empty())
  262. return {};
  263. if (regmatch) {
  264. if (!m_regex_result.matches.size())
  265. return {};
  266. regex::Match match;
  267. bool use_whole_match { false };
  268. auto next_match = [&] {
  269. m_regex_result_match_capture_group_index = 0;
  270. if (m_regex_result_match_index == m_regex_result.matches.size() - 1) {
  271. if (should_wrap == SearchShouldWrap::Yes)
  272. m_regex_result_match_index = 0;
  273. else
  274. ++m_regex_result_match_index;
  275. } else
  276. ++m_regex_result_match_index;
  277. };
  278. if (m_regex_result.n_capture_groups) {
  279. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  280. next_match();
  281. else {
  282. // check if last capture group has been reached
  283. if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) {
  284. next_match();
  285. } else {
  286. // get to the next capture group item
  287. ++m_regex_result_match_capture_group_index;
  288. }
  289. }
  290. // use whole match, if there is no capture group for current index
  291. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  292. use_whole_match = true;
  293. else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  294. next_match();
  295. } else {
  296. next_match();
  297. }
  298. if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  299. match = m_regex_result.matches.at(m_regex_result_match_index);
  300. else
  301. match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index);
  302. return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } };
  303. }
  304. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  305. TextPosition original_position = position;
  306. TextPosition start_of_potential_match;
  307. size_t needle_index = 0;
  308. Utf8View unicode_needle(needle);
  309. Vector<u32> needle_code_points;
  310. for (u32 code_point : unicode_needle)
  311. needle_code_points.append(code_point);
  312. do {
  313. auto ch = code_point_at(position);
  314. bool code_point_matches = false;
  315. if (needle_index >= needle_code_points.size())
  316. code_point_matches = false;
  317. else if (match_case)
  318. code_point_matches = ch == needle_code_points[needle_index];
  319. else
  320. code_point_matches = Unicode::to_unicode_lowercase(ch) == Unicode::to_unicode_lowercase(needle_code_points[needle_index]);
  321. if (code_point_matches) {
  322. if (needle_index == 0)
  323. start_of_potential_match = position;
  324. ++needle_index;
  325. if (needle_index >= needle_code_points.size())
  326. return { start_of_potential_match, next_position_after(position, should_wrap) };
  327. } else {
  328. if (needle_index > 0)
  329. position = start_of_potential_match;
  330. needle_index = 0;
  331. }
  332. position = next_position_after(position, should_wrap);
  333. } while (position.is_valid() && position != original_position);
  334. return {};
  335. }
  336. TextRange TextDocument::find_previous(StringView needle, TextPosition const& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case)
  337. {
  338. if (needle.is_empty())
  339. return {};
  340. if (regmatch) {
  341. if (!m_regex_result.matches.size())
  342. return {};
  343. regex::Match match;
  344. bool use_whole_match { false };
  345. auto next_match = [&] {
  346. if (m_regex_result_match_index == 0) {
  347. if (should_wrap == SearchShouldWrap::Yes)
  348. m_regex_result_match_index = m_regex_result.matches.size() - 1;
  349. else
  350. --m_regex_result_match_index;
  351. } else
  352. --m_regex_result_match_index;
  353. m_regex_result_match_capture_group_index = m_regex_result.capture_group_matches.at(m_regex_result_match_index).size() - 1;
  354. };
  355. if (m_regex_result.n_capture_groups) {
  356. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  357. next_match();
  358. else {
  359. // check if last capture group has been reached
  360. if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) {
  361. next_match();
  362. } else {
  363. // get to the next capture group item
  364. --m_regex_result_match_capture_group_index;
  365. }
  366. }
  367. // use whole match, if there is no capture group for current index
  368. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  369. use_whole_match = true;
  370. else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  371. next_match();
  372. } else {
  373. next_match();
  374. }
  375. if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  376. match = m_regex_result.matches.at(m_regex_result_match_index);
  377. else
  378. match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index);
  379. return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } };
  380. }
  381. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  382. position = previous_position_before(position, should_wrap);
  383. if (position.line() >= line_count())
  384. return {};
  385. TextPosition original_position = position;
  386. Utf8View unicode_needle(needle);
  387. Vector<u32> needle_code_points;
  388. for (u32 code_point : unicode_needle)
  389. needle_code_points.append(code_point);
  390. TextPosition end_of_potential_match;
  391. size_t needle_index = needle_code_points.size() - 1;
  392. do {
  393. auto ch = code_point_at(position);
  394. bool code_point_matches = false;
  395. if (needle_index >= needle_code_points.size())
  396. code_point_matches = false;
  397. else if (match_case)
  398. code_point_matches = ch == needle_code_points[needle_index];
  399. else
  400. code_point_matches = Unicode::to_unicode_lowercase(ch) == Unicode::to_unicode_lowercase(needle_code_points[needle_index]);
  401. if (code_point_matches) {
  402. if (needle_index == needle_code_points.size() - 1)
  403. end_of_potential_match = position;
  404. if (needle_index == 0)
  405. return { position, next_position_after(end_of_potential_match, should_wrap) };
  406. --needle_index;
  407. } else {
  408. if (needle_index < needle_code_points.size() - 1)
  409. position = end_of_potential_match;
  410. needle_index = needle_code_points.size() - 1;
  411. }
  412. position = previous_position_before(position, should_wrap);
  413. } while (position.is_valid() && position != original_position);
  414. return {};
  415. }
  416. Vector<TextRange> TextDocument::find_all(StringView needle, bool regmatch, bool match_case)
  417. {
  418. Vector<TextRange> ranges;
  419. TextPosition position;
  420. for (;;) {
  421. auto range = find_next(needle, position, SearchShouldWrap::No, regmatch, match_case);
  422. if (!range.is_valid())
  423. break;
  424. ranges.append(range);
  425. position = range.end();
  426. }
  427. return ranges;
  428. }
  429. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_before(TextPosition const& position) const
  430. {
  431. for (int i = m_spans.size() - 1; i >= 0; --i) {
  432. if (!m_spans[i].range.contains(position))
  433. continue;
  434. while ((i - 1) >= 0 && m_spans[i - 1].is_skippable)
  435. --i;
  436. if (i <= 0)
  437. return {};
  438. return m_spans[i - 1];
  439. }
  440. return {};
  441. }
  442. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_after(TextPosition const& position) const
  443. {
  444. size_t i = 0;
  445. // Find the first span containing the cursor
  446. for (; i < m_spans.size(); ++i) {
  447. if (m_spans[i].range.contains(position))
  448. break;
  449. }
  450. // Find the first span *after* the cursor
  451. // TODO: For a large number of spans, binary search would be faster.
  452. for (; i < m_spans.size(); ++i) {
  453. if (!m_spans[i].range.contains(position))
  454. break;
  455. }
  456. // Skip skippable spans
  457. for (; i < m_spans.size(); ++i) {
  458. if (!m_spans[i].is_skippable)
  459. break;
  460. }
  461. if (i < m_spans.size())
  462. return m_spans[i];
  463. return {};
  464. }
  465. static bool should_continue_beyond_word(Utf32View const& view)
  466. {
  467. static auto punctuation = Unicode::general_category_from_string("Punctuation"sv);
  468. static auto separator = Unicode::general_category_from_string("Separator"sv);
  469. if (!punctuation.has_value() || !separator.has_value())
  470. return false;
  471. auto has_any_gc = [&](auto code_point, auto&&... categories) {
  472. return (Unicode::code_point_has_general_category(code_point, *categories) || ...);
  473. };
  474. for (auto code_point : view) {
  475. if (!has_any_gc(code_point, punctuation, separator))
  476. return false;
  477. }
  478. return true;
  479. }
  480. TextPosition TextDocument::first_word_break_before(TextPosition const& position, bool start_at_column_before) const
  481. {
  482. if (position.column() == 0) {
  483. if (position.line() == 0) {
  484. return TextPosition(0, 0);
  485. }
  486. auto previous_line = this->line(position.line() - 1);
  487. return TextPosition(position.line() - 1, previous_line.length());
  488. }
  489. auto target = position;
  490. auto const& line = this->line(target.line());
  491. auto modifier = start_at_column_before ? 1 : 0;
  492. if (target.column() == line.length())
  493. modifier = 1;
  494. target.set_column(target.column() - modifier);
  495. while (target.column() > 0) {
  496. if (auto index = Unicode::previous_word_segmentation_boundary(line.view(), target.column()); index.has_value()) {
  497. auto view_between_target_and_index = line.view().substring_view(*index, target.column() - *index);
  498. if (should_continue_beyond_word(view_between_target_and_index)) {
  499. target.set_column(*index == 0 ? 0 : *index - 1);
  500. continue;
  501. }
  502. target.set_column(*index);
  503. break;
  504. }
  505. }
  506. return target;
  507. }
  508. TextPosition TextDocument::first_word_break_after(TextPosition const& position) const
  509. {
  510. auto target = position;
  511. auto const& line = this->line(target.line());
  512. if (position.column() >= line.length()) {
  513. if (position.line() >= this->line_count() - 1) {
  514. return position;
  515. }
  516. return TextPosition(position.line() + 1, 0);
  517. }
  518. while (target.column() < line.length()) {
  519. if (auto index = Unicode::next_word_segmentation_boundary(line.view(), target.column()); index.has_value()) {
  520. auto view_between_target_and_index = line.view().substring_view(target.column(), *index - target.column());
  521. if (should_continue_beyond_word(view_between_target_and_index)) {
  522. target.set_column(min(*index + 1, line.length()));
  523. continue;
  524. }
  525. target.set_column(*index);
  526. break;
  527. }
  528. }
  529. return target;
  530. }
  531. TextPosition TextDocument::first_word_before(TextPosition const& position, bool start_at_column_before) const
  532. {
  533. if (position.column() == 0) {
  534. if (position.line() == 0) {
  535. return TextPosition(0, 0);
  536. }
  537. auto previous_line = this->line(position.line() - 1);
  538. return TextPosition(position.line() - 1, previous_line.length());
  539. }
  540. auto target = position;
  541. auto line = this->line(target.line());
  542. if (target.column() == line.length())
  543. start_at_column_before = 1;
  544. auto nonblank_passed = !is_ascii_blank(line.code_points()[target.column() - start_at_column_before]);
  545. while (target.column() > 0) {
  546. auto prev_code_point = line.code_points()[target.column() - 1];
  547. nonblank_passed |= !is_ascii_blank(prev_code_point);
  548. if (nonblank_passed && is_ascii_blank(prev_code_point)) {
  549. break;
  550. } else if (is_ascii_punctuation(prev_code_point)) {
  551. target.set_column(target.column() - 1);
  552. break;
  553. }
  554. target.set_column(target.column() - 1);
  555. }
  556. return target;
  557. }
  558. void TextDocument::undo()
  559. {
  560. if (!can_undo())
  561. return;
  562. m_undo_stack.undo();
  563. notify_did_change();
  564. }
  565. void TextDocument::redo()
  566. {
  567. if (!can_redo())
  568. return;
  569. m_undo_stack.redo();
  570. notify_did_change();
  571. }
  572. void TextDocument::add_to_undo_stack(NonnullOwnPtr<TextDocumentUndoCommand> undo_command)
  573. {
  574. m_undo_stack.push(move(undo_command));
  575. }
  576. TextDocumentUndoCommand::TextDocumentUndoCommand(TextDocument& document)
  577. : m_document(document)
  578. {
  579. }
  580. InsertTextCommand::InsertTextCommand(TextDocument& document, DeprecatedString const& text, TextPosition const& position)
  581. : TextDocumentUndoCommand(document)
  582. , m_text(text)
  583. , m_range({ position, position })
  584. {
  585. }
  586. DeprecatedString InsertTextCommand::action_text() const
  587. {
  588. return "Insert Text";
  589. }
  590. bool InsertTextCommand::merge_with(GUI::Command const& other)
  591. {
  592. if (!is<InsertTextCommand>(other) || commit_time_expired())
  593. return false;
  594. auto const& typed_other = static_cast<InsertTextCommand const&>(other);
  595. if (typed_other.m_text.is_whitespace() && !m_text.is_whitespace())
  596. return false; // Skip if other is whitespace while this is not
  597. if (m_range.end() != typed_other.m_range.start())
  598. return false;
  599. if (m_range.start().line() != m_range.end().line())
  600. return false;
  601. StringBuilder builder(m_text.length() + typed_other.m_text.length());
  602. builder.append(m_text);
  603. builder.append(typed_other.m_text);
  604. m_text = builder.to_deprecated_string();
  605. m_range.set_end(typed_other.m_range.end());
  606. m_timestamp = MonotonicTime::now();
  607. return true;
  608. }
  609. void InsertTextCommand::perform_formatting(TextDocument::Client const& client)
  610. {
  611. const size_t tab_width = client.soft_tab_width();
  612. auto const& dest_line = m_document.line(m_range.start().line());
  613. bool const should_auto_indent = client.is_automatic_indentation_enabled();
  614. StringBuilder builder;
  615. size_t column = m_range.start().column();
  616. size_t line_indentation = dest_line.leading_spaces();
  617. bool at_start_of_line = line_indentation == column;
  618. for (auto input_char : m_text) {
  619. if (input_char == '\n') {
  620. size_t spaces_at_end = 0;
  621. if (column < line_indentation)
  622. spaces_at_end = line_indentation - column;
  623. line_indentation -= spaces_at_end;
  624. builder.append('\n');
  625. column = 0;
  626. if (should_auto_indent) {
  627. for (; column < line_indentation; ++column) {
  628. builder.append(' ');
  629. }
  630. }
  631. at_start_of_line = true;
  632. } else if (input_char == '\t') {
  633. size_t next_soft_tab_stop = ((column + tab_width) / tab_width) * tab_width;
  634. size_t spaces_to_insert = next_soft_tab_stop - column;
  635. for (size_t i = 0; i < spaces_to_insert; ++i) {
  636. builder.append(' ');
  637. }
  638. column = next_soft_tab_stop;
  639. if (at_start_of_line) {
  640. line_indentation = column;
  641. }
  642. } else {
  643. if (input_char == ' ') {
  644. if (at_start_of_line) {
  645. ++line_indentation;
  646. }
  647. } else {
  648. at_start_of_line = false;
  649. }
  650. builder.append(input_char);
  651. ++column;
  652. }
  653. }
  654. m_text = builder.to_deprecated_string();
  655. }
  656. void InsertTextCommand::redo()
  657. {
  658. auto new_cursor = m_document.insert_at(m_range.start(), m_text, m_client);
  659. // NOTE: We don't know where the range ends until after doing redo().
  660. // This is okay since we always do redo() after adding this to the undo stack.
  661. m_range.set_end(new_cursor);
  662. m_document.set_all_cursors(new_cursor);
  663. }
  664. void InsertTextCommand::undo()
  665. {
  666. m_document.remove(m_range);
  667. m_document.set_all_cursors(m_range.start());
  668. }
  669. RemoveTextCommand::RemoveTextCommand(TextDocument& document, DeprecatedString const& text, TextRange const& range, TextPosition const& original_cursor_position)
  670. : TextDocumentUndoCommand(document)
  671. , m_text(text)
  672. , m_range(range)
  673. , m_original_cursor_position(original_cursor_position)
  674. {
  675. }
  676. DeprecatedString RemoveTextCommand::action_text() const
  677. {
  678. return "Remove Text";
  679. }
  680. bool RemoveTextCommand::merge_with(GUI::Command const& other)
  681. {
  682. if (!is<RemoveTextCommand>(other) || commit_time_expired())
  683. return false;
  684. auto const& typed_other = static_cast<RemoveTextCommand const&>(other);
  685. if (m_range.start() != typed_other.m_range.end())
  686. return false;
  687. if (m_range.start().line() != m_range.end().line())
  688. return false;
  689. // Merge backspaces
  690. StringBuilder builder(m_text.length() + typed_other.m_text.length());
  691. builder.append(typed_other.m_text);
  692. builder.append(m_text);
  693. m_text = builder.to_deprecated_string();
  694. m_range.set_start(typed_other.m_range.start());
  695. m_timestamp = MonotonicTime::now();
  696. return true;
  697. }
  698. void RemoveTextCommand::redo()
  699. {
  700. m_document.remove(m_range);
  701. m_document.set_all_cursors(m_range.start());
  702. }
  703. void RemoveTextCommand::undo()
  704. {
  705. m_document.insert_at(m_range.start(), m_text);
  706. m_document.set_all_cursors(m_original_cursor_position);
  707. }
  708. InsertLineCommand::InsertLineCommand(TextDocument& document, TextPosition cursor, DeprecatedString&& text, InsertPosition pos)
  709. : TextDocumentUndoCommand(document)
  710. , m_cursor(cursor)
  711. , m_text(move(text))
  712. , m_pos(pos)
  713. {
  714. }
  715. void InsertLineCommand::redo()
  716. {
  717. size_t line_number = compute_line_number();
  718. m_document.insert_line(line_number, make<TextDocumentLine>(m_document, m_text));
  719. m_document.set_all_cursors(TextPosition { line_number, m_document.line(line_number).length() });
  720. }
  721. void InsertLineCommand::undo()
  722. {
  723. size_t line_number = compute_line_number();
  724. m_document.remove_line(line_number);
  725. m_document.set_all_cursors(m_cursor);
  726. }
  727. size_t InsertLineCommand::compute_line_number() const
  728. {
  729. if (m_pos == InsertPosition::Above)
  730. return m_cursor.line();
  731. if (m_pos == InsertPosition::Below)
  732. return m_cursor.line() + 1;
  733. VERIFY_NOT_REACHED();
  734. }
  735. DeprecatedString InsertLineCommand::action_text() const
  736. {
  737. StringBuilder action_text_builder;
  738. action_text_builder.append("Insert Line"sv);
  739. if (m_pos == InsertPosition::Above) {
  740. action_text_builder.append(" (Above)"sv);
  741. } else if (m_pos == InsertPosition::Below) {
  742. action_text_builder.append(" (Below)"sv);
  743. } else {
  744. VERIFY_NOT_REACHED();
  745. }
  746. return action_text_builder.to_deprecated_string();
  747. }
  748. ReplaceAllTextCommand::ReplaceAllTextCommand(GUI::TextDocument& document, DeprecatedString const& text, DeprecatedString const& action_text)
  749. : TextDocumentUndoCommand(document)
  750. , m_original_text(document.text())
  751. , m_new_text(text)
  752. , m_action_text(action_text)
  753. {
  754. }
  755. void ReplaceAllTextCommand::redo()
  756. {
  757. m_document.set_all_cursors({ 0, 0 });
  758. m_document.set_text(m_new_text, AllowCallback::Yes, TextDocument::IsNewDocument::No);
  759. }
  760. void ReplaceAllTextCommand::undo()
  761. {
  762. m_document.set_all_cursors({ 0, 0 });
  763. m_document.set_text(m_original_text, AllowCallback::Yes, TextDocument::IsNewDocument::No);
  764. }
  765. bool ReplaceAllTextCommand::merge_with(GUI::Command const&)
  766. {
  767. return false;
  768. }
  769. DeprecatedString ReplaceAllTextCommand::action_text() const
  770. {
  771. return m_action_text;
  772. }
  773. IndentSelection::IndentSelection(TextDocument& document, size_t tab_width, TextRange const& range)
  774. : TextDocumentUndoCommand(document)
  775. , m_tab_width(tab_width)
  776. , m_range(range)
  777. {
  778. }
  779. void IndentSelection::redo()
  780. {
  781. auto const tab = DeprecatedString::repeated(' ', m_tab_width);
  782. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  783. m_document.insert_at({ i, 0 }, tab, m_client);
  784. }
  785. m_document.set_all_cursors(m_range.start());
  786. }
  787. void IndentSelection::undo()
  788. {
  789. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  790. m_document.remove({ { i, 0 }, { i, m_tab_width } });
  791. }
  792. m_document.set_all_cursors(m_range.start());
  793. }
  794. UnindentSelection::UnindentSelection(TextDocument& document, size_t tab_width, TextRange const& range)
  795. : TextDocumentUndoCommand(document)
  796. , m_tab_width(tab_width)
  797. , m_range(range)
  798. {
  799. }
  800. void UnindentSelection::redo()
  801. {
  802. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  803. if (m_document.line(i).leading_spaces() >= m_tab_width)
  804. m_document.remove({ { i, 0 }, { i, m_tab_width } });
  805. else
  806. m_document.remove({ { i, 0 }, { i, m_document.line(i).leading_spaces() } });
  807. }
  808. m_document.set_all_cursors(m_range.start());
  809. }
  810. void UnindentSelection::undo()
  811. {
  812. auto const tab = DeprecatedString::repeated(' ', m_tab_width);
  813. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++)
  814. m_document.insert_at({ i, 0 }, tab, m_client);
  815. m_document.set_all_cursors(m_range.start());
  816. }
  817. CommentSelection::CommentSelection(TextDocument& document, StringView prefix, StringView suffix, TextRange const& range)
  818. : TextDocumentUndoCommand(document)
  819. , m_prefix(prefix)
  820. , m_suffix(suffix)
  821. , m_range(range)
  822. {
  823. }
  824. void CommentSelection::undo()
  825. {
  826. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  827. if (m_document.line(i).is_empty())
  828. continue;
  829. auto line = m_document.line(i).to_utf8();
  830. auto prefix_start = line.find(m_prefix).value_or(0);
  831. m_document.line(i).keep_range(
  832. m_document,
  833. prefix_start + m_prefix.length(),
  834. m_document.line(i).last_non_whitespace_column().value_or(line.length()) - prefix_start - m_prefix.length() - m_suffix.length());
  835. }
  836. m_document.set_all_cursors(m_range.start());
  837. }
  838. void CommentSelection::redo()
  839. {
  840. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  841. if (m_document.line(i).is_empty())
  842. continue;
  843. m_document.insert_at({ i, 0 }, m_prefix, m_client);
  844. for (auto const& b : m_suffix.bytes()) {
  845. m_document.line(i).append(m_document, b);
  846. }
  847. }
  848. m_document.set_all_cursors(m_range.start());
  849. }
  850. UncommentSelection::UncommentSelection(TextDocument& document, StringView prefix, StringView suffix, TextRange const& range)
  851. : TextDocumentUndoCommand(document)
  852. , m_prefix(prefix)
  853. , m_suffix(suffix)
  854. , m_range(range)
  855. {
  856. }
  857. void UncommentSelection::undo()
  858. {
  859. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  860. if (m_document.line(i).is_empty())
  861. continue;
  862. m_document.insert_at({ i, 0 }, m_prefix, m_client);
  863. for (auto const& b : m_suffix.bytes()) {
  864. m_document.line(i).append(m_document, b);
  865. }
  866. }
  867. m_document.set_all_cursors(m_range.start());
  868. }
  869. void UncommentSelection::redo()
  870. {
  871. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  872. if (m_document.line(i).is_empty())
  873. continue;
  874. auto line = m_document.line(i).to_utf8();
  875. auto prefix_start = line.find(m_prefix).value_or(0);
  876. m_document.line(i).keep_range(
  877. m_document,
  878. prefix_start + m_prefix.length(),
  879. m_document.line(i).last_non_whitespace_column().value_or(line.length()) - prefix_start - m_prefix.length() - m_suffix.length());
  880. }
  881. m_document.set_all_cursors(m_range.start());
  882. }
  883. TextPosition TextDocument::insert_at(TextPosition const& position, StringView text, Client const* client)
  884. {
  885. TextPosition cursor = position;
  886. Utf8View utf8_view(text);
  887. for (auto code_point : utf8_view)
  888. cursor = insert_at(cursor, code_point, client);
  889. return cursor;
  890. }
  891. TextPosition TextDocument::insert_at(TextPosition const& position, u32 code_point, Client const*)
  892. {
  893. if (code_point == '\n') {
  894. auto new_line = make<TextDocumentLine>(*this);
  895. new_line->append(*this, line(position.line()).code_points() + position.column(), line(position.line()).length() - position.column());
  896. line(position.line()).truncate(*this, position.column());
  897. insert_line(position.line() + 1, move(new_line));
  898. notify_did_change();
  899. return { position.line() + 1, 0 };
  900. } else {
  901. line(position.line()).insert(*this, position.column(), code_point);
  902. notify_did_change();
  903. return { position.line(), position.column() + 1 };
  904. }
  905. }
  906. void TextDocument::remove(TextRange const& unnormalized_range)
  907. {
  908. if (!unnormalized_range.is_valid())
  909. return;
  910. auto range = unnormalized_range.normalized();
  911. // First delete all the lines in between the first and last one.
  912. for (size_t i = range.start().line() + 1; i < range.end().line();) {
  913. remove_line(i);
  914. range.end().set_line(range.end().line() - 1);
  915. }
  916. if (range.start().line() == range.end().line()) {
  917. // Delete within same line.
  918. auto& line = this->line(range.start().line());
  919. if (line.length() == 0)
  920. return;
  921. bool whole_line_is_selected = range.start().column() == 0 && range.end().column() == line.length();
  922. if (whole_line_is_selected) {
  923. line.clear(*this);
  924. } else {
  925. line.remove_range(*this, range.start().column(), range.end().column() - range.start().column());
  926. }
  927. } else {
  928. // Delete across a newline, merging lines.
  929. VERIFY(range.start().line() == range.end().line() - 1);
  930. auto& first_line = line(range.start().line());
  931. auto& second_line = line(range.end().line());
  932. Vector<u32> code_points;
  933. code_points.append(first_line.code_points(), range.start().column());
  934. if (!second_line.is_empty())
  935. code_points.append(second_line.code_points() + range.end().column(), second_line.length() - range.end().column());
  936. first_line.set_text(*this, move(code_points));
  937. remove_line(range.end().line());
  938. }
  939. if (lines().is_empty()) {
  940. append_line(make<TextDocumentLine>(*this));
  941. }
  942. notify_did_change();
  943. }
  944. bool TextDocument::is_empty() const
  945. {
  946. return line_count() == 1 && line(0).is_empty();
  947. }
  948. TextRange TextDocument::range_for_entire_line(size_t line_index) const
  949. {
  950. if (line_index >= line_count())
  951. return {};
  952. return { { line_index, 0 }, { line_index, line(line_index).length() } };
  953. }
  954. void TextDocument::set_unmodified()
  955. {
  956. m_undo_stack.set_current_unmodified();
  957. }
  958. }