TextDocument.cpp 41 KB

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