TextDocument.cpp 19 KB

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