3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Dov Feldstern
9 * \author Jean-Marc Lasgouttes
11 * \author André Pönitz
12 * \author Stefan Schimanski
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "CompletionList.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
37 #include "InsetList.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TextMetrics.h"
49 #include "WordLangTuple.h"
52 #include "insets/InsetText.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetCaption.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetNewpage.h"
57 #include "insets/InsetArgument.h"
58 #include "insets/InsetIPAMacro.h"
59 #include "insets/InsetSpace.h"
60 #include "insets/InsetSpecialChar.h"
61 #include "insets/InsetTabular.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/lyxalgo.h"
70 #include "support/lyxtime.h"
71 #include "support/textutils.h"
72 #include "support/unique_ptr.h"
78 using namespace lyx::support;
82 using cap::cutSelection;
83 using cap::pasteParagraphList;
85 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
86 Paragraph & toPar, pos_type toPos, BufferParams const & params)
88 // Note: moveItem() does not honour change tracking!
89 // Therefore, it should only be used for breaking and merging paragraphs
91 // We need a copy here because the character at fromPos is going to be erased.
92 Font const tmpFont = fromPar.getFontSettings(params, fromPos);
93 Change const tmpChange = fromPar.lookupChange(fromPos);
95 if (Inset * tmpInset = fromPar.getInset(fromPos)) {
96 fromPar.releaseInset(fromPos);
97 // The inset is not in fromPar any more.
98 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
105 char_type const tmpChar = fromPar.getChar(fromPos);
106 fromPar.eraseChar(fromPos, false);
107 toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
112 void breakParagraphConservative(BufferParams const & bparams,
113 ParagraphList & pars, pit_type pit, pos_type pos)
115 // create a new paragraph
116 Paragraph & tmp = *pars.insert(lyx::next(pars.begin(), pit + 1),
118 Paragraph & par = pars[pit];
120 tmp.setInsetOwner(&par.inInset());
121 tmp.makeSameLayout(par);
123 LASSERT(pos <= par.size(), return);
125 if (pos < par.size()) {
126 // move everything behind the break position to the new paragraph
127 pos_type pos_end = par.size() - 1;
129 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
130 if (moveItem(par, pos, tmp, j, bparams)) {
134 // Move over the end-of-par change information
135 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
136 par.setChange(par.size(), Change(bparams.track_changes ?
137 Change::INSERTED : Change::UNCHANGED));
142 void mergeParagraph(BufferParams const & bparams,
143 ParagraphList & pars, pit_type par_offset)
145 Paragraph & next = pars[par_offset + 1];
146 Paragraph & par = pars[par_offset];
148 pos_type pos_end = next.size() - 1;
149 pos_type pos_insert = par.size();
151 // the imaginary end-of-paragraph character (at par.size()) has to be
152 // marked as unmodified. Otherwise, its change is adopted by the first
153 // character of the next paragraph.
154 if (par.isChanged(par.size())) {
155 LYXERR(Debug::CHANGES,
156 "merging par with inserted/deleted end-of-par character");
157 par.setChange(par.size(), Change(Change::UNCHANGED));
160 Change change = next.lookupChange(next.size());
162 // move the content of the second paragraph to the end of the first one
163 for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
164 if (moveItem(next, 0, par, j, bparams)) {
169 // move the change of the end-of-paragraph character
170 par.setChange(par.size(), change);
172 pars.erase(lyx::next(pars.begin(), par_offset + 1));
176 Text::Text(InsetText * owner, bool use_default_layout)
179 pars_.push_back(Paragraph());
180 Paragraph & par = pars_.back();
181 par.setInsetOwner(owner);
182 DocumentClass const & dc = owner->buffer().params().documentClass();
183 if (use_default_layout)
184 par.setDefaultLayout(dc);
186 par.setPlainLayout(dc);
190 Text::Text(InsetText * owner, Text const & text)
191 : owner_(owner), pars_(text.pars_)
193 ParagraphList::iterator const end = pars_.end();
194 ParagraphList::iterator it = pars_.begin();
195 for (; it != end; ++it)
196 it->setInsetOwner(owner);
200 pit_type Text::depthHook(pit_type pit, depth_type depth) const
202 pit_type newpit = pit;
207 while (newpit != 0 && pars_[newpit].getDepth() > depth)
210 if (pars_[newpit].getDepth() > depth)
217 pit_type Text::outerHook(pit_type par_offset) const
219 Paragraph const & par = pars_[par_offset];
221 if (par.getDepth() == 0)
223 return depthHook(par_offset, depth_type(par.getDepth() - 1));
227 bool Text::isFirstInSequence(pit_type par_offset) const
229 Paragraph const & par = pars_[par_offset];
231 pit_type dhook_offset = depthHook(par_offset, par.getDepth());
233 if (dhook_offset == par_offset)
236 Paragraph const & dhook = pars_[dhook_offset];
238 return dhook.layout() != par.layout()
239 || dhook.getDepth() != par.getDepth();
243 pit_type Text::lastInSequence(pit_type pit) const
245 depth_type const depth = pars_[pit].getDepth();
246 pit_type newpit = pit;
248 while (size_t(newpit + 1) < pars_.size() &&
249 (pars_[newpit + 1].getDepth() > depth ||
250 (pars_[newpit + 1].getDepth() == depth &&
251 pars_[newpit + 1].layout() == pars_[pit].layout())))
258 int Text::getTocLevel(pit_type par_offset) const
260 Paragraph const & par = pars_[par_offset];
262 if (par.layout().isEnvironment() && !isFirstInSequence(par_offset))
263 return Layout::NOT_IN_TOC;
265 return par.layout().toclevel;
269 Font const Text::outerFont(pit_type par_offset) const
271 depth_type par_depth = pars_[par_offset].getDepth();
272 FontInfo tmpfont = inherit_font;
273 depth_type prev_par_depth = 0;
274 // Resolve against environment font information
275 while (par_offset != pit_type(pars_.size())
276 && par_depth != prev_par_depth
278 && !tmpfont.resolved()) {
279 prev_par_depth = par_depth;
280 par_offset = outerHook(par_offset);
281 if (par_offset != pit_type(pars_.size())) {
282 tmpfont.realize(pars_[par_offset].layout().font);
283 par_depth = pars_[par_offset].getDepth();
287 return Font(tmpfont);
291 int Text::getEndLabel(pit_type p) const
294 depth_type par_depth = pars_[p].getDepth();
295 while (pit != pit_type(pars_.size())) {
296 Layout const & layout = pars_[pit].layout();
297 int const endlabeltype = layout.endlabeltype;
299 if (endlabeltype != END_LABEL_NO_LABEL) {
300 if (p + 1 == pit_type(pars_.size()))
303 depth_type const next_depth =
304 pars_[p + 1].getDepth();
305 if (par_depth > next_depth ||
306 (par_depth == next_depth && layout != pars_[p + 1].layout()))
312 pit = outerHook(pit);
313 if (pit != pit_type(pars_.size()))
314 par_depth = pars_[pit].getDepth();
316 return END_LABEL_NO_LABEL;
320 static void acceptOrRejectChanges(ParagraphList & pars,
321 BufferParams const & bparams, Text::ChangeOp op)
323 pit_type pars_size = static_cast<pit_type>(pars.size());
325 // first, accept or reject changes within each individual
326 // paragraph (do not consider end-of-par)
327 for (pit_type pit = 0; pit < pars_size; ++pit) {
328 // prevent assertion failure
329 if (!pars[pit].empty()) {
330 if (op == Text::ACCEPT)
331 pars[pit].acceptChanges(0, pars[pit].size());
333 pars[pit].rejectChanges(0, pars[pit].size());
337 // next, accept or reject imaginary end-of-par characters
338 for (pit_type pit = 0; pit < pars_size; ++pit) {
339 pos_type pos = pars[pit].size();
340 if (pars[pit].isChanged(pos)) {
341 // keep the end-of-par char if it is inserted and accepted
342 // or when it is deleted and rejected.
343 if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
344 pars[pit].setChange(pos, Change(Change::UNCHANGED));
346 if (pit == pars_size - 1) {
347 // we cannot remove a par break at the end of the last
348 // paragraph; instead, we mark it unchanged
349 pars[pit].setChange(pos, Change(Change::UNCHANGED));
351 mergeParagraph(bparams, pars, pit);
361 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
363 acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
367 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
369 acceptOrRejectChanges(pars, bparams, Text::REJECT);
373 InsetText const & Text::inset() const
380 void Text::readParToken(Paragraph & par, Lexer & lex,
381 string const & token, Font & font, Change & change, ErrorList & errorList)
383 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
384 BufferParams & bp = buf->params();
386 if (token[0] != '\\') {
387 docstring dstr = lex.getDocString();
388 par.appendString(dstr, font, change);
390 } else if (token == "\\begin_layout") {
392 docstring layoutname = lex.getDocString();
394 font = Font(inherit_font, bp.language);
395 change = Change(Change::UNCHANGED);
397 DocumentClass const & tclass = bp.documentClass();
399 if (layoutname.empty())
400 layoutname = tclass.defaultLayoutName();
402 if (owner_->forcePlainLayout()) {
403 // in this case only the empty layout is allowed
404 layoutname = tclass.plainLayoutName();
405 } else if (par.usePlainLayout()) {
406 // in this case, default layout maps to empty layout
407 if (layoutname == tclass.defaultLayoutName())
408 layoutname = tclass.plainLayoutName();
410 // otherwise, the empty layout maps to the default
411 if (layoutname == tclass.plainLayoutName())
412 layoutname = tclass.defaultLayoutName();
415 // When we apply an unknown layout to a document, we add this layout to the textclass
416 // of this document. For example, when you apply class article to a beamer document,
417 // all unknown layouts such as frame will be added to document class article so that
418 // these layouts can keep their original names.
419 bool const added_one = tclass.addLayoutIfNeeded(layoutname);
422 docstring const s = bformat(_("Layout `%1$s' was not found."), layoutname);
423 errorList.push_back(ErrorItem(_("Layout Not Found"), s,
424 {par.id(), 0}, {par.id(), -1}));
427 par.setLayout(bp.documentClass()[layoutname]);
429 // Test whether the layout is obsolete.
430 Layout const & layout = par.layout();
431 if (!layout.obsoleted_by().empty())
432 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
434 par.params().read(lex);
436 } else if (token == "\\end_layout") {
437 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
438 << "Missing \\begin_layout ?");
439 } else if (token == "\\end_inset") {
440 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
441 << "Missing \\begin_inset ?");
442 } else if (token == "\\begin_inset") {
443 Inset * inset = readInset(lex, buf);
445 par.insertInset(par.size(), inset, font, change);
448 docstring line = lex.getDocString();
449 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
450 {par.id(), 0}, {par.id(), -1}));
452 } else if (token == "\\family") {
454 setLyXFamily(lex.getString(), font.fontInfo());
455 } else if (token == "\\series") {
457 setLyXSeries(lex.getString(), font.fontInfo());
458 } else if (token == "\\shape") {
460 setLyXShape(lex.getString(), font.fontInfo());
461 } else if (token == "\\size") {
463 setLyXSize(lex.getString(), font.fontInfo());
464 } else if (token == "\\lang") {
466 string const tok = lex.getString();
467 Language const * lang = languages.getLanguage(tok);
469 font.setLanguage(lang);
471 font.setLanguage(bp.language);
472 lex.printError("Unknown language `$$Token'");
474 } else if (token == "\\numeric") {
476 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
477 } else if (token == "\\nospellcheck") {
479 font.fontInfo().setNoSpellcheck(setLyXMisc(lex.getString()));
480 } else if (token == "\\emph") {
482 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
483 } else if (token == "\\bar") {
485 string const tok = lex.getString();
488 font.fontInfo().setUnderbar(FONT_ON);
489 else if (tok == "no")
490 font.fontInfo().setUnderbar(FONT_OFF);
491 else if (tok == "default")
492 font.fontInfo().setUnderbar(FONT_INHERIT);
494 lex.printError("Unknown bar font flag "
496 } else if (token == "\\strikeout") {
498 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
499 } else if (token == "\\xout") {
501 font.fontInfo().setXout(setLyXMisc(lex.getString()));
502 } else if (token == "\\uuline") {
504 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
505 } else if (token == "\\uwave") {
507 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
508 } else if (token == "\\noun") {
510 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
511 } else if (token == "\\color") {
513 setLyXColor(lex.getString(), font.fontInfo());
514 } else if (token == "\\SpecialChar" ||
515 (token == "\\SpecialCharNoPassThru" &&
516 !par.layout().pass_thru && !inset().isPassThru())) {
517 auto inset = make_unique<InsetSpecialChar>();
519 inset->setBuffer(*buf);
520 par.insertInset(par.size(), inset.release(), font, change);
521 } else if (token == "\\SpecialCharNoPassThru") {
523 docstring const s = ltrim(lex.getDocString(), "\\");
524 par.insert(par.size(), s, font, change);
525 } else if (token == "\\IPAChar") {
526 auto inset = make_unique<InsetIPAChar>();
528 inset->setBuffer(*buf);
529 par.insertInset(par.size(), inset.release(), font, change);
530 } else if (token == "\\twohyphens" || token == "\\threehyphens") {
531 // Ideally, this should be done by lyx2lyx, but lyx2lyx does not know the
532 // running font and does not know anything about layouts (and CopyStyle).
533 Layout const & layout(par.layout());
534 FontInfo info = font.fontInfo();
535 info.realize(layout.resfont);
536 if (layout.pass_thru || inset().isPassThru() ||
537 info.family() == TYPEWRITER_FAMILY) {
538 if (token == "\\twohyphens")
539 par.insert(par.size(), from_ascii("--"), font, change);
541 par.insert(par.size(), from_ascii("---"), font, change);
543 if (token == "\\twohyphens")
544 par.insertChar(par.size(), 0x2013, font, change);
546 par.insertChar(par.size(), 0x2014, font, change);
548 } else if (token == "\\backslash") {
549 par.appendChar('\\', font, change);
550 } else if (token == "\\LyXTable") {
551 auto inset = make_unique<InsetTabular>(buf);
553 par.insertInset(par.size(), inset.release(), font, change);
554 } else if (token == "\\change_unchanged") {
555 change = Change(Change::UNCHANGED);
556 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
558 istringstream is(lex.getString());
562 BufferParams::AuthorMap const & am = bp.author_map_;
563 if (am.find(aid) == am.end()) {
564 errorList.push_back(ErrorItem(
565 _("Change tracking author index missing"),
566 bformat(_("A change tracking author information for index "
567 "%1$d is missing. This can happen after a wrong "
568 "merge by a version control system. In this case, "
569 "either fix the merge, or have this information "
570 "missing until the corresponding tracked changes "
571 "are merged or this user edits the file again.\n"),
573 {par.id(), par.size()}, {par.id(), par.size() + 1}));
574 bp.addAuthor(Author(aid));
576 if (token == "\\change_inserted")
577 change = Change(Change::INSERTED, am.find(aid)->second, ct);
579 change = Change(Change::DELETED, am.find(aid)->second, ct);
582 errorList.push_back(ErrorItem(_("Unknown token"),
583 bformat(_("Unknown token: %1$s %2$s\n"),
586 {par.id(), 0}, {par.id(), -1}));
591 void Text::readParagraph(Paragraph & par, Lexer & lex,
592 ErrorList & errorList)
595 string token = lex.getString();
597 Change change(Change::UNCHANGED);
600 readParToken(par, lex, token, font, change, errorList);
603 token = lex.getString();
608 if (token == "\\end_layout") {
609 //Ok, paragraph finished
613 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
614 if (token == "\\begin_layout" || token == "\\end_document"
615 || token == "\\end_inset" || token == "\\begin_deeper"
616 || token == "\\end_deeper") {
617 lex.pushToken(token);
618 lyxerr << "Paragraph ended in line "
619 << lex.lineNumber() << "\n"
620 << "Missing \\end_layout.\n";
624 // Final change goes to paragraph break:
625 par.setChange(par.size(), change);
627 // Initialize begin_of_body_ on load; redoParagraph maintains
628 par.setBeginOfBody();
630 // mark paragraph for spell checking on load
631 // par.requestSpellCheck();
635 class TextCompletionList : public CompletionList
639 TextCompletionList(Cursor const & cur, WordList const & list)
640 : buffer_(cur.buffer()), list_(list)
643 virtual ~TextCompletionList() {}
646 virtual bool sorted() const { return true; }
648 virtual size_t size() const
653 virtual docstring const & data(size_t idx) const
655 return list_.word(idx);
660 Buffer const * buffer_;
662 WordList const & list_;
666 bool Text::empty() const
668 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
669 // FIXME: Should we consider the labeled type as empty too?
670 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
674 double Text::spacing(Paragraph const & par) const
676 if (par.params().spacing().isDefault())
677 return owner_->buffer().params().spacing().getValue();
678 return par.params().spacing().getValue();
683 * This breaks a paragraph at the specified position.
684 * The new paragraph will:
685 * - Decrease depth by one (or change layout to default layout) when
686 * keep_layout == false
687 * - keep current depth and layout when keep_layout == true
689 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
692 BufferParams const & bparams = text.inset().buffer().params();
693 ParagraphList & pars = text.paragraphs();
694 // create a new paragraph, and insert into the list
695 ParagraphList::iterator tmp =
696 pars.insert(lyx::next(pars.begin(), par_offset + 1),
699 Paragraph & par = pars[par_offset];
701 // remember to set the inset_owner
702 tmp->setInsetOwner(&par.inInset());
703 // without doing that we get a crash when typing <Return> at the
704 // end of a paragraph
705 tmp->setPlainOrDefaultLayout(bparams.documentClass());
708 tmp->setLayout(par.layout());
709 tmp->setLabelWidthString(par.params().labelWidthString());
710 tmp->params().depth(par.params().depth());
711 } else if (par.params().depth() > 0) {
712 Paragraph const & hook = pars[text.outerHook(par_offset)];
713 tmp->setLayout(hook.layout());
714 // not sure the line below is useful
715 tmp->setLabelWidthString(par.params().labelWidthString());
716 tmp->params().depth(hook.params().depth());
719 bool const isempty = (par.allowEmpty() && par.empty());
721 if (!isempty && (par.size() > pos || par.empty())) {
722 tmp->setLayout(par.layout());
723 tmp->params().align(par.params().align());
724 tmp->setLabelWidthString(par.params().labelWidthString());
726 tmp->params().depth(par.params().depth());
727 tmp->params().noindent(par.params().noindent());
729 // move everything behind the break position
730 // to the new paragraph
732 /* Note: if !keepempty, empty() == true, then we reach
733 * here with size() == 0. So pos_end becomes - 1. This
734 * doesn't cause problems because both loops below
735 * enforce pos <= pos_end and 0 <= pos
737 pos_type pos_end = par.size() - 1;
739 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
740 if (moveItem(par, pos, *tmp, j, bparams)) {
746 // Move over the end-of-par change information
747 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
748 par.setChange(par.size(), Change(bparams.track_changes ?
749 Change::INSERTED : Change::UNCHANGED));
752 // Make sure that we keep the language when
753 // breaking paragraph.
755 Font changed = tmp->getFirstFontSettings(bparams);
756 Font const & old = par.getFontSettings(bparams, par.size());
757 changed.setLanguage(old.language());
758 tmp->setFont(0, changed);
765 bool const soa = par.params().startOfAppendix();
766 par.params().clear();
767 // do not lose start of appendix marker (bug 4212)
768 par.params().startOfAppendix(soa);
769 par.setPlainOrDefaultLayout(bparams.documentClass());
773 par.setLayout(tmp->layout());
774 par.setLabelWidthString(tmp->params().labelWidthString());
775 par.params().depth(tmp->params().depth());
780 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
782 LBUFERR(this == cur.text());
784 Paragraph & cpar = cur.paragraph();
785 pit_type cpit = cur.pit();
787 DocumentClass const & tclass = cur.buffer()->params().documentClass();
788 Layout const & layout = cpar.layout();
790 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
791 if (changeDepthAllowed(cur, DEC_DEPTH)) {
792 changeDepth(cur, DEC_DEPTH);
793 pit_type const prev = depthHook(cpit, cpar.getDepth());
794 docstring const & lay = pars_[prev].layout().name();
795 if (lay != layout.name())
798 docstring const & lay = cur.paragraph().usePlainLayout()
799 ? tclass.plainLayoutName() : tclass.defaultLayoutName();
800 if (lay != layout.name())
808 // Always break behind a space
809 // It is better to erase the space (Dekel)
810 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
811 cpar.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
813 // What should the layout for the new paragraph be?
814 bool keep_layout = layout.isEnvironment()
815 || (layout.isParagraph() && layout.parbreak_is_newline);
817 keep_layout = !keep_layout;
819 // We need to remember this before we break the paragraph, because
820 // that invalidates the layout variable
821 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
823 // we need to set this before we insert the paragraph.
824 bool const isempty = cpar.allowEmpty() && cpar.empty();
826 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
828 // After this, neither paragraph contains any rows!
831 pit_type next_par = cpit + 1;
833 // well this is the caption hack since one caption is really enough
836 // set to standard-layout
837 //FIXME Check if this should be plainLayout() in some cases
838 pars_[cpit].applyLayout(tclass.defaultLayout());
840 // set to standard-layout
841 //FIXME Check if this should be plainLayout() in some cases
842 pars_[next_par].applyLayout(tclass.defaultLayout());
845 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
846 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().track_changes))
847 break; // the character couldn't be deleted physically due to change tracking
850 // A singlePar update is not enough in this case.
851 cur.screenUpdateFlags(Update::Force);
852 cur.forceBufferUpdate();
854 // This check is necessary. Otherwise the new empty paragraph will
855 // be deleted automatically. And it is more friendly for the user!
856 if (cur.pos() != 0 || isempty)
857 setCursor(cur, cur.pit() + 1, 0);
859 setCursor(cur, cur.pit(), 0);
863 // needed to insert the selection
864 void Text::insertStringAsLines(Cursor & cur, docstring const & str,
867 BufferParams const & bparams = owner_->buffer().params();
868 pit_type pit = cur.pit();
869 pos_type pos = cur.pos();
871 // insert the string, don't insert doublespace
872 bool space_inserted = true;
873 for (docstring::const_iterator cit = str.begin();
874 cit != str.end(); ++cit) {
875 Paragraph & par = pars_[pit];
877 if (inset().allowMultiPar() && (!par.empty() || par.allowEmpty())) {
878 lyx::breakParagraph(*this, pit, pos,
879 par.layout().isEnvironment());
882 space_inserted = true;
886 // do not insert consecutive spaces if !free_spacing
887 } else if ((*cit == ' ' || *cit == '\t') &&
888 space_inserted && !par.isFreeSpacing()) {
890 } else if (*cit == '\t') {
891 if (!par.isFreeSpacing()) {
892 // tabs are like spaces here
893 par.insertChar(pos, ' ', font, bparams.track_changes);
895 space_inserted = true;
897 par.insertChar(pos, *cit, font, bparams.track_changes);
899 space_inserted = true;
901 } else if (!isPrintable(*cit)) {
902 // Ignore unprintables
905 // just insert the character
906 par.insertChar(pos, *cit, font, bparams.track_changes);
908 space_inserted = (*cit == ' ');
911 setCursor(cur, pit, pos);
915 // turn double CR to single CR, others are converted into one
916 // blank. Then insertStringAsLines is called
917 void Text::insertStringAsParagraphs(Cursor & cur, docstring const & str,
920 docstring linestr = str;
921 bool newline_inserted = false;
923 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
924 if (linestr[i] == '\n') {
925 if (newline_inserted) {
926 // we know that \r will be ignored by
927 // insertStringAsLines. Of course, it is a dirty
928 // trick, but it works...
929 linestr[i - 1] = '\r';
933 newline_inserted = true;
935 } else if (isPrintable(linestr[i])) {
936 newline_inserted = false;
939 insertStringAsLines(cur, linestr, font);
945 bool canInsertChar(Cursor const & cur, char_type c)
947 Paragraph const & par = cur.paragraph();
948 // If not in free spacing mode, check if there will be two blanks together or a blank at
949 // the beginning of a paragraph.
950 if (!par.isFreeSpacing() && isLineSeparatorChar(c)) {
951 if (cur.pos() == 0) {
953 "You cannot insert a space at the "
954 "beginning of a paragraph. Please read the Tutorial."));
957 // If something is wrong, ignore this character.
958 LASSERT(cur.pos() > 0, return false);
959 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
960 && !par.isDeleted(cur.pos() - 1)) {
962 "You cannot type two spaces this way. "
963 "Please read the Tutorial."));
968 // Prevent to insert uncodable characters in verbatim and ERT.
969 // The encoding is inherited from the context here.
970 if (par.isPassThru() && cur.getEncoding()) {
971 Encoding const * e = cur.getEncoding();
972 if (!e->encodable(c)) {
973 cur.message(_("Character is uncodable in this verbatim context."));
983 // insert a character, moves all the following breaks in the
984 // same Paragraph one to the right and make a rebreak
985 void Text::insertChar(Cursor & cur, char_type c)
987 LBUFERR(this == cur.text());
989 if (!canInsertChar(cur,c))
992 cur.recordUndo(INSERT_UNDO);
994 TextMetrics const & tm = cur.bv().textMetrics(this);
995 Buffer const & buffer = *cur.buffer();
996 Paragraph & par = cur.paragraph();
997 // try to remove this
998 pit_type const pit = cur.pit();
1000 if (lyxrc.auto_number) {
1001 static docstring const number_operators = from_ascii("+-/*");
1002 static docstring const number_unary_operators = from_ascii("+-");
1004 // European Number Separators: comma, dot etc.
1005 // European Number Terminators: percent, permille, degree, euro etc.
1006 if (cur.current_font.fontInfo().number() == FONT_ON) {
1007 if (!isDigitASCII(c) && !contains(number_operators, c) &&
1008 !(isEuropeanNumberSeparator(c) &&
1010 cur.pos() != cur.lastpos() &&
1011 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
1012 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON) &&
1013 !(isEuropeanNumberTerminator(c) &&
1015 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
1016 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
1018 number(cur); // Set current_font.number to OFF
1019 } else if (isDigitASCII(c) &&
1020 cur.real_current_font.isVisibleRightToLeft()) {
1021 number(cur); // Set current_font.number to ON
1023 if (cur.pos() != 0) {
1024 char_type const ch = par.getChar(cur.pos() - 1);
1025 if (contains(number_unary_operators, ch) &&
1027 || par.isSeparator(cur.pos() - 2)
1028 || par.isEnvSeparator(cur.pos() - 2)
1029 || par.isNewline(cur.pos() - 2))
1031 setCharFont(pit, cur.pos() - 1, cur.current_font,
1033 } else if (isEuropeanNumberSeparator(ch)
1035 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
1036 setCharFont(pit, cur.pos() - 1, cur.current_font,
1043 // In Bidi text, we want spaces to be treated in a special way: spaces
1044 // which are between words in different languages should get the
1045 // paragraph's language; otherwise, spaces should keep the language
1046 // they were originally typed in. This is only in effect while typing;
1047 // after the text is already typed in, the user can always go back and
1048 // explicitly set the language of a space as desired. But 99.9% of the
1049 // time, what we're doing here is what the user actually meant.
1051 // The following cases are the ones in which the language of the space
1052 // should be changed to match that of the containing paragraph. In the
1053 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
1054 // represents a space, pipe (|) represents the cursor position (so the
1055 // character before it is the one just typed in). The different cases
1056 // are depicted logically (not visually), from left to right:
1061 // Theoretically, there are other situations that we should, perhaps, deal
1062 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
1063 // point (to understand why, just try to create this situation...).
1065 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
1066 // get font in front and behind the space in question. But do NOT
1067 // use getFont(cur.pos()) because the character c is not inserted yet
1068 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
1069 Font const & post_space_font = cur.real_current_font;
1070 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
1071 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
1073 if (pre_space_rtl != post_space_rtl) {
1074 // Set the space's language to match the language of the
1075 // adjacent character whose direction is the paragraph's
1076 // direction; don't touch other properties of the font
1077 Language const * lang =
1078 (pre_space_rtl == par.isRTL(buffer.params())) ?
1079 pre_space_font.language() : post_space_font.language();
1081 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
1082 space_font.setLanguage(lang);
1083 par.setFont(cur.pos() - 1, space_font);
1087 pos_type pos = cur.pos();
1088 if (!cur.paragraph().isPassThru() && owner_->lyxCode() != IPA_CODE &&
1089 cur.real_current_font.fontInfo().family() != TYPEWRITER_FAMILY &&
1090 c == '-' && pos > 0) {
1091 if (par.getChar(pos - 1) == '-') {
1092 // convert "--" to endash
1093 par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1096 } else if (par.getChar(pos - 1) == 0x2013) {
1097 // convert "---" to emdash
1098 par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1104 par.insertChar(pos, c, cur.current_font,
1105 cur.buffer()->params().track_changes);
1106 cur.checkBufferStructure();
1108 // cur.screenUpdateFlags(Update::Force);
1109 bool boundary = cur.boundary()
1110 || tm.isRTLBoundary(cur.pit(), pos + 1);
1111 setCursor(cur, cur.pit(), pos + 1, false, boundary);
1116 void Text::charInserted(Cursor & cur)
1118 Paragraph & par = cur.paragraph();
1120 // register word if a non-letter was entered
1122 && !par.isWordSeparator(cur.pos() - 2)
1123 && par.isWordSeparator(cur.pos() - 1)) {
1124 // get the word in front of cursor
1125 LBUFERR(this == cur.text());
1126 cur.paragraph().updateWords();
1131 // the cursor set functions have a special mechanism. When they
1132 // realize, that you left an empty paragraph, they will delete it.
1134 bool Text::cursorForwardOneWord(Cursor & cur)
1136 LBUFERR(this == cur.text());
1138 pos_type const lastpos = cur.lastpos();
1139 pit_type pit = cur.pit();
1140 pos_type pos = cur.pos();
1141 Paragraph const & par = cur.paragraph();
1143 // Paragraph boundary is a word boundary
1144 if (pos == lastpos || (pos + 1 == lastpos && par.isEnvSeparator(pos))) {
1145 if (pit != cur.lastpit())
1146 return setCursor(cur, pit + 1, 0);
1151 if (lyxrc.mac_like_cursor_movement) {
1152 // Skip through trailing punctuation and spaces.
1153 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1156 // Skip over either a non-char inset or a full word
1157 if (pos != lastpos && par.isWordSeparator(pos))
1159 else while (pos != lastpos && !par.isWordSeparator(pos))
1162 LASSERT(pos < lastpos, return false); // see above
1163 if (!par.isWordSeparator(pos))
1164 while (pos != lastpos && !par.isWordSeparator(pos))
1166 else if (par.isChar(pos))
1167 while (pos != lastpos && par.isChar(pos))
1169 else if (!par.isSpace(pos)) // non-char inset
1172 // Skip over white space
1173 while (pos != lastpos && par.isSpace(pos))
1177 // Don't skip a separator inset at the end of a paragraph
1178 if (pos == lastpos && pos && par.isEnvSeparator(pos - 1))
1181 return setCursor(cur, pit, pos);
1185 bool Text::cursorBackwardOneWord(Cursor & cur)
1187 LBUFERR(this == cur.text());
1189 pit_type pit = cur.pit();
1190 pos_type pos = cur.pos();
1191 Paragraph & par = cur.paragraph();
1193 // Paragraph boundary is a word boundary
1194 if (pos == 0 && pit != 0) {
1195 Paragraph & prevpar = getPar(pit - 1);
1196 pos = prevpar.size();
1197 // Don't stop after an environment separator
1198 if (pos && prevpar.isEnvSeparator(pos - 1))
1200 return setCursor(cur, pit - 1, pos);
1203 if (lyxrc.mac_like_cursor_movement) {
1204 // Skip through punctuation and spaces.
1205 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1208 // Skip over either a non-char inset or a full word
1209 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1211 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1214 // Skip over white space
1215 while (pos != 0 && par.isSpace(pos - 1))
1218 if (pos != 0 && !par.isWordSeparator(pos - 1))
1219 while (pos != 0 && !par.isWordSeparator(pos - 1))
1221 else if (pos != 0 && par.isChar(pos - 1))
1222 while (pos != 0 && par.isChar(pos - 1))
1224 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1228 return setCursor(cur, pit, pos);
1232 bool Text::cursorVisLeftOneWord(Cursor & cur)
1234 LBUFERR(this == cur.text());
1236 pos_type left_pos, right_pos;
1238 Cursor temp_cur = cur;
1240 // always try to move at least once...
1241 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1243 // collect some information about current cursor position
1244 temp_cur.getSurroundingPos(left_pos, right_pos);
1245 bool left_is_letter =
1246 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1247 bool right_is_letter =
1248 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1250 // if we're not at a letter/non-letter boundary, continue moving
1251 if (left_is_letter == right_is_letter)
1254 // we should stop when we have an LTR word on our right or an RTL word
1256 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1257 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1258 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1259 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1263 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1264 true, temp_cur.boundary());
1268 bool Text::cursorVisRightOneWord(Cursor & cur)
1270 LBUFERR(this == cur.text());
1272 pos_type left_pos, right_pos;
1274 Cursor temp_cur = cur;
1276 // always try to move at least once...
1277 while (temp_cur.posVisRight(true /* skip_inset */)) {
1279 // collect some information about current cursor position
1280 temp_cur.getSurroundingPos(left_pos, right_pos);
1281 bool left_is_letter =
1282 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1283 bool right_is_letter =
1284 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1286 // if we're not at a letter/non-letter boundary, continue moving
1287 if (left_is_letter == right_is_letter)
1290 // we should stop when we have an LTR word on our right or an RTL word
1292 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1293 temp_cur.buffer()->params(),
1294 left_pos).isRightToLeft())
1295 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1296 temp_cur.buffer()->params(),
1297 right_pos).isRightToLeft()))
1301 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1302 true, temp_cur.boundary());
1306 void Text::selectWord(Cursor & cur, word_location loc)
1308 LBUFERR(this == cur.text());
1309 CursorSlice from = cur.top();
1311 getWord(from, to, loc);
1312 if (cur.top() != from)
1313 setCursor(cur, from.pit(), from.pos());
1316 if (!cur.selection())
1318 setCursor(cur, to.pit(), to.pos());
1320 cur.setWordSelection(true);
1324 void Text::selectAll(Cursor & cur)
1326 LBUFERR(this == cur.text());
1327 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1329 // If the cursor is at the beginning, make sure the cursor ends there
1330 if (cur.pit() == 0 && cur.pos() == 0) {
1331 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1333 setCursor(cur, 0, 0);
1335 setCursor(cur, 0, 0);
1337 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1343 // Select the word currently under the cursor when no
1344 // selection is currently set
1345 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1347 LBUFERR(this == cur.text());
1348 if (cur.selection())
1350 selectWord(cur, loc);
1351 return cur.selection();
1355 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1357 LBUFERR(this == cur.text());
1359 if (!cur.selection()) {
1360 if (!selectChange(cur))
1364 cur.recordUndoSelection();
1366 pit_type begPit = cur.selectionBegin().pit();
1367 pit_type endPit = cur.selectionEnd().pit();
1369 pos_type begPos = cur.selectionBegin().pos();
1370 pos_type endPos = cur.selectionEnd().pos();
1372 // keep selection info, because endPos becomes invalid after the first loop
1373 bool const endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1375 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1376 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1377 pos_type parSize = pars_[pit].size();
1379 // ignore empty paragraphs; otherwise, an assertion will fail for
1380 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1384 // do not consider first paragraph if the cursor starts at pos size()
1385 if (pit == begPit && begPos == parSize)
1388 // do not consider last paragraph if the cursor ends at pos 0
1389 if (pit == endPit && endPos == 0)
1390 break; // last iteration anyway
1392 pos_type const left = (pit == begPit ? begPos : 0);
1393 pos_type const right = (pit == endPit ? endPos : parSize);
1396 // there is no change here
1400 pars_[pit].acceptChanges(left, right);
1402 pars_[pit].rejectChanges(left, right);
1406 // next, accept/reject imaginary end-of-par characters
1408 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1409 pos_type pos = pars_[pit].size();
1411 // skip if the selection ends before the end-of-par
1412 if (pit == endPit && endsBeforeEndOfPar)
1413 break; // last iteration anyway
1415 // skip if this is not the last paragraph of the document
1416 // note: the user should be able to accept/reject the par break of the last par!
1417 if (pit == endPit && pit + 1 != int(pars_.size()))
1418 break; // last iteration anway
1421 if (pars_[pit].isInserted(pos)) {
1422 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1423 } else if (pars_[pit].isDeleted(pos)) {
1424 if (pit + 1 == int(pars_.size())) {
1425 // we cannot remove a par break at the end of the last paragraph;
1426 // instead, we mark it unchanged
1427 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1429 mergeParagraph(cur.buffer()->params(), pars_, pit);
1435 if (pars_[pit].isDeleted(pos)) {
1436 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1437 } else if (pars_[pit].isInserted(pos)) {
1438 if (pit + 1 == int(pars_.size())) {
1439 // we mark the par break at the end of the last paragraph unchanged
1440 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1442 mergeParagraph(cur.buffer()->params(), pars_, pit);
1450 // finally, invoke the DEPM
1451 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().track_changes);
1454 cur.clearSelection();
1455 setCursorIntern(cur, begPit, begPos);
1456 cur.screenUpdateFlags(Update::Force);
1457 cur.forceBufferUpdate();
1461 void Text::acceptChanges()
1463 BufferParams const & bparams = owner_->buffer().params();
1464 lyx::acceptChanges(pars_, bparams);
1465 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.track_changes);
1469 void Text::rejectChanges()
1471 BufferParams const & bparams = owner_->buffer().params();
1472 pit_type pars_size = static_cast<pit_type>(pars_.size());
1474 // first, reject changes within each individual paragraph
1475 // (do not consider end-of-par)
1476 for (pit_type pit = 0; pit < pars_size; ++pit) {
1477 if (!pars_[pit].empty()) // prevent assertion failure
1478 pars_[pit].rejectChanges(0, pars_[pit].size());
1481 // next, reject imaginary end-of-par characters
1482 for (pit_type pit = 0; pit < pars_size; ++pit) {
1483 pos_type pos = pars_[pit].size();
1485 if (pars_[pit].isDeleted(pos)) {
1486 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1487 } else if (pars_[pit].isInserted(pos)) {
1488 if (pit == pars_size - 1) {
1489 // we mark the par break at the end of the last
1490 // paragraph unchanged
1491 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1493 mergeParagraph(bparams, pars_, pit);
1500 // finally, invoke the DEPM
1501 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.track_changes);
1505 void Text::deleteWordForward(Cursor & cur, bool const force)
1507 LBUFERR(this == cur.text());
1508 if (cur.lastpos() == 0)
1512 cur.selection(true);
1513 cursorForwardOneWord(cur);
1515 if (force || !cur.confirmDeletion()) {
1516 cutSelection(cur, false);
1517 cur.checkBufferStructure();
1523 void Text::deleteWordBackward(Cursor & cur, bool const force)
1525 LBUFERR(this == cur.text());
1526 if (cur.lastpos() == 0)
1527 cursorBackward(cur);
1530 cur.selection(true);
1531 cursorBackwardOneWord(cur);
1533 if (force || !cur.confirmDeletion()) {
1534 cutSelection(cur, false);
1535 cur.checkBufferStructure();
1541 // Kill to end of line.
1542 void Text::changeCase(Cursor & cur, TextCase action, bool partial)
1544 LBUFERR(this == cur.text());
1548 bool const gotsel = cur.selection();
1550 from = cur.selBegin();
1554 getWord(from, to, partial ? PARTIAL_WORD : WHOLE_WORD);
1555 cursorForwardOneWord(cur);
1558 cur.recordUndoSelection();
1560 pit_type begPit = from.pit();
1561 pit_type endPit = to.pit();
1563 pos_type begPos = from.pos();
1564 pos_type endPos = to.pos();
1566 pos_type right = 0; // needed after the for loop
1568 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1569 Paragraph & par = pars_[pit];
1570 pos_type const pos = (pit == begPit ? begPos : 0);
1571 right = (pit == endPit ? endPos : par.size());
1572 par.changeCase(cur.buffer()->params(), pos, right, action);
1575 // the selection may have changed due to logically-only deleted chars
1577 setCursor(cur, begPit, begPos);
1579 setCursor(cur, endPit, right);
1582 setCursor(cur, endPit, right);
1584 cur.checkBufferStructure();
1588 bool Text::handleBibitems(Cursor & cur)
1590 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1596 BufferParams const & bufparams = cur.buffer()->params();
1597 Paragraph const & par = cur.paragraph();
1598 Cursor prevcur = cur;
1599 if (cur.pit() > 0) {
1601 prevcur.pos() = prevcur.lastpos();
1603 Paragraph const & prevpar = prevcur.paragraph();
1605 // if a bibitem is deleted, merge with previous paragraph
1606 // if this is a bibliography item as well
1607 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1608 cur.recordUndo(prevcur.pit());
1609 mergeParagraph(bufparams, cur.text()->paragraphs(),
1611 cur.forceBufferUpdate();
1612 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1613 cur.screenUpdateFlags(Update::Force);
1617 // otherwise reset to default
1618 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1623 bool Text::erase(Cursor & cur)
1625 LASSERT(this == cur.text(), return false);
1626 bool needsUpdate = false;
1627 Paragraph & par = cur.paragraph();
1629 if (cur.pos() != cur.lastpos()) {
1630 // this is the code for a normal delete, not pasting
1632 cur.recordUndo(DELETE_UNDO);
1633 bool const was_inset = cur.paragraph().isInset(cur.pos());
1634 if(!par.eraseChar(cur.pos(), cur.buffer()->params().track_changes))
1635 // the character has been logically deleted only => skip it
1636 cur.top().forwardPos();
1639 cur.forceBufferUpdate();
1641 cur.checkBufferStructure();
1644 if (cur.pit() == cur.lastpit())
1645 return dissolveInset(cur);
1647 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1648 cur.recordUndo(DELETE_UNDO);
1649 par.setChange(cur.pos(), Change(Change::DELETED));
1653 setCursorIntern(cur, cur.pit() + 1, 0);
1654 needsUpdate = backspacePos0(cur);
1658 needsUpdate |= handleBibitems(cur);
1661 // Make sure the cursor is correct. Is this really needed?
1662 // No, not really... at least not here!
1663 cur.top().setPitPos(cur.pit(), cur.pos());
1664 cur.checkBufferStructure();
1671 bool Text::backspacePos0(Cursor & cur)
1673 LBUFERR(this == cur.text());
1677 bool needsUpdate = false;
1679 BufferParams const & bufparams = cur.buffer()->params();
1680 DocumentClass const & tclass = bufparams.documentClass();
1681 ParagraphList & plist = cur.text()->paragraphs();
1682 Paragraph const & par = cur.paragraph();
1683 Cursor prevcur = cur;
1685 prevcur.pos() = prevcur.lastpos();
1686 Paragraph const & prevpar = prevcur.paragraph();
1688 // is it an empty paragraph?
1689 if (cur.lastpos() == 0
1690 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1691 cur.recordUndo(prevcur.pit());
1692 plist.erase(lyx::next(plist.begin(), cur.pit()));
1695 // is previous par empty?
1696 else if (prevcur.lastpos() == 0
1697 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1698 cur.recordUndo(prevcur.pit());
1699 plist.erase(lyx::next(plist.begin(), prevcur.pit()));
1702 // FIXME: Do we really not want to allow this???
1703 // Pasting is not allowed, if the paragraphs have different
1704 // layouts. I think it is a real bug of all other
1705 // word processors to allow it. It confuses the user.
1706 // Correction: Pasting is always allowed with standard-layout
1707 // or the empty layout.
1708 else if (par.layout() == prevpar.layout()
1709 || tclass.isDefaultLayout(par.layout())
1710 || tclass.isPlainLayout(par.layout())) {
1711 cur.recordUndo(prevcur.pit());
1712 mergeParagraph(bufparams, plist, prevcur.pit());
1717 cur.forceBufferUpdate();
1718 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1725 bool Text::backspace(Cursor & cur)
1727 LBUFERR(this == cur.text());
1728 bool needsUpdate = false;
1729 if (cur.pos() == 0) {
1731 return dissolveInset(cur);
1733 Cursor prev_cur = cur;
1736 if (!prev_cur.paragraph().isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1737 cur.recordUndo(prev_cur.pit(), prev_cur.pit());
1738 prev_cur.paragraph().setChange(prev_cur.lastpos(), Change(Change::DELETED));
1739 setCursorIntern(cur, prev_cur.pit(), prev_cur.lastpos());
1742 // The cursor is at the beginning of a paragraph, so
1743 // the backspace will collapse two paragraphs into one.
1744 needsUpdate = backspacePos0(cur);
1747 // this is the code for a normal backspace, not pasting
1749 cur.recordUndo(DELETE_UNDO);
1750 // We used to do cursorBackwardIntern() here, but it is
1751 // not a good idea since it triggers the auto-delete
1752 // mechanism. So we do a cursorBackwardIntern()-lite,
1753 // without the dreaded mechanism. (JMarc)
1754 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1755 false, cur.boundary());
1756 bool const was_inset = cur.paragraph().isInset(cur.pos());
1757 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().track_changes);
1759 cur.forceBufferUpdate();
1761 cur.checkBufferStructure();
1764 if (cur.pos() == cur.lastpos())
1765 cur.setCurrentFont();
1767 needsUpdate |= handleBibitems(cur);
1769 // A singlePar update is not enough in this case.
1770 // cur.screenUpdateFlags(Update::Force);
1771 cur.top().setPitPos(cur.pit(), cur.pos());
1777 bool Text::dissolveInset(Cursor & cur)
1779 LASSERT(this == cur.text(), return false);
1781 if (isMainText() || cur.inset().nargs() != 1)
1784 cur.recordUndoInset();
1786 cur.selHandle(false);
1787 // save position inside inset
1788 pos_type spos = cur.pos();
1789 pit_type spit = cur.pit();
1790 ParagraphList plist;
1791 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1792 plist = paragraphs();
1794 // update cursor offset
1798 // remember position outside inset to delete inset later
1799 // we do not do it now to avoid memory reuse issues (see #10667).
1800 DocIterator inset_it = cur;
1804 Buffer & b = *cur.buffer();
1805 if (!plist.empty()) {
1807 // we clear the cache so that we won't get conflicts with labels
1808 // that get pasted into the buffer. we should update this before
1809 // its being empty matters. if not (i.e., if we encounter bugs),
1810 // then this should instead be:
1811 // cur.buffer().updateBuffer();
1812 // but we'll try the cheaper solution here.
1813 cur.buffer()->clearReferenceCache();
1815 // ERT paragraphs have the Language latex_language.
1816 // This is invalid outside of ERT, so we need to
1817 // change it to the buffer language.
1818 ParagraphList::iterator it = plist.begin();
1819 ParagraphList::iterator it_end = plist.end();
1820 for (; it != it_end; ++it)
1821 it->changeLanguage(b.params(), latex_language, b.language());
1823 /* If the inset is the only thing in paragraph and the layout
1824 * is not plain, then the layout of the first paragraph of
1825 * inset should be remembered.
1826 * FIXME: this does not work as expected when change tracking
1827 * is on However, we do not really know what to do in this
1830 DocumentClass const & tclass = cur.buffer()->params().documentClass();
1831 if (inset_it.lastpos() == 1
1832 && plist[0].layout().name() != tclass.plainLayoutName())
1833 cur.paragraph().makeSameLayout(plist[0]);
1835 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1836 b.errorList("Paste"));
1839 // delete the inset now
1840 inset_it.paragraph().eraseChar(inset_it.pos(), b.params().track_changes);
1843 cur.pit() = min(cur.lastpit(), spit);
1844 cur.pos() = min(cur.lastpos(), spos);
1845 // Ensure the current language is set correctly (bug 6292)
1846 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1847 cur.clearSelection();
1849 cur.forceBufferUpdate();
1855 void Text::getWord(CursorSlice & from, CursorSlice & to,
1856 word_location const loc) const
1859 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1863 void Text::write(ostream & os) const
1865 Buffer const & buf = owner_->buffer();
1866 ParagraphList::const_iterator pit = paragraphs().begin();
1867 ParagraphList::const_iterator end = paragraphs().end();
1869 for (; pit != end; ++pit)
1870 pit->write(os, buf.params(), dth);
1872 // Close begin_deeper
1873 for(; dth > 0; --dth)
1874 os << "\n\\end_deeper";
1878 bool Text::read(Lexer & lex,
1879 ErrorList & errorList, InsetText * insetPtr)
1881 Buffer const & buf = owner_->buffer();
1882 depth_type depth = 0;
1885 while (lex.isOK()) {
1887 string const token = lex.getString();
1892 if (token == "\\end_inset")
1895 if (token == "\\end_body")
1898 if (token == "\\begin_body")
1901 if (token == "\\end_document") {
1906 if (token == "\\begin_layout") {
1907 lex.pushToken(token);
1910 par.setInsetOwner(insetPtr);
1911 par.params().depth(depth);
1912 par.setFont(0, Font(inherit_font, buf.params().language));
1913 pars_.push_back(par);
1914 readParagraph(pars_.back(), lex, errorList);
1916 // register the words in the global word list
1917 pars_.back().updateWords();
1918 } else if (token == "\\begin_deeper") {
1920 } else if (token == "\\end_deeper") {
1922 lex.printError("\\end_deeper: " "depth is already null");
1926 LYXERR0("Handling unknown body token: `" << token << '\'');
1930 // avoid a crash on weird documents (bug 4859)
1931 if (pars_.empty()) {
1933 par.setInsetOwner(insetPtr);
1934 par.params().depth(depth);
1935 par.setFont(0, Font(inherit_font,
1936 buf.params().language));
1937 par.setPlainOrDefaultLayout(buf.params().documentClass());
1938 pars_.push_back(par);
1945 // Returns the current font and depth as a message.
1946 docstring Text::currentState(CursorData const & cur, bool devel_mode) const
1948 LBUFERR(this == cur.text());
1949 Buffer & buf = *cur.buffer();
1950 Paragraph const & par = cur.paragraph();
1951 odocstringstream os;
1953 if (buf.params().track_changes)
1954 os << _("[Change Tracking] ");
1956 Change change = par.lookupChange(cur.pos());
1958 if (change.changed()) {
1959 docstring const author =
1960 buf.params().authors().get(change.author).nameAndEmail();
1961 docstring const date = formatted_datetime(change.changetime);
1962 os << bformat(_("Changed by %1$s[[author]] on %2$s[[date]]. "),
1966 // I think we should only show changes from the default
1968 // No, from the document font (MV)
1969 Font font = cur.real_current_font;
1970 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1972 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1974 // The paragraph depth
1975 int depth = cur.paragraph().getDepth();
1977 os << bformat(_(", Depth: %1$d"), depth);
1979 // The paragraph spacing, but only if different from
1981 Spacing const & spacing = par.params().spacing();
1982 if (!spacing.isDefault()) {
1983 os << _(", Spacing: ");
1984 switch (spacing.getSpace()) {
1985 case Spacing::Single:
1988 case Spacing::Onehalf:
1991 case Spacing::Double:
1994 case Spacing::Other:
1995 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1997 case Spacing::Default:
1998 // should never happen, do nothing
2004 os << _(", Inset: ") << &cur.inset();
2005 if (cur.lastidx() > 0)
2006 os << _(", Cell: ") << cur.idx();
2007 os << _(", Paragraph: ") << cur.pit();
2008 os << _(", Id: ") << par.id();
2009 os << _(", Position: ") << cur.pos();
2010 // FIXME: Why is the check for par.size() needed?
2011 // We are called with cur.pos() == par.size() quite often.
2012 if (!par.empty() && cur.pos() < par.size()) {
2013 // Force output of code point, not character
2014 size_t const c = par.getChar(cur.pos());
2015 os << _(", Char: 0x") << hex << c;
2017 os << _(", Boundary: ") << cur.boundary();
2018 // Row & row = cur.textRow();
2019 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2025 docstring Text::getPossibleLabel(DocIterator const & cur) const
2027 pit_type textpit = cur.pit();
2028 Layout const * layout = &(pars_[textpit].layout());
2030 // Will contain the label prefix.
2033 // For captions, we just take the caption type
2034 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
2035 if (caption_inset) {
2036 string const & ftype = static_cast<InsetCaption *>(caption_inset)->floattype();
2037 FloatList const & fl = cur.buffer()->params().documentClass().floats();
2038 if (fl.typeExist(ftype)) {
2039 Floating const & flt = fl.getType(ftype);
2040 name = from_utf8(flt.refPrefix());
2043 name = from_utf8(ftype.substr(0,3));
2045 // For section, subsection, etc...
2046 if (layout->latextype == LATEX_PARAGRAPH && textpit != 0) {
2047 Layout const * layout2 = &(pars_[textpit - 1].layout());
2048 if (layout2->latextype != LATEX_PARAGRAPH) {
2053 if (layout->latextype != LATEX_PARAGRAPH)
2054 name = layout->refprefix;
2056 // If none of the above worked, see if the inset knows.
2058 InsetLayout const & il = cur.inset().getLayout();
2059 name = il.refprefix();
2064 docstring par_text = pars_[textpit].asString(AS_STR_SKIPDELETE);
2066 // The return string of math matrices might contain linebreaks
2067 par_text = subst(par_text, '\n', '-');
2068 int const numwords = 3;
2069 for (int i = 0; i < numwords; ++i) {
2070 if (par_text.empty())
2073 par_text = split(par_text, head, ' ');
2074 // Is it legal to use spaces in labels ?
2080 // Make sure it isn't too long
2081 unsigned int const max_label_length = 32;
2082 if (text.size() > max_label_length)
2083 text.resize(max_label_length);
2086 text = name + ':' + text;
2088 // We need a unique label
2089 docstring label = text;
2091 while (cur.buffer()->activeLabel(label)) {
2092 label = text + '-' + convert<docstring>(i);
2100 docstring Text::asString(int options) const
2102 return asString(0, pars_.size(), options);
2106 docstring Text::asString(pit_type beg, pit_type end, int options) const
2108 size_t i = size_t(beg);
2109 docstring str = pars_[i].asString(options);
2110 for (++i; i != size_t(end); ++i) {
2112 str += pars_[i].asString(options);
2118 void Text::shortenForOutliner(docstring & str, size_t const maxlen)
2120 support::truncateWithEllipsis(str, maxlen);
2121 for (char_type & c : str)
2122 if (c == L'\n' || c == L'\t')
2127 void Text::forOutliner(docstring & os, size_t const maxlen,
2128 bool const shorten) const
2130 pit_type end = pars_.size() - 1;
2131 if (0 <= end && !pars_[0].labelString().empty())
2132 os += pars_[0].labelString() + ' ';
2133 forOutliner(os, maxlen, 0, end, shorten);
2137 void Text::forOutliner(docstring & os, size_t const maxlen,
2138 pit_type pit_start, pit_type pit_end,
2139 bool const shorten) const
2141 size_t tmplen = shorten ? maxlen + 1 : maxlen;
2142 pit_type end = min(size_t(pit_end), pars_.size() - 1);
2144 for (pit_type i = pit_start; i <= end && os.length() < tmplen; ++i) {
2147 // This function lets the first label be treated separately
2148 pars_[i].forOutliner(os, tmplen, false, !first);
2152 shortenForOutliner(os, maxlen);
2156 void Text::charsTranspose(Cursor & cur)
2158 LBUFERR(this == cur.text());
2160 pos_type pos = cur.pos();
2162 // If cursor is at beginning or end of paragraph, do nothing.
2163 if (pos == cur.lastpos() || pos == 0)
2166 Paragraph & par = cur.paragraph();
2168 // Get the positions of the characters to be transposed.
2169 pos_type pos1 = pos - 1;
2170 pos_type pos2 = pos;
2172 // In change tracking mode, ignore deleted characters.
2173 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2175 if (pos2 == cur.lastpos())
2178 while (pos1 >= 0 && par.isDeleted(pos1))
2183 // Don't do anything if one of the "characters" is not regular text.
2184 if (par.isInset(pos1) || par.isInset(pos2))
2187 // Store the characters to be transposed (including font information).
2188 char_type const char1 = par.getChar(pos1);
2190 par.getFontSettings(cur.buffer()->params(), pos1);
2192 char_type const char2 = par.getChar(pos2);
2194 par.getFontSettings(cur.buffer()->params(), pos2);
2196 // And finally, we are ready to perform the transposition.
2197 // Track the changes if Change Tracking is enabled.
2198 bool const trackChanges = cur.buffer()->params().track_changes;
2202 par.eraseChar(pos2, trackChanges);
2203 par.eraseChar(pos1, trackChanges);
2204 par.insertChar(pos1, char2, font2, trackChanges);
2205 par.insertChar(pos2, char1, font1, trackChanges);
2207 cur.checkBufferStructure();
2209 // After the transposition, move cursor to after the transposition.
2210 setCursor(cur, cur.pit(), pos2);
2215 DocIterator Text::macrocontextPosition() const
2217 return macrocontext_position_;
2221 void Text::setMacrocontextPosition(DocIterator const & pos)
2223 macrocontext_position_ = pos;
2227 docstring Text::previousWord(CursorSlice const & sl) const
2229 CursorSlice from = sl;
2230 CursorSlice to = sl;
2231 getWord(from, to, PREVIOUS_WORD);
2232 if (sl == from || to == from)
2235 Paragraph const & par = sl.paragraph();
2236 return par.asString(from.pos(), to.pos());
2240 bool Text::completionSupported(Cursor const & cur) const
2242 Paragraph const & par = cur.paragraph();
2243 return !cur.selection()
2245 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2246 && !par.isWordSeparator(cur.pos() - 1);
2250 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2252 WordList const & list = theWordList(cur.getFont().language()->lang());
2253 return new TextCompletionList(cur, list);
2257 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2259 LBUFERR(cur.bv().cursor() == cur);
2261 cur.bv().cursor() = cur;
2262 if (!(cur.result().screenUpdate() & Update::Force))
2263 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2268 docstring Text::completionPrefix(Cursor const & cur) const
2270 return previousWord(cur.top());