TextDocument.cpp 37 KB

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