TextDocument.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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 StringView& text)
  105. {
  106. if (text.is_empty()) {
  107. clear(document);
  108. return;
  109. }
  110. m_text.clear();
  111. Utf8View utf8_view(text);
  112. for (auto codepoint : utf8_view)
  113. m_text.append(codepoint);
  114. document.update_views({});
  115. }
  116. void TextDocumentLine::append(TextDocument& document, const u32* codepoints, size_t length)
  117. {
  118. m_text.append(codepoints, length);
  119. document.update_views({});
  120. }
  121. void TextDocumentLine::append(TextDocument& document, u32 codepoint)
  122. {
  123. insert(document, length(), codepoint);
  124. }
  125. void TextDocumentLine::prepend(TextDocument& document, u32 codepoint)
  126. {
  127. insert(document, 0, codepoint);
  128. }
  129. void TextDocumentLine::insert(TextDocument& document, size_t index, u32 codepoint)
  130. {
  131. if (index == length()) {
  132. m_text.append(codepoint);
  133. } else {
  134. m_text.insert(index, codepoint);
  135. }
  136. document.update_views({});
  137. }
  138. void TextDocumentLine::remove(TextDocument& document, size_t index)
  139. {
  140. if (index == length()) {
  141. m_text.take_last();
  142. } else {
  143. m_text.remove(index);
  144. }
  145. document.update_views({});
  146. }
  147. void TextDocumentLine::remove_range(TextDocument& document, size_t start, size_t length)
  148. {
  149. ASSERT(length <= m_text.size());
  150. Vector<u32> new_data;
  151. new_data.ensure_capacity(m_text.size() - length);
  152. for (size_t i = 0; i < start; ++i)
  153. new_data.append(m_text[i]);
  154. for (size_t i = (start + length); i < m_text.size(); ++i)
  155. new_data.append(m_text[i]);
  156. m_text = move(new_data);
  157. document.update_views({});
  158. }
  159. void TextDocumentLine::truncate(TextDocument& document, size_t length)
  160. {
  161. m_text.resize(length);
  162. document.update_views({});
  163. }
  164. void TextDocument::append_line(NonnullOwnPtr<TextDocumentLine> line)
  165. {
  166. lines().append(move(line));
  167. if (m_client_notifications_enabled) {
  168. for (auto* client : m_clients)
  169. client->document_did_append_line();
  170. }
  171. }
  172. void TextDocument::insert_line(size_t line_index, NonnullOwnPtr<TextDocumentLine> line)
  173. {
  174. lines().insert((int)line_index, move(line));
  175. if (m_client_notifications_enabled) {
  176. for (auto* client : m_clients)
  177. client->document_did_insert_line(line_index);
  178. }
  179. }
  180. void TextDocument::remove_line(size_t line_index)
  181. {
  182. lines().remove((int)line_index);
  183. if (m_client_notifications_enabled) {
  184. for (auto* client : m_clients)
  185. client->document_did_remove_line(line_index);
  186. }
  187. }
  188. void TextDocument::remove_all_lines()
  189. {
  190. lines().clear();
  191. if (m_client_notifications_enabled) {
  192. for (auto* client : m_clients)
  193. client->document_did_remove_all_lines();
  194. }
  195. }
  196. TextDocument::Client::~Client()
  197. {
  198. }
  199. void TextDocument::register_client(Client& client)
  200. {
  201. m_clients.set(&client);
  202. }
  203. void TextDocument::unregister_client(Client& client)
  204. {
  205. m_clients.remove(&client);
  206. }
  207. void TextDocument::update_views(Badge<TextDocumentLine>)
  208. {
  209. notify_did_change();
  210. }
  211. void TextDocument::notify_did_change()
  212. {
  213. if (m_client_notifications_enabled) {
  214. for (auto* client : m_clients)
  215. client->document_did_change();
  216. }
  217. }
  218. void TextDocument::set_all_cursors(const TextPosition& position)
  219. {
  220. if (m_client_notifications_enabled) {
  221. for (auto* client : m_clients)
  222. client->document_did_set_cursor(position);
  223. }
  224. }
  225. String TextDocument::text_in_range(const TextRange& a_range) const
  226. {
  227. auto range = a_range.normalized();
  228. StringBuilder builder;
  229. for (size_t i = range.start().line(); i <= range.end().line(); ++i) {
  230. auto& line = this->line(i);
  231. size_t selection_start_column_on_line = range.start().line() == i ? range.start().column() : 0;
  232. size_t selection_end_column_on_line = range.end().line() == i ? range.end().column() : line.length();
  233. builder.append(Utf32View(line.codepoints() + selection_start_column_on_line, selection_end_column_on_line - selection_start_column_on_line));
  234. if (i != range.end().line())
  235. builder.append('\n');
  236. }
  237. return builder.to_string();
  238. }
  239. u32 TextDocument::codepoint_at(const TextPosition& position) const
  240. {
  241. ASSERT(position.line() < line_count());
  242. auto& line = this->line(position.line());
  243. if (position.column() == line.length())
  244. return '\n';
  245. return line.codepoints()[position.column()];
  246. }
  247. TextPosition TextDocument::next_position_after(const TextPosition& position, SearchShouldWrap should_wrap) const
  248. {
  249. auto& line = this->line(position.line());
  250. if (position.column() == line.length()) {
  251. if (position.line() == line_count() - 1) {
  252. if (should_wrap == SearchShouldWrap::Yes)
  253. return { 0, 0 };
  254. return {};
  255. }
  256. return { position.line() + 1, 0 };
  257. }
  258. return { position.line(), position.column() + 1 };
  259. }
  260. TextPosition TextDocument::previous_position_before(const TextPosition& position, SearchShouldWrap should_wrap) const
  261. {
  262. if (position.column() == 0) {
  263. if (position.line() == 0) {
  264. if (should_wrap == SearchShouldWrap::Yes) {
  265. auto& last_line = this->line(line_count() - 1);
  266. return { line_count() - 1, last_line.length() };
  267. }
  268. return {};
  269. }
  270. auto& prev_line = this->line(position.line() - 1);
  271. return { position.line() - 1, prev_line.length() };
  272. }
  273. return { position.line(), position.column() - 1 };
  274. }
  275. TextRange TextDocument::find_next(const StringView& needle, const TextPosition& start, SearchShouldWrap should_wrap) const
  276. {
  277. if (needle.is_empty())
  278. return {};
  279. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  280. TextPosition original_position = position;
  281. TextPosition start_of_potential_match;
  282. size_t needle_index = 0;
  283. do {
  284. auto ch = codepoint_at(position);
  285. // FIXME: This is not the right way to use a Unicode needle!
  286. if (ch == (u32)needle[needle_index]) {
  287. if (needle_index == 0)
  288. start_of_potential_match = position;
  289. ++needle_index;
  290. if (needle_index >= needle.length())
  291. return { start_of_potential_match, next_position_after(position, should_wrap) };
  292. } else {
  293. if (needle_index > 0)
  294. position = start_of_potential_match;
  295. needle_index = 0;
  296. }
  297. position = next_position_after(position, should_wrap);
  298. } while (position.is_valid() && position != original_position);
  299. return {};
  300. }
  301. TextRange TextDocument::find_previous(const StringView& needle, const TextPosition& start, SearchShouldWrap should_wrap) const
  302. {
  303. if (needle.is_empty())
  304. return {};
  305. TextPosition position = start.is_valid() ? start : TextPosition(0, 0);
  306. position = previous_position_before(position, should_wrap);
  307. TextPosition original_position = position;
  308. TextPosition end_of_potential_match;
  309. size_t needle_index = needle.length() - 1;
  310. do {
  311. auto ch = codepoint_at(position);
  312. // FIXME: This is not the right way to use a Unicode needle!
  313. if (ch == (u32)needle[needle_index]) {
  314. if (needle_index == needle.length() - 1)
  315. end_of_potential_match = position;
  316. if (needle_index == 0)
  317. return { position, next_position_after(end_of_potential_match, should_wrap) };
  318. --needle_index;
  319. } else {
  320. if (needle_index < needle.length() - 1)
  321. position = end_of_potential_match;
  322. needle_index = needle.length() - 1;
  323. }
  324. position = previous_position_before(position, should_wrap);
  325. } while (position.is_valid() && position != original_position);
  326. return {};
  327. }
  328. Vector<TextRange> TextDocument::find_all(const StringView& needle) const
  329. {
  330. Vector<TextRange> ranges;
  331. TextPosition position;
  332. for (;;) {
  333. auto range = find_next(needle, position, SearchShouldWrap::No);
  334. if (!range.is_valid())
  335. break;
  336. ranges.append(range);
  337. position = range.end();
  338. }
  339. return ranges;
  340. }
  341. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_before(const TextPosition& position) const
  342. {
  343. for (int i = m_spans.size() - 1; i >= 0; --i) {
  344. if (!m_spans[i].range.contains(position))
  345. continue;
  346. while ((i - 1) >= 0 && m_spans[i - 1].is_skippable)
  347. --i;
  348. if (i <= 0)
  349. return {};
  350. return m_spans[i - 1];
  351. }
  352. return {};
  353. }
  354. Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_after(const TextPosition& position) const
  355. {
  356. for (size_t i = 0; i < m_spans.size(); ++i) {
  357. if (!m_spans[i].range.contains(position))
  358. continue;
  359. while ((i + 1) < m_spans.size() && m_spans[i + 1].is_skippable)
  360. ++i;
  361. if (i >= (m_spans.size() - 1))
  362. return {};
  363. return m_spans[i + 1];
  364. }
  365. return {};
  366. }
  367. void TextDocument::undo()
  368. {
  369. if (!can_undo())
  370. return;
  371. m_undo_stack.undo();
  372. notify_did_change();
  373. }
  374. void TextDocument::redo()
  375. {
  376. if (!can_redo())
  377. return;
  378. m_undo_stack.redo();
  379. notify_did_change();
  380. }
  381. void TextDocument::add_to_undo_stack(NonnullOwnPtr<TextDocumentUndoCommand> undo_command)
  382. {
  383. m_undo_stack.push(move(undo_command));
  384. }
  385. TextDocumentUndoCommand::TextDocumentUndoCommand(TextDocument& document)
  386. : m_document(document)
  387. {
  388. }
  389. TextDocumentUndoCommand::~TextDocumentUndoCommand()
  390. {
  391. }
  392. InsertTextCommand::InsertTextCommand(TextDocument& document, const String& text, const TextPosition& position)
  393. : TextDocumentUndoCommand(document)
  394. , m_text(text)
  395. , m_range({ position, position })
  396. {
  397. }
  398. void InsertTextCommand::redo()
  399. {
  400. auto new_cursor = m_document.insert_at(m_range.start(), m_text, m_client);
  401. // NOTE: We don't know where the range ends until after doing redo().
  402. // This is okay since we always do redo() after adding this to the undo stack.
  403. m_range.set_end(new_cursor);
  404. m_document.set_all_cursors(new_cursor);
  405. }
  406. void InsertTextCommand::undo()
  407. {
  408. m_document.remove(m_range);
  409. m_document.set_all_cursors(m_range.start());
  410. }
  411. RemoveTextCommand::RemoveTextCommand(TextDocument& document, const String& text, const TextRange& range)
  412. : TextDocumentUndoCommand(document)
  413. , m_text(text)
  414. , m_range(range)
  415. {
  416. }
  417. void RemoveTextCommand::redo()
  418. {
  419. m_document.remove(m_range);
  420. m_document.set_all_cursors(m_range.start());
  421. }
  422. void RemoveTextCommand::undo()
  423. {
  424. auto new_cursor = m_document.insert_at(m_range.start(), m_text);
  425. m_document.set_all_cursors(new_cursor);
  426. }
  427. void TextDocument::update_undo_timer()
  428. {
  429. m_undo_stack.finalize_current_combo();
  430. }
  431. TextPosition TextDocument::insert_at(const TextPosition& position, const StringView& text, const Client* client)
  432. {
  433. TextPosition cursor = position;
  434. Utf8View utf8_view(text);
  435. for (auto codepoint : utf8_view)
  436. cursor = insert_at(cursor, codepoint, client);
  437. return cursor;
  438. }
  439. TextPosition TextDocument::insert_at(const TextPosition& position, u32 codepoint, const Client* client)
  440. {
  441. bool automatic_indentation_enabled = client ? client->is_automatic_indentation_enabled() : false;
  442. size_t m_soft_tab_width = client ? client->soft_tab_width() : 4;
  443. bool at_head = position.column() == 0;
  444. bool at_tail = position.column() == line(position.line()).length();
  445. if (codepoint == '\n') {
  446. if (at_tail || at_head) {
  447. String new_line_contents;
  448. if (automatic_indentation_enabled && at_tail) {
  449. size_t leading_spaces = 0;
  450. auto& old_line = lines()[position.line()];
  451. for (size_t i = 0; i < old_line.length(); ++i) {
  452. if (old_line.codepoints()[i] == ' ')
  453. ++leading_spaces;
  454. else
  455. break;
  456. }
  457. if (leading_spaces)
  458. new_line_contents = String::repeated(' ', leading_spaces);
  459. }
  460. size_t row = position.line();
  461. Vector<u32> line_content;
  462. for (size_t i = position.column(); i < line(row).length(); i++)
  463. line_content.append(line(row).codepoints()[i]);
  464. insert_line(position.line() + (at_tail ? 1 : 0), make<TextDocumentLine>(*this, new_line_contents));
  465. notify_did_change();
  466. return { position.line() + 1, line(position.line() + 1).length() };
  467. }
  468. auto new_line = make<TextDocumentLine>(*this);
  469. new_line->append(*this, line(position.line()).codepoints() + position.column(), line(position.line()).length() - position.column());
  470. Vector<u32> line_content;
  471. for (size_t i = 0; i < new_line->length(); i++)
  472. line_content.append(new_line->codepoints()[i]);
  473. line(position.line()).truncate(*this, position.column());
  474. insert_line(position.line() + 1, move(new_line));
  475. notify_did_change();
  476. return { position.line() + 1, 0 };
  477. }
  478. if (codepoint == '\t') {
  479. size_t next_soft_tab_stop = ((position.column() + m_soft_tab_width) / m_soft_tab_width) * m_soft_tab_width;
  480. size_t spaces_to_insert = next_soft_tab_stop - position.column();
  481. for (size_t i = 0; i < spaces_to_insert; ++i) {
  482. line(position.line()).insert(*this, position.column(), ' ');
  483. }
  484. notify_did_change();
  485. return { position.line(), next_soft_tab_stop };
  486. }
  487. line(position.line()).insert(*this, position.column(), codepoint);
  488. notify_did_change();
  489. return { position.line(), position.column() + 1 };
  490. }
  491. void TextDocument::remove(const TextRange& unnormalized_range)
  492. {
  493. if (!unnormalized_range.is_valid())
  494. return;
  495. auto range = unnormalized_range.normalized();
  496. // First delete all the lines in between the first and last one.
  497. for (size_t i = range.start().line() + 1; i < range.end().line();) {
  498. remove_line(i);
  499. range.end().set_line(range.end().line() - 1);
  500. }
  501. if (range.start().line() == range.end().line()) {
  502. // Delete within same line.
  503. auto& line = this->line(range.start().line());
  504. bool whole_line_is_selected = range.start().column() == 0 && range.end().column() == line.length();
  505. if (whole_line_is_selected) {
  506. line.clear(*this);
  507. } else {
  508. line.remove_range(*this, range.start().column(), range.end().column() - range.start().column());
  509. }
  510. } else {
  511. // Delete across a newline, merging lines.
  512. ASSERT(range.start().line() == range.end().line() - 1);
  513. auto& first_line = line(range.start().line());
  514. auto& second_line = line(range.end().line());
  515. first_line.clear(*this);
  516. first_line.append(*this, first_line.codepoints(), range.start().column());
  517. first_line.append(*this, second_line.codepoints() + range.end().column(), second_line.length() - range.end().column());
  518. remove_line(range.end().line());
  519. }
  520. if (lines().is_empty()) {
  521. append_line(make<TextDocumentLine>(*this));
  522. }
  523. notify_did_change();
  524. }
  525. TextRange TextDocument::range_for_entire_line(size_t line_index) const
  526. {
  527. if (line_index >= line_count())
  528. return {};
  529. return { { line_index, 0 }, { line_index, line(line_index).length() } };
  530. }
  531. }