TextDocument.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Badge.h>
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <AK/StringBuilder.h>
  10. #include <AK/Utf8View.h>
  11. #include <LibCore/Timer.h>
  12. #include <LibGUI/TextDocument.h>
  13. #include <LibRegex/Regex.h>
  14. namespace GUI {
  15. NonnullRefPtr<TextDocument> TextDocument::create(Client* client)
  16. {
  17. return adopt_ref(*new TextDocument(client));
  18. }
  19. TextDocument::TextDocument(Client* client)
  20. {
  21. if (client)
  22. m_clients.set(client);
  23. append_line(make<TextDocumentLine>(*this));
  24. set_unmodified();
  25. m_undo_stack.on_state_change = [this] {
  26. if (m_client_notifications_enabled) {
  27. for (auto* client : m_clients)
  28. client->document_did_update_undo_stack();
  29. }
  30. };
  31. }
  32. TextDocument::~TextDocument()
  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, const Vector<u32> 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, const u32* 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. TextDocument::Client::~Client()
  247. {
  248. }
  249. void TextDocument::register_client(Client& client)
  250. {
  251. m_clients.set(&client);
  252. }
  253. void TextDocument::unregister_client(Client& client)
  254. {
  255. m_clients.remove(&client);
  256. }
  257. void TextDocument::update_views(Badge<TextDocumentLine>)
  258. {
  259. notify_did_change();
  260. }
  261. void TextDocument::notify_did_change()
  262. {
  263. if (m_client_notifications_enabled) {
  264. for (auto* client : m_clients)
  265. client->document_did_change();
  266. }
  267. m_regex_needs_update = true;
  268. }
  269. void TextDocument::set_all_cursors(const TextPosition& position)
  270. {
  271. if (m_client_notifications_enabled) {
  272. for (auto* client : m_clients)
  273. client->document_did_set_cursor(position);
  274. }
  275. }
  276. String TextDocument::text() const
  277. {
  278. StringBuilder builder;
  279. for (size_t i = 0; i < line_count(); ++i) {
  280. auto& line = this->line(i);
  281. builder.append(line.view());
  282. if (i != line_count() - 1)
  283. builder.append('\n');
  284. }
  285. return builder.to_string();
  286. }
  287. String TextDocument::text_in_range(const TextRange& a_range) const
  288. {
  289. auto range = a_range.normalized();
  290. if (is_empty() || line_count() < range.end().line() - range.start().line())
  291. return String("");
  292. StringBuilder builder;
  293. for (size_t i = range.start().line(); i <= range.end().line(); ++i) {
  294. auto& line = this->line(i);
  295. size_t selection_start_column_on_line = range.start().line() == i ? range.start().column() : 0;
  296. size_t selection_end_column_on_line = range.end().line() == i ? range.end().column() : line.length();
  297. if (!line.is_empty()) {
  298. builder.append(
  299. Utf32View(
  300. line.code_points() + selection_start_column_on_line,
  301. selection_end_column_on_line - selection_start_column_on_line));
  302. }
  303. if (i != range.end().line())
  304. builder.append('\n');
  305. }
  306. return builder.to_string();
  307. }
  308. u32 TextDocument::code_point_at(const TextPosition& position) const
  309. {
  310. VERIFY(position.line() < line_count());
  311. auto& line = this->line(position.line());
  312. if (position.column() == line.length())
  313. return '\n';
  314. return line.code_points()[position.column()];
  315. }
  316. TextPosition TextDocument::next_position_after(const TextPosition& position, SearchShouldWrap should_wrap) const
  317. {
  318. auto& line = this->line(position.line());
  319. if (position.column() == line.length()) {
  320. if (position.line() == line_count() - 1) {
  321. if (should_wrap == SearchShouldWrap::Yes)
  322. return { 0, 0 };
  323. return {};
  324. }
  325. return { position.line() + 1, 0 };
  326. }
  327. return { position.line(), position.column() + 1 };
  328. }
  329. TextPosition TextDocument::previous_position_before(const TextPosition& position, SearchShouldWrap should_wrap) const
  330. {
  331. if (position.column() == 0) {
  332. if (position.line() == 0) {
  333. if (should_wrap == SearchShouldWrap::Yes) {
  334. auto& last_line = this->line(line_count() - 1);
  335. return { line_count() - 1, last_line.length() };
  336. }
  337. return {};
  338. }
  339. auto& prev_line = this->line(position.line() - 1);
  340. return { position.line() - 1, prev_line.length() };
  341. }
  342. return { position.line(), position.column() - 1 };
  343. }
  344. void TextDocument::update_regex_matches(StringView needle)
  345. {
  346. if (m_regex_needs_update || needle != m_regex_needle) {
  347. Regex<PosixExtended> re(needle);
  348. Vector<RegexStringView> views;
  349. for (size_t line = 0; line < m_lines.size(); ++line) {
  350. views.append(m_lines.at(line).view());
  351. }
  352. re.search(views, m_regex_result);
  353. m_regex_needs_update = false;
  354. m_regex_needle = String { needle };
  355. m_regex_result_match_index = -1;
  356. m_regex_result_match_capture_group_index = -1;
  357. }
  358. }
  359. TextRange TextDocument::find_next(StringView needle, const TextPosition& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case)
  360. {
  361. if (needle.is_empty())
  362. return {};
  363. if (regmatch) {
  364. if (!m_regex_result.matches.size())
  365. return {};
  366. regex::Match match;
  367. bool use_whole_match { false };
  368. auto next_match = [&] {
  369. m_regex_result_match_capture_group_index = 0;
  370. if (m_regex_result_match_index == m_regex_result.matches.size() - 1) {
  371. if (should_wrap == SearchShouldWrap::Yes)
  372. m_regex_result_match_index = 0;
  373. else
  374. ++m_regex_result_match_index;
  375. } else
  376. ++m_regex_result_match_index;
  377. };
  378. if (m_regex_result.n_capture_groups) {
  379. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  380. next_match();
  381. else {
  382. // check if last capture group has been reached
  383. if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) {
  384. next_match();
  385. } else {
  386. // get to the next capture group item
  387. ++m_regex_result_match_capture_group_index;
  388. }
  389. }
  390. // use whole match, if there is no capture group for current index
  391. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  392. use_whole_match = true;
  393. else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  394. next_match();
  395. } else {
  396. next_match();
  397. }
  398. if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  399. match = m_regex_result.matches.at(m_regex_result_match_index);
  400. else
  401. match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index);
  402. return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } };
  403. }
  404. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  405. TextPosition original_position = position;
  406. TextPosition start_of_potential_match;
  407. size_t needle_index = 0;
  408. do {
  409. auto ch = code_point_at(position);
  410. // FIXME: This is not the right way to use a Unicode needle!
  411. if (match_case ? ch == (u32)needle[needle_index] : tolower(ch) == tolower((u32)needle[needle_index])) {
  412. if (needle_index == 0)
  413. start_of_potential_match = position;
  414. ++needle_index;
  415. if (needle_index >= needle.length())
  416. return { start_of_potential_match, next_position_after(position, should_wrap) };
  417. } else {
  418. if (needle_index > 0)
  419. position = start_of_potential_match;
  420. needle_index = 0;
  421. }
  422. position = next_position_after(position, should_wrap);
  423. } while (position.is_valid() && position != original_position);
  424. return {};
  425. }
  426. TextRange TextDocument::find_previous(StringView needle, const TextPosition& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case)
  427. {
  428. if (needle.is_empty())
  429. return {};
  430. if (regmatch) {
  431. if (!m_regex_result.matches.size())
  432. return {};
  433. regex::Match match;
  434. bool use_whole_match { false };
  435. auto next_match = [&] {
  436. if (m_regex_result_match_index == 0) {
  437. if (should_wrap == SearchShouldWrap::Yes)
  438. m_regex_result_match_index = m_regex_result.matches.size() - 1;
  439. else
  440. --m_regex_result_match_index;
  441. } else
  442. --m_regex_result_match_index;
  443. m_regex_result_match_capture_group_index = m_regex_result.capture_group_matches.at(m_regex_result_match_index).size() - 1;
  444. };
  445. if (m_regex_result.n_capture_groups) {
  446. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  447. next_match();
  448. else {
  449. // check if last capture group has been reached
  450. if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) {
  451. next_match();
  452. } else {
  453. // get to the next capture group item
  454. --m_regex_result_match_capture_group_index;
  455. }
  456. }
  457. // use whole match, if there is no capture group for current index
  458. if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size())
  459. use_whole_match = true;
  460. else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  461. next_match();
  462. } else {
  463. next_match();
  464. }
  465. if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size())
  466. match = m_regex_result.matches.at(m_regex_result_match_index);
  467. else
  468. match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index);
  469. return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } };
  470. }
  471. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  472. position = previous_position_before(position, should_wrap);
  473. if (position.line() >= line_count())
  474. return {};
  475. TextPosition original_position = position;
  476. TextPosition end_of_potential_match;
  477. size_t needle_index = needle.length() - 1;
  478. do {
  479. auto ch = code_point_at(position);
  480. // FIXME: This is not the right way to use a Unicode needle!
  481. if (match_case ? ch == (u32)needle[needle_index] : tolower(ch) == tolower((u32)needle[needle_index])) {
  482. if (needle_index == needle.length() - 1)
  483. end_of_potential_match = position;
  484. if (needle_index == 0)
  485. return { position, next_position_after(end_of_potential_match, should_wrap) };
  486. --needle_index;
  487. } else {
  488. if (needle_index < needle.length() - 1)
  489. position = end_of_potential_match;
  490. needle_index = needle.length() - 1;
  491. }
  492. position = previous_position_before(position, should_wrap);
  493. } while (position.is_valid() && position != original_position);
  494. return {};
  495. }
  496. Vector<TextRange> TextDocument::find_all(StringView needle, bool regmatch)
  497. {
  498. Vector<TextRange> ranges;
  499. TextPosition position;
  500. for (;;) {
  501. auto range = find_next(needle, position, SearchShouldWrap::No, regmatch);
  502. if (!range.is_valid())
  503. break;
  504. ranges.append(range);
  505. position = range.end();
  506. }
  507. return ranges;
  508. }
  509. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_before(const TextPosition& position) const
  510. {
  511. for (int i = m_spans.size() - 1; i >= 0; --i) {
  512. if (!m_spans[i].range.contains(position))
  513. continue;
  514. while ((i - 1) >= 0 && m_spans[i - 1].is_skippable)
  515. --i;
  516. if (i <= 0)
  517. return {};
  518. return m_spans[i - 1];
  519. }
  520. return {};
  521. }
  522. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_after(const TextPosition& position) const
  523. {
  524. size_t i = 0;
  525. // Find the first span containing the cursor
  526. for (; i < m_spans.size(); ++i) {
  527. if (m_spans[i].range.contains(position))
  528. break;
  529. }
  530. // Find the first span *after* the cursor
  531. // TODO: For a large number of spans, binary search would be faster.
  532. for (; i < m_spans.size(); ++i) {
  533. if (!m_spans[i].range.contains(position))
  534. break;
  535. }
  536. // Skip skippable spans
  537. for (; i < m_spans.size(); ++i) {
  538. if (m_spans[i].is_skippable)
  539. break;
  540. }
  541. if (i < m_spans.size())
  542. return m_spans[i + 1];
  543. return {};
  544. }
  545. TextPosition TextDocument::first_word_break_before(const TextPosition& position, bool start_at_column_before) const
  546. {
  547. if (position.column() == 0) {
  548. if (position.line() == 0) {
  549. return TextPosition(0, 0);
  550. }
  551. auto previous_line = this->line(position.line() - 1);
  552. return TextPosition(position.line() - 1, previous_line.length());
  553. }
  554. auto target = position;
  555. auto line = this->line(target.line());
  556. auto modifier = start_at_column_before ? 1 : 0;
  557. if (target.column() == line.length())
  558. modifier = 1;
  559. auto is_start_alphanumeric = is_ascii_alphanumeric(line.code_points()[target.column() - modifier]);
  560. while (target.column() > 0) {
  561. auto prev_code_point = line.code_points()[target.column() - 1];
  562. if ((is_start_alphanumeric && !is_ascii_alphanumeric(prev_code_point)) || (!is_start_alphanumeric && is_ascii_alphanumeric(prev_code_point)))
  563. break;
  564. target.set_column(target.column() - 1);
  565. }
  566. return target;
  567. }
  568. TextPosition TextDocument::first_word_break_after(const TextPosition& position) const
  569. {
  570. auto target = position;
  571. auto line = this->line(target.line());
  572. if (position.column() >= line.length()) {
  573. if (position.line() >= this->line_count() - 1) {
  574. return position;
  575. }
  576. return TextPosition(position.line() + 1, 0);
  577. }
  578. auto is_start_alphanumeric = is_ascii_alphanumeric(line.code_points()[target.column()]);
  579. while (target.column() < line.length()) {
  580. auto next_code_point = line.code_points()[target.column()];
  581. if ((is_start_alphanumeric && !is_ascii_alphanumeric(next_code_point)) || (!is_start_alphanumeric && is_ascii_alphanumeric(next_code_point)))
  582. break;
  583. target.set_column(target.column() + 1);
  584. }
  585. return target;
  586. }
  587. TextPosition TextDocument::first_word_before(const TextPosition& position, bool start_at_column_before) const
  588. {
  589. if (position.column() == 0) {
  590. if (position.line() == 0) {
  591. return TextPosition(0, 0);
  592. }
  593. auto previous_line = this->line(position.line() - 1);
  594. return TextPosition(position.line() - 1, previous_line.length());
  595. }
  596. auto target = position;
  597. auto line = this->line(target.line());
  598. if (target.column() == line.length())
  599. start_at_column_before = 1;
  600. auto nonblank_passed = !is_ascii_blank(line.code_points()[target.column() - start_at_column_before]);
  601. while (target.column() > 0) {
  602. auto prev_code_point = line.code_points()[target.column() - 1];
  603. nonblank_passed |= !is_ascii_blank(prev_code_point);
  604. if (nonblank_passed && is_ascii_blank(prev_code_point)) {
  605. break;
  606. } else if (is_ascii_punctuation(prev_code_point)) {
  607. target.set_column(target.column() - 1);
  608. break;
  609. }
  610. target.set_column(target.column() - 1);
  611. }
  612. return target;
  613. }
  614. void TextDocument::undo()
  615. {
  616. if (!can_undo())
  617. return;
  618. m_undo_stack.undo();
  619. notify_did_change();
  620. }
  621. void TextDocument::redo()
  622. {
  623. if (!can_redo())
  624. return;
  625. m_undo_stack.redo();
  626. notify_did_change();
  627. }
  628. void TextDocument::add_to_undo_stack(NonnullOwnPtr<TextDocumentUndoCommand> undo_command)
  629. {
  630. m_undo_stack.push(move(undo_command));
  631. }
  632. TextDocumentUndoCommand::TextDocumentUndoCommand(TextDocument& document)
  633. : m_document(document)
  634. {
  635. }
  636. TextDocumentUndoCommand::~TextDocumentUndoCommand()
  637. {
  638. }
  639. InsertTextCommand::InsertTextCommand(TextDocument& document, const String& text, const TextPosition& position)
  640. : TextDocumentUndoCommand(document)
  641. , m_text(text)
  642. , m_range({ position, position })
  643. {
  644. }
  645. String InsertTextCommand::action_text() const
  646. {
  647. return "Insert Text";
  648. }
  649. bool InsertTextCommand::merge_with(GUI::Command const& other)
  650. {
  651. if (!is<InsertTextCommand>(other))
  652. return false;
  653. auto& typed_other = static_cast<InsertTextCommand const&>(other);
  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. return true;
  664. }
  665. void InsertTextCommand::perform_formatting(const TextDocument::Client& client)
  666. {
  667. const size_t tab_width = client.soft_tab_width();
  668. const auto& dest_line = m_document.line(m_range.start().line());
  669. const bool should_auto_indent = client.is_automatic_indentation_enabled();
  670. StringBuilder builder;
  671. size_t column = m_range.start().column();
  672. size_t line_indentation = dest_line.leading_spaces();
  673. bool at_start_of_line = line_indentation == column;
  674. for (auto input_char : m_text) {
  675. if (input_char == '\n') {
  676. size_t spaces_at_end = 0;
  677. if (column < line_indentation)
  678. spaces_at_end = line_indentation - column;
  679. line_indentation -= spaces_at_end;
  680. builder.append('\n');
  681. column = 0;
  682. if (should_auto_indent) {
  683. for (; column < line_indentation; ++column) {
  684. builder.append(' ');
  685. }
  686. }
  687. at_start_of_line = true;
  688. } else if (input_char == '\t') {
  689. size_t next_soft_tab_stop = ((column + tab_width) / tab_width) * tab_width;
  690. size_t spaces_to_insert = next_soft_tab_stop - column;
  691. for (size_t i = 0; i < spaces_to_insert; ++i) {
  692. builder.append(' ');
  693. }
  694. column = next_soft_tab_stop;
  695. if (at_start_of_line) {
  696. line_indentation = column;
  697. }
  698. } else {
  699. if (input_char == ' ') {
  700. if (at_start_of_line) {
  701. ++line_indentation;
  702. }
  703. } else {
  704. at_start_of_line = false;
  705. }
  706. builder.append(input_char);
  707. ++column;
  708. }
  709. }
  710. m_text = builder.build();
  711. }
  712. void InsertTextCommand::redo()
  713. {
  714. auto new_cursor = m_document.insert_at(m_range.start(), m_text, m_client);
  715. // NOTE: We don't know where the range ends until after doing redo().
  716. // This is okay since we always do redo() after adding this to the undo stack.
  717. m_range.set_end(new_cursor);
  718. m_document.set_all_cursors(new_cursor);
  719. }
  720. void InsertTextCommand::undo()
  721. {
  722. m_document.remove(m_range);
  723. m_document.set_all_cursors(m_range.start());
  724. }
  725. RemoveTextCommand::RemoveTextCommand(TextDocument& document, const String& text, const TextRange& range)
  726. : TextDocumentUndoCommand(document)
  727. , m_text(text)
  728. , m_range(range)
  729. {
  730. }
  731. String RemoveTextCommand::action_text() const
  732. {
  733. return "Remove Text";
  734. }
  735. bool RemoveTextCommand::merge_with(GUI::Command const& other)
  736. {
  737. if (!is<RemoveTextCommand>(other))
  738. return false;
  739. auto& typed_other = static_cast<RemoveTextCommand const&>(other);
  740. if (m_range.start() != typed_other.m_range.end())
  741. return false;
  742. if (m_range.start().line() != m_range.end().line())
  743. return false;
  744. // Merge backspaces
  745. StringBuilder builder(m_text.length() + typed_other.m_text.length());
  746. builder.append(typed_other.m_text);
  747. builder.append(m_text);
  748. m_text = builder.to_string();
  749. m_range.set_start(typed_other.m_range.start());
  750. return true;
  751. }
  752. void RemoveTextCommand::redo()
  753. {
  754. m_document.remove(m_range);
  755. m_document.set_all_cursors(m_range.start());
  756. }
  757. void RemoveTextCommand::undo()
  758. {
  759. auto new_cursor = m_document.insert_at(m_range.start(), m_text);
  760. m_document.set_all_cursors(new_cursor);
  761. }
  762. TextPosition TextDocument::insert_at(const TextPosition& position, StringView text, const Client* client)
  763. {
  764. TextPosition cursor = position;
  765. Utf8View utf8_view(text);
  766. for (auto code_point : utf8_view)
  767. cursor = insert_at(cursor, code_point, client);
  768. return cursor;
  769. }
  770. TextPosition TextDocument::insert_at(const TextPosition& position, u32 code_point, const Client*)
  771. {
  772. if (code_point == '\n') {
  773. auto new_line = make<TextDocumentLine>(*this);
  774. new_line->append(*this, line(position.line()).code_points() + position.column(), line(position.line()).length() - position.column());
  775. line(position.line()).truncate(*this, position.column());
  776. insert_line(position.line() + 1, move(new_line));
  777. notify_did_change();
  778. return { position.line() + 1, 0 };
  779. } else {
  780. line(position.line()).insert(*this, position.column(), code_point);
  781. notify_did_change();
  782. return { position.line(), position.column() + 1 };
  783. }
  784. }
  785. void TextDocument::remove(const TextRange& unnormalized_range)
  786. {
  787. if (!unnormalized_range.is_valid())
  788. return;
  789. auto range = unnormalized_range.normalized();
  790. // First delete all the lines in between the first and last one.
  791. for (size_t i = range.start().line() + 1; i < range.end().line();) {
  792. remove_line(i);
  793. range.end().set_line(range.end().line() - 1);
  794. }
  795. if (range.start().line() == range.end().line()) {
  796. // Delete within same line.
  797. auto& line = this->line(range.start().line());
  798. if (line.length() == 0)
  799. return;
  800. bool whole_line_is_selected = range.start().column() == 0 && range.end().column() == line.length();
  801. if (whole_line_is_selected) {
  802. line.clear(*this);
  803. } else {
  804. line.remove_range(*this, range.start().column(), range.end().column() - range.start().column());
  805. }
  806. } else {
  807. // Delete across a newline, merging lines.
  808. VERIFY(range.start().line() == range.end().line() - 1);
  809. auto& first_line = line(range.start().line());
  810. auto& second_line = line(range.end().line());
  811. Vector<u32> code_points;
  812. code_points.append(first_line.code_points(), range.start().column());
  813. if (!second_line.is_empty())
  814. code_points.append(second_line.code_points() + range.end().column(), second_line.length() - range.end().column());
  815. first_line.set_text(*this, move(code_points));
  816. remove_line(range.end().line());
  817. }
  818. if (lines().is_empty()) {
  819. append_line(make<TextDocumentLine>(*this));
  820. }
  821. notify_did_change();
  822. }
  823. bool TextDocument::is_empty() const
  824. {
  825. return line_count() == 1 && line(0).is_empty();
  826. }
  827. TextRange TextDocument::range_for_entire_line(size_t line_index) const
  828. {
  829. if (line_index >= line_count())
  830. return {};
  831. return { { line_index, 0 }, { line_index, line(line_index).length() } };
  832. }
  833. const TextDocumentSpan* TextDocument::span_at(const TextPosition& position) const
  834. {
  835. for (auto& span : m_spans) {
  836. if (span.range.contains(position))
  837. return &span;
  838. }
  839. return nullptr;
  840. }
  841. void TextDocument::set_unmodified()
  842. {
  843. m_undo_stack.set_current_unmodified();
  844. }
  845. }