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 static void acceptOrRejectChanges(ParagraphList & pars,
292 BufferParams const & bparams, Text::ChangeOp op)
294 pit_type pars_size = static_cast<pit_type>(pars.size());
296 // first, accept or reject changes within each individual
297 // paragraph (do not consider end-of-par)
298 for (pit_type pit = 0; pit < pars_size; ++pit) {
299 // prevent assertion failure
300 if (!pars[pit].empty()) {
301 if (op == Text::ACCEPT)
302 pars[pit].acceptChanges(0, pars[pit].size());
304 pars[pit].rejectChanges(0, pars[pit].size());
308 // next, accept or reject imaginary end-of-par characters
309 for (pit_type pit = 0; pit < pars_size; ++pit) {
310 pos_type pos = pars[pit].size();
311 if (pars[pit].isChanged(pos)) {
312 // keep the end-of-par char if it is inserted and accepted
313 // or when it is deleted and rejected.
314 if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
315 pars[pit].setChange(pos, Change(Change::UNCHANGED));
317 if (pit == pars_size - 1) {
318 // we cannot remove a par break at the end of the last
319 // paragraph; instead, we mark it unchanged
320 pars[pit].setChange(pos, Change(Change::UNCHANGED));
322 mergeParagraph(bparams, pars, pit);
332 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
334 acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
338 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
340 acceptOrRejectChanges(pars, bparams, Text::REJECT);
344 InsetText const & Text::inset() const
351 void Text::readParToken(Paragraph & par, Lexer & lex,
352 string const & token, Font & font, Change & change, ErrorList & errorList)
354 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
355 BufferParams & bp = buf->params();
357 if (token[0] != '\\') {
358 docstring dstr = lex.getDocString();
359 par.appendString(dstr, font, change);
361 } else if (token == "\\begin_layout") {
363 docstring layoutname = lex.getDocString();
365 font = Font(inherit_font, bp.language);
366 change = Change(Change::UNCHANGED);
368 DocumentClass const & tclass = bp.documentClass();
370 if (layoutname.empty())
371 layoutname = tclass.defaultLayoutName();
373 if (owner_->forcePlainLayout()) {
374 // in this case only the empty layout is allowed
375 layoutname = tclass.plainLayoutName();
376 } else if (par.usePlainLayout()) {
377 // in this case, default layout maps to empty layout
378 if (layoutname == tclass.defaultLayoutName())
379 layoutname = tclass.plainLayoutName();
381 // otherwise, the empty layout maps to the default
382 if (layoutname == tclass.plainLayoutName())
383 layoutname = tclass.defaultLayoutName();
386 // When we apply an unknown layout to a document, we add this layout to the textclass
387 // of this document. For example, when you apply class article to a beamer document,
388 // all unknown layouts such as frame will be added to document class article so that
389 // these layouts can keep their original names.
390 bool const added_one = tclass.addLayoutIfNeeded(layoutname);
393 docstring const s = bformat(_("Layout `%1$s' was not found."), layoutname);
394 errorList.push_back(ErrorItem(_("Layout Not Found"), s,
395 {par.id(), 0}, {par.id(), -1}));
398 par.setLayout(bp.documentClass()[layoutname]);
400 // Test whether the layout is obsolete.
401 Layout const & layout = par.layout();
402 if (!layout.obsoleted_by().empty())
403 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
405 par.params().read(lex);
407 } else if (token == "\\end_layout") {
408 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
409 << "Missing \\begin_layout ?");
410 } else if (token == "\\end_inset") {
411 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
412 << "Missing \\begin_inset ?");
413 } else if (token == "\\begin_inset") {
414 Inset * inset = readInset(lex, buf);
416 par.insertInset(par.size(), inset, font, change);
419 docstring line = lex.getDocString();
420 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
421 {par.id(), 0}, {par.id(), -1}));
423 } else if (token == "\\family") {
425 setLyXFamily(lex.getString(), font.fontInfo());
426 } else if (token == "\\series") {
428 setLyXSeries(lex.getString(), font.fontInfo());
429 } else if (token == "\\shape") {
431 setLyXShape(lex.getString(), font.fontInfo());
432 } else if (token == "\\size") {
434 setLyXSize(lex.getString(), font.fontInfo());
435 } else if (token == "\\lang") {
437 string const tok = lex.getString();
438 Language const * lang = languages.getLanguage(tok);
440 font.setLanguage(lang);
442 font.setLanguage(bp.language);
443 lex.printError("Unknown language `$$Token'");
445 } else if (token == "\\numeric") {
447 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
448 } else if (token == "\\emph") {
450 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
451 } else if (token == "\\bar") {
453 string const tok = lex.getString();
456 font.fontInfo().setUnderbar(FONT_ON);
457 else if (tok == "no")
458 font.fontInfo().setUnderbar(FONT_OFF);
459 else if (tok == "default")
460 font.fontInfo().setUnderbar(FONT_INHERIT);
462 lex.printError("Unknown bar font flag "
464 } else if (token == "\\strikeout") {
466 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
467 } else if (token == "\\xout") {
469 font.fontInfo().setXout(setLyXMisc(lex.getString()));
470 } else if (token == "\\uuline") {
472 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
473 } else if (token == "\\uwave") {
475 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
476 } else if (token == "\\noun") {
478 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
479 } else if (token == "\\color") {
481 setLyXColor(lex.getString(), font.fontInfo());
482 } else if (token == "\\SpecialChar" ||
483 (token == "\\SpecialCharNoPassThru" &&
484 !par.layout().pass_thru && !inset().isPassThru())) {
485 auto inset = make_unique<InsetSpecialChar>();
487 inset->setBuffer(*buf);
488 par.insertInset(par.size(), inset.release(), font, change);
489 } else if (token == "\\SpecialCharNoPassThru") {
491 docstring const s = ltrim(lex.getDocString(), "\\");
492 par.insert(par.size(), s, font, change);
493 } else if (token == "\\IPAChar") {
494 auto inset = make_unique<InsetIPAChar>();
496 inset->setBuffer(*buf);
497 par.insertInset(par.size(), inset.release(), font, change);
498 } else if (token == "\\twohyphens" || token == "\\threehyphens") {
499 // Ideally, this should be done by lyx2lyx, but lyx2lyx does not know the
500 // running font and does not know anything about layouts (and CopyStyle).
501 Layout const & layout(par.layout());
502 FontInfo info = font.fontInfo();
503 info.realize(layout.resfont);
504 if (layout.pass_thru || inset().isPassThru() ||
505 info.family() == TYPEWRITER_FAMILY) {
506 if (token == "\\twohyphens")
507 par.insert(par.size(), from_ascii("--"), font, change);
509 par.insert(par.size(), from_ascii("---"), font, change);
511 if (token == "\\twohyphens")
512 par.insertChar(par.size(), 0x2013, font, change);
514 par.insertChar(par.size(), 0x2014, font, change);
516 } else if (token == "\\backslash") {
517 par.appendChar('\\', font, change);
518 } else if (token == "\\LyXTable") {
519 auto inset = make_unique<InsetTabular>(buf);
521 par.insertInset(par.size(), inset.release(), font, change);
522 } else if (token == "\\change_unchanged") {
523 change = Change(Change::UNCHANGED);
524 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
526 istringstream is(lex.getString());
530 BufferParams::AuthorMap const & am = bp.author_map_;
531 if (am.find(aid) == am.end()) {
532 errorList.push_back(ErrorItem(
533 _("Change tracking author index missing"),
534 bformat(_("A change tracking author information for index "
535 "%1$d is missing. This can happen after a wrong "
536 "merge by a version control system. In this case, "
537 "either fix the merge, or have this information "
538 "missing until the corresponding tracked changes "
539 "are merged or this user edits the file again.\n"),
541 {par.id(), par.size()}, {par.id(), par.size() + 1}));
542 bp.addAuthor(Author(aid));
544 if (token == "\\change_inserted")
545 change = Change(Change::INSERTED, am.find(aid)->second, ct);
547 change = Change(Change::DELETED, am.find(aid)->second, ct);
550 errorList.push_back(ErrorItem(_("Unknown token"),
551 bformat(_("Unknown token: %1$s %2$s\n"),
554 {par.id(), 0}, {par.id(), -1}));
559 void Text::readParagraph(Paragraph & par, Lexer & lex,
560 ErrorList & errorList)
563 string token = lex.getString();
565 Change change(Change::UNCHANGED);
568 readParToken(par, lex, token, font, change, errorList);
571 token = lex.getString();
576 if (token == "\\end_layout") {
577 //Ok, paragraph finished
581 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
582 if (token == "\\begin_layout" || token == "\\end_document"
583 || token == "\\end_inset" || token == "\\begin_deeper"
584 || token == "\\end_deeper") {
585 lex.pushToken(token);
586 lyxerr << "Paragraph ended in line "
587 << lex.lineNumber() << "\n"
588 << "Missing \\end_layout.\n";
592 // Final change goes to paragraph break:
593 par.setChange(par.size(), change);
595 // Initialize begin_of_body_ on load; redoParagraph maintains
596 par.setBeginOfBody();
598 // mark paragraph for spell checking on load
599 // par.requestSpellCheck();
603 class TextCompletionList : public CompletionList
607 TextCompletionList(Cursor const & cur, WordList const & list)
608 : buffer_(cur.buffer()), list_(list)
611 virtual ~TextCompletionList() {}
614 virtual bool sorted() const { return true; }
616 virtual size_t size() const
621 virtual docstring const & data(size_t idx) const
623 return list_.word(idx);
628 Buffer const * buffer_;
630 WordList const & list_;
634 bool Text::empty() const
636 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
637 // FIXME: Should we consider the labeled type as empty too?
638 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
642 double Text::spacing(Paragraph const & par) const
644 if (par.params().spacing().isDefault())
645 return owner_->buffer().params().spacing().getValue();
646 return par.params().spacing().getValue();
651 * This breaks a paragraph at the specified position.
652 * The new paragraph will:
653 * - Decrease depth by one (or change layout to default layout) when
654 * keep_layout == false
655 * - keep current depth and layout when keep_layout == true
657 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
660 BufferParams const & bparams = text.inset().buffer().params();
661 ParagraphList & pars = text.paragraphs();
662 // create a new paragraph, and insert into the list
663 ParagraphList::iterator tmp =
664 pars.insert(lyx::next(pars.begin(), par_offset + 1),
667 Paragraph & par = pars[par_offset];
669 // remember to set the inset_owner
670 tmp->setInsetOwner(&par.inInset());
671 // without doing that we get a crash when typing <Return> at the
672 // end of a paragraph
673 tmp->setPlainOrDefaultLayout(bparams.documentClass());
676 tmp->setLayout(par.layout());
677 tmp->setLabelWidthString(par.params().labelWidthString());
678 tmp->params().depth(par.params().depth());
679 } else if (par.params().depth() > 0) {
680 Paragraph const & hook = pars[text.outerHook(par_offset)];
681 tmp->setLayout(hook.layout());
682 // not sure the line below is useful
683 tmp->setLabelWidthString(par.params().labelWidthString());
684 tmp->params().depth(hook.params().depth());
687 bool const isempty = (par.allowEmpty() && par.empty());
689 if (!isempty && (par.size() > pos || par.empty())) {
690 tmp->setLayout(par.layout());
691 tmp->params().align(par.params().align());
692 tmp->setLabelWidthString(par.params().labelWidthString());
694 tmp->params().depth(par.params().depth());
695 tmp->params().noindent(par.params().noindent());
697 // move everything behind the break position
698 // to the new paragraph
700 /* Note: if !keepempty, empty() == true, then we reach
701 * here with size() == 0. So pos_end becomes - 1. This
702 * doesn't cause problems because both loops below
703 * enforce pos <= pos_end and 0 <= pos
705 pos_type pos_end = par.size() - 1;
707 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
708 if (moveItem(par, pos, *tmp, j, bparams)) {
714 // Move over the end-of-par change information
715 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
716 par.setChange(par.size(), Change(bparams.track_changes ?
717 Change::INSERTED : Change::UNCHANGED));
720 // Make sure that we keep the language when
721 // breaking paragraph.
723 Font changed = tmp->getFirstFontSettings(bparams);
724 Font const & old = par.getFontSettings(bparams, par.size());
725 changed.setLanguage(old.language());
726 tmp->setFont(0, changed);
733 bool const soa = par.params().startOfAppendix();
734 par.params().clear();
735 // do not lose start of appendix marker (bug 4212)
736 par.params().startOfAppendix(soa);
737 par.setPlainOrDefaultLayout(bparams.documentClass());
741 par.setLayout(tmp->layout());
742 par.setLabelWidthString(tmp->params().labelWidthString());
743 par.params().depth(tmp->params().depth());
748 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
750 LBUFERR(this == cur.text());
752 Paragraph & cpar = cur.paragraph();
753 pit_type cpit = cur.pit();
755 DocumentClass const & tclass = cur.buffer()->params().documentClass();
756 Layout const & layout = cpar.layout();
758 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
759 if (changeDepthAllowed(cur, DEC_DEPTH)) {
760 changeDepth(cur, DEC_DEPTH);
761 pit_type const prev = depthHook(cpit, cpar.getDepth());
762 docstring const & lay = pars_[prev].layout().name();
763 if (lay != layout.name())
766 docstring const & lay = cur.paragraph().usePlainLayout()
767 ? tclass.plainLayoutName() : tclass.defaultLayoutName();
768 if (lay != layout.name())
776 // Always break behind a space
777 // It is better to erase the space (Dekel)
778 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
779 cpar.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
781 // What should the layout for the new paragraph be?
782 bool keep_layout = layout.isEnvironment()
783 || (layout.isParagraph() && layout.parbreak_is_newline);
785 keep_layout = !keep_layout;
787 // We need to remember this before we break the paragraph, because
788 // that invalidates the layout variable
789 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
791 // we need to set this before we insert the paragraph.
792 bool const isempty = cpar.allowEmpty() && cpar.empty();
794 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
796 // After this, neither paragraph contains any rows!
799 pit_type next_par = cpit + 1;
801 // well this is the caption hack since one caption is really enough
804 // set to standard-layout
805 //FIXME Check if this should be plainLayout() in some cases
806 pars_[cpit].applyLayout(tclass.defaultLayout());
808 // set to standard-layout
809 //FIXME Check if this should be plainLayout() in some cases
810 pars_[next_par].applyLayout(tclass.defaultLayout());
813 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
814 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().track_changes))
815 break; // the character couldn't be deleted physically due to change tracking
818 // A singlePar update is not enough in this case.
819 cur.screenUpdateFlags(Update::Force);
820 cur.forceBufferUpdate();
822 // This check is necessary. Otherwise the new empty paragraph will
823 // be deleted automatically. And it is more friendly for the user!
824 if (cur.pos() != 0 || isempty)
825 setCursor(cur, cur.pit() + 1, 0);
827 setCursor(cur, cur.pit(), 0);
831 // needed to insert the selection
832 void Text::insertStringAsLines(Cursor & cur, docstring const & str,
835 BufferParams const & bparams = owner_->buffer().params();
836 pit_type pit = cur.pit();
837 pos_type pos = cur.pos();
839 // insert the string, don't insert doublespace
840 bool space_inserted = true;
841 for (docstring::const_iterator cit = str.begin();
842 cit != str.end(); ++cit) {
843 Paragraph & par = pars_[pit];
845 if (inset().allowMultiPar() && (!par.empty() || par.allowEmpty())) {
846 lyx::breakParagraph(*this, pit, pos,
847 par.layout().isEnvironment());
850 space_inserted = true;
854 // do not insert consecutive spaces if !free_spacing
855 } else if ((*cit == ' ' || *cit == '\t') &&
856 space_inserted && !par.isFreeSpacing()) {
858 } else if (*cit == '\t') {
859 if (!par.isFreeSpacing()) {
860 // tabs are like spaces here
861 par.insertChar(pos, ' ', font, bparams.track_changes);
863 space_inserted = true;
865 par.insertChar(pos, *cit, font, bparams.track_changes);
867 space_inserted = true;
869 } else if (!isPrintable(*cit)) {
870 // Ignore unprintables
873 // just insert the character
874 par.insertChar(pos, *cit, font, bparams.track_changes);
876 space_inserted = (*cit == ' ');
879 setCursor(cur, pit, pos);
883 // turn double CR to single CR, others are converted into one
884 // blank. Then insertStringAsLines is called
885 void Text::insertStringAsParagraphs(Cursor & cur, docstring const & str,
888 docstring linestr = str;
889 bool newline_inserted = false;
891 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
892 if (linestr[i] == '\n') {
893 if (newline_inserted) {
894 // we know that \r will be ignored by
895 // insertStringAsLines. Of course, it is a dirty
896 // trick, but it works...
897 linestr[i - 1] = '\r';
901 newline_inserted = true;
903 } else if (isPrintable(linestr[i])) {
904 newline_inserted = false;
907 insertStringAsLines(cur, linestr, font);
913 bool canInsertChar(Cursor const & cur, char_type c)
915 Paragraph const & par = cur.paragraph();
916 // If not in free spacing mode, check if there will be two blanks together or a blank at
917 // the beginning of a paragraph.
918 if (!par.isFreeSpacing() && isLineSeparatorChar(c)) {
919 if (cur.pos() == 0) {
921 "You cannot insert a space at the "
922 "beginning of a paragraph. Please read the Tutorial."));
925 // LASSERT: Is it safe to continue here?
926 LASSERT(cur.pos() > 0, /**/);
927 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
928 && !par.isDeleted(cur.pos() - 1)) {
930 "You cannot type two spaces this way. "
931 "Please read the Tutorial."));
936 // Prevent to insert uncodable characters in verbatim and ERT.
937 // The encoding is inherited from the context here.
938 if (par.isPassThru() && cur.getEncoding()) {
939 Encoding const * e = cur.getEncoding();
940 if (!e->encodable(c)) {
941 cur.message(_("Character is uncodable in this verbatim context."));
951 // insert a character, moves all the following breaks in the
952 // same Paragraph one to the right and make a rebreak
953 void Text::insertChar(Cursor & cur, char_type c)
955 LBUFERR(this == cur.text());
957 if (!canInsertChar(cur,c))
960 cur.recordUndo(INSERT_UNDO);
962 TextMetrics const & tm = cur.bv().textMetrics(this);
963 Buffer const & buffer = *cur.buffer();
964 Paragraph & par = cur.paragraph();
965 // try to remove this
966 pit_type const pit = cur.pit();
968 if (lyxrc.auto_number) {
969 static docstring const number_operators = from_ascii("+-/*");
970 static docstring const number_unary_operators = from_ascii("+-");
971 static docstring const number_separators = from_ascii(".,:");
973 if (cur.current_font.fontInfo().number() == FONT_ON) {
974 if (!isDigitASCII(c) && !contains(number_operators, c) &&
975 !(contains(number_separators, c) &&
977 cur.pos() != cur.lastpos() &&
978 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
979 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
981 number(cur); // Set current_font.number to OFF
982 } else if (isDigitASCII(c) &&
983 cur.real_current_font.isVisibleRightToLeft()) {
984 number(cur); // Set current_font.number to ON
986 if (cur.pos() != 0) {
987 char_type const ch = par.getChar(cur.pos() - 1);
988 if (contains(number_unary_operators, ch) &&
990 || par.isSeparator(cur.pos() - 2)
991 || par.isEnvSeparator(cur.pos() - 2)
992 || par.isNewline(cur.pos() - 2))
994 setCharFont(pit, cur.pos() - 1, cur.current_font,
996 } else if (contains(number_separators, ch)
998 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
999 setCharFont(pit, cur.pos() - 1, cur.current_font,
1006 // In Bidi text, we want spaces to be treated in a special way: spaces
1007 // which are between words in different languages should get the
1008 // paragraph's language; otherwise, spaces should keep the language
1009 // they were originally typed in. This is only in effect while typing;
1010 // after the text is already typed in, the user can always go back and
1011 // explicitly set the language of a space as desired. But 99.9% of the
1012 // time, what we're doing here is what the user actually meant.
1014 // The following cases are the ones in which the language of the space
1015 // should be changed to match that of the containing paragraph. In the
1016 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
1017 // represents a space, pipe (|) represents the cursor position (so the
1018 // character before it is the one just typed in). The different cases
1019 // are depicted logically (not visually), from left to right:
1024 // Theoretically, there are other situations that we should, perhaps, deal
1025 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
1026 // point (to understand why, just try to create this situation...).
1028 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
1029 // get font in front and behind the space in question. But do NOT
1030 // use getFont(cur.pos()) because the character c is not inserted yet
1031 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
1032 Font const & post_space_font = cur.real_current_font;
1033 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
1034 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
1036 if (pre_space_rtl != post_space_rtl) {
1037 // Set the space's language to match the language of the
1038 // adjacent character whose direction is the paragraph's
1039 // direction; don't touch other properties of the font
1040 Language const * lang =
1041 (pre_space_rtl == par.isRTL(buffer.params())) ?
1042 pre_space_font.language() : post_space_font.language();
1044 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
1045 space_font.setLanguage(lang);
1046 par.setFont(cur.pos() - 1, space_font);
1050 pos_type pos = cur.pos();
1051 if (!cur.paragraph().isPassThru() && owner_->lyxCode() != IPA_CODE &&
1052 cur.real_current_font.fontInfo().family() != TYPEWRITER_FAMILY &&
1053 c == '-' && pos > 0) {
1054 if (par.getChar(pos - 1) == '-') {
1055 // convert "--" to endash
1056 par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1059 } else if (par.getChar(pos - 1) == 0x2013) {
1060 // convert "---" to emdash
1061 par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1067 par.insertChar(pos, c, cur.current_font,
1068 cur.buffer()->params().track_changes);
1069 cur.checkBufferStructure();
1071 // cur.screenUpdateFlags(Update::Force);
1072 bool boundary = cur.boundary()
1073 || tm.isRTLBoundary(cur.pit(), pos + 1);
1074 setCursor(cur, cur.pit(), pos + 1, false, boundary);
1079 void Text::charInserted(Cursor & cur)
1081 Paragraph & par = cur.paragraph();
1083 // register word if a non-letter was entered
1085 && !par.isWordSeparator(cur.pos() - 2)
1086 && par.isWordSeparator(cur.pos() - 1)) {
1087 // get the word in front of cursor
1088 LBUFERR(this == cur.text());
1089 cur.paragraph().updateWords();
1094 // the cursor set functions have a special mechanism. When they
1095 // realize, that you left an empty paragraph, they will delete it.
1097 bool Text::cursorForwardOneWord(Cursor & cur)
1099 LBUFERR(this == cur.text());
1101 pos_type const lastpos = cur.lastpos();
1102 pit_type pit = cur.pit();
1103 pos_type pos = cur.pos();
1104 Paragraph const & par = cur.paragraph();
1106 // Paragraph boundary is a word boundary
1107 if (pos == lastpos || (pos + 1 == lastpos && par.isEnvSeparator(pos))) {
1108 if (pit != cur.lastpit())
1109 return setCursor(cur, pit + 1, 0);
1114 if (lyxrc.mac_like_cursor_movement) {
1115 // Skip through trailing punctuation and spaces.
1116 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1119 // Skip over either a non-char inset or a full word
1120 if (pos != lastpos && par.isWordSeparator(pos))
1122 else while (pos != lastpos && !par.isWordSeparator(pos))
1125 LASSERT(pos < lastpos, return false); // see above
1126 if (!par.isWordSeparator(pos))
1127 while (pos != lastpos && !par.isWordSeparator(pos))
1129 else if (par.isChar(pos))
1130 while (pos != lastpos && par.isChar(pos))
1132 else if (!par.isSpace(pos)) // non-char inset
1135 // Skip over white space
1136 while (pos != lastpos && par.isSpace(pos))
1140 // Don't skip a separator inset at the end of a paragraph
1141 if (pos == lastpos && pos && par.isEnvSeparator(pos - 1))
1144 return setCursor(cur, pit, pos);
1148 bool Text::cursorBackwardOneWord(Cursor & cur)
1150 LBUFERR(this == cur.text());
1152 pit_type pit = cur.pit();
1153 pos_type pos = cur.pos();
1154 Paragraph & par = cur.paragraph();
1156 // Paragraph boundary is a word boundary
1157 if (pos == 0 && pit != 0) {
1158 Paragraph & prevpar = getPar(pit - 1);
1159 pos = prevpar.size();
1160 // Don't stop after an environment separator
1161 if (pos && prevpar.isEnvSeparator(pos - 1))
1163 return setCursor(cur, pit - 1, pos);
1166 if (lyxrc.mac_like_cursor_movement) {
1167 // Skip through punctuation and spaces.
1168 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1171 // Skip over either a non-char inset or a full word
1172 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1174 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1177 // Skip over white space
1178 while (pos != 0 && par.isSpace(pos - 1))
1181 if (pos != 0 && !par.isWordSeparator(pos - 1))
1182 while (pos != 0 && !par.isWordSeparator(pos - 1))
1184 else if (pos != 0 && par.isChar(pos - 1))
1185 while (pos != 0 && par.isChar(pos - 1))
1187 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1191 return setCursor(cur, pit, pos);
1195 bool Text::cursorVisLeftOneWord(Cursor & cur)
1197 LBUFERR(this == cur.text());
1199 pos_type left_pos, right_pos;
1201 Cursor temp_cur = cur;
1203 // always try to move at least once...
1204 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1206 // collect some information about current cursor position
1207 temp_cur.getSurroundingPos(left_pos, right_pos);
1208 bool left_is_letter =
1209 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1210 bool right_is_letter =
1211 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1213 // if we're not at a letter/non-letter boundary, continue moving
1214 if (left_is_letter == right_is_letter)
1217 // we should stop when we have an LTR word on our right or an RTL word
1219 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1220 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1221 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1222 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1226 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1227 true, temp_cur.boundary());
1231 bool Text::cursorVisRightOneWord(Cursor & cur)
1233 LBUFERR(this == cur.text());
1235 pos_type left_pos, right_pos;
1237 Cursor temp_cur = cur;
1239 // always try to move at least once...
1240 while (temp_cur.posVisRight(true /* skip_inset */)) {
1242 // collect some information about current cursor position
1243 temp_cur.getSurroundingPos(left_pos, right_pos);
1244 bool left_is_letter =
1245 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1246 bool right_is_letter =
1247 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1249 // if we're not at a letter/non-letter boundary, continue moving
1250 if (left_is_letter == right_is_letter)
1253 // we should stop when we have an LTR word on our right or an RTL word
1255 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1256 temp_cur.buffer()->params(),
1257 left_pos).isRightToLeft())
1258 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1259 temp_cur.buffer()->params(),
1260 right_pos).isRightToLeft()))
1264 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1265 true, temp_cur.boundary());
1269 void Text::selectWord(Cursor & cur, word_location loc)
1271 LBUFERR(this == cur.text());
1272 CursorSlice from = cur.top();
1274 getWord(from, to, loc);
1275 if (cur.top() != from)
1276 setCursor(cur, from.pit(), from.pos());
1279 if (!cur.selection())
1281 setCursor(cur, to.pit(), to.pos());
1283 cur.setWordSelection(true);
1287 void Text::selectAll(Cursor & cur)
1289 LBUFERR(this == cur.text());
1290 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1292 // If the cursor is at the beginning, make sure the cursor ends there
1293 if (cur.pit() == 0 && cur.pos() == 0) {
1294 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1296 setCursor(cur, 0, 0);
1298 setCursor(cur, 0, 0);
1300 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1306 // Select the word currently under the cursor when no
1307 // selection is currently set
1308 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1310 LBUFERR(this == cur.text());
1311 if (cur.selection())
1313 selectWord(cur, loc);
1314 return cur.selection();
1318 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1320 LBUFERR(this == cur.text());
1322 if (!cur.selection()) {
1323 if (!selectChange(cur))
1327 cur.recordUndoSelection();
1329 pit_type begPit = cur.selectionBegin().pit();
1330 pit_type endPit = cur.selectionEnd().pit();
1332 pos_type begPos = cur.selectionBegin().pos();
1333 pos_type endPos = cur.selectionEnd().pos();
1335 // keep selection info, because endPos becomes invalid after the first loop
1336 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1338 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1339 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1340 pos_type parSize = pars_[pit].size();
1342 // ignore empty paragraphs; otherwise, an assertion will fail for
1343 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1347 // do not consider first paragraph if the cursor starts at pos size()
1348 if (pit == begPit && begPos == parSize)
1351 // do not consider last paragraph if the cursor ends at pos 0
1352 if (pit == endPit && endPos == 0)
1353 break; // last iteration anyway
1355 pos_type left = (pit == begPit ? begPos : 0);
1356 pos_type right = (pit == endPit ? endPos : parSize);
1359 // there is no change here
1363 pars_[pit].acceptChanges(left, right);
1365 pars_[pit].rejectChanges(left, right);
1369 // next, accept/reject imaginary end-of-par characters
1371 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1372 pos_type pos = pars_[pit].size();
1374 // skip if the selection ends before the end-of-par
1375 if (pit == endPit && endsBeforeEndOfPar)
1376 break; // last iteration anyway
1378 // skip if this is not the last paragraph of the document
1379 // note: the user should be able to accept/reject the par break of the last par!
1380 if (pit == endPit && pit + 1 != int(pars_.size()))
1381 break; // last iteration anway
1384 if (pars_[pit].isInserted(pos)) {
1385 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1386 } else if (pars_[pit].isDeleted(pos)) {
1387 if (pit + 1 == int(pars_.size())) {
1388 // we cannot remove a par break at the end of the last paragraph;
1389 // instead, we mark it unchanged
1390 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1392 mergeParagraph(cur.buffer()->params(), pars_, pit);
1398 if (pars_[pit].isDeleted(pos)) {
1399 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1400 } else if (pars_[pit].isInserted(pos)) {
1401 if (pit + 1 == int(pars_.size())) {
1402 // we mark the par break at the end of the last paragraph unchanged
1403 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1405 mergeParagraph(cur.buffer()->params(), pars_, pit);
1413 // finally, invoke the DEPM
1414 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().track_changes);
1417 cur.clearSelection();
1418 setCursorIntern(cur, begPit, begPos);
1419 cur.screenUpdateFlags(Update::Force);
1420 cur.forceBufferUpdate();
1424 void Text::acceptChanges()
1426 BufferParams const & bparams = owner_->buffer().params();
1427 lyx::acceptChanges(pars_, bparams);
1428 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.track_changes);
1432 void Text::rejectChanges()
1434 BufferParams const & bparams = owner_->buffer().params();
1435 pit_type pars_size = static_cast<pit_type>(pars_.size());
1437 // first, reject changes within each individual paragraph
1438 // (do not consider end-of-par)
1439 for (pit_type pit = 0; pit < pars_size; ++pit) {
1440 if (!pars_[pit].empty()) // prevent assertion failure
1441 pars_[pit].rejectChanges(0, pars_[pit].size());
1444 // next, reject imaginary end-of-par characters
1445 for (pit_type pit = 0; pit < pars_size; ++pit) {
1446 pos_type pos = pars_[pit].size();
1448 if (pars_[pit].isDeleted(pos)) {
1449 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1450 } else if (pars_[pit].isInserted(pos)) {
1451 if (pit == pars_size - 1) {
1452 // we mark the par break at the end of the last
1453 // paragraph unchanged
1454 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1456 mergeParagraph(bparams, pars_, pit);
1463 // finally, invoke the DEPM
1464 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.track_changes);
1468 void Text::deleteWordForward(Cursor & cur, bool const force)
1470 LBUFERR(this == cur.text());
1471 if (cur.lastpos() == 0)
1475 cur.selection(true);
1476 cursorForwardOneWord(cur);
1478 if (force || !cur.confirmDeletion()) {
1479 cutSelection(cur, true, false);
1480 cur.checkBufferStructure();
1486 void Text::deleteWordBackward(Cursor & cur, bool const force)
1488 LBUFERR(this == cur.text());
1489 if (cur.lastpos() == 0)
1490 cursorBackward(cur);
1493 cur.selection(true);
1494 cursorBackwardOneWord(cur);
1496 if (force || !cur.confirmDeletion()) {
1497 cutSelection(cur, true, false);
1498 cur.checkBufferStructure();
1504 // Kill to end of line.
1505 void Text::changeCase(Cursor & cur, TextCase action, bool partial)
1507 LBUFERR(this == cur.text());
1511 bool const gotsel = cur.selection();
1513 from = cur.selBegin();
1517 getWord(from, to, partial ? PARTIAL_WORD : WHOLE_WORD);
1518 cursorForwardOneWord(cur);
1521 cur.recordUndoSelection();
1523 pit_type begPit = from.pit();
1524 pit_type endPit = to.pit();
1526 pos_type begPos = from.pos();
1527 pos_type endPos = to.pos();
1529 pos_type right = 0; // needed after the for loop
1531 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1532 Paragraph & par = pars_[pit];
1533 pos_type const pos = (pit == begPit ? begPos : 0);
1534 right = (pit == endPit ? endPos : par.size());
1535 par.changeCase(cur.buffer()->params(), pos, right, action);
1538 // the selection may have changed due to logically-only deleted chars
1540 setCursor(cur, begPit, begPos);
1542 setCursor(cur, endPit, right);
1545 setCursor(cur, endPit, right);
1547 cur.checkBufferStructure();
1551 bool Text::handleBibitems(Cursor & cur)
1553 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1559 BufferParams const & bufparams = cur.buffer()->params();
1560 Paragraph const & par = cur.paragraph();
1561 Cursor prevcur = cur;
1562 if (cur.pit() > 0) {
1564 prevcur.pos() = prevcur.lastpos();
1566 Paragraph const & prevpar = prevcur.paragraph();
1568 // if a bibitem is deleted, merge with previous paragraph
1569 // if this is a bibliography item as well
1570 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1571 cur.recordUndo(prevcur.pit());
1572 mergeParagraph(bufparams, cur.text()->paragraphs(),
1574 cur.forceBufferUpdate();
1575 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1576 cur.screenUpdateFlags(Update::Force);
1580 // otherwise reset to default
1581 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1586 bool Text::erase(Cursor & cur)
1588 LASSERT(this == cur.text(), return false);
1589 bool needsUpdate = false;
1590 Paragraph & par = cur.paragraph();
1592 if (cur.pos() != cur.lastpos()) {
1593 // this is the code for a normal delete, not pasting
1595 cur.recordUndo(DELETE_UNDO);
1596 bool const was_inset = cur.paragraph().isInset(cur.pos());
1597 if(!par.eraseChar(cur.pos(), cur.buffer()->params().track_changes))
1598 // the character has been logically deleted only => skip it
1599 cur.top().forwardPos();
1602 cur.forceBufferUpdate();
1604 cur.checkBufferStructure();
1607 if (cur.pit() == cur.lastpit())
1608 return dissolveInset(cur);
1610 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1611 cur.recordUndo(DELETE_UNDO);
1612 par.setChange(cur.pos(), Change(Change::DELETED));
1616 setCursorIntern(cur, cur.pit() + 1, 0);
1617 needsUpdate = backspacePos0(cur);
1621 needsUpdate |= handleBibitems(cur);
1624 // Make sure the cursor is correct. Is this really needed?
1625 // No, not really... at least not here!
1626 cur.top().setPitPos(cur.pit(), cur.pos());
1627 cur.checkBufferStructure();
1634 bool Text::backspacePos0(Cursor & cur)
1636 LBUFERR(this == cur.text());
1640 bool needsUpdate = false;
1642 BufferParams const & bufparams = cur.buffer()->params();
1643 DocumentClass const & tclass = bufparams.documentClass();
1644 ParagraphList & plist = cur.text()->paragraphs();
1645 Paragraph const & par = cur.paragraph();
1646 Cursor prevcur = cur;
1648 prevcur.pos() = prevcur.lastpos();
1649 Paragraph const & prevpar = prevcur.paragraph();
1651 // is it an empty paragraph?
1652 if (cur.lastpos() == 0
1653 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1654 cur.recordUndo(prevcur.pit());
1655 plist.erase(lyx::next(plist.begin(), cur.pit()));
1658 // is previous par empty?
1659 else if (prevcur.lastpos() == 0
1660 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1661 cur.recordUndo(prevcur.pit());
1662 plist.erase(lyx::next(plist.begin(), prevcur.pit()));
1665 // Pasting is not allowed, if the paragraphs have different
1666 // layouts. I think it is a real bug of all other
1667 // word processors to allow it. It confuses the user.
1668 // Correction: Pasting is always allowed with standard-layout
1669 // or the empty layout.
1670 else if (par.layout() == prevpar.layout()
1671 || tclass.isDefaultLayout(par.layout())
1672 || tclass.isPlainLayout(par.layout())) {
1673 cur.recordUndo(prevcur.pit());
1674 mergeParagraph(bufparams, plist, prevcur.pit());
1679 cur.forceBufferUpdate();
1680 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1687 bool Text::backspace(Cursor & cur)
1689 LBUFERR(this == cur.text());
1690 bool needsUpdate = false;
1691 if (cur.pos() == 0) {
1693 return dissolveInset(cur);
1695 Cursor prev_cur = cur;
1698 if (!prev_cur.paragraph().isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1699 cur.recordUndo(prev_cur.pit(), prev_cur.pit());
1700 prev_cur.paragraph().setChange(prev_cur.lastpos(), Change(Change::DELETED));
1701 setCursorIntern(cur, prev_cur.pit(), prev_cur.lastpos());
1704 // The cursor is at the beginning of a paragraph, so
1705 // the backspace will collapse two paragraphs into one.
1706 needsUpdate = backspacePos0(cur);
1709 // this is the code for a normal backspace, not pasting
1711 cur.recordUndo(DELETE_UNDO);
1712 // We used to do cursorBackwardIntern() here, but it is
1713 // not a good idea since it triggers the auto-delete
1714 // mechanism. So we do a cursorBackwardIntern()-lite,
1715 // without the dreaded mechanism. (JMarc)
1716 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1717 false, cur.boundary());
1718 bool const was_inset = cur.paragraph().isInset(cur.pos());
1719 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().track_changes);
1721 cur.forceBufferUpdate();
1723 cur.checkBufferStructure();
1726 if (cur.pos() == cur.lastpos())
1727 cur.setCurrentFont();
1729 needsUpdate |= handleBibitems(cur);
1731 // A singlePar update is not enough in this case.
1732 // cur.screenUpdateFlags(Update::Force);
1733 cur.top().setPitPos(cur.pit(), cur.pos());
1739 bool Text::dissolveInset(Cursor & cur)
1741 LASSERT(this == cur.text(), return false);
1743 if (isMainText() || cur.inset().nargs() != 1)
1746 cur.recordUndoInset();
1748 cur.selHandle(false);
1749 // save position inside inset
1750 pos_type spos = cur.pos();
1751 pit_type spit = cur.pit();
1752 ParagraphList plist;
1753 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1754 plist = paragraphs();
1756 // update cursor offset
1760 // remember position outside inset to delete inset later
1761 // we do not do it now to avoid memory reuse issues (see #10667).
1762 DocIterator inset_it = cur;
1766 Buffer & b = *cur.buffer();
1767 if (!plist.empty()) {
1769 // we clear the cache so that we won't get conflicts with labels
1770 // that get pasted into the buffer. we should update this before
1771 // its being empty matters. if not (i.e., if we encounter bugs),
1772 // then this should instead be:
1773 // cur.buffer().updateBuffer();
1774 // but we'll try the cheaper solution here.
1775 cur.buffer()->clearReferenceCache();
1777 // ERT paragraphs have the Language latex_language.
1778 // This is invalid outside of ERT, so we need to
1779 // change it to the buffer language.
1780 ParagraphList::iterator it = plist.begin();
1781 ParagraphList::iterator it_end = plist.end();
1782 for (; it != it_end; ++it)
1783 it->changeLanguage(b.params(), latex_language, b.language());
1785 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1786 b.errorList("Paste"));
1789 // delete the inset now
1790 inset_it.paragraph().eraseChar(inset_it.pos(), b.params().track_changes);
1793 cur.pit() = min(cur.lastpit(), spit);
1794 cur.pos() = min(cur.lastpos(), spos);
1795 // Ensure the current language is set correctly (bug 6292)
1796 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1797 cur.clearSelection();
1799 cur.forceBufferUpdate();
1805 void Text::getWord(CursorSlice & from, CursorSlice & to,
1806 word_location const loc) const
1809 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1813 void Text::write(ostream & os) const
1815 Buffer const & buf = owner_->buffer();
1816 ParagraphList::const_iterator pit = paragraphs().begin();
1817 ParagraphList::const_iterator end = paragraphs().end();
1819 for (; pit != end; ++pit)
1820 pit->write(os, buf.params(), dth);
1822 // Close begin_deeper
1823 for(; dth > 0; --dth)
1824 os << "\n\\end_deeper";
1828 bool Text::read(Lexer & lex,
1829 ErrorList & errorList, InsetText * insetPtr)
1831 Buffer const & buf = owner_->buffer();
1832 depth_type depth = 0;
1835 while (lex.isOK()) {
1837 string const token = lex.getString();
1842 if (token == "\\end_inset")
1845 if (token == "\\end_body")
1848 if (token == "\\begin_body")
1851 if (token == "\\end_document") {
1856 if (token == "\\begin_layout") {
1857 lex.pushToken(token);
1860 par.setInsetOwner(insetPtr);
1861 par.params().depth(depth);
1862 par.setFont(0, Font(inherit_font, buf.params().language));
1863 pars_.push_back(par);
1864 readParagraph(pars_.back(), lex, errorList);
1866 // register the words in the global word list
1867 pars_.back().updateWords();
1868 } else if (token == "\\begin_deeper") {
1870 } else if (token == "\\end_deeper") {
1872 lex.printError("\\end_deeper: " "depth is already null");
1876 LYXERR0("Handling unknown body token: `" << token << '\'');
1880 // avoid a crash on weird documents (bug 4859)
1881 if (pars_.empty()) {
1883 par.setInsetOwner(insetPtr);
1884 par.params().depth(depth);
1885 par.setFont(0, Font(inherit_font,
1886 buf.params().language));
1887 par.setPlainOrDefaultLayout(buf.params().documentClass());
1888 pars_.push_back(par);
1895 // Returns the current font and depth as a message.
1896 docstring Text::currentState(CursorData const & cur, bool devel_mode) const
1898 LBUFERR(this == cur.text());
1899 Buffer & buf = *cur.buffer();
1900 Paragraph const & par = cur.paragraph();
1901 odocstringstream os;
1903 if (buf.params().track_changes)
1904 os << _("[Change Tracking] ");
1906 Change change = par.lookupChange(cur.pos());
1908 if (change.changed()) {
1909 docstring const author =
1910 buf.params().authors().get(change.author).nameAndEmail();
1911 docstring const date = formatted_datetime(change.changetime);
1912 os << bformat(_("Changed by %1$s[[author]] on %2$s[[date]]. "),
1916 // I think we should only show changes from the default
1918 // No, from the document font (MV)
1919 Font font = cur.real_current_font;
1920 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1922 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1924 // The paragraph depth
1925 int depth = cur.paragraph().getDepth();
1927 os << bformat(_(", Depth: %1$d"), depth);
1929 // The paragraph spacing, but only if different from
1931 Spacing const & spacing = par.params().spacing();
1932 if (!spacing.isDefault()) {
1933 os << _(", Spacing: ");
1934 switch (spacing.getSpace()) {
1935 case Spacing::Single:
1938 case Spacing::Onehalf:
1941 case Spacing::Double:
1944 case Spacing::Other:
1945 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1947 case Spacing::Default:
1948 // should never happen, do nothing
1954 os << _(", Inset: ") << &cur.inset();
1955 if (cur.lastidx() > 0)
1956 os << _(", Cell: ") << cur.idx();
1957 os << _(", Paragraph: ") << cur.pit();
1958 os << _(", Id: ") << par.id();
1959 os << _(", Position: ") << cur.pos();
1960 // FIXME: Why is the check for par.size() needed?
1961 // We are called with cur.pos() == par.size() quite often.
1962 if (!par.empty() && cur.pos() < par.size()) {
1963 // Force output of code point, not character
1964 size_t const c = par.getChar(cur.pos());
1965 os << _(", Char: 0x") << hex << c;
1967 os << _(", Boundary: ") << cur.boundary();
1968 // Row & row = cur.textRow();
1969 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1975 docstring Text::getPossibleLabel(DocIterator const & cur) const
1977 pit_type pit = cur.pit();
1979 Layout const * layout = &(pars_[pit].layout());
1982 docstring par_text = pars_[pit].asString(AS_STR_SKIPDELETE);
1984 // The return string of math matrices might contain linebreaks
1985 par_text = subst(par_text, '\n', '-');
1986 int const numwords = 3;
1987 for (int i = 0; i < numwords; ++i) {
1988 if (par_text.empty())
1991 par_text = split(par_text, head, ' ');
1992 // Is it legal to use spaces in labels ?
1998 // Make sure it isn't too long
1999 unsigned int const max_label_length = 32;
2000 if (text.size() > max_label_length)
2001 text.resize(max_label_length);
2003 // Will contain the label prefix.
2006 // For section, subsection, etc...
2007 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2008 Layout const * layout2 = &(pars_[pit - 1].layout());
2009 if (layout2->latextype != LATEX_PARAGRAPH) {
2014 if (layout->latextype != LATEX_PARAGRAPH)
2015 name = layout->refprefix;
2017 // For captions, we just take the caption type
2018 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
2019 if (caption_inset) {
2020 string const & ftype = static_cast<InsetCaption *>(caption_inset)->floattype();
2021 FloatList const & fl = cur.buffer()->params().documentClass().floats();
2022 if (fl.typeExist(ftype)) {
2023 Floating const & flt = fl.getType(ftype);
2024 name = from_utf8(flt.refPrefix());
2027 name = from_utf8(ftype.substr(0,3));
2030 // If none of the above worked, see if the inset knows.
2032 InsetLayout const & il = cur.inset().getLayout();
2033 name = il.refprefix();
2037 text = name + ':' + text;
2039 // We need a unique label
2040 docstring label = text;
2042 while (cur.buffer()->insetLabel(label)) {
2043 label = text + '-' + convert<docstring>(i);
2051 docstring Text::asString(int options) const
2053 return asString(0, pars_.size(), options);
2057 docstring Text::asString(pit_type beg, pit_type end, int options) const
2059 size_t i = size_t(beg);
2060 docstring str = pars_[i].asString(options);
2061 for (++i; i != size_t(end); ++i) {
2063 str += pars_[i].asString(options);
2069 void Text::shortenForOutliner(docstring & str, size_t const maxlen)
2071 support::truncateWithEllipsis(str, maxlen);
2072 for (char_type & c : str)
2073 if (c == L'\n' || c == L'\t')
2078 void Text::forOutliner(docstring & os, size_t const maxlen,
2079 bool const shorten) const
2081 pit_type end = pars_.size() - 1;
2082 if (0 <= end && !pars_[0].labelString().empty())
2083 os += pars_[0].labelString() + ' ';
2084 forOutliner(os, maxlen, 0, end, shorten);
2088 void Text::forOutliner(docstring & os, size_t const maxlen,
2089 pit_type pit_start, pit_type pit_end,
2090 bool const shorten) const
2092 size_t tmplen = shorten ? maxlen + 1 : maxlen;
2093 pit_type end = min(size_t(pit_end), pars_.size() - 1);
2095 for (pit_type i = pit_start; i <= end && os.length() < tmplen; ++i) {
2098 // This function lets the first label be treated separately
2099 pars_[i].forOutliner(os, tmplen, false, !first);
2103 shortenForOutliner(os, maxlen);
2107 void Text::charsTranspose(Cursor & cur)
2109 LBUFERR(this == cur.text());
2111 pos_type pos = cur.pos();
2113 // If cursor is at beginning or end of paragraph, do nothing.
2114 if (pos == cur.lastpos() || pos == 0)
2117 Paragraph & par = cur.paragraph();
2119 // Get the positions of the characters to be transposed.
2120 pos_type pos1 = pos - 1;
2121 pos_type pos2 = pos;
2123 // In change tracking mode, ignore deleted characters.
2124 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2126 if (pos2 == cur.lastpos())
2129 while (pos1 >= 0 && par.isDeleted(pos1))
2134 // Don't do anything if one of the "characters" is not regular text.
2135 if (par.isInset(pos1) || par.isInset(pos2))
2138 // Store the characters to be transposed (including font information).
2139 char_type const char1 = par.getChar(pos1);
2141 par.getFontSettings(cur.buffer()->params(), pos1);
2143 char_type const char2 = par.getChar(pos2);
2145 par.getFontSettings(cur.buffer()->params(), pos2);
2147 // And finally, we are ready to perform the transposition.
2148 // Track the changes if Change Tracking is enabled.
2149 bool const trackChanges = cur.buffer()->params().track_changes;
2153 par.eraseChar(pos2, trackChanges);
2154 par.eraseChar(pos1, trackChanges);
2155 par.insertChar(pos1, char2, font2, trackChanges);
2156 par.insertChar(pos2, char1, font1, trackChanges);
2158 cur.checkBufferStructure();
2160 // After the transposition, move cursor to after the transposition.
2161 setCursor(cur, cur.pit(), pos2);
2166 DocIterator Text::macrocontextPosition() const
2168 return macrocontext_position_;
2172 void Text::setMacrocontextPosition(DocIterator const & pos)
2174 macrocontext_position_ = pos;
2178 docstring Text::previousWord(CursorSlice const & sl) const
2180 CursorSlice from = sl;
2181 CursorSlice to = sl;
2182 getWord(from, to, PREVIOUS_WORD);
2183 if (sl == from || to == from)
2186 Paragraph const & par = sl.paragraph();
2187 return par.asString(from.pos(), to.pos());
2191 bool Text::completionSupported(Cursor const & cur) const
2193 Paragraph const & par = cur.paragraph();
2194 return cur.pos() > 0
2195 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2196 && !par.isWordSeparator(cur.pos() - 1);
2200 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2202 WordList const & list = theWordList(cur.getFont().language()->lang());
2203 return new TextCompletionList(cur, list);
2207 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2209 LBUFERR(cur.bv().cursor() == cur);
2211 cur.bv().cursor() = cur;
2212 if (!(cur.result().screenUpdate() & Update::Force))
2213 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2218 docstring Text::completionPrefix(Cursor const & cur) const
2220 return previousWord(cur.top());