TextDocument.cpp 19 KB

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