TextDocument.cpp 19 KB

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