TextDocument.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  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. size_t TextDocumentLine::first_non_whitespace_column() const
  87. {
  88. for (size_t i = 0; i < length(); ++i) {
  89. auto code_point = code_points()[i];
  90. if (!is_ascii_space(code_point))
  91. return i;
  92. }
  93. return length();
  94. }
  95. Optional<size_t> TextDocumentLine::last_non_whitespace_column() const
  96. {
  97. for (ssize_t i = length() - 1; i >= 0; --i) {
  98. auto code_point = code_points()[i];
  99. if (!is_ascii_space(code_point))
  100. return i;
  101. }
  102. return {};
  103. }
  104. bool TextDocumentLine::ends_in_whitespace() const
  105. {
  106. if (!length())
  107. return false;
  108. return is_ascii_space(code_points()[length() - 1]);
  109. }
  110. bool TextDocumentLine::can_select() const
  111. {
  112. if (is_empty())
  113. return false;
  114. for (size_t i = 0; i < length(); ++i) {
  115. auto code_point = code_points()[i];
  116. if (code_point != '\n' && code_point != '\r' && code_point != '\f' && code_point != '\v')
  117. return true;
  118. }
  119. return false;
  120. }
  121. size_t TextDocumentLine::leading_spaces() const
  122. {
  123. size_t count = 0;
  124. for (; count < m_text.size(); ++count) {
  125. if (m_text[count] != ' ') {
  126. break;
  127. }
  128. }
  129. return count;
  130. }
  131. DeprecatedString TextDocumentLine::to_utf8() const
  132. {
  133. StringBuilder builder;
  134. builder.append(view());
  135. return builder.to_deprecated_string();
  136. }
  137. TextDocumentLine::TextDocumentLine(TextDocument& document)
  138. {
  139. clear(document);
  140. }
  141. TextDocumentLine::TextDocumentLine(TextDocument& document, StringView text)
  142. {
  143. set_text(document, text);
  144. }
  145. void TextDocumentLine::clear(TextDocument& document)
  146. {
  147. m_text.clear();
  148. document.update_views({});
  149. }
  150. void TextDocumentLine::set_text(TextDocument& document, Vector<u32> const text)
  151. {
  152. m_text = move(text);
  153. document.update_views({});
  154. }
  155. bool TextDocumentLine::set_text(TextDocument& document, StringView text)
  156. {
  157. if (text.is_empty()) {
  158. clear(document);
  159. return true;
  160. }
  161. m_text.clear();
  162. Utf8View utf8_view(text);
  163. if (!utf8_view.validate()) {
  164. return false;
  165. }
  166. for (auto code_point : utf8_view)
  167. m_text.append(code_point);
  168. document.update_views({});
  169. return true;
  170. }
  171. void TextDocumentLine::append(TextDocument& document, u32 const* code_points, size_t length)
  172. {
  173. if (length == 0)
  174. return;
  175. m_text.append(code_points, length);
  176. document.update_views({});
  177. }
  178. void TextDocumentLine::append(TextDocument& document, u32 code_point)
  179. {
  180. insert(document, length(), code_point);
  181. }
  182. void TextDocumentLine::prepend(TextDocument& document, u32 code_point)
  183. {
  184. insert(document, 0, code_point);
  185. }
  186. void TextDocumentLine::insert(TextDocument& document, size_t index, u32 code_point)
  187. {
  188. if (index == length()) {
  189. m_text.append(code_point);
  190. } else {
  191. m_text.insert(index, code_point);
  192. }
  193. document.update_views({});
  194. }
  195. void TextDocumentLine::remove(TextDocument& document, size_t index)
  196. {
  197. if (index == length()) {
  198. m_text.take_last();
  199. } else {
  200. m_text.remove(index);
  201. }
  202. document.update_views({});
  203. }
  204. void TextDocumentLine::remove_range(TextDocument& document, size_t start, size_t length)
  205. {
  206. VERIFY(length <= m_text.size());
  207. Vector<u32> new_data;
  208. new_data.ensure_capacity(m_text.size() - length);
  209. for (size_t i = 0; i < start; ++i)
  210. new_data.append(m_text[i]);
  211. for (size_t i = (start + length); i < m_text.size(); ++i)
  212. new_data.append(m_text[i]);
  213. m_text = move(new_data);
  214. document.update_views({});
  215. }
  216. void TextDocumentLine::keep_range(TextDocument& document, size_t start_index, size_t length)
  217. {
  218. VERIFY(start_index + length < m_text.size());
  219. Vector<u32> new_data;
  220. new_data.ensure_capacity(m_text.size());
  221. for (size_t i = start_index; i <= (start_index + length); i++)
  222. new_data.append(m_text[i]);
  223. m_text = move(new_data);
  224. document.update_views({});
  225. }
  226. void TextDocumentLine::truncate(TextDocument& document, size_t length)
  227. {
  228. m_text.resize(length);
  229. document.update_views({});
  230. }
  231. void TextDocument::append_line(NonnullOwnPtr<TextDocumentLine> line)
  232. {
  233. lines().append(move(line));
  234. if (m_client_notifications_enabled) {
  235. for (auto* client : m_clients)
  236. client->document_did_append_line();
  237. }
  238. }
  239. void TextDocument::insert_line(size_t line_index, NonnullOwnPtr<TextDocumentLine> line)
  240. {
  241. lines().insert(line_index, move(line));
  242. if (m_client_notifications_enabled) {
  243. for (auto* client : m_clients)
  244. client->document_did_insert_line(line_index);
  245. }
  246. }
  247. NonnullOwnPtr<TextDocumentLine> TextDocument::take_line(size_t line_index)
  248. {
  249. auto line = lines().take(line_index);
  250. if (m_client_notifications_enabled) {
  251. for (auto* client : m_clients)
  252. client->document_did_remove_line(line_index);
  253. }
  254. return line;
  255. }
  256. void TextDocument::remove_line(size_t line_index)
  257. {
  258. lines().remove(line_index);
  259. if (m_client_notifications_enabled) {
  260. for (auto* client : m_clients)
  261. client->document_did_remove_line(line_index);
  262. }
  263. }
  264. void TextDocument::remove_all_lines()
  265. {
  266. lines().clear();
  267. if (m_client_notifications_enabled) {
  268. for (auto* client : m_clients)
  269. client->document_did_remove_all_lines();
  270. }
  271. }
  272. void TextDocument::register_client(Client& client)
  273. {
  274. m_clients.set(&client);
  275. }
  276. void TextDocument::unregister_client(Client& client)
  277. {
  278. m_clients.remove(&client);
  279. }
  280. void TextDocument::update_views(Badge<TextDocumentLine>)
  281. {
  282. notify_did_change();
  283. }
  284. void TextDocument::notify_did_change()
  285. {
  286. if (m_client_notifications_enabled) {
  287. for (auto* client : m_clients)
  288. client->document_did_change();
  289. }
  290. m_regex_needs_update = true;
  291. }
  292. void TextDocument::set_all_cursors(TextPosition const& position)
  293. {
  294. if (m_client_notifications_enabled) {
  295. for (auto* client : m_clients)
  296. client->document_did_set_cursor(position);
  297. }
  298. }
  299. DeprecatedString TextDocument::text() const
  300. {
  301. StringBuilder builder;
  302. for (size_t i = 0; i < line_count(); ++i) {
  303. auto& line = this->line(i);
  304. builder.append(line.view());
  305. if (i != line_count() - 1)
  306. builder.append('\n');
  307. }
  308. return builder.to_deprecated_string();
  309. }
  310. DeprecatedString TextDocument::text_in_range(TextRange const& a_range) const
  311. {
  312. auto range = a_range.normalized();
  313. if (is_empty() || line_count() < range.end().line() - range.start().line())
  314. return DeprecatedString("");
  315. StringBuilder builder;
  316. for (size_t i = range.start().line(); i <= range.end().line(); ++i) {
  317. auto& line = this->line(i);
  318. size_t selection_start_column_on_line = range.start().line() == i ? range.start().column() : 0;
  319. size_t selection_end_column_on_line = range.end().line() == i ? range.end().column() : line.length();
  320. if (!line.is_empty()) {
  321. builder.append(
  322. Utf32View(
  323. line.code_points() + selection_start_column_on_line,
  324. selection_end_column_on_line - selection_start_column_on_line));
  325. }
  326. if (i != range.end().line())
  327. builder.append('\n');
  328. }
  329. return builder.to_deprecated_string();
  330. }
  331. // This function will return the position of the previous grapheme cluster
  332. // break, relative to the cursor, for "correct looking" parsing of unicode based
  333. // on grapheme cluster boundary algorithm.
  334. size_t TextDocument::get_previous_grapheme_cluster_boundary(TextPosition const& cursor) const
  335. {
  336. if (!cursor.is_valid())
  337. return 0;
  338. auto const& line = this->line(cursor.line());
  339. auto index = Unicode::previous_grapheme_segmentation_boundary(line.view(), cursor.column());
  340. return index.value_or(cursor.column() - 1);
  341. }
  342. // This function will return the position of the next grapheme cluster break,
  343. // relative to the cursor, for "correct looking" parsing of unicode based on
  344. // grapheme cluster boundary algorithm.
  345. size_t TextDocument::get_next_grapheme_cluster_boundary(TextPosition const& cursor) const
  346. {
  347. if (!cursor.is_valid())
  348. return 0;
  349. auto const& line = this->line(cursor.line());
  350. auto index = Unicode::next_grapheme_segmentation_boundary(line.view(), cursor.column());
  351. return index.value_or(cursor.column() + 1);
  352. }
  353. u32 TextDocument::code_point_at(TextPosition const& position) const
  354. {
  355. VERIFY(position.line() < line_count());
  356. auto& line = this->line(position.line());
  357. if (position.column() == line.length())
  358. return '\n';
  359. return line.code_points()[position.column()];
  360. }
  361. TextPosition TextDocument::next_position_after(TextPosition const& position, SearchShouldWrap should_wrap) const
  362. {
  363. auto& line = this->line(position.line());
  364. if (position.column() == line.length()) {
  365. if (position.line() == line_count() - 1) {
  366. if (should_wrap == SearchShouldWrap::Yes)
  367. return { 0, 0 };
  368. return {};
  369. }
  370. return { position.line() + 1, 0 };
  371. }
  372. return { position.line(), position.column() + 1 };
  373. }
  374. TextPosition TextDocument::previous_position_before(TextPosition const& position, SearchShouldWrap should_wrap) const
  375. {
  376. if (position.column() == 0) {
  377. if (position.line() == 0) {
  378. if (should_wrap == SearchShouldWrap::Yes) {
  379. auto& last_line = this->line(line_count() - 1);
  380. return { line_count() - 1, last_line.length() };
  381. }
  382. return {};
  383. }
  384. auto& prev_line = this->line(position.line() - 1);
  385. return { position.line() - 1, prev_line.length() };
  386. }
  387. return { position.line(), position.column() - 1 };
  388. }
  389. void TextDocument::update_regex_matches(StringView needle)
  390. {
  391. if (m_regex_needs_update || needle != m_regex_needle) {
  392. Regex<PosixExtended> re(needle);
  393. Vector<RegexStringView> views;
  394. for (size_t line = 0; line < m_lines.size(); ++line) {
  395. views.append(m_lines[line]->view());
  396. }
  397. re.search(views, m_regex_result);
  398. m_regex_needs_update = false;
  399. m_regex_needle = DeprecatedString { needle };
  400. m_regex_result_match_index = -1;
  401. m_regex_result_match_capture_group_index = -1;
  402. }
  403. }
  404. TextRange TextDocument::find_next(StringView needle, TextPosition const& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case)
  405. {
  406. if (needle.is_empty())
  407. return {};
  408. if (regmatch) {
  409. if (!m_regex_result.matches.size())
  410. return {};
  411. regex::Match match;
  412. bool use_whole_match { false };
  413. auto next_match = [&] {
  414. m_regex_result_match_capture_group_index = 0;
  415. if (m_regex_result_match_index == m_regex_result.matches.size() - 1) {
  416. if (should_wrap == SearchShouldWrap::Yes)
  417. m_regex_result_match_index = 0;
  418. else
  419. ++m_regex_result_match_index;
  420. } else
  421. ++m_regex_result_match_index;
  422. };
  423. if (m_regex_result.n_capture_groups) {
  424. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  425. next_match();
  426. else {
  427. // check if last capture group has been reached
  428. if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) {
  429. next_match();
  430. } else {
  431. // get to the next capture group item
  432. ++m_regex_result_match_capture_group_index;
  433. }
  434. }
  435. // use whole match, if there is no capture group for current index
  436. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  437. use_whole_match = true;
  438. else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  439. next_match();
  440. } else {
  441. next_match();
  442. }
  443. if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  444. match = m_regex_result.matches.at(m_regex_result_match_index);
  445. else
  446. match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index);
  447. return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } };
  448. }
  449. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  450. TextPosition original_position = position;
  451. TextPosition start_of_potential_match;
  452. size_t needle_index = 0;
  453. Utf8View unicode_needle(needle);
  454. Vector<u32> needle_code_points;
  455. for (u32 code_point : unicode_needle)
  456. needle_code_points.append(code_point);
  457. do {
  458. auto ch = code_point_at(position);
  459. bool code_point_matches = false;
  460. if (needle_index >= needle_code_points.size())
  461. code_point_matches = false;
  462. else if (match_case)
  463. code_point_matches = ch == needle_code_points[needle_index];
  464. else
  465. code_point_matches = Unicode::to_unicode_lowercase(ch) == Unicode::to_unicode_lowercase(needle_code_points[needle_index]);
  466. if (code_point_matches) {
  467. if (needle_index == 0)
  468. start_of_potential_match = position;
  469. ++needle_index;
  470. if (needle_index >= needle_code_points.size())
  471. return { start_of_potential_match, next_position_after(position, should_wrap) };
  472. } else {
  473. if (needle_index > 0)
  474. position = start_of_potential_match;
  475. needle_index = 0;
  476. }
  477. position = next_position_after(position, should_wrap);
  478. } while (position.is_valid() && position != original_position);
  479. return {};
  480. }
  481. TextRange TextDocument::find_previous(StringView needle, TextPosition const& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case)
  482. {
  483. if (needle.is_empty())
  484. return {};
  485. if (regmatch) {
  486. if (!m_regex_result.matches.size())
  487. return {};
  488. regex::Match match;
  489. bool use_whole_match { false };
  490. auto next_match = [&] {
  491. if (m_regex_result_match_index == 0) {
  492. if (should_wrap == SearchShouldWrap::Yes)
  493. m_regex_result_match_index = m_regex_result.matches.size() - 1;
  494. else
  495. --m_regex_result_match_index;
  496. } else
  497. --m_regex_result_match_index;
  498. m_regex_result_match_capture_group_index = m_regex_result.capture_group_matches.at(m_regex_result_match_index).size() - 1;
  499. };
  500. if (m_regex_result.n_capture_groups) {
  501. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  502. next_match();
  503. else {
  504. // check if last capture group has been reached
  505. if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) {
  506. next_match();
  507. } else {
  508. // get to the next capture group item
  509. --m_regex_result_match_capture_group_index;
  510. }
  511. }
  512. // use whole match, if there is no capture group for current index
  513. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  514. use_whole_match = true;
  515. else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  516. next_match();
  517. } else {
  518. next_match();
  519. }
  520. if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  521. match = m_regex_result.matches.at(m_regex_result_match_index);
  522. else
  523. match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index);
  524. return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } };
  525. }
  526. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  527. position = previous_position_before(position, should_wrap);
  528. if (position.line() >= line_count())
  529. return {};
  530. TextPosition original_position = position;
  531. Utf8View unicode_needle(needle);
  532. Vector<u32> needle_code_points;
  533. for (u32 code_point : unicode_needle)
  534. needle_code_points.append(code_point);
  535. TextPosition end_of_potential_match;
  536. size_t needle_index = needle_code_points.size() - 1;
  537. do {
  538. auto ch = code_point_at(position);
  539. bool code_point_matches = false;
  540. if (needle_index >= needle_code_points.size())
  541. code_point_matches = false;
  542. else if (match_case)
  543. code_point_matches = ch == needle_code_points[needle_index];
  544. else
  545. code_point_matches = Unicode::to_unicode_lowercase(ch) == Unicode::to_unicode_lowercase(needle_code_points[needle_index]);
  546. if (code_point_matches) {
  547. if (needle_index == needle_code_points.size() - 1)
  548. end_of_potential_match = position;
  549. if (needle_index == 0)
  550. return { position, next_position_after(end_of_potential_match, should_wrap) };
  551. --needle_index;
  552. } else {
  553. if (needle_index < needle_code_points.size() - 1)
  554. position = end_of_potential_match;
  555. needle_index = needle_code_points.size() - 1;
  556. }
  557. position = previous_position_before(position, should_wrap);
  558. } while (position.is_valid() && position != original_position);
  559. return {};
  560. }
  561. Vector<TextRange> TextDocument::find_all(StringView needle, bool regmatch, bool match_case)
  562. {
  563. Vector<TextRange> ranges;
  564. TextPosition position;
  565. for (;;) {
  566. auto range = find_next(needle, position, SearchShouldWrap::No, regmatch, match_case);
  567. if (!range.is_valid())
  568. break;
  569. ranges.append(range);
  570. position = range.end();
  571. }
  572. return ranges;
  573. }
  574. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_before(TextPosition const& position) const
  575. {
  576. for (int i = m_spans.size() - 1; i >= 0; --i) {
  577. if (!m_spans[i].range.contains(position))
  578. continue;
  579. while ((i - 1) >= 0 && m_spans[i - 1].is_skippable)
  580. --i;
  581. if (i <= 0)
  582. return {};
  583. return m_spans[i - 1];
  584. }
  585. return {};
  586. }
  587. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_after(TextPosition const& position) const
  588. {
  589. size_t i = 0;
  590. // Find the first span containing the cursor
  591. for (; i < m_spans.size(); ++i) {
  592. if (m_spans[i].range.contains(position))
  593. break;
  594. }
  595. // Find the first span *after* the cursor
  596. // TODO: For a large number of spans, binary search would be faster.
  597. for (; i < m_spans.size(); ++i) {
  598. if (!m_spans[i].range.contains(position))
  599. break;
  600. }
  601. // Skip skippable spans
  602. for (; i < m_spans.size(); ++i) {
  603. if (!m_spans[i].is_skippable)
  604. break;
  605. }
  606. if (i < m_spans.size())
  607. return m_spans[i];
  608. return {};
  609. }
  610. static bool should_continue_beyond_word(Utf32View const& view)
  611. {
  612. static auto punctuation = Unicode::general_category_from_string("Punctuation"sv);
  613. static auto separator = Unicode::general_category_from_string("Separator"sv);
  614. if (!punctuation.has_value() || !separator.has_value())
  615. return false;
  616. auto has_any_gc = [&](auto code_point, auto&&... categories) {
  617. return (Unicode::code_point_has_general_category(code_point, *categories) || ...);
  618. };
  619. for (auto code_point : view) {
  620. if (!has_any_gc(code_point, punctuation, separator))
  621. return false;
  622. }
  623. return true;
  624. }
  625. TextPosition TextDocument::first_word_break_before(TextPosition const& position, bool start_at_column_before) const
  626. {
  627. if (position.column() == 0) {
  628. if (position.line() == 0) {
  629. return TextPosition(0, 0);
  630. }
  631. auto previous_line = this->line(position.line() - 1);
  632. return TextPosition(position.line() - 1, previous_line.length());
  633. }
  634. auto target = position;
  635. auto const& line = this->line(target.line());
  636. auto modifier = start_at_column_before ? 1 : 0;
  637. if (target.column() == line.length())
  638. modifier = 1;
  639. target.set_column(target.column() - modifier);
  640. while (target.column() > 0) {
  641. if (auto index = Unicode::previous_word_segmentation_boundary(line.view(), target.column()); index.has_value()) {
  642. auto view_between_target_and_index = line.view().substring_view(*index, target.column() - *index);
  643. if (should_continue_beyond_word(view_between_target_and_index)) {
  644. target.set_column(*index == 0 ? 0 : *index - 1);
  645. continue;
  646. }
  647. target.set_column(*index);
  648. break;
  649. }
  650. }
  651. return target;
  652. }
  653. TextPosition TextDocument::first_word_break_after(TextPosition const& position) const
  654. {
  655. auto target = position;
  656. auto const& line = this->line(target.line());
  657. if (position.column() >= line.length()) {
  658. if (position.line() >= this->line_count() - 1) {
  659. return position;
  660. }
  661. return TextPosition(position.line() + 1, 0);
  662. }
  663. while (target.column() < line.length()) {
  664. if (auto index = Unicode::next_word_segmentation_boundary(line.view(), target.column()); index.has_value()) {
  665. auto view_between_target_and_index = line.view().substring_view(target.column(), *index - target.column());
  666. if (should_continue_beyond_word(view_between_target_and_index)) {
  667. target.set_column(min(*index + 1, line.length()));
  668. continue;
  669. }
  670. target.set_column(*index);
  671. break;
  672. }
  673. }
  674. return target;
  675. }
  676. TextPosition TextDocument::first_word_before(TextPosition const& position, bool start_at_column_before) const
  677. {
  678. if (position.column() == 0) {
  679. if (position.line() == 0) {
  680. return TextPosition(0, 0);
  681. }
  682. auto previous_line = this->line(position.line() - 1);
  683. return TextPosition(position.line() - 1, previous_line.length());
  684. }
  685. auto target = position;
  686. auto line = this->line(target.line());
  687. if (target.column() == line.length())
  688. start_at_column_before = 1;
  689. auto nonblank_passed = !is_ascii_blank(line.code_points()[target.column() - start_at_column_before]);
  690. while (target.column() > 0) {
  691. auto prev_code_point = line.code_points()[target.column() - 1];
  692. nonblank_passed |= !is_ascii_blank(prev_code_point);
  693. if (nonblank_passed && is_ascii_blank(prev_code_point)) {
  694. break;
  695. } else if (is_ascii_punctuation(prev_code_point)) {
  696. target.set_column(target.column() - 1);
  697. break;
  698. }
  699. target.set_column(target.column() - 1);
  700. }
  701. return target;
  702. }
  703. void TextDocument::undo()
  704. {
  705. if (!can_undo())
  706. return;
  707. m_undo_stack.undo();
  708. notify_did_change();
  709. }
  710. void TextDocument::redo()
  711. {
  712. if (!can_redo())
  713. return;
  714. m_undo_stack.redo();
  715. notify_did_change();
  716. }
  717. void TextDocument::add_to_undo_stack(NonnullOwnPtr<TextDocumentUndoCommand> undo_command)
  718. {
  719. m_undo_stack.push(move(undo_command));
  720. }
  721. TextDocumentUndoCommand::TextDocumentUndoCommand(TextDocument& document)
  722. : m_document(document)
  723. {
  724. }
  725. InsertTextCommand::InsertTextCommand(TextDocument& document, DeprecatedString const& text, TextPosition const& position)
  726. : TextDocumentUndoCommand(document)
  727. , m_text(text)
  728. , m_range({ position, position })
  729. {
  730. }
  731. DeprecatedString InsertTextCommand::action_text() const
  732. {
  733. return "Insert Text";
  734. }
  735. bool InsertTextCommand::merge_with(GUI::Command const& other)
  736. {
  737. if (!is<InsertTextCommand>(other) || commit_time_expired())
  738. return false;
  739. auto const& typed_other = static_cast<InsertTextCommand const&>(other);
  740. if (typed_other.m_text.is_whitespace() && !m_text.is_whitespace())
  741. return false; // Skip if other is whitespace while this is not
  742. if (m_range.end() != typed_other.m_range.start())
  743. return false;
  744. if (m_range.start().line() != m_range.end().line())
  745. return false;
  746. StringBuilder builder(m_text.length() + typed_other.m_text.length());
  747. builder.append(m_text);
  748. builder.append(typed_other.m_text);
  749. m_text = builder.to_deprecated_string();
  750. m_range.set_end(typed_other.m_range.end());
  751. m_timestamp = MonotonicTime::now();
  752. return true;
  753. }
  754. void InsertTextCommand::perform_formatting(TextDocument::Client const& client)
  755. {
  756. const size_t tab_width = client.soft_tab_width();
  757. auto const& dest_line = m_document.line(m_range.start().line());
  758. bool const should_auto_indent = client.is_automatic_indentation_enabled();
  759. StringBuilder builder;
  760. size_t column = m_range.start().column();
  761. size_t line_indentation = dest_line.leading_spaces();
  762. bool at_start_of_line = line_indentation == column;
  763. for (auto input_char : m_text) {
  764. if (input_char == '\n') {
  765. size_t spaces_at_end = 0;
  766. if (column < line_indentation)
  767. spaces_at_end = line_indentation - column;
  768. line_indentation -= spaces_at_end;
  769. builder.append('\n');
  770. column = 0;
  771. if (should_auto_indent) {
  772. for (; column < line_indentation; ++column) {
  773. builder.append(' ');
  774. }
  775. }
  776. at_start_of_line = true;
  777. } else if (input_char == '\t') {
  778. size_t next_soft_tab_stop = ((column + tab_width) / tab_width) * tab_width;
  779. size_t spaces_to_insert = next_soft_tab_stop - column;
  780. for (size_t i = 0; i < spaces_to_insert; ++i) {
  781. builder.append(' ');
  782. }
  783. column = next_soft_tab_stop;
  784. if (at_start_of_line) {
  785. line_indentation = column;
  786. }
  787. } else {
  788. if (input_char == ' ') {
  789. if (at_start_of_line) {
  790. ++line_indentation;
  791. }
  792. } else {
  793. at_start_of_line = false;
  794. }
  795. builder.append(input_char);
  796. ++column;
  797. }
  798. }
  799. m_text = builder.to_deprecated_string();
  800. }
  801. void InsertTextCommand::redo()
  802. {
  803. auto new_cursor = m_document.insert_at(m_range.start(), m_text, m_client);
  804. // NOTE: We don't know where the range ends until after doing redo().
  805. // This is okay since we always do redo() after adding this to the undo stack.
  806. m_range.set_end(new_cursor);
  807. m_document.set_all_cursors(new_cursor);
  808. }
  809. void InsertTextCommand::undo()
  810. {
  811. m_document.remove(m_range);
  812. m_document.set_all_cursors(m_range.start());
  813. }
  814. RemoveTextCommand::RemoveTextCommand(TextDocument& document, DeprecatedString const& text, TextRange const& range, TextPosition const& original_cursor_position)
  815. : TextDocumentUndoCommand(document)
  816. , m_text(text)
  817. , m_range(range)
  818. , m_original_cursor_position(original_cursor_position)
  819. {
  820. }
  821. DeprecatedString RemoveTextCommand::action_text() const
  822. {
  823. return "Remove Text";
  824. }
  825. bool RemoveTextCommand::merge_with(GUI::Command const& other)
  826. {
  827. if (!is<RemoveTextCommand>(other) || commit_time_expired())
  828. return false;
  829. auto const& typed_other = static_cast<RemoveTextCommand const&>(other);
  830. if (m_range.start() != typed_other.m_range.end())
  831. return false;
  832. if (m_range.start().line() != m_range.end().line())
  833. return false;
  834. // Merge backspaces
  835. StringBuilder builder(m_text.length() + typed_other.m_text.length());
  836. builder.append(typed_other.m_text);
  837. builder.append(m_text);
  838. m_text = builder.to_deprecated_string();
  839. m_range.set_start(typed_other.m_range.start());
  840. m_timestamp = MonotonicTime::now();
  841. return true;
  842. }
  843. void RemoveTextCommand::redo()
  844. {
  845. m_document.remove(m_range);
  846. m_document.set_all_cursors(m_range.start());
  847. }
  848. void RemoveTextCommand::undo()
  849. {
  850. m_document.insert_at(m_range.start(), m_text);
  851. m_document.set_all_cursors(m_original_cursor_position);
  852. }
  853. InsertLineCommand::InsertLineCommand(TextDocument& document, TextPosition cursor, DeprecatedString&& text, InsertPosition pos)
  854. : TextDocumentUndoCommand(document)
  855. , m_cursor(cursor)
  856. , m_text(move(text))
  857. , m_pos(pos)
  858. {
  859. }
  860. void InsertLineCommand::redo()
  861. {
  862. size_t line_number = compute_line_number();
  863. m_document.insert_line(line_number, make<TextDocumentLine>(m_document, m_text));
  864. m_document.set_all_cursors(TextPosition { line_number, m_document.line(line_number).length() });
  865. }
  866. void InsertLineCommand::undo()
  867. {
  868. size_t line_number = compute_line_number();
  869. m_document.remove_line(line_number);
  870. m_document.set_all_cursors(m_cursor);
  871. }
  872. size_t InsertLineCommand::compute_line_number() const
  873. {
  874. if (m_pos == InsertPosition::Above)
  875. return m_cursor.line();
  876. if (m_pos == InsertPosition::Below)
  877. return m_cursor.line() + 1;
  878. VERIFY_NOT_REACHED();
  879. }
  880. DeprecatedString InsertLineCommand::action_text() const
  881. {
  882. StringBuilder action_text_builder;
  883. action_text_builder.append("Insert Line"sv);
  884. if (m_pos == InsertPosition::Above) {
  885. action_text_builder.append(" (Above)"sv);
  886. } else if (m_pos == InsertPosition::Below) {
  887. action_text_builder.append(" (Below)"sv);
  888. } else {
  889. VERIFY_NOT_REACHED();
  890. }
  891. return action_text_builder.to_deprecated_string();
  892. }
  893. ReplaceAllTextCommand::ReplaceAllTextCommand(GUI::TextDocument& document, DeprecatedString const& text, DeprecatedString const& action_text)
  894. : TextDocumentUndoCommand(document)
  895. , m_original_text(document.text())
  896. , m_new_text(text)
  897. , m_action_text(action_text)
  898. {
  899. }
  900. void ReplaceAllTextCommand::redo()
  901. {
  902. m_document.set_all_cursors({ 0, 0 });
  903. m_document.set_text(m_new_text, AllowCallback::Yes, TextDocument::IsNewDocument::No);
  904. }
  905. void ReplaceAllTextCommand::undo()
  906. {
  907. m_document.set_all_cursors({ 0, 0 });
  908. m_document.set_text(m_original_text, AllowCallback::Yes, TextDocument::IsNewDocument::No);
  909. }
  910. bool ReplaceAllTextCommand::merge_with(GUI::Command const&)
  911. {
  912. return false;
  913. }
  914. DeprecatedString ReplaceAllTextCommand::action_text() const
  915. {
  916. return m_action_text;
  917. }
  918. IndentSelection::IndentSelection(TextDocument& document, size_t tab_width, TextRange const& range)
  919. : TextDocumentUndoCommand(document)
  920. , m_tab_width(tab_width)
  921. , m_range(range)
  922. {
  923. }
  924. void IndentSelection::redo()
  925. {
  926. auto const tab = DeprecatedString::repeated(' ', m_tab_width);
  927. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  928. m_document.insert_at({ i, 0 }, tab, m_client);
  929. }
  930. m_document.set_all_cursors(m_range.start());
  931. }
  932. void IndentSelection::undo()
  933. {
  934. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  935. m_document.remove({ { i, 0 }, { i, m_tab_width } });
  936. }
  937. m_document.set_all_cursors(m_range.start());
  938. }
  939. UnindentSelection::UnindentSelection(TextDocument& document, size_t tab_width, TextRange const& range)
  940. : TextDocumentUndoCommand(document)
  941. , m_tab_width(tab_width)
  942. , m_range(range)
  943. {
  944. }
  945. void UnindentSelection::redo()
  946. {
  947. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  948. if (m_document.line(i).leading_spaces() >= m_tab_width)
  949. m_document.remove({ { i, 0 }, { i, m_tab_width } });
  950. else
  951. m_document.remove({ { i, 0 }, { i, m_document.line(i).leading_spaces() } });
  952. }
  953. m_document.set_all_cursors(m_range.start());
  954. }
  955. void UnindentSelection::undo()
  956. {
  957. auto const tab = DeprecatedString::repeated(' ', m_tab_width);
  958. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++)
  959. m_document.insert_at({ i, 0 }, tab, m_client);
  960. m_document.set_all_cursors(m_range.start());
  961. }
  962. CommentSelection::CommentSelection(TextDocument& document, StringView prefix, StringView suffix, TextRange const& range)
  963. : TextDocumentUndoCommand(document)
  964. , m_prefix(prefix)
  965. , m_suffix(suffix)
  966. , m_range(range)
  967. {
  968. }
  969. void CommentSelection::undo()
  970. {
  971. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  972. if (m_document.line(i).is_empty())
  973. continue;
  974. auto line = m_document.line(i).to_utf8();
  975. auto prefix_start = line.find(m_prefix).value_or(0);
  976. m_document.line(i).keep_range(
  977. m_document,
  978. prefix_start + m_prefix.length(),
  979. m_document.line(i).last_non_whitespace_column().value_or(line.length()) - prefix_start - m_prefix.length() - m_suffix.length());
  980. }
  981. m_document.set_all_cursors(m_range.start());
  982. }
  983. void CommentSelection::redo()
  984. {
  985. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  986. if (m_document.line(i).is_empty())
  987. continue;
  988. m_document.insert_at({ i, 0 }, m_prefix, m_client);
  989. for (auto const& b : m_suffix.bytes()) {
  990. m_document.line(i).append(m_document, b);
  991. }
  992. }
  993. m_document.set_all_cursors(m_range.start());
  994. }
  995. UncommentSelection::UncommentSelection(TextDocument& document, StringView prefix, StringView suffix, TextRange const& range)
  996. : TextDocumentUndoCommand(document)
  997. , m_prefix(prefix)
  998. , m_suffix(suffix)
  999. , m_range(range)
  1000. {
  1001. }
  1002. void UncommentSelection::undo()
  1003. {
  1004. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  1005. if (m_document.line(i).is_empty())
  1006. continue;
  1007. m_document.insert_at({ i, 0 }, m_prefix, m_client);
  1008. for (auto const& b : m_suffix.bytes()) {
  1009. m_document.line(i).append(m_document, b);
  1010. }
  1011. }
  1012. m_document.set_all_cursors(m_range.start());
  1013. }
  1014. void UncommentSelection::redo()
  1015. {
  1016. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  1017. if (m_document.line(i).is_empty())
  1018. continue;
  1019. auto line = m_document.line(i).to_utf8();
  1020. auto prefix_start = line.find(m_prefix).value_or(0);
  1021. m_document.line(i).keep_range(
  1022. m_document,
  1023. prefix_start + m_prefix.length(),
  1024. m_document.line(i).last_non_whitespace_column().value_or(line.length()) - prefix_start - m_prefix.length() - m_suffix.length());
  1025. }
  1026. m_document.set_all_cursors(m_range.start());
  1027. }
  1028. TextPosition TextDocument::insert_at(TextPosition const& position, StringView text, Client const* client)
  1029. {
  1030. TextPosition cursor = position;
  1031. Utf8View utf8_view(text);
  1032. for (auto code_point : utf8_view)
  1033. cursor = insert_at(cursor, code_point, client);
  1034. return cursor;
  1035. }
  1036. TextPosition TextDocument::insert_at(TextPosition const& position, u32 code_point, Client const*)
  1037. {
  1038. if (code_point == '\n') {
  1039. auto new_line = make<TextDocumentLine>(*this);
  1040. new_line->append(*this, line(position.line()).code_points() + position.column(), line(position.line()).length() - position.column());
  1041. line(position.line()).truncate(*this, position.column());
  1042. insert_line(position.line() + 1, move(new_line));
  1043. notify_did_change();
  1044. return { position.line() + 1, 0 };
  1045. } else {
  1046. line(position.line()).insert(*this, position.column(), code_point);
  1047. notify_did_change();
  1048. return { position.line(), position.column() + 1 };
  1049. }
  1050. }
  1051. void TextDocument::remove(TextRange const& unnormalized_range)
  1052. {
  1053. if (!unnormalized_range.is_valid())
  1054. return;
  1055. auto range = unnormalized_range.normalized();
  1056. // First delete all the lines in between the first and last one.
  1057. for (size_t i = range.start().line() + 1; i < range.end().line();) {
  1058. remove_line(i);
  1059. range.end().set_line(range.end().line() - 1);
  1060. }
  1061. if (range.start().line() == range.end().line()) {
  1062. // Delete within same line.
  1063. auto& line = this->line(range.start().line());
  1064. if (line.length() == 0)
  1065. return;
  1066. bool whole_line_is_selected = range.start().column() == 0 && range.end().column() == line.length();
  1067. if (whole_line_is_selected) {
  1068. line.clear(*this);
  1069. } else {
  1070. line.remove_range(*this, range.start().column(), range.end().column() - range.start().column());
  1071. }
  1072. } else {
  1073. // Delete across a newline, merging lines.
  1074. VERIFY(range.start().line() == range.end().line() - 1);
  1075. auto& first_line = line(range.start().line());
  1076. auto& second_line = line(range.end().line());
  1077. Vector<u32> code_points;
  1078. code_points.append(first_line.code_points(), range.start().column());
  1079. if (!second_line.is_empty())
  1080. code_points.append(second_line.code_points() + range.end().column(), second_line.length() - range.end().column());
  1081. first_line.set_text(*this, move(code_points));
  1082. remove_line(range.end().line());
  1083. }
  1084. if (lines().is_empty()) {
  1085. append_line(make<TextDocumentLine>(*this));
  1086. }
  1087. notify_did_change();
  1088. }
  1089. bool TextDocument::is_empty() const
  1090. {
  1091. return line_count() == 1 && line(0).is_empty();
  1092. }
  1093. TextRange TextDocument::range_for_entire_line(size_t line_index) const
  1094. {
  1095. if (line_index >= line_count())
  1096. return {};
  1097. return { { line_index, 0 }, { line_index, line(line_index).length() } };
  1098. }
  1099. TextDocumentSpan const* TextDocument::span_at(TextPosition const& position) const
  1100. {
  1101. for (auto& span : m_spans) {
  1102. if (span.range.contains(position))
  1103. return &span;
  1104. }
  1105. return nullptr;
  1106. }
  1107. void TextDocument::set_unmodified()
  1108. {
  1109. m_undo_stack.set_current_unmodified();
  1110. }
  1111. void TextDocument::set_spans(u32 span_collection_index, Vector<TextDocumentSpan> spans)
  1112. {
  1113. m_span_collections.set(span_collection_index, move(spans));
  1114. merge_span_collections();
  1115. }
  1116. struct SpanAndCollectionIndex {
  1117. TextDocumentSpan span;
  1118. u32 collection_index { 0 };
  1119. };
  1120. void TextDocument::merge_span_collections()
  1121. {
  1122. Vector<SpanAndCollectionIndex> sorted_spans;
  1123. auto collection_indices = m_span_collections.keys();
  1124. quick_sort(collection_indices);
  1125. for (auto collection_index : collection_indices) {
  1126. auto spans = m_span_collections.get(collection_index).value();
  1127. for (auto span : spans) {
  1128. sorted_spans.append({ move(span), collection_index });
  1129. }
  1130. }
  1131. quick_sort(sorted_spans, [](SpanAndCollectionIndex const& a, SpanAndCollectionIndex const& b) {
  1132. if (a.span.range.start() == b.span.range.start()) {
  1133. return a.collection_index < b.collection_index;
  1134. }
  1135. return a.span.range.start() < b.span.range.start();
  1136. });
  1137. // The end of the TextRanges of spans are non-inclusive, i.e span range = [X,y).
  1138. // This transforms the span's range to be inclusive, i.e [X,Y].
  1139. auto adjust_end = [](GUI::TextDocumentSpan span) -> GUI::TextDocumentSpan {
  1140. span.range.set_end({ span.range.end().line(), span.range.end().column() == 0 ? 0 : span.range.end().column() - 1 });
  1141. return span;
  1142. };
  1143. Vector<SpanAndCollectionIndex> merged_spans;
  1144. for (auto& span_and_collection_index : sorted_spans) {
  1145. if (merged_spans.is_empty()) {
  1146. merged_spans.append(span_and_collection_index);
  1147. continue;
  1148. }
  1149. auto const& span = span_and_collection_index.span;
  1150. auto last_span_and_collection_index = merged_spans.last();
  1151. auto const& last_span = last_span_and_collection_index.span;
  1152. if (adjust_end(span).range.start() > adjust_end(last_span).range.end()) {
  1153. // Current span does not intersect with previous one, can simply append to merged list.
  1154. merged_spans.append(span_and_collection_index);
  1155. continue;
  1156. }
  1157. merged_spans.take_last();
  1158. if (span.range.start() > last_span.range.start()) {
  1159. SpanAndCollectionIndex first_part = last_span_and_collection_index;
  1160. first_part.span.range.set_end(span.range.start());
  1161. merged_spans.append(move(first_part));
  1162. }
  1163. SpanAndCollectionIndex merged_span;
  1164. merged_span.collection_index = span_and_collection_index.collection_index;
  1165. merged_span.span.range = { span.range.start(), min(span.range.end(), last_span.range.end()) };
  1166. merged_span.span.is_skippable = span.is_skippable | last_span.is_skippable;
  1167. merged_span.span.data = span.data ? span.data : last_span.data;
  1168. merged_span.span.attributes.color = span_and_collection_index.collection_index > last_span_and_collection_index.collection_index ? span.attributes.color : last_span.attributes.color;
  1169. merged_span.span.attributes.bold = span.attributes.bold | last_span.attributes.bold;
  1170. merged_span.span.attributes.background_color = span.attributes.background_color.has_value() ? span.attributes.background_color.value() : last_span.attributes.background_color;
  1171. merged_span.span.attributes.underline_color = span.attributes.underline_color.has_value() ? span.attributes.underline_color.value() : last_span.attributes.underline_color;
  1172. merged_span.span.attributes.underline_style = span.attributes.underline_style.has_value() ? span.attributes.underline_style : last_span.attributes.underline_style;
  1173. merged_spans.append(move(merged_span));
  1174. if (span.range.end() == last_span.range.end())
  1175. continue;
  1176. if (span.range.end() > last_span.range.end()) {
  1177. SpanAndCollectionIndex last_part = span_and_collection_index;
  1178. last_part.span.range.set_start(last_span.range.end());
  1179. merged_spans.append(move(last_part));
  1180. continue;
  1181. }
  1182. SpanAndCollectionIndex last_part = last_span_and_collection_index;
  1183. last_part.span.range.set_start(span.range.end());
  1184. merged_spans.append(move(last_part));
  1185. }
  1186. m_spans.clear();
  1187. TextDocumentSpan previous_span { .range = { TextPosition(0, 0), TextPosition(0, 0) }, .attributes = {} };
  1188. for (auto span : merged_spans) {
  1189. // Validate spans
  1190. if (!span.span.range.is_valid()) {
  1191. dbgln_if(TEXTEDITOR_DEBUG, "Invalid span {} => ignoring", span.span.range);
  1192. continue;
  1193. }
  1194. if (span.span.range.end() < span.span.range.start()) {
  1195. dbgln_if(TEXTEDITOR_DEBUG, "Span {} has negative length => ignoring", span.span.range);
  1196. continue;
  1197. }
  1198. if (span.span.range.end() < previous_span.range.start()) {
  1199. dbgln_if(TEXTEDITOR_DEBUG, "Spans not sorted (Span {} ends before previous span {}) => ignoring", span.span.range, previous_span.range);
  1200. continue;
  1201. }
  1202. if (span.span.range.start() < previous_span.range.end()) {
  1203. dbgln_if(TEXTEDITOR_DEBUG, "Span {} overlaps previous span {} => ignoring", span.span.range, previous_span.range);
  1204. continue;
  1205. }
  1206. previous_span = span.span;
  1207. m_spans.append(move(span.span));
  1208. }
  1209. }
  1210. void TextDocument::set_folding_regions(Vector<TextDocumentFoldingRegion> folding_regions)
  1211. {
  1212. // Remove any regions that don't span at least 3 lines.
  1213. // Currently, we can't do anything useful with them, and our implementation gets very confused by
  1214. // single-line regions, so drop them.
  1215. folding_regions.remove_all_matching([](TextDocumentFoldingRegion const& region) {
  1216. return region.range.line_count() < 3;
  1217. });
  1218. quick_sort(folding_regions, [](TextDocumentFoldingRegion const& a, TextDocumentFoldingRegion const& b) {
  1219. return a.range.start() < b.range.start();
  1220. });
  1221. for (auto& folding_region : folding_regions) {
  1222. folding_region.line_ptr = &line(folding_region.range.start().line());
  1223. // Map the new folding region to an old one, to preserve which regions were folded.
  1224. // FIXME: This is O(n*n).
  1225. for (auto const& existing_folding_region : m_folding_regions) {
  1226. // We treat two folding regions as the same if they start on the same TextDocumentLine,
  1227. // and have the same line count. The actual line *numbers* might change, but the pointer
  1228. // and count should not.
  1229. if (existing_folding_region.line_ptr
  1230. && existing_folding_region.line_ptr == folding_region.line_ptr
  1231. && existing_folding_region.range.line_count() == folding_region.range.line_count()) {
  1232. folding_region.is_folded = existing_folding_region.is_folded;
  1233. break;
  1234. }
  1235. }
  1236. }
  1237. // FIXME: Remove any regions that partially overlap another region, since these are invalid.
  1238. m_folding_regions = move(folding_regions);
  1239. if constexpr (TEXTEDITOR_DEBUG) {
  1240. dbgln("TextDocument got {} fold regions:", m_folding_regions.size());
  1241. for (auto const& item : m_folding_regions) {
  1242. dbgln("- {} (ptr: {:p}, folded: {})", item.range, item.line_ptr, item.is_folded);
  1243. }
  1244. }
  1245. }
  1246. Optional<TextDocumentFoldingRegion&> TextDocument::folding_region_starting_on_line(size_t line)
  1247. {
  1248. return m_folding_regions.first_matching([line](auto& region) {
  1249. return region.range.start().line() == line;
  1250. });
  1251. }
  1252. bool TextDocument::line_is_visible(size_t line) const
  1253. {
  1254. // FIXME: line_is_visible() gets called a lot.
  1255. // We could avoid a lot of repeated work if we saved this state on the TextDocumentLine.
  1256. return !any_of(m_folding_regions, [line](auto& region) {
  1257. return region.is_folded
  1258. && line > region.range.start().line()
  1259. && line < region.range.end().line();
  1260. });
  1261. }
  1262. Vector<TextDocumentFoldingRegion const&> TextDocument::currently_folded_regions() const
  1263. {
  1264. Vector<TextDocumentFoldingRegion const&> folded_regions;
  1265. for (auto& region : m_folding_regions) {
  1266. if (region.is_folded) {
  1267. // Only add this region if it's not contained within a previous folded region.
  1268. // Because regions are sorted by their start position, and regions cannot partially overlap,
  1269. // we can just see if it starts inside the last region we appended.
  1270. if (!folded_regions.is_empty() && folded_regions.last().range.contains(region.range.start()))
  1271. continue;
  1272. folded_regions.append(region);
  1273. }
  1274. }
  1275. return folded_regions;
  1276. }
  1277. }