TextDocument.cpp 48 KB

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