TextDocument.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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. String TextDocumentLine::to_utf8() const
  125. {
  126. StringBuilder builder;
  127. builder.append(view());
  128. return builder.to_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::truncate(TextDocument& document, size_t length)
  210. {
  211. m_text.resize(length);
  212. document.update_views({});
  213. }
  214. void TextDocument::append_line(NonnullOwnPtr<TextDocumentLine> line)
  215. {
  216. lines().append(move(line));
  217. if (m_client_notifications_enabled) {
  218. for (auto* client : m_clients)
  219. client->document_did_append_line();
  220. }
  221. }
  222. void TextDocument::insert_line(size_t line_index, NonnullOwnPtr<TextDocumentLine> line)
  223. {
  224. lines().insert((int)line_index, move(line));
  225. if (m_client_notifications_enabled) {
  226. for (auto* client : m_clients)
  227. client->document_did_insert_line(line_index);
  228. }
  229. }
  230. void TextDocument::remove_line(size_t line_index)
  231. {
  232. lines().remove((int)line_index);
  233. if (m_client_notifications_enabled) {
  234. for (auto* client : m_clients)
  235. client->document_did_remove_line(line_index);
  236. }
  237. }
  238. void TextDocument::remove_all_lines()
  239. {
  240. lines().clear();
  241. if (m_client_notifications_enabled) {
  242. for (auto* client : m_clients)
  243. client->document_did_remove_all_lines();
  244. }
  245. }
  246. void TextDocument::register_client(Client& client)
  247. {
  248. m_clients.set(&client);
  249. }
  250. void TextDocument::unregister_client(Client& client)
  251. {
  252. m_clients.remove(&client);
  253. }
  254. void TextDocument::update_views(Badge<TextDocumentLine>)
  255. {
  256. notify_did_change();
  257. }
  258. void TextDocument::notify_did_change()
  259. {
  260. if (m_client_notifications_enabled) {
  261. for (auto* client : m_clients)
  262. client->document_did_change();
  263. }
  264. m_regex_needs_update = true;
  265. }
  266. void TextDocument::set_all_cursors(TextPosition const& position)
  267. {
  268. if (m_client_notifications_enabled) {
  269. for (auto* client : m_clients)
  270. client->document_did_set_cursor(position);
  271. }
  272. }
  273. String TextDocument::text() const
  274. {
  275. StringBuilder builder;
  276. for (size_t i = 0; i < line_count(); ++i) {
  277. auto& line = this->line(i);
  278. builder.append(line.view());
  279. if (i != line_count() - 1)
  280. builder.append('\n');
  281. }
  282. return builder.to_string();
  283. }
  284. String TextDocument::text_in_range(TextRange const& a_range) const
  285. {
  286. auto range = a_range.normalized();
  287. if (is_empty() || line_count() < range.end().line() - range.start().line())
  288. return String("");
  289. StringBuilder builder;
  290. for (size_t i = range.start().line(); i <= range.end().line(); ++i) {
  291. auto& line = this->line(i);
  292. size_t selection_start_column_on_line = range.start().line() == i ? range.start().column() : 0;
  293. size_t selection_end_column_on_line = range.end().line() == i ? range.end().column() : line.length();
  294. if (!line.is_empty()) {
  295. builder.append(
  296. Utf32View(
  297. line.code_points() + selection_start_column_on_line,
  298. selection_end_column_on_line - selection_start_column_on_line));
  299. }
  300. if (i != range.end().line())
  301. builder.append('\n');
  302. }
  303. return builder.to_string();
  304. }
  305. u32 TextDocument::code_point_at(TextPosition const& position) const
  306. {
  307. VERIFY(position.line() < line_count());
  308. auto& line = this->line(position.line());
  309. if (position.column() == line.length())
  310. return '\n';
  311. return line.code_points()[position.column()];
  312. }
  313. TextPosition TextDocument::next_position_after(TextPosition const& position, SearchShouldWrap should_wrap) const
  314. {
  315. auto& line = this->line(position.line());
  316. if (position.column() == line.length()) {
  317. if (position.line() == line_count() - 1) {
  318. if (should_wrap == SearchShouldWrap::Yes)
  319. return { 0, 0 };
  320. return {};
  321. }
  322. return { position.line() + 1, 0 };
  323. }
  324. return { position.line(), position.column() + 1 };
  325. }
  326. TextPosition TextDocument::previous_position_before(TextPosition const& position, SearchShouldWrap should_wrap) const
  327. {
  328. if (position.column() == 0) {
  329. if (position.line() == 0) {
  330. if (should_wrap == SearchShouldWrap::Yes) {
  331. auto& last_line = this->line(line_count() - 1);
  332. return { line_count() - 1, last_line.length() };
  333. }
  334. return {};
  335. }
  336. auto& prev_line = this->line(position.line() - 1);
  337. return { position.line() - 1, prev_line.length() };
  338. }
  339. return { position.line(), position.column() - 1 };
  340. }
  341. void TextDocument::update_regex_matches(StringView needle)
  342. {
  343. if (m_regex_needs_update || needle != m_regex_needle) {
  344. Regex<PosixExtended> re(needle);
  345. Vector<RegexStringView> views;
  346. for (size_t line = 0; line < m_lines.size(); ++line) {
  347. views.append(m_lines.at(line).view());
  348. }
  349. re.search(views, m_regex_result);
  350. m_regex_needs_update = false;
  351. m_regex_needle = String { needle };
  352. m_regex_result_match_index = -1;
  353. m_regex_result_match_capture_group_index = -1;
  354. }
  355. }
  356. TextRange TextDocument::find_next(StringView needle, TextPosition const& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case)
  357. {
  358. if (needle.is_empty())
  359. return {};
  360. if (regmatch) {
  361. if (!m_regex_result.matches.size())
  362. return {};
  363. regex::Match match;
  364. bool use_whole_match { false };
  365. auto next_match = [&] {
  366. m_regex_result_match_capture_group_index = 0;
  367. if (m_regex_result_match_index == m_regex_result.matches.size() - 1) {
  368. if (should_wrap == SearchShouldWrap::Yes)
  369. m_regex_result_match_index = 0;
  370. else
  371. ++m_regex_result_match_index;
  372. } else
  373. ++m_regex_result_match_index;
  374. };
  375. if (m_regex_result.n_capture_groups) {
  376. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  377. next_match();
  378. else {
  379. // check if last capture group has been reached
  380. if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) {
  381. next_match();
  382. } else {
  383. // get to the next capture group item
  384. ++m_regex_result_match_capture_group_index;
  385. }
  386. }
  387. // use whole match, if there is no capture group for current index
  388. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  389. use_whole_match = true;
  390. else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  391. next_match();
  392. } else {
  393. next_match();
  394. }
  395. if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  396. match = m_regex_result.matches.at(m_regex_result_match_index);
  397. else
  398. match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index);
  399. return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } };
  400. }
  401. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  402. TextPosition original_position = position;
  403. TextPosition start_of_potential_match;
  404. size_t needle_index = 0;
  405. do {
  406. auto ch = code_point_at(position);
  407. // FIXME: This is not the right way to use a Unicode needle!
  408. if (match_case ? ch == (u32)needle[needle_index] : tolower(ch) == tolower((u32)needle[needle_index])) {
  409. if (needle_index == 0)
  410. start_of_potential_match = position;
  411. ++needle_index;
  412. if (needle_index >= needle.length())
  413. return { start_of_potential_match, next_position_after(position, should_wrap) };
  414. } else {
  415. if (needle_index > 0)
  416. position = start_of_potential_match;
  417. needle_index = 0;
  418. }
  419. position = next_position_after(position, should_wrap);
  420. } while (position.is_valid() && position != original_position);
  421. return {};
  422. }
  423. TextRange TextDocument::find_previous(StringView needle, TextPosition const& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case)
  424. {
  425. if (needle.is_empty())
  426. return {};
  427. if (regmatch) {
  428. if (!m_regex_result.matches.size())
  429. return {};
  430. regex::Match match;
  431. bool use_whole_match { false };
  432. auto next_match = [&] {
  433. if (m_regex_result_match_index == 0) {
  434. if (should_wrap == SearchShouldWrap::Yes)
  435. m_regex_result_match_index = m_regex_result.matches.size() - 1;
  436. else
  437. --m_regex_result_match_index;
  438. } else
  439. --m_regex_result_match_index;
  440. m_regex_result_match_capture_group_index = m_regex_result.capture_group_matches.at(m_regex_result_match_index).size() - 1;
  441. };
  442. if (m_regex_result.n_capture_groups) {
  443. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  444. next_match();
  445. else {
  446. // check if last capture group has been reached
  447. if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) {
  448. next_match();
  449. } else {
  450. // get to the next capture group item
  451. --m_regex_result_match_capture_group_index;
  452. }
  453. }
  454. // use whole match, if there is no capture group for current index
  455. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  456. use_whole_match = true;
  457. else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  458. next_match();
  459. } else {
  460. next_match();
  461. }
  462. if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  463. match = m_regex_result.matches.at(m_regex_result_match_index);
  464. else
  465. match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index);
  466. return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } };
  467. }
  468. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  469. position = previous_position_before(position, should_wrap);
  470. if (position.line() >= line_count())
  471. return {};
  472. TextPosition original_position = position;
  473. TextPosition end_of_potential_match;
  474. size_t needle_index = needle.length() - 1;
  475. do {
  476. auto ch = code_point_at(position);
  477. // FIXME: This is not the right way to use a Unicode needle!
  478. if (match_case ? ch == (u32)needle[needle_index] : tolower(ch) == tolower((u32)needle[needle_index])) {
  479. if (needle_index == needle.length() - 1)
  480. end_of_potential_match = position;
  481. if (needle_index == 0)
  482. return { position, next_position_after(end_of_potential_match, should_wrap) };
  483. --needle_index;
  484. } else {
  485. if (needle_index < needle.length() - 1)
  486. position = end_of_potential_match;
  487. needle_index = needle.length() - 1;
  488. }
  489. position = previous_position_before(position, should_wrap);
  490. } while (position.is_valid() && position != original_position);
  491. return {};
  492. }
  493. Vector<TextRange> TextDocument::find_all(StringView needle, bool regmatch, bool match_case)
  494. {
  495. Vector<TextRange> ranges;
  496. TextPosition position;
  497. for (;;) {
  498. auto range = find_next(needle, position, SearchShouldWrap::No, regmatch, match_case);
  499. if (!range.is_valid())
  500. break;
  501. ranges.append(range);
  502. position = range.end();
  503. }
  504. return ranges;
  505. }
  506. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_before(TextPosition const& position) const
  507. {
  508. for (int i = m_spans.size() - 1; i >= 0; --i) {
  509. if (!m_spans[i].range.contains(position))
  510. continue;
  511. while ((i - 1) >= 0 && m_spans[i - 1].is_skippable)
  512. --i;
  513. if (i <= 0)
  514. return {};
  515. return m_spans[i - 1];
  516. }
  517. return {};
  518. }
  519. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_after(TextPosition const& position) const
  520. {
  521. size_t i = 0;
  522. // Find the first span containing the cursor
  523. for (; i < m_spans.size(); ++i) {
  524. if (m_spans[i].range.contains(position))
  525. break;
  526. }
  527. // Find the first span *after* the cursor
  528. // TODO: For a large number of spans, binary search would be faster.
  529. for (; i < m_spans.size(); ++i) {
  530. if (!m_spans[i].range.contains(position))
  531. break;
  532. }
  533. // Skip skippable spans
  534. for (; i < m_spans.size(); ++i) {
  535. if (!m_spans[i].is_skippable)
  536. break;
  537. }
  538. if (i < m_spans.size())
  539. return m_spans[i];
  540. return {};
  541. }
  542. TextPosition TextDocument::first_word_break_before(TextPosition const& position, bool start_at_column_before) const
  543. {
  544. if (position.column() == 0) {
  545. if (position.line() == 0) {
  546. return TextPosition(0, 0);
  547. }
  548. auto previous_line = this->line(position.line() - 1);
  549. return TextPosition(position.line() - 1, previous_line.length());
  550. }
  551. auto target = position;
  552. auto line = this->line(target.line());
  553. auto modifier = start_at_column_before ? 1 : 0;
  554. if (target.column() == line.length())
  555. modifier = 1;
  556. while (target.column() > 0 && is_ascii_blank(line.code_points()[target.column() - modifier]))
  557. target.set_column(target.column() - 1);
  558. auto is_start_alphanumeric = is_ascii_alphanumeric(line.code_points()[target.column() - modifier]);
  559. while (target.column() > 0) {
  560. auto prev_code_point = line.code_points()[target.column() - 1];
  561. if ((is_start_alphanumeric && !is_ascii_alphanumeric(prev_code_point)) || (!is_start_alphanumeric && is_ascii_alphanumeric(prev_code_point)))
  562. break;
  563. target.set_column(target.column() - 1);
  564. }
  565. return target;
  566. }
  567. TextPosition TextDocument::first_word_break_after(TextPosition const& position) const
  568. {
  569. auto target = position;
  570. auto line = this->line(target.line());
  571. if (position.column() >= line.length()) {
  572. if (position.line() >= this->line_count() - 1) {
  573. return position;
  574. }
  575. return TextPosition(position.line() + 1, 0);
  576. }
  577. while (target.column() < line.length() && is_ascii_space(line.code_points()[target.column()]))
  578. target.set_column(target.column() + 1);
  579. auto is_start_alphanumeric = is_ascii_alphanumeric(line.code_points()[target.column()]);
  580. while (target.column() < line.length()) {
  581. auto next_code_point = line.code_points()[target.column()];
  582. if ((is_start_alphanumeric && !is_ascii_alphanumeric(next_code_point)) || (!is_start_alphanumeric && is_ascii_alphanumeric(next_code_point)))
  583. break;
  584. target.set_column(target.column() + 1);
  585. }
  586. return target;
  587. }
  588. TextPosition TextDocument::first_word_before(TextPosition const& position, bool start_at_column_before) const
  589. {
  590. if (position.column() == 0) {
  591. if (position.line() == 0) {
  592. return TextPosition(0, 0);
  593. }
  594. auto previous_line = this->line(position.line() - 1);
  595. return TextPosition(position.line() - 1, previous_line.length());
  596. }
  597. auto target = position;
  598. auto line = this->line(target.line());
  599. if (target.column() == line.length())
  600. start_at_column_before = 1;
  601. auto nonblank_passed = !is_ascii_blank(line.code_points()[target.column() - start_at_column_before]);
  602. while (target.column() > 0) {
  603. auto prev_code_point = line.code_points()[target.column() - 1];
  604. nonblank_passed |= !is_ascii_blank(prev_code_point);
  605. if (nonblank_passed && is_ascii_blank(prev_code_point)) {
  606. break;
  607. } else if (is_ascii_punctuation(prev_code_point)) {
  608. target.set_column(target.column() - 1);
  609. break;
  610. }
  611. target.set_column(target.column() - 1);
  612. }
  613. return target;
  614. }
  615. void TextDocument::undo()
  616. {
  617. if (!can_undo())
  618. return;
  619. m_undo_stack.undo();
  620. notify_did_change();
  621. }
  622. void TextDocument::redo()
  623. {
  624. if (!can_redo())
  625. return;
  626. m_undo_stack.redo();
  627. notify_did_change();
  628. }
  629. void TextDocument::add_to_undo_stack(NonnullOwnPtr<TextDocumentUndoCommand> undo_command)
  630. {
  631. m_undo_stack.push(move(undo_command));
  632. }
  633. TextDocumentUndoCommand::TextDocumentUndoCommand(TextDocument& document)
  634. : m_document(document)
  635. {
  636. }
  637. InsertTextCommand::InsertTextCommand(TextDocument& document, String const& text, TextPosition const& position)
  638. : TextDocumentUndoCommand(document)
  639. , m_text(text)
  640. , m_range({ position, position })
  641. {
  642. }
  643. String InsertTextCommand::action_text() const
  644. {
  645. return "Insert Text";
  646. }
  647. bool InsertTextCommand::merge_with(GUI::Command const& other)
  648. {
  649. if (!is<InsertTextCommand>(other) || commit_time_expired())
  650. return false;
  651. auto const& typed_other = static_cast<InsertTextCommand const&>(other);
  652. if (typed_other.m_text.is_whitespace() && !m_text.is_whitespace())
  653. return false; // Skip if other is whitespace while this is not
  654. if (m_range.end() != typed_other.m_range.start())
  655. return false;
  656. if (m_range.start().line() != m_range.end().line())
  657. return false;
  658. StringBuilder builder(m_text.length() + typed_other.m_text.length());
  659. builder.append(m_text);
  660. builder.append(typed_other.m_text);
  661. m_text = builder.to_string();
  662. m_range.set_end(typed_other.m_range.end());
  663. m_timestamp = Time::now_monotonic();
  664. return true;
  665. }
  666. void InsertTextCommand::perform_formatting(TextDocument::Client const& client)
  667. {
  668. const size_t tab_width = client.soft_tab_width();
  669. auto const& dest_line = m_document.line(m_range.start().line());
  670. bool const should_auto_indent = client.is_automatic_indentation_enabled();
  671. StringBuilder builder;
  672. size_t column = m_range.start().column();
  673. size_t line_indentation = dest_line.leading_spaces();
  674. bool at_start_of_line = line_indentation == column;
  675. for (auto input_char : m_text) {
  676. if (input_char == '\n') {
  677. size_t spaces_at_end = 0;
  678. if (column < line_indentation)
  679. spaces_at_end = line_indentation - column;
  680. line_indentation -= spaces_at_end;
  681. builder.append('\n');
  682. column = 0;
  683. if (should_auto_indent) {
  684. for (; column < line_indentation; ++column) {
  685. builder.append(' ');
  686. }
  687. }
  688. at_start_of_line = true;
  689. } else if (input_char == '\t') {
  690. size_t next_soft_tab_stop = ((column + tab_width) / tab_width) * tab_width;
  691. size_t spaces_to_insert = next_soft_tab_stop - column;
  692. for (size_t i = 0; i < spaces_to_insert; ++i) {
  693. builder.append(' ');
  694. }
  695. column = next_soft_tab_stop;
  696. if (at_start_of_line) {
  697. line_indentation = column;
  698. }
  699. } else {
  700. if (input_char == ' ') {
  701. if (at_start_of_line) {
  702. ++line_indentation;
  703. }
  704. } else {
  705. at_start_of_line = false;
  706. }
  707. builder.append(input_char);
  708. ++column;
  709. }
  710. }
  711. m_text = builder.build();
  712. }
  713. void InsertTextCommand::redo()
  714. {
  715. auto new_cursor = m_document.insert_at(m_range.start(), m_text, m_client);
  716. // NOTE: We don't know where the range ends until after doing redo().
  717. // This is okay since we always do redo() after adding this to the undo stack.
  718. m_range.set_end(new_cursor);
  719. m_document.set_all_cursors(new_cursor);
  720. }
  721. void InsertTextCommand::undo()
  722. {
  723. m_document.remove(m_range);
  724. m_document.set_all_cursors(m_range.start());
  725. }
  726. RemoveTextCommand::RemoveTextCommand(TextDocument& document, String const& text, TextRange const& range)
  727. : TextDocumentUndoCommand(document)
  728. , m_text(text)
  729. , m_range(range)
  730. {
  731. }
  732. String RemoveTextCommand::action_text() const
  733. {
  734. return "Remove Text";
  735. }
  736. bool RemoveTextCommand::merge_with(GUI::Command const& other)
  737. {
  738. if (!is<RemoveTextCommand>(other) || commit_time_expired())
  739. return false;
  740. auto const& typed_other = static_cast<RemoveTextCommand const&>(other);
  741. if (m_range.start() != typed_other.m_range.end())
  742. return false;
  743. if (m_range.start().line() != m_range.end().line())
  744. return false;
  745. // Merge backspaces
  746. StringBuilder builder(m_text.length() + typed_other.m_text.length());
  747. builder.append(typed_other.m_text);
  748. builder.append(m_text);
  749. m_text = builder.to_string();
  750. m_range.set_start(typed_other.m_range.start());
  751. m_timestamp = Time::now_monotonic();
  752. return true;
  753. }
  754. void RemoveTextCommand::redo()
  755. {
  756. m_document.remove(m_range);
  757. m_document.set_all_cursors(m_range.start());
  758. }
  759. void RemoveTextCommand::undo()
  760. {
  761. auto new_cursor = m_document.insert_at(m_range.start(), m_text);
  762. m_document.set_all_cursors(new_cursor);
  763. }
  764. ReplaceAllTextCommand::ReplaceAllTextCommand(GUI::TextDocument& document, String const& text, GUI::TextRange const& range, String const& action_text)
  765. : TextDocumentUndoCommand(document)
  766. , m_text(text)
  767. , m_range(range)
  768. , m_action_text(action_text)
  769. {
  770. }
  771. void ReplaceAllTextCommand::redo()
  772. {
  773. m_document.remove(m_range);
  774. m_document.set_all_cursors(m_range.start());
  775. auto new_cursor = m_document.insert_at(m_range.start(), m_text, m_client);
  776. m_range.set_end(new_cursor);
  777. m_document.set_all_cursors(new_cursor);
  778. }
  779. void ReplaceAllTextCommand::undo()
  780. {
  781. m_document.remove(m_range);
  782. m_document.set_all_cursors(m_range.start());
  783. auto new_cursor = m_document.insert_at(m_range.start(), m_text);
  784. m_range.set_end(new_cursor);
  785. m_document.set_all_cursors(new_cursor);
  786. }
  787. bool ReplaceAllTextCommand::merge_with(GUI::Command const&)
  788. {
  789. return false;
  790. }
  791. String ReplaceAllTextCommand::action_text() const
  792. {
  793. return m_action_text;
  794. }
  795. IndentSelection::IndentSelection(TextDocument& document, size_t tab_width, TextRange const& range)
  796. : TextDocumentUndoCommand(document)
  797. , m_tab_width(tab_width)
  798. , m_range(range)
  799. {
  800. }
  801. void IndentSelection::redo()
  802. {
  803. auto const tab = String::repeated(' ', m_tab_width);
  804. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  805. m_document.insert_at({ i, 0 }, tab, m_client);
  806. }
  807. m_document.set_all_cursors(m_range.start());
  808. }
  809. void IndentSelection::undo()
  810. {
  811. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  812. m_document.remove({ { i, 0 }, { i, m_tab_width } });
  813. }
  814. m_document.set_all_cursors(m_range.start());
  815. }
  816. UnindentSelection::UnindentSelection(TextDocument& document, size_t tab_width, TextRange const& range)
  817. : TextDocumentUndoCommand(document)
  818. , m_tab_width(tab_width)
  819. , m_range(range)
  820. {
  821. }
  822. void UnindentSelection::redo()
  823. {
  824. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++) {
  825. if (m_document.line(i).leading_spaces() >= m_tab_width)
  826. m_document.remove({ { i, 0 }, { i, m_tab_width } });
  827. else
  828. m_document.remove({ { i, 0 }, { i, m_document.line(i).leading_spaces() } });
  829. }
  830. m_document.set_all_cursors(m_range.start());
  831. }
  832. void UnindentSelection::undo()
  833. {
  834. auto const tab = String::repeated(' ', m_tab_width);
  835. for (size_t i = m_range.start().line(); i <= m_range.end().line(); i++)
  836. m_document.insert_at({ i, 0 }, tab, m_client);
  837. m_document.set_all_cursors(m_range.start());
  838. }
  839. TextPosition TextDocument::insert_at(TextPosition const& position, StringView text, Client const* client)
  840. {
  841. TextPosition cursor = position;
  842. Utf8View utf8_view(text);
  843. for (auto code_point : utf8_view)
  844. cursor = insert_at(cursor, code_point, client);
  845. return cursor;
  846. }
  847. TextPosition TextDocument::insert_at(TextPosition const& position, u32 code_point, Client const*)
  848. {
  849. if (code_point == '\n') {
  850. auto new_line = make<TextDocumentLine>(*this);
  851. new_line->append(*this, line(position.line()).code_points() + position.column(), line(position.line()).length() - position.column());
  852. line(position.line()).truncate(*this, position.column());
  853. insert_line(position.line() + 1, move(new_line));
  854. notify_did_change();
  855. return { position.line() + 1, 0 };
  856. } else {
  857. line(position.line()).insert(*this, position.column(), code_point);
  858. notify_did_change();
  859. return { position.line(), position.column() + 1 };
  860. }
  861. }
  862. void TextDocument::remove(TextRange const& unnormalized_range)
  863. {
  864. if (!unnormalized_range.is_valid())
  865. return;
  866. auto range = unnormalized_range.normalized();
  867. // First delete all the lines in between the first and last one.
  868. for (size_t i = range.start().line() + 1; i < range.end().line();) {
  869. remove_line(i);
  870. range.end().set_line(range.end().line() - 1);
  871. }
  872. if (range.start().line() == range.end().line()) {
  873. // Delete within same line.
  874. auto& line = this->line(range.start().line());
  875. if (line.length() == 0)
  876. return;
  877. bool whole_line_is_selected = range.start().column() == 0 && range.end().column() == line.length();
  878. if (whole_line_is_selected) {
  879. line.clear(*this);
  880. } else {
  881. line.remove_range(*this, range.start().column(), range.end().column() - range.start().column());
  882. }
  883. } else {
  884. // Delete across a newline, merging lines.
  885. VERIFY(range.start().line() == range.end().line() - 1);
  886. auto& first_line = line(range.start().line());
  887. auto& second_line = line(range.end().line());
  888. Vector<u32> code_points;
  889. code_points.append(first_line.code_points(), range.start().column());
  890. if (!second_line.is_empty())
  891. code_points.append(second_line.code_points() + range.end().column(), second_line.length() - range.end().column());
  892. first_line.set_text(*this, move(code_points));
  893. remove_line(range.end().line());
  894. }
  895. if (lines().is_empty()) {
  896. append_line(make<TextDocumentLine>(*this));
  897. }
  898. notify_did_change();
  899. }
  900. bool TextDocument::is_empty() const
  901. {
  902. return line_count() == 1 && line(0).is_empty();
  903. }
  904. TextRange TextDocument::range_for_entire_line(size_t line_index) const
  905. {
  906. if (line_index >= line_count())
  907. return {};
  908. return { { line_index, 0 }, { line_index, line(line_index).length() } };
  909. }
  910. TextDocumentSpan const* TextDocument::span_at(TextPosition const& position) const
  911. {
  912. for (auto& span : m_spans) {
  913. if (span.range.contains(position))
  914. return &span;
  915. }
  916. return nullptr;
  917. }
  918. void TextDocument::set_unmodified()
  919. {
  920. m_undo_stack.set_current_unmodified();
  921. }
  922. void TextDocument::set_spans(u32 span_collection_index, Vector<TextDocumentSpan> spans)
  923. {
  924. m_span_collections.set(span_collection_index, move(spans));
  925. merge_span_collections();
  926. }
  927. struct SpanAndCollectionIndex {
  928. TextDocumentSpan span;
  929. u32 collection_index { 0 };
  930. };
  931. void TextDocument::merge_span_collections()
  932. {
  933. Vector<SpanAndCollectionIndex> sorted_spans;
  934. auto collection_indices = m_span_collections.keys();
  935. quick_sort(collection_indices);
  936. for (auto collection_index : collection_indices) {
  937. auto spans = m_span_collections.get(collection_index).value();
  938. for (auto span : spans) {
  939. sorted_spans.append({ move(span), collection_index });
  940. }
  941. }
  942. quick_sort(sorted_spans, [](SpanAndCollectionIndex const& a, SpanAndCollectionIndex const& b) {
  943. if (a.span.range.start() == b.span.range.start()) {
  944. return a.collection_index < b.collection_index;
  945. }
  946. return a.span.range.start() < b.span.range.start();
  947. });
  948. // The end of the TextRanges of spans are non-inclusive, i.e span range = [X,y).
  949. // This transforms the span's range to be inclusive, i.e [X,Y].
  950. auto adjust_end = [](GUI::TextDocumentSpan span) -> GUI::TextDocumentSpan {
  951. span.range.set_end({ span.range.end().line(), span.range.end().column() == 0 ? 0 : span.range.end().column() - 1 });
  952. return span;
  953. };
  954. Vector<SpanAndCollectionIndex> merged_spans;
  955. for (auto& span_and_collection_index : sorted_spans) {
  956. if (merged_spans.is_empty()) {
  957. merged_spans.append(span_and_collection_index);
  958. continue;
  959. }
  960. auto const& span = span_and_collection_index.span;
  961. auto last_span_and_collection_index = merged_spans.last();
  962. auto const& last_span = last_span_and_collection_index.span;
  963. if (adjust_end(span).range.start() > adjust_end(last_span).range.end()) {
  964. // Current span does not intersect with previous one, can simply append to merged list.
  965. merged_spans.append(span_and_collection_index);
  966. continue;
  967. }
  968. merged_spans.take_last();
  969. if (span.range.start() > last_span.range.start()) {
  970. SpanAndCollectionIndex first_part = last_span_and_collection_index;
  971. first_part.span.range.set_end(span.range.start());
  972. merged_spans.append(move(first_part));
  973. }
  974. SpanAndCollectionIndex merged_span;
  975. merged_span.collection_index = span_and_collection_index.collection_index;
  976. merged_span.span.range = { span.range.start(), min(span.range.end(), last_span.range.end()) };
  977. merged_span.span.is_skippable = span.is_skippable | last_span.is_skippable;
  978. merged_span.span.data = span.data ? span.data : last_span.data;
  979. 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;
  980. merged_span.span.attributes.bold = span.attributes.bold | last_span.attributes.bold;
  981. merged_span.span.attributes.background_color = span.attributes.background_color.has_value() ? span.attributes.background_color.value() : last_span.attributes.background_color;
  982. merged_span.span.attributes.underline = span.attributes.underline | last_span.attributes.underline;
  983. merged_span.span.attributes.underline_color = span.attributes.underline_color.has_value() ? span.attributes.underline_color.value() : last_span.attributes.underline_color;
  984. merged_span.span.attributes.underline_style = span.attributes.underline_style;
  985. merged_spans.append(move(merged_span));
  986. if (span.range.end() == last_span.range.end())
  987. continue;
  988. if (span.range.end() > last_span.range.end()) {
  989. SpanAndCollectionIndex last_part = span_and_collection_index;
  990. last_part.span.range.set_start(last_span.range.end());
  991. merged_spans.append(move(last_part));
  992. continue;
  993. }
  994. SpanAndCollectionIndex last_part = last_span_and_collection_index;
  995. last_part.span.range.set_start(span.range.end());
  996. merged_spans.append(move(last_part));
  997. }
  998. m_spans.clear();
  999. for (auto span : merged_spans) {
  1000. m_spans.append(move(span.span));
  1001. }
  1002. }
  1003. }