TextDocument.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Badge.h>
  27. #include <AK/StringBuilder.h>
  28. #include <AK/Utf8View.h>
  29. #include <LibCore/Timer.h>
  30. #include <LibGUI/TextDocument.h>
  31. #include <LibGUI/TextEditor.h>
  32. #include <ctype.h>
  33. namespace GUI {
  34. NonnullRefPtr<TextDocument> TextDocument::create(Client* client)
  35. {
  36. return adopt(*new TextDocument(client));
  37. }
  38. TextDocument::TextDocument(Client* client)
  39. {
  40. if (client)
  41. m_clients.set(client);
  42. append_line(make<TextDocumentLine>(*this));
  43. // TODO: Instead of a repating timer, this we should call a delayed 2 sec timer when the user types.
  44. m_undo_timer = Core::Timer::construct(
  45. 2000, [this] {
  46. update_undo_timer();
  47. });
  48. }
  49. TextDocument::~TextDocument()
  50. {
  51. }
  52. void TextDocument::set_text(const StringView& text)
  53. {
  54. m_client_notifications_enabled = false;
  55. m_spans.clear();
  56. remove_all_lines();
  57. size_t start_of_current_line = 0;
  58. auto add_line = [&](size_t current_position) {
  59. size_t line_length = current_position - start_of_current_line;
  60. auto line = make<TextDocumentLine>(*this);
  61. if (line_length)
  62. line->set_text(*this, text.substring_view(start_of_current_line, current_position - start_of_current_line));
  63. append_line(move(line));
  64. start_of_current_line = current_position + 1;
  65. };
  66. size_t i = 0;
  67. for (i = 0; i < text.length(); ++i) {
  68. if (text[i] == '\n')
  69. add_line(i);
  70. }
  71. add_line(i);
  72. m_client_notifications_enabled = true;
  73. for (auto* client : m_clients)
  74. client->document_did_set_text();
  75. }
  76. size_t TextDocumentLine::first_non_whitespace_column() const
  77. {
  78. for (size_t i = 0; i < length(); ++i) {
  79. auto codepoint = codepoints()[i];
  80. if (!isspace(codepoint))
  81. return i;
  82. }
  83. return length();
  84. }
  85. String TextDocumentLine::to_utf8() const
  86. {
  87. StringBuilder builder;
  88. builder.append(view());
  89. return builder.to_string();
  90. }
  91. TextDocumentLine::TextDocumentLine(TextDocument& document)
  92. {
  93. clear(document);
  94. }
  95. TextDocumentLine::TextDocumentLine(TextDocument& document, const StringView& text)
  96. {
  97. set_text(document, text);
  98. }
  99. void TextDocumentLine::clear(TextDocument& document)
  100. {
  101. m_text.clear();
  102. document.update_views({});
  103. }
  104. void TextDocumentLine::set_text(TextDocument& document, const Vector<u32> text)
  105. {
  106. m_text = move(text);
  107. document.update_views({});
  108. }
  109. void TextDocumentLine::set_text(TextDocument& document, const StringView& text)
  110. {
  111. if (text.is_empty()) {
  112. clear(document);
  113. return;
  114. }
  115. m_text.clear();
  116. Utf8View utf8_view(text);
  117. for (auto codepoint : utf8_view)
  118. m_text.append(codepoint);
  119. document.update_views({});
  120. }
  121. void TextDocumentLine::append(TextDocument& document, const u32* codepoints, size_t length)
  122. {
  123. if (length == 0)
  124. return;
  125. m_text.append(codepoints, length);
  126. document.update_views({});
  127. }
  128. void TextDocumentLine::append(TextDocument& document, u32 codepoint)
  129. {
  130. insert(document, length(), codepoint);
  131. }
  132. void TextDocumentLine::prepend(TextDocument& document, u32 codepoint)
  133. {
  134. insert(document, 0, codepoint);
  135. }
  136. void TextDocumentLine::insert(TextDocument& document, size_t index, u32 codepoint)
  137. {
  138. if (index == length()) {
  139. m_text.append(codepoint);
  140. } else {
  141. m_text.insert(index, codepoint);
  142. }
  143. document.update_views({});
  144. }
  145. void TextDocumentLine::remove(TextDocument& document, size_t index)
  146. {
  147. if (index == length()) {
  148. m_text.take_last();
  149. } else {
  150. m_text.remove(index);
  151. }
  152. document.update_views({});
  153. }
  154. void TextDocumentLine::remove_range(TextDocument& document, size_t start, size_t length)
  155. {
  156. ASSERT(length <= m_text.size());
  157. Vector<u32> new_data;
  158. new_data.ensure_capacity(m_text.size() - length);
  159. for (size_t i = 0; i < start; ++i)
  160. new_data.append(m_text[i]);
  161. for (size_t i = (start + length); i < m_text.size(); ++i)
  162. new_data.append(m_text[i]);
  163. m_text = move(new_data);
  164. document.update_views({});
  165. }
  166. void TextDocumentLine::truncate(TextDocument& document, size_t length)
  167. {
  168. m_text.resize(length);
  169. document.update_views({});
  170. }
  171. void TextDocument::append_line(NonnullOwnPtr<TextDocumentLine> line)
  172. {
  173. lines().append(move(line));
  174. if (m_client_notifications_enabled) {
  175. for (auto* client : m_clients)
  176. client->document_did_append_line();
  177. }
  178. }
  179. void TextDocument::insert_line(size_t line_index, NonnullOwnPtr<TextDocumentLine> line)
  180. {
  181. lines().insert((int)line_index, move(line));
  182. if (m_client_notifications_enabled) {
  183. for (auto* client : m_clients)
  184. client->document_did_insert_line(line_index);
  185. }
  186. }
  187. void TextDocument::remove_line(size_t line_index)
  188. {
  189. lines().remove((int)line_index);
  190. if (m_client_notifications_enabled) {
  191. for (auto* client : m_clients)
  192. client->document_did_remove_line(line_index);
  193. }
  194. }
  195. void TextDocument::remove_all_lines()
  196. {
  197. lines().clear();
  198. if (m_client_notifications_enabled) {
  199. for (auto* client : m_clients)
  200. client->document_did_remove_all_lines();
  201. }
  202. }
  203. TextDocument::Client::~Client()
  204. {
  205. }
  206. void TextDocument::register_client(Client& client)
  207. {
  208. m_clients.set(&client);
  209. }
  210. void TextDocument::unregister_client(Client& client)
  211. {
  212. m_clients.remove(&client);
  213. }
  214. void TextDocument::update_views(Badge<TextDocumentLine>)
  215. {
  216. notify_did_change();
  217. }
  218. void TextDocument::notify_did_change()
  219. {
  220. if (m_client_notifications_enabled) {
  221. for (auto* client : m_clients)
  222. client->document_did_change();
  223. }
  224. }
  225. void TextDocument::set_all_cursors(const TextPosition& position)
  226. {
  227. if (m_client_notifications_enabled) {
  228. for (auto* client : m_clients)
  229. client->document_did_set_cursor(position);
  230. }
  231. }
  232. String TextDocument::text_in_range(const TextRange& a_range) const
  233. {
  234. auto range = a_range.normalized();
  235. StringBuilder builder;
  236. for (size_t i = range.start().line(); i <= range.end().line(); ++i) {
  237. auto& line = this->line(i);
  238. size_t selection_start_column_on_line = range.start().line() == i ? range.start().column() : 0;
  239. size_t selection_end_column_on_line = range.end().line() == i ? range.end().column() : line.length();
  240. builder.append(Utf32View(line.codepoints() + selection_start_column_on_line, selection_end_column_on_line - selection_start_column_on_line));
  241. if (i != range.end().line())
  242. builder.append('\n');
  243. }
  244. return builder.to_string();
  245. }
  246. u32 TextDocument::codepoint_at(const TextPosition& position) const
  247. {
  248. ASSERT(position.line() < line_count());
  249. auto& line = this->line(position.line());
  250. if (position.column() == line.length())
  251. return '\n';
  252. return line.codepoints()[position.column()];
  253. }
  254. TextPosition TextDocument::next_position_after(const TextPosition& position, SearchShouldWrap should_wrap) const
  255. {
  256. auto& line = this->line(position.line());
  257. if (position.column() == line.length()) {
  258. if (position.line() == line_count() - 1) {
  259. if (should_wrap == SearchShouldWrap::Yes)
  260. return { 0, 0 };
  261. return {};
  262. }
  263. return { position.line() + 1, 0 };
  264. }
  265. return { position.line(), position.column() + 1 };
  266. }
  267. TextPosition TextDocument::previous_position_before(const TextPosition& position, SearchShouldWrap should_wrap) const
  268. {
  269. if (position.column() == 0) {
  270. if (position.line() == 0) {
  271. if (should_wrap == SearchShouldWrap::Yes) {
  272. auto& last_line = this->line(line_count() - 1);
  273. return { line_count() - 1, last_line.length() };
  274. }
  275. return {};
  276. }
  277. auto& prev_line = this->line(position.line() - 1);
  278. return { position.line() - 1, prev_line.length() };
  279. }
  280. return { position.line(), position.column() - 1 };
  281. }
  282. TextRange TextDocument::find_next(const StringView& needle, const TextPosition& start, SearchShouldWrap should_wrap) const
  283. {
  284. if (needle.is_empty())
  285. return {};
  286. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  287. TextPosition original_position = position;
  288. TextPosition start_of_potential_match;
  289. size_t needle_index = 0;
  290. do {
  291. auto ch = codepoint_at(position);
  292. // FIXME: This is not the right way to use a Unicode needle!
  293. if (ch == (u32)needle[needle_index]) {
  294. if (needle_index == 0)
  295. start_of_potential_match = position;
  296. ++needle_index;
  297. if (needle_index >= needle.length())
  298. return { start_of_potential_match, next_position_after(position, should_wrap) };
  299. } else {
  300. if (needle_index > 0)
  301. position = start_of_potential_match;
  302. needle_index = 0;
  303. }
  304. position = next_position_after(position, should_wrap);
  305. } while (position.is_valid() && position != original_position);
  306. return {};
  307. }
  308. TextRange TextDocument::find_previous(const StringView& needle, const TextPosition& start, SearchShouldWrap should_wrap) const
  309. {
  310. if (needle.is_empty())
  311. return {};
  312. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  313. position = previous_position_before(position, should_wrap);
  314. TextPosition original_position = position;
  315. TextPosition end_of_potential_match;
  316. size_t needle_index = needle.length() - 1;
  317. do {
  318. auto ch = codepoint_at(position);
  319. // FIXME: This is not the right way to use a Unicode needle!
  320. if (ch == (u32)needle[needle_index]) {
  321. if (needle_index == needle.length() - 1)
  322. end_of_potential_match = position;
  323. if (needle_index == 0)
  324. return { position, next_position_after(end_of_potential_match, should_wrap) };
  325. --needle_index;
  326. } else {
  327. if (needle_index < needle.length() - 1)
  328. position = end_of_potential_match;
  329. needle_index = needle.length() - 1;
  330. }
  331. position = previous_position_before(position, should_wrap);
  332. } while (position.is_valid() && position != original_position);
  333. return {};
  334. }
  335. Vector<TextRange> TextDocument::find_all(const StringView& needle) const
  336. {
  337. Vector<TextRange> ranges;
  338. TextPosition position;
  339. for (;;) {
  340. auto range = find_next(needle, position, SearchShouldWrap::No);
  341. if (!range.is_valid())
  342. break;
  343. ranges.append(range);
  344. position = range.end();
  345. }
  346. return ranges;
  347. }
  348. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_before(const TextPosition& position) const
  349. {
  350. for (int i = m_spans.size() - 1; i >= 0; --i) {
  351. if (!m_spans[i].range.contains(position))
  352. continue;
  353. while ((i - 1) >= 0 && m_spans[i - 1].is_skippable)
  354. --i;
  355. if (i <= 0)
  356. return {};
  357. return m_spans[i - 1];
  358. }
  359. return {};
  360. }
  361. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_after(const TextPosition& position) const
  362. {
  363. for (size_t i = 0; i < m_spans.size(); ++i) {
  364. if (!m_spans[i].range.contains(position))
  365. continue;
  366. while ((i + 1) < m_spans.size() && m_spans[i + 1].is_skippable)
  367. ++i;
  368. if (i >= (m_spans.size() - 1))
  369. return {};
  370. return m_spans[i + 1];
  371. }
  372. return {};
  373. }
  374. TextPosition TextDocument::first_word_break_before(const TextPosition& position, bool start_at_column_before) const
  375. {
  376. if (position.column() == 0) {
  377. if (position.line() == 0) {
  378. return TextPosition(0, 0);
  379. }
  380. auto previous_line = this->line(position.line() - 1);
  381. return TextPosition(position.line() - 1, previous_line.length());
  382. }
  383. auto target = position;
  384. auto line = this->line(target.line());
  385. auto is_start_alphanumeric = isalnum(line.codepoints()[target.column() - (start_at_column_before ? 1 : 0)]);
  386. while (target.column() > 0) {
  387. auto prev_codepoint = line.codepoints()[target.column() - 1];
  388. if ((is_start_alphanumeric && !isalnum(prev_codepoint)) || (!is_start_alphanumeric && isalnum(prev_codepoint)))
  389. break;
  390. target.set_column(target.column() - 1);
  391. }
  392. return target;
  393. }
  394. TextPosition TextDocument::first_word_break_after(const TextPosition& position) const
  395. {
  396. auto target = position;
  397. auto line = this->line(target.line());
  398. if (position.column() >= line.length()) {
  399. if (position.line() >= this->line_count() - 1) {
  400. return position;
  401. }
  402. return TextPosition(position.line() + 1, 0);
  403. }
  404. auto is_start_alphanumeric = isalnum(line.codepoints()[target.column()]);
  405. while (target.column() < line.length()) {
  406. auto next_codepoint = line.codepoints()[target.column()];
  407. if ((is_start_alphanumeric && !isalnum(next_codepoint)) || (!is_start_alphanumeric && isalnum(next_codepoint)))
  408. break;
  409. target.set_column(target.column() + 1);
  410. }
  411. return target;
  412. }
  413. void TextDocument::undo()
  414. {
  415. if (!can_undo())
  416. return;
  417. m_undo_stack.undo();
  418. notify_did_change();
  419. }
  420. void TextDocument::redo()
  421. {
  422. if (!can_redo())
  423. return;
  424. m_undo_stack.redo();
  425. notify_did_change();
  426. }
  427. void TextDocument::add_to_undo_stack(NonnullOwnPtr<TextDocumentUndoCommand> undo_command)
  428. {
  429. m_undo_stack.push(move(undo_command));
  430. }
  431. TextDocumentUndoCommand::TextDocumentUndoCommand(TextDocument& document)
  432. : m_document(document)
  433. {
  434. }
  435. TextDocumentUndoCommand::~TextDocumentUndoCommand()
  436. {
  437. }
  438. InsertTextCommand::InsertTextCommand(TextDocument& document, const String& text, const TextPosition& position)
  439. : TextDocumentUndoCommand(document)
  440. , m_text(text)
  441. , m_range({ position, position })
  442. {
  443. }
  444. void InsertTextCommand::redo()
  445. {
  446. auto new_cursor = m_document.insert_at(m_range.start(), m_text, m_client);
  447. // NOTE: We don't know where the range ends until after doing redo().
  448. // This is okay since we always do redo() after adding this to the undo stack.
  449. m_range.set_end(new_cursor);
  450. m_document.set_all_cursors(new_cursor);
  451. }
  452. void InsertTextCommand::undo()
  453. {
  454. m_document.remove(m_range);
  455. m_document.set_all_cursors(m_range.start());
  456. }
  457. RemoveTextCommand::RemoveTextCommand(TextDocument& document, const String& text, const TextRange& range)
  458. : TextDocumentUndoCommand(document)
  459. , m_text(text)
  460. , m_range(range)
  461. {
  462. }
  463. void RemoveTextCommand::redo()
  464. {
  465. m_document.remove(m_range);
  466. m_document.set_all_cursors(m_range.start());
  467. }
  468. void RemoveTextCommand::undo()
  469. {
  470. auto new_cursor = m_document.insert_at(m_range.start(), m_text);
  471. m_document.set_all_cursors(new_cursor);
  472. }
  473. void TextDocument::update_undo_timer()
  474. {
  475. m_undo_stack.finalize_current_combo();
  476. }
  477. TextPosition TextDocument::insert_at(const TextPosition& position, const StringView& text, const Client* client)
  478. {
  479. TextPosition cursor = position;
  480. Utf8View utf8_view(text);
  481. for (auto codepoint : utf8_view)
  482. cursor = insert_at(cursor, codepoint, client);
  483. return cursor;
  484. }
  485. TextPosition TextDocument::insert_at(const TextPosition& position, u32 codepoint, const Client* client)
  486. {
  487. bool automatic_indentation_enabled = client ? client->is_automatic_indentation_enabled() : false;
  488. size_t m_soft_tab_width = client ? client->soft_tab_width() : 4;
  489. bool at_head = position.column() == 0;
  490. bool at_tail = position.column() == line(position.line()).length();
  491. if (codepoint == '\n') {
  492. if (at_tail || at_head) {
  493. String new_line_contents;
  494. if (automatic_indentation_enabled && at_tail) {
  495. size_t leading_spaces = 0;
  496. auto& old_line = lines()[position.line()];
  497. for (size_t i = 0; i < old_line.length(); ++i) {
  498. if (old_line.codepoints()[i] == ' ')
  499. ++leading_spaces;
  500. else
  501. break;
  502. }
  503. if (leading_spaces)
  504. new_line_contents = String::repeated(' ', leading_spaces);
  505. }
  506. size_t row = position.line();
  507. Vector<u32> line_content;
  508. for (size_t i = position.column(); i < line(row).length(); i++)
  509. line_content.append(line(row).codepoints()[i]);
  510. insert_line(position.line() + (at_tail ? 1 : 0), make<TextDocumentLine>(*this, new_line_contents));
  511. notify_did_change();
  512. return { position.line() + 1, line(position.line() + 1).length() };
  513. }
  514. auto new_line = make<TextDocumentLine>(*this);
  515. new_line->append(*this, line(position.line()).codepoints() + position.column(), line(position.line()).length() - position.column());
  516. Vector<u32> line_content;
  517. for (size_t i = 0; i < new_line->length(); i++)
  518. line_content.append(new_line->codepoints()[i]);
  519. line(position.line()).truncate(*this, position.column());
  520. insert_line(position.line() + 1, move(new_line));
  521. notify_did_change();
  522. return { position.line() + 1, 0 };
  523. }
  524. if (codepoint == '\t') {
  525. size_t next_soft_tab_stop = ((position.column() + m_soft_tab_width) / m_soft_tab_width) * m_soft_tab_width;
  526. size_t spaces_to_insert = next_soft_tab_stop - position.column();
  527. for (size_t i = 0; i < spaces_to_insert; ++i) {
  528. line(position.line()).insert(*this, position.column(), ' ');
  529. }
  530. notify_did_change();
  531. return { position.line(), next_soft_tab_stop };
  532. }
  533. line(position.line()).insert(*this, position.column(), codepoint);
  534. notify_did_change();
  535. return { position.line(), position.column() + 1 };
  536. }
  537. void TextDocument::remove(const TextRange& unnormalized_range)
  538. {
  539. if (!unnormalized_range.is_valid())
  540. return;
  541. auto range = unnormalized_range.normalized();
  542. // First delete all the lines in between the first and last one.
  543. for (size_t i = range.start().line() + 1; i < range.end().line();) {
  544. remove_line(i);
  545. range.end().set_line(range.end().line() - 1);
  546. }
  547. if (range.start().line() == range.end().line()) {
  548. // Delete within same line.
  549. auto& line = this->line(range.start().line());
  550. bool whole_line_is_selected = range.start().column() == 0 && range.end().column() == line.length();
  551. if (whole_line_is_selected) {
  552. line.clear(*this);
  553. } else {
  554. line.remove_range(*this, range.start().column(), range.end().column() - range.start().column());
  555. }
  556. } else {
  557. // Delete across a newline, merging lines.
  558. ASSERT(range.start().line() == range.end().line() - 1);
  559. auto& first_line = line(range.start().line());
  560. auto& second_line = line(range.end().line());
  561. Vector<u32> codepoints;
  562. codepoints.append(first_line.codepoints(), range.start().column());
  563. codepoints.append(second_line.codepoints() + range.end().column(), second_line.length() - range.end().column());
  564. first_line.set_text(*this, move(codepoints));
  565. remove_line(range.end().line());
  566. }
  567. if (lines().is_empty()) {
  568. append_line(make<TextDocumentLine>(*this));
  569. }
  570. notify_did_change();
  571. }
  572. TextRange TextDocument::range_for_entire_line(size_t line_index) const
  573. {
  574. if (line_index >= line_count())
  575. return {};
  576. return { { line_index, 0 }, { line_index, line(line_index).length() } };
  577. }
  578. }