TextDocument.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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/ScopeGuard.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/Utf8View.h>
  12. #include <LibCore/Timer.h>
  13. #include <LibGUI/TextDocument.h>
  14. #include <LibRegex/Regex.h>
  15. namespace GUI {
  16. NonnullRefPtr<TextDocument> TextDocument::create(Client* client)
  17. {
  18. return adopt_ref(*new TextDocument(client));
  19. }
  20. TextDocument::TextDocument(Client* client)
  21. {
  22. if (client)
  23. m_clients.set(client);
  24. append_line(make<TextDocumentLine>(*this));
  25. set_unmodified();
  26. m_undo_stack.on_state_change = [this] {
  27. if (m_client_notifications_enabled) {
  28. for (auto* client : m_clients)
  29. client->document_did_update_undo_stack();
  30. }
  31. };
  32. }
  33. bool TextDocument::set_text(StringView text, AllowCallback allow_callback)
  34. {
  35. m_client_notifications_enabled = false;
  36. m_undo_stack.clear();
  37. m_spans.clear();
  38. remove_all_lines();
  39. ArmedScopeGuard clear_text_guard([this]() {
  40. set_text({});
  41. });
  42. size_t start_of_current_line = 0;
  43. auto add_line = [&](size_t current_position) -> bool {
  44. size_t line_length = current_position - start_of_current_line;
  45. auto line = make<TextDocumentLine>(*this);
  46. bool success = true;
  47. if (line_length)
  48. success = line->set_text(*this, text.substring_view(start_of_current_line, current_position - start_of_current_line));
  49. if (!success)
  50. return false;
  51. append_line(move(line));
  52. start_of_current_line = current_position + 1;
  53. return true;
  54. };
  55. size_t i = 0;
  56. for (i = 0; i < text.length(); ++i) {
  57. if (text[i] != '\n')
  58. continue;
  59. auto success = add_line(i);
  60. if (!success)
  61. return false;
  62. }
  63. auto success = add_line(i);
  64. if (!success)
  65. return false;
  66. // Don't show the file's trailing newline as an actual new line.
  67. if (line_count() > 1 && line(line_count() - 1).is_empty())
  68. (void)m_lines.take_last();
  69. m_client_notifications_enabled = true;
  70. for (auto* client : m_clients)
  71. client->document_did_set_text(allow_callback);
  72. clear_text_guard.disarm();
  73. // FIXME: Should the modified state be cleared on some of the earlier returns as well?
  74. set_unmodified();
  75. return true;
  76. }
  77. size_t TextDocumentLine::first_non_whitespace_column() const
  78. {
  79. for (size_t i = 0; i < length(); ++i) {
  80. auto code_point = code_points()[i];
  81. if (!is_ascii_space(code_point))
  82. return i;
  83. }
  84. return length();
  85. }
  86. Optional<size_t> TextDocumentLine::last_non_whitespace_column() const
  87. {
  88. for (ssize_t i = length() - 1; i >= 0; --i) {
  89. auto code_point = code_points()[i];
  90. if (!is_ascii_space(code_point))
  91. return i;
  92. }
  93. return {};
  94. }
  95. bool TextDocumentLine::ends_in_whitespace() const
  96. {
  97. if (!length())
  98. return false;
  99. return is_ascii_space(code_points()[length() - 1]);
  100. }
  101. bool TextDocumentLine::can_select() const
  102. {
  103. if (is_empty())
  104. return false;
  105. for (size_t i = 0; i < length(); ++i) {
  106. auto code_point = code_points()[i];
  107. if (code_point != '\n' && code_point != '\r' && code_point != '\f' && code_point != '\v')
  108. return true;
  109. }
  110. return false;
  111. }
  112. size_t TextDocumentLine::leading_spaces() const
  113. {
  114. size_t count = 0;
  115. for (; count < m_text.size(); ++count) {
  116. if (m_text[count] != ' ') {
  117. break;
  118. }
  119. }
  120. return count;
  121. }
  122. String TextDocumentLine::to_utf8() const
  123. {
  124. StringBuilder builder;
  125. builder.append(view());
  126. return builder.to_string();
  127. }
  128. TextDocumentLine::TextDocumentLine(TextDocument& document)
  129. {
  130. clear(document);
  131. }
  132. TextDocumentLine::TextDocumentLine(TextDocument& document, StringView text)
  133. {
  134. set_text(document, text);
  135. }
  136. void TextDocumentLine::clear(TextDocument& document)
  137. {
  138. m_text.clear();
  139. document.update_views({});
  140. }
  141. void TextDocumentLine::set_text(TextDocument& document, const Vector<u32> text)
  142. {
  143. m_text = move(text);
  144. document.update_views({});
  145. }
  146. bool TextDocumentLine::set_text(TextDocument& document, StringView text)
  147. {
  148. if (text.is_empty()) {
  149. clear(document);
  150. return true;
  151. }
  152. m_text.clear();
  153. Utf8View utf8_view(text);
  154. if (!utf8_view.validate()) {
  155. return false;
  156. }
  157. for (auto code_point : utf8_view)
  158. m_text.append(code_point);
  159. document.update_views({});
  160. return true;
  161. }
  162. void TextDocumentLine::append(TextDocument& document, const u32* code_points, size_t length)
  163. {
  164. if (length == 0)
  165. return;
  166. m_text.append(code_points, length);
  167. document.update_views({});
  168. }
  169. void TextDocumentLine::append(TextDocument& document, u32 code_point)
  170. {
  171. insert(document, length(), code_point);
  172. }
  173. void TextDocumentLine::prepend(TextDocument& document, u32 code_point)
  174. {
  175. insert(document, 0, code_point);
  176. }
  177. void TextDocumentLine::insert(TextDocument& document, size_t index, u32 code_point)
  178. {
  179. if (index == length()) {
  180. m_text.append(code_point);
  181. } else {
  182. m_text.insert(index, code_point);
  183. }
  184. document.update_views({});
  185. }
  186. void TextDocumentLine::remove(TextDocument& document, size_t index)
  187. {
  188. if (index == length()) {
  189. m_text.take_last();
  190. } else {
  191. m_text.remove(index);
  192. }
  193. document.update_views({});
  194. }
  195. void TextDocumentLine::remove_range(TextDocument& document, size_t start, size_t length)
  196. {
  197. VERIFY(length <= m_text.size());
  198. Vector<u32> new_data;
  199. new_data.ensure_capacity(m_text.size() - length);
  200. for (size_t i = 0; i < start; ++i)
  201. new_data.append(m_text[i]);
  202. for (size_t i = (start + length); i < m_text.size(); ++i)
  203. new_data.append(m_text[i]);
  204. m_text = move(new_data);
  205. document.update_views({});
  206. }
  207. void TextDocumentLine::truncate(TextDocument& document, size_t length)
  208. {
  209. m_text.resize(length);
  210. document.update_views({});
  211. }
  212. void TextDocument::append_line(NonnullOwnPtr<TextDocumentLine> line)
  213. {
  214. lines().append(move(line));
  215. if (m_client_notifications_enabled) {
  216. for (auto* client : m_clients)
  217. client->document_did_append_line();
  218. }
  219. }
  220. void TextDocument::insert_line(size_t line_index, NonnullOwnPtr<TextDocumentLine> line)
  221. {
  222. lines().insert((int)line_index, move(line));
  223. if (m_client_notifications_enabled) {
  224. for (auto* client : m_clients)
  225. client->document_did_insert_line(line_index);
  226. }
  227. }
  228. void TextDocument::remove_line(size_t line_index)
  229. {
  230. lines().remove((int)line_index);
  231. if (m_client_notifications_enabled) {
  232. for (auto* client : m_clients)
  233. client->document_did_remove_line(line_index);
  234. }
  235. }
  236. void TextDocument::remove_all_lines()
  237. {
  238. lines().clear();
  239. if (m_client_notifications_enabled) {
  240. for (auto* client : m_clients)
  241. client->document_did_remove_all_lines();
  242. }
  243. }
  244. void TextDocument::register_client(Client& client)
  245. {
  246. m_clients.set(&client);
  247. }
  248. void TextDocument::unregister_client(Client& client)
  249. {
  250. m_clients.remove(&client);
  251. }
  252. void TextDocument::update_views(Badge<TextDocumentLine>)
  253. {
  254. notify_did_change();
  255. }
  256. void TextDocument::notify_did_change()
  257. {
  258. if (m_client_notifications_enabled) {
  259. for (auto* client : m_clients)
  260. client->document_did_change();
  261. }
  262. m_regex_needs_update = true;
  263. }
  264. void TextDocument::set_all_cursors(const TextPosition& position)
  265. {
  266. if (m_client_notifications_enabled) {
  267. for (auto* client : m_clients)
  268. client->document_did_set_cursor(position);
  269. }
  270. }
  271. String TextDocument::text() const
  272. {
  273. StringBuilder builder;
  274. for (size_t i = 0; i < line_count(); ++i) {
  275. auto& line = this->line(i);
  276. builder.append(line.view());
  277. if (i != line_count() - 1)
  278. builder.append('\n');
  279. }
  280. return builder.to_string();
  281. }
  282. String TextDocument::text_in_range(const TextRange& a_range) const
  283. {
  284. auto range = a_range.normalized();
  285. if (is_empty() || line_count() < range.end().line() - range.start().line())
  286. return String("");
  287. StringBuilder builder;
  288. for (size_t i = range.start().line(); i <= range.end().line(); ++i) {
  289. auto& line = this->line(i);
  290. size_t selection_start_column_on_line = range.start().line() == i ? range.start().column() : 0;
  291. size_t selection_end_column_on_line = range.end().line() == i ? range.end().column() : line.length();
  292. if (!line.is_empty()) {
  293. builder.append(
  294. Utf32View(
  295. line.code_points() + selection_start_column_on_line,
  296. selection_end_column_on_line - selection_start_column_on_line));
  297. }
  298. if (i != range.end().line())
  299. builder.append('\n');
  300. }
  301. return builder.to_string();
  302. }
  303. u32 TextDocument::code_point_at(const TextPosition& position) const
  304. {
  305. VERIFY(position.line() < line_count());
  306. auto& line = this->line(position.line());
  307. if (position.column() == line.length())
  308. return '\n';
  309. return line.code_points()[position.column()];
  310. }
  311. TextPosition TextDocument::next_position_after(const TextPosition& position, SearchShouldWrap should_wrap) const
  312. {
  313. auto& line = this->line(position.line());
  314. if (position.column() == line.length()) {
  315. if (position.line() == line_count() - 1) {
  316. if (should_wrap == SearchShouldWrap::Yes)
  317. return { 0, 0 };
  318. return {};
  319. }
  320. return { position.line() + 1, 0 };
  321. }
  322. return { position.line(), position.column() + 1 };
  323. }
  324. TextPosition TextDocument::previous_position_before(const TextPosition& position, SearchShouldWrap should_wrap) const
  325. {
  326. if (position.column() == 0) {
  327. if (position.line() == 0) {
  328. if (should_wrap == SearchShouldWrap::Yes) {
  329. auto& last_line = this->line(line_count() - 1);
  330. return { line_count() - 1, last_line.length() };
  331. }
  332. return {};
  333. }
  334. auto& prev_line = this->line(position.line() - 1);
  335. return { position.line() - 1, prev_line.length() };
  336. }
  337. return { position.line(), position.column() - 1 };
  338. }
  339. void TextDocument::update_regex_matches(StringView needle)
  340. {
  341. if (m_regex_needs_update || needle != m_regex_needle) {
  342. Regex<PosixExtended> re(needle);
  343. Vector<RegexStringView> views;
  344. for (size_t line = 0; line < m_lines.size(); ++line) {
  345. views.append(m_lines.at(line).view());
  346. }
  347. re.search(views, m_regex_result);
  348. m_regex_needs_update = false;
  349. m_regex_needle = String { needle };
  350. m_regex_result_match_index = -1;
  351. m_regex_result_match_capture_group_index = -1;
  352. }
  353. }
  354. TextRange TextDocument::find_next(StringView needle, const TextPosition& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case)
  355. {
  356. if (needle.is_empty())
  357. return {};
  358. if (regmatch) {
  359. if (!m_regex_result.matches.size())
  360. return {};
  361. regex::Match match;
  362. bool use_whole_match { false };
  363. auto next_match = [&] {
  364. m_regex_result_match_capture_group_index = 0;
  365. if (m_regex_result_match_index == m_regex_result.matches.size() - 1) {
  366. if (should_wrap == SearchShouldWrap::Yes)
  367. m_regex_result_match_index = 0;
  368. else
  369. ++m_regex_result_match_index;
  370. } else
  371. ++m_regex_result_match_index;
  372. };
  373. if (m_regex_result.n_capture_groups) {
  374. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  375. next_match();
  376. else {
  377. // check if last capture group has been reached
  378. if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) {
  379. next_match();
  380. } else {
  381. // get to the next capture group item
  382. ++m_regex_result_match_capture_group_index;
  383. }
  384. }
  385. // use whole match, if there is no capture group for current index
  386. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  387. use_whole_match = true;
  388. else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  389. next_match();
  390. } else {
  391. next_match();
  392. }
  393. if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  394. match = m_regex_result.matches.at(m_regex_result_match_index);
  395. else
  396. match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index);
  397. return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } };
  398. }
  399. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  400. TextPosition original_position = position;
  401. TextPosition start_of_potential_match;
  402. size_t needle_index = 0;
  403. do {
  404. auto ch = code_point_at(position);
  405. // FIXME: This is not the right way to use a Unicode needle!
  406. if (match_case ? ch == (u32)needle[needle_index] : tolower(ch) == tolower((u32)needle[needle_index])) {
  407. if (needle_index == 0)
  408. start_of_potential_match = position;
  409. ++needle_index;
  410. if (needle_index >= needle.length())
  411. return { start_of_potential_match, next_position_after(position, should_wrap) };
  412. } else {
  413. if (needle_index > 0)
  414. position = start_of_potential_match;
  415. needle_index = 0;
  416. }
  417. position = next_position_after(position, should_wrap);
  418. } while (position.is_valid() && position != original_position);
  419. return {};
  420. }
  421. TextRange TextDocument::find_previous(StringView needle, const TextPosition& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case)
  422. {
  423. if (needle.is_empty())
  424. return {};
  425. if (regmatch) {
  426. if (!m_regex_result.matches.size())
  427. return {};
  428. regex::Match match;
  429. bool use_whole_match { false };
  430. auto next_match = [&] {
  431. if (m_regex_result_match_index == 0) {
  432. if (should_wrap == SearchShouldWrap::Yes)
  433. m_regex_result_match_index = m_regex_result.matches.size() - 1;
  434. else
  435. --m_regex_result_match_index;
  436. } else
  437. --m_regex_result_match_index;
  438. m_regex_result_match_capture_group_index = m_regex_result.capture_group_matches.at(m_regex_result_match_index).size() - 1;
  439. };
  440. if (m_regex_result.n_capture_groups) {
  441. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  442. next_match();
  443. else {
  444. // check if last capture group has been reached
  445. if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) {
  446. next_match();
  447. } else {
  448. // get to the next capture group item
  449. --m_regex_result_match_capture_group_index;
  450. }
  451. }
  452. // use whole match, if there is no capture group for current index
  453. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  454. use_whole_match = true;
  455. else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  456. next_match();
  457. } else {
  458. next_match();
  459. }
  460. if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  461. match = m_regex_result.matches.at(m_regex_result_match_index);
  462. else
  463. match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index);
  464. return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } };
  465. }
  466. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  467. position = previous_position_before(position, should_wrap);
  468. if (position.line() >= line_count())
  469. return {};
  470. TextPosition original_position = position;
  471. TextPosition end_of_potential_match;
  472. size_t needle_index = needle.length() - 1;
  473. do {
  474. auto ch = code_point_at(position);
  475. // FIXME: This is not the right way to use a Unicode needle!
  476. if (match_case ? ch == (u32)needle[needle_index] : tolower(ch) == tolower((u32)needle[needle_index])) {
  477. if (needle_index == needle.length() - 1)
  478. end_of_potential_match = position;
  479. if (needle_index == 0)
  480. return { position, next_position_after(end_of_potential_match, should_wrap) };
  481. --needle_index;
  482. } else {
  483. if (needle_index < needle.length() - 1)
  484. position = end_of_potential_match;
  485. needle_index = needle.length() - 1;
  486. }
  487. position = previous_position_before(position, should_wrap);
  488. } while (position.is_valid() && position != original_position);
  489. return {};
  490. }
  491. Vector<TextRange> TextDocument::find_all(StringView needle, bool regmatch)
  492. {
  493. Vector<TextRange> ranges;
  494. TextPosition position;
  495. for (;;) {
  496. auto range = find_next(needle, position, SearchShouldWrap::No, regmatch);
  497. if (!range.is_valid())
  498. break;
  499. ranges.append(range);
  500. position = range.end();
  501. }
  502. return ranges;
  503. }
  504. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_before(const TextPosition& position) const
  505. {
  506. for (int i = m_spans.size() - 1; i >= 0; --i) {
  507. if (!m_spans[i].range.contains(position))
  508. continue;
  509. while ((i - 1) >= 0 && m_spans[i - 1].is_skippable)
  510. --i;
  511. if (i <= 0)
  512. return {};
  513. return m_spans[i - 1];
  514. }
  515. return {};
  516. }
  517. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_after(const TextPosition& position) const
  518. {
  519. size_t i = 0;
  520. // Find the first span containing the cursor
  521. for (; i < m_spans.size(); ++i) {
  522. if (m_spans[i].range.contains(position))
  523. break;
  524. }
  525. // Find the first span *after* the cursor
  526. // TODO: For a large number of spans, binary search would be faster.
  527. for (; i < m_spans.size(); ++i) {
  528. if (!m_spans[i].range.contains(position))
  529. break;
  530. }
  531. // Skip skippable spans
  532. for (; i < m_spans.size(); ++i) {
  533. if (!m_spans[i].is_skippable)
  534. break;
  535. }
  536. if (i < m_spans.size())
  537. return m_spans[i];
  538. return {};
  539. }
  540. TextPosition TextDocument::first_word_break_before(const TextPosition& position, bool start_at_column_before) const
  541. {
  542. if (position.column() == 0) {
  543. if (position.line() == 0) {
  544. return TextPosition(0, 0);
  545. }
  546. auto previous_line = this->line(position.line() - 1);
  547. return TextPosition(position.line() - 1, previous_line.length());
  548. }
  549. auto target = position;
  550. auto line = this->line(target.line());
  551. auto modifier = start_at_column_before ? 1 : 0;
  552. if (target.column() == line.length())
  553. modifier = 1;
  554. while (target.column() > 0 && is_ascii_blank(line.code_points()[target.column() - modifier]))
  555. target.set_column(target.column() - 1);
  556. auto is_start_alphanumeric = is_ascii_alphanumeric(line.code_points()[target.column() - modifier]);
  557. while (target.column() > 0) {
  558. auto prev_code_point = line.code_points()[target.column() - 1];
  559. if ((is_start_alphanumeric && !is_ascii_alphanumeric(prev_code_point)) || (!is_start_alphanumeric && is_ascii_alphanumeric(prev_code_point)))
  560. break;
  561. target.set_column(target.column() - 1);
  562. }
  563. return target;
  564. }
  565. TextPosition TextDocument::first_word_break_after(const TextPosition& position) const
  566. {
  567. auto target = position;
  568. auto line = this->line(target.line());
  569. if (position.column() >= line.length()) {
  570. if (position.line() >= this->line_count() - 1) {
  571. return position;
  572. }
  573. return TextPosition(position.line() + 1, 0);
  574. }
  575. while (target.column() < line.length() && is_ascii_space(line.code_points()[target.column()]))
  576. target.set_column(target.column() + 1);
  577. auto is_start_alphanumeric = is_ascii_alphanumeric(line.code_points()[target.column()]);
  578. while (target.column() < line.length()) {
  579. auto next_code_point = line.code_points()[target.column()];
  580. if ((is_start_alphanumeric && !is_ascii_alphanumeric(next_code_point)) || (!is_start_alphanumeric && is_ascii_alphanumeric(next_code_point)))
  581. break;
  582. target.set_column(target.column() + 1);
  583. }
  584. return target;
  585. }
  586. TextPosition TextDocument::first_word_before(const TextPosition& position, bool start_at_column_before) const
  587. {
  588. if (position.column() == 0) {
  589. if (position.line() == 0) {
  590. return TextPosition(0, 0);
  591. }
  592. auto previous_line = this->line(position.line() - 1);
  593. return TextPosition(position.line() - 1, previous_line.length());
  594. }
  595. auto target = position;
  596. auto line = this->line(target.line());
  597. if (target.column() == line.length())
  598. start_at_column_before = 1;
  599. auto nonblank_passed = !is_ascii_blank(line.code_points()[target.column() - start_at_column_before]);
  600. while (target.column() > 0) {
  601. auto prev_code_point = line.code_points()[target.column() - 1];
  602. nonblank_passed |= !is_ascii_blank(prev_code_point);
  603. if (nonblank_passed && is_ascii_blank(prev_code_point)) {
  604. break;
  605. } else if (is_ascii_punctuation(prev_code_point)) {
  606. target.set_column(target.column() - 1);
  607. break;
  608. }
  609. target.set_column(target.column() - 1);
  610. }
  611. return target;
  612. }
  613. void TextDocument::undo()
  614. {
  615. if (!can_undo())
  616. return;
  617. m_undo_stack.undo();
  618. notify_did_change();
  619. }
  620. void TextDocument::redo()
  621. {
  622. if (!can_redo())
  623. return;
  624. m_undo_stack.redo();
  625. notify_did_change();
  626. }
  627. void TextDocument::add_to_undo_stack(NonnullOwnPtr<TextDocumentUndoCommand> undo_command)
  628. {
  629. m_undo_stack.push(move(undo_command));
  630. }
  631. TextDocumentUndoCommand::TextDocumentUndoCommand(TextDocument& document)
  632. : m_document(document)
  633. {
  634. }
  635. InsertTextCommand::InsertTextCommand(TextDocument& document, const String& text, const TextPosition& position)
  636. : TextDocumentUndoCommand(document)
  637. , m_text(text)
  638. , m_range({ position, position })
  639. {
  640. }
  641. String InsertTextCommand::action_text() const
  642. {
  643. return "Insert Text";
  644. }
  645. bool InsertTextCommand::merge_with(GUI::Command const& other)
  646. {
  647. if (!is<InsertTextCommand>(other))
  648. return false;
  649. auto& typed_other = static_cast<InsertTextCommand const&>(other);
  650. if (m_range.end() != typed_other.m_range.start())
  651. return false;
  652. if (m_range.start().line() != m_range.end().line())
  653. return false;
  654. StringBuilder builder(m_text.length() + typed_other.m_text.length());
  655. builder.append(m_text);
  656. builder.append(typed_other.m_text);
  657. m_text = builder.to_string();
  658. m_range.set_end(typed_other.m_range.end());
  659. return true;
  660. }
  661. void InsertTextCommand::perform_formatting(const TextDocument::Client& client)
  662. {
  663. const size_t tab_width = client.soft_tab_width();
  664. const auto& dest_line = m_document.line(m_range.start().line());
  665. const bool should_auto_indent = client.is_automatic_indentation_enabled();
  666. StringBuilder builder;
  667. size_t column = m_range.start().column();
  668. size_t line_indentation = dest_line.leading_spaces();
  669. bool at_start_of_line = line_indentation == column;
  670. for (auto input_char : m_text) {
  671. if (input_char == '\n') {
  672. size_t spaces_at_end = 0;
  673. if (column < line_indentation)
  674. spaces_at_end = line_indentation - column;
  675. line_indentation -= spaces_at_end;
  676. builder.append('\n');
  677. column = 0;
  678. if (should_auto_indent) {
  679. for (; column < line_indentation; ++column) {
  680. builder.append(' ');
  681. }
  682. }
  683. at_start_of_line = true;
  684. } else if (input_char == '\t') {
  685. size_t next_soft_tab_stop = ((column + tab_width) / tab_width) * tab_width;
  686. size_t spaces_to_insert = next_soft_tab_stop - column;
  687. for (size_t i = 0; i < spaces_to_insert; ++i) {
  688. builder.append(' ');
  689. }
  690. column = next_soft_tab_stop;
  691. if (at_start_of_line) {
  692. line_indentation = column;
  693. }
  694. } else {
  695. if (input_char == ' ') {
  696. if (at_start_of_line) {
  697. ++line_indentation;
  698. }
  699. } else {
  700. at_start_of_line = false;
  701. }
  702. builder.append(input_char);
  703. ++column;
  704. }
  705. }
  706. m_text = builder.build();
  707. }
  708. void InsertTextCommand::redo()
  709. {
  710. auto new_cursor = m_document.insert_at(m_range.start(), m_text, m_client);
  711. // NOTE: We don't know where the range ends until after doing redo().
  712. // This is okay since we always do redo() after adding this to the undo stack.
  713. m_range.set_end(new_cursor);
  714. m_document.set_all_cursors(new_cursor);
  715. }
  716. void InsertTextCommand::undo()
  717. {
  718. m_document.remove(m_range);
  719. m_document.set_all_cursors(m_range.start());
  720. }
  721. RemoveTextCommand::RemoveTextCommand(TextDocument& document, const String& text, const TextRange& range)
  722. : TextDocumentUndoCommand(document)
  723. , m_text(text)
  724. , m_range(range)
  725. {
  726. }
  727. String RemoveTextCommand::action_text() const
  728. {
  729. return "Remove Text";
  730. }
  731. bool RemoveTextCommand::merge_with(GUI::Command const& other)
  732. {
  733. if (!is<RemoveTextCommand>(other))
  734. return false;
  735. auto& typed_other = static_cast<RemoveTextCommand const&>(other);
  736. if (m_range.start() != typed_other.m_range.end())
  737. return false;
  738. if (m_range.start().line() != m_range.end().line())
  739. return false;
  740. // Merge backspaces
  741. StringBuilder builder(m_text.length() + typed_other.m_text.length());
  742. builder.append(typed_other.m_text);
  743. builder.append(m_text);
  744. m_text = builder.to_string();
  745. m_range.set_start(typed_other.m_range.start());
  746. return true;
  747. }
  748. void RemoveTextCommand::redo()
  749. {
  750. m_document.remove(m_range);
  751. m_document.set_all_cursors(m_range.start());
  752. }
  753. void RemoveTextCommand::undo()
  754. {
  755. auto new_cursor = m_document.insert_at(m_range.start(), m_text);
  756. m_document.set_all_cursors(new_cursor);
  757. }
  758. TextPosition TextDocument::insert_at(const TextPosition& position, StringView text, const Client* client)
  759. {
  760. TextPosition cursor = position;
  761. Utf8View utf8_view(text);
  762. for (auto code_point : utf8_view)
  763. cursor = insert_at(cursor, code_point, client);
  764. return cursor;
  765. }
  766. TextPosition TextDocument::insert_at(const TextPosition& position, u32 code_point, const Client*)
  767. {
  768. if (code_point == '\n') {
  769. auto new_line = make<TextDocumentLine>(*this);
  770. new_line->append(*this, line(position.line()).code_points() + position.column(), line(position.line()).length() - position.column());
  771. line(position.line()).truncate(*this, position.column());
  772. insert_line(position.line() + 1, move(new_line));
  773. notify_did_change();
  774. return { position.line() + 1, 0 };
  775. } else {
  776. line(position.line()).insert(*this, position.column(), code_point);
  777. notify_did_change();
  778. return { position.line(), position.column() + 1 };
  779. }
  780. }
  781. void TextDocument::remove(const TextRange& unnormalized_range)
  782. {
  783. if (!unnormalized_range.is_valid())
  784. return;
  785. auto range = unnormalized_range.normalized();
  786. // First delete all the lines in between the first and last one.
  787. for (size_t i = range.start().line() + 1; i < range.end().line();) {
  788. remove_line(i);
  789. range.end().set_line(range.end().line() - 1);
  790. }
  791. if (range.start().line() == range.end().line()) {
  792. // Delete within same line.
  793. auto& line = this->line(range.start().line());
  794. if (line.length() == 0)
  795. return;
  796. bool whole_line_is_selected = range.start().column() == 0 && range.end().column() == line.length();
  797. if (whole_line_is_selected) {
  798. line.clear(*this);
  799. } else {
  800. line.remove_range(*this, range.start().column(), range.end().column() - range.start().column());
  801. }
  802. } else {
  803. // Delete across a newline, merging lines.
  804. VERIFY(range.start().line() == range.end().line() - 1);
  805. auto& first_line = line(range.start().line());
  806. auto& second_line = line(range.end().line());
  807. Vector<u32> code_points;
  808. code_points.append(first_line.code_points(), range.start().column());
  809. if (!second_line.is_empty())
  810. code_points.append(second_line.code_points() + range.end().column(), second_line.length() - range.end().column());
  811. first_line.set_text(*this, move(code_points));
  812. remove_line(range.end().line());
  813. }
  814. if (lines().is_empty()) {
  815. append_line(make<TextDocumentLine>(*this));
  816. }
  817. notify_did_change();
  818. }
  819. bool TextDocument::is_empty() const
  820. {
  821. return line_count() == 1 && line(0).is_empty();
  822. }
  823. TextRange TextDocument::range_for_entire_line(size_t line_index) const
  824. {
  825. if (line_index >= line_count())
  826. return {};
  827. return { { line_index, 0 }, { line_index, line(line_index).length() } };
  828. }
  829. const TextDocumentSpan* TextDocument::span_at(const TextPosition& position) const
  830. {
  831. for (auto& span : m_spans) {
  832. if (span.range.contains(position))
  833. return &span;
  834. }
  835. return nullptr;
  836. }
  837. void TextDocument::set_unmodified()
  838. {
  839. m_undo_stack.set_current_unmodified();
  840. }
  841. }