GTextDocument.cpp 19 KB

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