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/textutils.h"
71 #include <boost/next_prior.hpp>
77 // TODO: replace if in Text::readParToken() with compile time switch
80 #include "support/metahash.h"
82 typedef boost::mpl::string<'\\end','_lay','out'> end_layout;
83 typedef boost::mpl::string<'\\end','in','set'> end_inset;
87 std::string token = "\\end_layout";
89 switch (boost::hash_value(token)) {
90 case lyx::support::hash_string<end_layout>::value:
92 case lyx::support::hash_string<end_inset>::value:
102 using namespace lyx::support;
106 using cap::cutSelection;
107 using cap::pasteParagraphList;
109 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
110 Paragraph & toPar, pos_type toPos, BufferParams const & params)
112 // Note: moveItem() does not honour change tracking!
113 // Therefore, it should only be used for breaking and merging paragraphs
115 // We need a copy here because the character at fromPos is going to be erased.
116 Font const tmpFont = fromPar.getFontSettings(params, fromPos);
117 Change const tmpChange = fromPar.lookupChange(fromPos);
119 if (Inset * tmpInset = fromPar.getInset(fromPos)) {
120 fromPar.releaseInset(fromPos);
121 // The inset is not in fromPar any more.
122 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
129 char_type const tmpChar = fromPar.getChar(fromPos);
130 fromPar.eraseChar(fromPos, false);
131 toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
136 void breakParagraphConservative(BufferParams const & bparams,
137 ParagraphList & pars, pit_type par_offset, pos_type pos)
139 // create a new paragraph
140 Paragraph & tmp = *pars.insert(boost::next(pars.begin(), par_offset + 1),
142 Paragraph & par = pars[par_offset];
144 tmp.setInsetOwner(&par.inInset());
145 tmp.makeSameLayout(par);
147 LASSERT(pos <= par.size(), return);
149 if (pos < par.size()) {
150 // move everything behind the break position to the new paragraph
151 pos_type pos_end = par.size() - 1;
153 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
154 if (moveItem(par, pos, tmp, j, bparams)) {
158 // Move over the end-of-par change information
159 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
160 par.setChange(par.size(), Change(bparams.track_changes ?
161 Change::INSERTED : Change::UNCHANGED));
166 void mergeParagraph(BufferParams const & bparams,
167 ParagraphList & pars, pit_type par_offset)
169 Paragraph & next = pars[par_offset + 1];
170 Paragraph & par = pars[par_offset];
172 pos_type pos_end = next.size() - 1;
173 pos_type pos_insert = par.size();
175 // the imaginary end-of-paragraph character (at par.size()) has to be
176 // marked as unmodified. Otherwise, its change is adopted by the first
177 // character of the next paragraph.
178 if (par.isChanged(par.size())) {
179 LYXERR(Debug::CHANGES,
180 "merging par with inserted/deleted end-of-par character");
181 par.setChange(par.size(), Change(Change::UNCHANGED));
184 Change change = next.lookupChange(next.size());
186 // move the content of the second paragraph to the end of the first one
187 for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
188 if (moveItem(next, 0, par, j, bparams)) {
193 // move the change of the end-of-paragraph character
194 par.setChange(par.size(), change);
196 pars.erase(boost::next(pars.begin(), par_offset + 1));
200 Text::Text(InsetText * owner, bool use_default_layout)
203 pars_.push_back(Paragraph());
204 Paragraph & par = pars_.back();
205 par.setInsetOwner(owner);
206 DocumentClass const & dc = owner->buffer().params().documentClass();
207 if (use_default_layout)
208 par.setDefaultLayout(dc);
210 par.setPlainLayout(dc);
214 Text::Text(InsetText * owner, Text const & text)
218 ParagraphList::iterator const end = pars_.end();
219 ParagraphList::iterator it = pars_.begin();
220 for (; it != end; ++it)
221 it->setInsetOwner(owner);
225 pit_type Text::depthHook(pit_type pit, depth_type depth) const
227 pit_type newpit = pit;
232 while (newpit != 0 && pars_[newpit].getDepth() > depth)
235 if (pars_[newpit].getDepth() > depth)
242 pit_type Text::outerHook(pit_type par_offset) const
244 Paragraph const & par = pars_[par_offset];
246 if (par.getDepth() == 0)
248 return depthHook(par_offset, depth_type(par.getDepth() - 1));
252 bool Text::isFirstInSequence(pit_type par_offset) const
254 Paragraph const & par = pars_[par_offset];
256 pit_type dhook_offset = depthHook(par_offset, par.getDepth());
258 if (dhook_offset == par_offset)
261 Paragraph const & dhook = pars_[dhook_offset];
263 return dhook.layout() != par.layout()
264 || dhook.getDepth() != par.getDepth();
268 int Text::getTocLevel(pit_type par_offset) const
270 Paragraph const & par = pars_[par_offset];
272 if (par.layout().isEnvironment() && !isFirstInSequence(par_offset))
273 return Layout::NOT_IN_TOC;
275 return par.layout().toclevel;
279 Font const Text::outerFont(pit_type par_offset) const
281 depth_type par_depth = pars_[par_offset].getDepth();
282 FontInfo tmpfont = inherit_font;
283 depth_type prev_par_depth = 0;
284 // Resolve against environment font information
285 while (par_offset != pit_type(pars_.size())
286 && par_depth != prev_par_depth
288 && !tmpfont.resolved()) {
289 prev_par_depth = par_depth;
290 par_offset = outerHook(par_offset);
291 if (par_offset != pit_type(pars_.size())) {
292 tmpfont.realize(pars_[par_offset].layout().font);
293 par_depth = pars_[par_offset].getDepth();
297 return Font(tmpfont);
301 static void acceptOrRejectChanges(ParagraphList & pars,
302 BufferParams const & bparams, Text::ChangeOp op)
304 pit_type pars_size = static_cast<pit_type>(pars.size());
306 // first, accept or reject changes within each individual
307 // paragraph (do not consider end-of-par)
308 for (pit_type pit = 0; pit < pars_size; ++pit) {
309 // prevent assertion failure
310 if (!pars[pit].empty()) {
311 if (op == Text::ACCEPT)
312 pars[pit].acceptChanges(0, pars[pit].size());
314 pars[pit].rejectChanges(0, pars[pit].size());
318 // next, accept or reject imaginary end-of-par characters
319 for (pit_type pit = 0; pit < pars_size; ++pit) {
320 pos_type pos = pars[pit].size();
321 if (pars[pit].isChanged(pos)) {
322 // keep the end-of-par char if it is inserted and accepted
323 // or when it is deleted and rejected.
324 if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
325 pars[pit].setChange(pos, Change(Change::UNCHANGED));
327 if (pit == pars_size - 1) {
328 // we cannot remove a par break at the end of the last
329 // paragraph; instead, we mark it unchanged
330 pars[pit].setChange(pos, Change(Change::UNCHANGED));
332 mergeParagraph(bparams, pars, pit);
342 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
344 acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
348 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
350 acceptOrRejectChanges(pars, bparams, Text::REJECT);
354 InsetText const & Text::inset() const
361 void Text::readParToken(Paragraph & par, Lexer & lex,
362 string const & token, Font & font, Change & change, ErrorList & errorList)
364 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
365 BufferParams const & bp = buf->params();
367 if (token[0] != '\\') {
368 docstring dstr = lex.getDocString();
369 par.appendString(dstr, font, change);
371 } else if (token == "\\begin_layout") {
373 docstring layoutname = lex.getDocString();
375 font = Font(inherit_font, bp.language);
376 change = Change(Change::UNCHANGED);
378 DocumentClass const & tclass = bp.documentClass();
380 if (layoutname.empty())
381 layoutname = tclass.defaultLayoutName();
383 if (owner_->forcePlainLayout()) {
384 // in this case only the empty layout is allowed
385 layoutname = tclass.plainLayoutName();
386 } else if (par.usePlainLayout()) {
387 // in this case, default layout maps to empty layout
388 if (layoutname == tclass.defaultLayoutName())
389 layoutname = tclass.plainLayoutName();
391 // otherwise, the empty layout maps to the default
392 if (layoutname == tclass.plainLayoutName())
393 layoutname = tclass.defaultLayoutName();
396 // When we apply an unknown layout to a document, we add this layout to the textclass
397 // of this document. For example, when you apply class article to a beamer document,
398 // all unknown layouts such as frame will be added to document class article so that
399 // these layouts can keep their original names.
400 bool const added_one = tclass.addLayoutIfNeeded(layoutname);
403 docstring const s = bformat(_("Layout `%1$s' was not found."), layoutname);
405 ErrorItem(_("Layout Not Found"), s, par.id(), 0, par.size()));
408 par.setLayout(bp.documentClass()[layoutname]);
410 // Test whether the layout is obsolete.
411 Layout const & layout = par.layout();
412 if (!layout.obsoleted_by().empty())
413 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
415 par.params().read(lex);
417 } else if (token == "\\end_layout") {
418 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
419 << "Missing \\begin_layout ?");
420 } else if (token == "\\end_inset") {
421 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
422 << "Missing \\begin_inset ?");
423 } else if (token == "\\begin_inset") {
424 Inset * inset = readInset(lex, buf);
426 par.insertInset(par.size(), inset, font, change);
429 docstring line = lex.getDocString();
430 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
431 par.id(), 0, par.size()));
433 } else if (token == "\\family") {
435 setLyXFamily(lex.getString(), font.fontInfo());
436 } else if (token == "\\series") {
438 setLyXSeries(lex.getString(), font.fontInfo());
439 } else if (token == "\\shape") {
441 setLyXShape(lex.getString(), font.fontInfo());
442 } else if (token == "\\size") {
444 setLyXSize(lex.getString(), font.fontInfo());
445 } else if (token == "\\lang") {
447 string const tok = lex.getString();
448 Language const * lang = languages.getLanguage(tok);
450 font.setLanguage(lang);
452 font.setLanguage(bp.language);
453 lex.printError("Unknown language `$$Token'");
455 } else if (token == "\\numeric") {
457 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
458 } else if (token == "\\emph") {
460 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
461 } else if (token == "\\bar") {
463 string const tok = lex.getString();
466 font.fontInfo().setUnderbar(FONT_ON);
467 else if (tok == "no")
468 font.fontInfo().setUnderbar(FONT_OFF);
469 else if (tok == "default")
470 font.fontInfo().setUnderbar(FONT_INHERIT);
472 lex.printError("Unknown bar font flag "
474 } else if (token == "\\strikeout") {
476 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
477 } else if (token == "\\uuline") {
479 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
480 } else if (token == "\\uwave") {
482 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
483 } else if (token == "\\noun") {
485 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
486 } else if (token == "\\color") {
488 setLyXColor(lex.getString(), font.fontInfo());
489 } else if (token == "\\SpecialChar" ||
490 (token == "\\SpecialCharNoPassThru" &&
491 !par.layout().pass_thru && !inset().isPassThru())) {
492 auto_ptr<Inset> inset;
493 inset.reset(new InsetSpecialChar);
495 inset->setBuffer(*buf);
496 par.insertInset(par.size(), inset.release(), font, change);
497 } else if (token == "\\SpecialCharNoPassThru") {
499 docstring const s = ltrim(lex.getDocString(), "\\");
500 par.insert(par.size(), s, font, change);
501 } else if (token == "\\IPAChar") {
502 auto_ptr<Inset> inset;
503 inset.reset(new InsetIPAChar);
505 inset->setBuffer(*buf);
506 par.insertInset(par.size(), inset.release(), font, change);
507 } else if (token == "\\twohyphens" || token == "\\threehyphens") {
508 // Ideally, this should be done by lyx2lyx, but lyx2lyx does not know the
509 // running font and does not know anything about layouts (and CopyStyle).
510 Layout const & layout(par.layout());
511 FontInfo info = font.fontInfo();
512 info.realize(layout.resfont);
513 if (layout.pass_thru || inset().isPassThru() ||
514 info.family() == TYPEWRITER_FAMILY) {
515 if (token == "\\twohyphens")
516 par.insert(par.size(), from_ascii("--"), font, change);
518 par.insert(par.size(), from_ascii("---"), font, change);
520 if (token == "\\twohyphens")
521 par.insertChar(par.size(), 0x2013, font, change);
523 par.insertChar(par.size(), 0x2014, font, change);
525 } else if (token == "\\backslash") {
526 par.appendChar('\\', font, change);
527 } else if (token == "\\LyXTable") {
528 auto_ptr<Inset> inset(new InsetTabular(buf));
530 par.insertInset(par.size(), inset.release(), font, change);
531 } else if (token == "\\change_unchanged") {
532 change = Change(Change::UNCHANGED);
533 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
535 istringstream is(lex.getString());
539 BufferParams::AuthorMap const & am = bp.author_map;
540 if (am.find(aid) == am.end()) {
541 errorList.push_back(ErrorItem(_("Change tracking error"),
542 bformat(_("Unknown author index for change: %1$d\n"), aid),
543 par.id(), 0, par.size()));
544 change = Change(Change::UNCHANGED);
546 if (token == "\\change_inserted")
547 change = Change(Change::INSERTED, am.find(aid)->second, ct);
549 change = Change(Change::DELETED, am.find(aid)->second, ct);
553 errorList.push_back(ErrorItem(_("Unknown token"),
554 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
556 par.id(), 0, par.size()));
561 void Text::readParagraph(Paragraph & par, Lexer & lex,
562 ErrorList & errorList)
565 string token = lex.getString();
567 Change change(Change::UNCHANGED);
570 readParToken(par, lex, token, font, change, errorList);
573 token = lex.getString();
578 if (token == "\\end_layout") {
579 //Ok, paragraph finished
583 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
584 if (token == "\\begin_layout" || token == "\\end_document"
585 || token == "\\end_inset" || token == "\\begin_deeper"
586 || token == "\\end_deeper") {
587 lex.pushToken(token);
588 lyxerr << "Paragraph ended in line "
589 << lex.lineNumber() << "\n"
590 << "Missing \\end_layout.\n";
594 // Final change goes to paragraph break:
595 par.setChange(par.size(), change);
597 // Initialize begin_of_body_ on load; redoParagraph maintains
598 par.setBeginOfBody();
600 // mark paragraph for spell checking on load
601 // par.requestSpellCheck();
605 class TextCompletionList : public CompletionList
609 TextCompletionList(Cursor const & cur, WordList const * list)
610 : buffer_(cur.buffer()), list_(list)
613 virtual ~TextCompletionList() {}
616 virtual bool sorted() const { return true; }
618 virtual size_t size() const
620 return list_->size();
623 virtual docstring const & data(size_t idx) const
625 return list_->word(idx);
630 Buffer const * buffer_;
632 WordList const * list_;
636 bool Text::empty() const
638 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
639 // FIXME: Should we consider the labeled type as empty too?
640 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
644 double Text::spacing(Paragraph const & par) const
646 if (par.params().spacing().isDefault())
647 return owner_->buffer().params().spacing().getValue();
648 return par.params().spacing().getValue();
653 * This breaks a paragraph at the specified position.
654 * The new paragraph will:
655 * - Decrease depth by one (or change layout to default layout) when
656 * keep_layout == false
657 * - keep current depth and layout when keep_layout == true
659 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
662 BufferParams const & bparams = text.inset().buffer().params();
663 ParagraphList & pars = text.paragraphs();
664 // create a new paragraph, and insert into the list
665 ParagraphList::iterator tmp =
666 pars.insert(boost::next(pars.begin(), par_offset + 1),
669 Paragraph & par = pars[par_offset];
671 // remember to set the inset_owner
672 tmp->setInsetOwner(&par.inInset());
673 // without doing that we get a crash when typing <Return> at the
674 // end of a paragraph
675 tmp->setPlainOrDefaultLayout(bparams.documentClass());
678 tmp->setLayout(par.layout());
679 tmp->setLabelWidthString(par.params().labelWidthString());
680 tmp->params().depth(par.params().depth());
681 } else if (par.params().depth() > 0) {
682 Paragraph const & hook = pars[text.outerHook(par_offset)];
683 tmp->setLayout(hook.layout());
684 // not sure the line below is useful
685 tmp->setLabelWidthString(par.params().labelWidthString());
686 tmp->params().depth(hook.params().depth());
689 bool const isempty = (par.allowEmpty() && par.empty());
691 if (!isempty && (par.size() > pos || par.empty())) {
692 tmp->setLayout(par.layout());
693 tmp->params().align(par.params().align());
694 tmp->setLabelWidthString(par.params().labelWidthString());
696 tmp->params().depth(par.params().depth());
697 tmp->params().noindent(par.params().noindent());
699 // move everything behind the break position
700 // to the new paragraph
702 /* Note: if !keepempty, empty() == true, then we reach
703 * here with size() == 0. So pos_end becomes - 1. This
704 * doesn't cause problems because both loops below
705 * enforce pos <= pos_end and 0 <= pos
707 pos_type pos_end = par.size() - 1;
709 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
710 if (moveItem(par, pos, *tmp, j, bparams)) {
716 // Move over the end-of-par change information
717 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
718 par.setChange(par.size(), Change(bparams.track_changes ?
719 Change::INSERTED : Change::UNCHANGED));
722 // Make sure that we keep the language when
723 // breaking paragraph.
725 Font changed = tmp->getFirstFontSettings(bparams);
726 Font const & old = par.getFontSettings(bparams, par.size());
727 changed.setLanguage(old.language());
728 tmp->setFont(0, changed);
735 bool const soa = par.params().startOfAppendix();
736 par.params().clear();
737 // do not lose start of appendix marker (bug 4212)
738 par.params().startOfAppendix(soa);
739 par.setPlainOrDefaultLayout(bparams.documentClass());
743 par.setLayout(tmp->layout());
744 par.setLabelWidthString(tmp->params().labelWidthString());
745 par.params().depth(tmp->params().depth());
750 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
752 LBUFERR(this == cur.text());
754 Paragraph & cpar = cur.paragraph();
755 pit_type cpit = cur.pit();
757 DocumentClass const & tclass = cur.buffer()->params().documentClass();
758 Layout const & layout = cpar.layout();
760 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
761 if (changeDepthAllowed(cur, DEC_DEPTH))
762 changeDepth(cur, DEC_DEPTH);
764 docstring const & lay = cur.paragraph().usePlainLayout()
765 ? tclass.plainLayoutName() : tclass.defaultLayoutName();
773 // Always break behind a space
774 // It is better to erase the space (Dekel)
775 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
776 cpar.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
778 // What should the layout for the new paragraph be?
779 bool keep_layout = layout.isEnvironment()
780 || (layout.isParagraph() && layout.parbreak_is_newline);
782 keep_layout = !keep_layout;
784 // We need to remember this before we break the paragraph, because
785 // that invalidates the layout variable
786 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
788 // we need to set this before we insert the paragraph.
789 bool const isempty = cpar.allowEmpty() && cpar.empty();
791 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
793 // After this, neither paragraph contains any rows!
796 pit_type next_par = cpit + 1;
798 // well this is the caption hack since one caption is really enough
801 // set to standard-layout
802 //FIXME Check if this should be plainLayout() in some cases
803 pars_[cpit].applyLayout(tclass.defaultLayout());
805 // set to standard-layout
806 //FIXME Check if this should be plainLayout() in some cases
807 pars_[next_par].applyLayout(tclass.defaultLayout());
810 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
811 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().track_changes))
812 break; // the character couldn't be deleted physically due to change tracking
815 // A singlePar update is not enough in this case.
816 cur.screenUpdateFlags(Update::Force);
817 cur.forceBufferUpdate();
819 // This check is necessary. Otherwise the new empty paragraph will
820 // be deleted automatically. And it is more friendly for the user!
821 if (cur.pos() != 0 || isempty)
822 setCursor(cur, cur.pit() + 1, 0);
824 setCursor(cur, cur.pit(), 0);
828 // needed to insert the selection
829 void Text::insertStringAsLines(Cursor & cur, docstring const & str,
832 BufferParams const & bparams = owner_->buffer().params();
833 pit_type pit = cur.pit();
834 pos_type pos = cur.pos();
836 // insert the string, don't insert doublespace
837 bool space_inserted = true;
838 for (docstring::const_iterator cit = str.begin();
839 cit != str.end(); ++cit) {
840 Paragraph & par = pars_[pit];
842 if (inset().allowMultiPar() && (!par.empty() || par.allowEmpty())) {
843 lyx::breakParagraph(*this, pit, pos,
844 par.layout().isEnvironment());
847 space_inserted = true;
851 // do not insert consecutive spaces if !free_spacing
852 } else if ((*cit == ' ' || *cit == '\t') &&
853 space_inserted && !par.isFreeSpacing()) {
855 } else if (*cit == '\t') {
856 if (!par.isFreeSpacing()) {
857 // tabs are like spaces here
858 par.insertChar(pos, ' ', font, bparams.track_changes);
860 space_inserted = true;
862 par.insertChar(pos, *cit, font, bparams.track_changes);
864 space_inserted = true;
866 } else if (!isPrintable(*cit)) {
867 // Ignore unprintables
870 // just insert the character
871 par.insertChar(pos, *cit, font, bparams.track_changes);
873 space_inserted = (*cit == ' ');
876 setCursor(cur, pit, pos);
880 // turn double CR to single CR, others are converted into one
881 // blank. Then insertStringAsLines is called
882 void Text::insertStringAsParagraphs(Cursor & cur, docstring const & str,
885 docstring linestr = str;
886 bool newline_inserted = false;
888 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
889 if (linestr[i] == '\n') {
890 if (newline_inserted) {
891 // we know that \r will be ignored by
892 // insertStringAsLines. Of course, it is a dirty
893 // trick, but it works...
894 linestr[i - 1] = '\r';
898 newline_inserted = true;
900 } else if (isPrintable(linestr[i])) {
901 newline_inserted = false;
904 insertStringAsLines(cur, linestr, font);
908 // insert a character, moves all the following breaks in the
909 // same Paragraph one to the right and make a rebreak
910 void Text::insertChar(Cursor & cur, char_type c)
912 LBUFERR(this == cur.text());
914 cur.recordUndo(INSERT_UNDO);
916 TextMetrics const & tm = cur.bv().textMetrics(this);
917 Buffer const & buffer = *cur.buffer();
918 Paragraph & par = cur.paragraph();
919 // try to remove this
920 pit_type const pit = cur.pit();
922 bool const freeSpacing = par.layout().free_spacing ||
925 if (lyxrc.auto_number) {
926 static docstring const number_operators = from_ascii("+-/*");
927 static docstring const number_unary_operators = from_ascii("+-");
928 static docstring const number_seperators = from_ascii(".,:");
930 if (cur.current_font.fontInfo().number() == FONT_ON) {
931 if (!isDigitASCII(c) && !contains(number_operators, c) &&
932 !(contains(number_seperators, c) &&
934 cur.pos() != cur.lastpos() &&
935 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
936 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
938 number(cur); // Set current_font.number to OFF
939 } else if (isDigitASCII(c) &&
940 cur.real_current_font.isVisibleRightToLeft()) {
941 number(cur); // Set current_font.number to ON
943 if (cur.pos() != 0) {
944 char_type const c = par.getChar(cur.pos() - 1);
945 if (contains(number_unary_operators, c) &&
947 || par.isSeparator(cur.pos() - 2)
948 || par.isEnvSeparator(cur.pos() - 2)
949 || par.isNewline(cur.pos() - 2))
951 setCharFont(pit, cur.pos() - 1, cur.current_font,
953 } else if (contains(number_seperators, c)
955 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
956 setCharFont(pit, cur.pos() - 1, cur.current_font,
963 // In Bidi text, we want spaces to be treated in a special way: spaces
964 // which are between words in different languages should get the
965 // paragraph's language; otherwise, spaces should keep the language
966 // they were originally typed in. This is only in effect while typing;
967 // after the text is already typed in, the user can always go back and
968 // explicitly set the language of a space as desired. But 99.9% of the
969 // time, what we're doing here is what the user actually meant.
971 // The following cases are the ones in which the language of the space
972 // should be changed to match that of the containing paragraph. In the
973 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
974 // represents a space, pipe (|) represents the cursor position (so the
975 // character before it is the one just typed in). The different cases
976 // are depicted logically (not visually), from left to right:
981 // Theoretically, there are other situations that we should, perhaps, deal
982 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
983 // point (to understand why, just try to create this situation...).
985 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
986 // get font in front and behind the space in question. But do NOT
987 // use getFont(cur.pos()) because the character c is not inserted yet
988 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
989 Font const & post_space_font = cur.real_current_font;
990 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
991 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
993 if (pre_space_rtl != post_space_rtl) {
994 // Set the space's language to match the language of the
995 // adjacent character whose direction is the paragraph's
996 // direction; don't touch other properties of the font
997 Language const * lang =
998 (pre_space_rtl == par.isRTL(buffer.params())) ?
999 pre_space_font.language() : post_space_font.language();
1001 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
1002 space_font.setLanguage(lang);
1003 par.setFont(cur.pos() - 1, space_font);
1007 // Next check, if there will be two blanks together or a blank at
1008 // the beginning of a paragraph.
1009 // I decided to handle blanks like normal characters, the main
1010 // difference are the special checks when calculating the row.fill
1011 // (blank does not count at the end of a row) and the check here
1013 // When the free-spacing option is set for the current layout,
1014 // disable the double-space checking
1015 if (!freeSpacing && isLineSeparatorChar(c)) {
1016 if (cur.pos() == 0) {
1018 "You cannot insert a space at the "
1019 "beginning of a paragraph. Please read the Tutorial."));
1022 // LASSERT: Is it safe to continue here?
1023 LASSERT(cur.pos() > 0, /**/);
1024 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
1025 && !par.isDeleted(cur.pos() - 1)) {
1027 "You cannot type two spaces this way. "
1028 "Please read the Tutorial."));
1033 // Prevent to insert uncodable characters in verbatim and ERT
1034 // (workaround for bug 9012)
1035 // Don't do it for listings inset, since InsetListings::latex() tries
1036 // to switch to a usable encoding which works in many cases (bug 9102).
1037 if (cur.paragraph().isPassThru() && owner_->lyxCode() != LISTINGS_CODE &&
1038 cur.current_font.language()) {
1039 Encoding const * e = cur.current_font.language()->encoding();
1040 if (!e->encodable(c)) {
1041 cur.message(_("Character is uncodable in verbatim paragraphs."));
1046 pos_type pos = cur.pos();
1047 if (!cur.paragraph().isPassThru() && owner_->lyxCode() != IPA_CODE &&
1048 cur.current_font.fontInfo().family() != TYPEWRITER_FAMILY &&
1049 c == '-' && pos > 0) {
1050 if (par.getChar(pos - 1) == '-') {
1051 // convert "--" to endash
1052 par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1055 } else if (par.getChar(pos - 1) == 0x2013) {
1056 // convert "---" to emdash
1057 par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1060 } else if (par.getChar(pos - 1) == 0x2014) {
1061 // convert "----" to "-"
1062 par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1068 par.insertChar(pos, c, cur.current_font,
1069 cur.buffer()->params().track_changes);
1070 cur.checkBufferStructure();
1072 // cur.screenUpdateFlags(Update::Force);
1073 bool boundary = cur.boundary()
1074 || tm.isRTLBoundary(cur.pit(), pos + 1);
1075 setCursor(cur, cur.pit(), pos + 1, false, boundary);
1080 void Text::charInserted(Cursor & cur)
1082 Paragraph & par = cur.paragraph();
1084 // register word if a non-letter was entered
1086 && !par.isWordSeparator(cur.pos() - 2)
1087 && par.isWordSeparator(cur.pos() - 1)) {
1088 // get the word in front of cursor
1089 LBUFERR(this == cur.text());
1090 cur.paragraph().updateWords();
1095 // the cursor set functions have a special mechanism. When they
1096 // realize, that you left an empty paragraph, they will delete it.
1098 bool Text::cursorForwardOneWord(Cursor & cur)
1100 LBUFERR(this == cur.text());
1102 pos_type const lastpos = cur.lastpos();
1103 pit_type pit = cur.pit();
1104 pos_type pos = cur.pos();
1105 Paragraph const & par = cur.paragraph();
1107 // Paragraph boundary is a word boundary
1108 if (pos == lastpos) {
1109 if (pit != cur.lastpit())
1110 return setCursor(cur, pit + 1, 0);
1115 if (lyxrc.mac_like_cursor_movement) {
1116 // Skip through trailing punctuation and spaces.
1117 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1120 // Skip over either a non-char inset or a full word
1121 if (pos != lastpos && par.isWordSeparator(pos))
1123 else while (pos != lastpos && !par.isWordSeparator(pos))
1126 LASSERT(pos < lastpos, return false); // see above
1127 if (!par.isWordSeparator(pos))
1128 while (pos != lastpos && !par.isWordSeparator(pos))
1130 else if (par.isChar(pos))
1131 while (pos != lastpos && par.isChar(pos))
1133 else if (!par.isSpace(pos)) // non-char inset
1136 // Skip over white space
1137 while (pos != lastpos && par.isSpace(pos))
1141 return setCursor(cur, pit, pos);
1145 bool Text::cursorBackwardOneWord(Cursor & cur)
1147 LBUFERR(this == cur.text());
1149 pit_type pit = cur.pit();
1150 pos_type pos = cur.pos();
1151 Paragraph & par = cur.paragraph();
1153 // Paragraph boundary is a word boundary
1154 if (pos == 0 && pit != 0)
1155 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1157 if (lyxrc.mac_like_cursor_movement) {
1158 // Skip through punctuation and spaces.
1159 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1162 // Skip over either a non-char inset or a full word
1163 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1165 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1168 // Skip over white space
1169 while (pos != 0 && par.isSpace(pos - 1))
1172 if (pos != 0 && !par.isWordSeparator(pos - 1))
1173 while (pos != 0 && !par.isWordSeparator(pos - 1))
1175 else if (pos != 0 && par.isChar(pos - 1))
1176 while (pos != 0 && par.isChar(pos - 1))
1178 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1182 return setCursor(cur, pit, pos);
1186 bool Text::cursorVisLeftOneWord(Cursor & cur)
1188 LBUFERR(this == cur.text());
1190 pos_type left_pos, right_pos;
1191 bool left_is_letter, right_is_letter;
1193 Cursor temp_cur = cur;
1195 // always try to move at least once...
1196 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1198 // collect some information about current cursor position
1199 temp_cur.getSurroundingPos(left_pos, right_pos);
1201 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1203 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1205 // if we're not at a letter/non-letter boundary, continue moving
1206 if (left_is_letter == right_is_letter)
1209 // we should stop when we have an LTR word on our right or an RTL word
1211 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1212 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1213 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1214 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1218 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1219 true, temp_cur.boundary());
1223 bool Text::cursorVisRightOneWord(Cursor & cur)
1225 LBUFERR(this == cur.text());
1227 pos_type left_pos, right_pos;
1228 bool left_is_letter, right_is_letter;
1230 Cursor temp_cur = cur;
1232 // always try to move at least once...
1233 while (temp_cur.posVisRight(true /* skip_inset */)) {
1235 // collect some information about current cursor position
1236 temp_cur.getSurroundingPos(left_pos, right_pos);
1238 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1240 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1242 // if we're not at a letter/non-letter boundary, continue moving
1243 if (left_is_letter == right_is_letter)
1246 // we should stop when we have an LTR word on our right or an RTL word
1248 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1249 temp_cur.buffer()->params(),
1250 left_pos).isRightToLeft())
1251 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1252 temp_cur.buffer()->params(),
1253 right_pos).isRightToLeft()))
1257 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1258 true, temp_cur.boundary());
1262 void Text::selectWord(Cursor & cur, word_location loc)
1264 LBUFERR(this == cur.text());
1265 CursorSlice from = cur.top();
1266 CursorSlice to = cur.top();
1267 getWord(from, to, loc);
1268 if (cur.top() != from)
1269 setCursor(cur, from.pit(), from.pos());
1272 if (!cur.selection())
1274 setCursor(cur, to.pit(), to.pos());
1276 cur.setWordSelection(true);
1280 void Text::selectAll(Cursor & cur)
1282 LBUFERR(this == cur.text());
1283 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1285 // If the cursor is at the beginning, make sure the cursor ends there
1286 if (cur.pit() == 0 && cur.pos() == 0) {
1287 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1289 setCursor(cur, 0, 0);
1291 setCursor(cur, 0, 0);
1293 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1299 // Select the word currently under the cursor when no
1300 // selection is currently set
1301 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1303 LBUFERR(this == cur.text());
1304 if (cur.selection())
1306 selectWord(cur, loc);
1307 return cur.selection();
1311 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1313 LBUFERR(this == cur.text());
1315 if (!cur.selection()) {
1316 if (!selectChange(cur))
1320 cur.recordUndoSelection();
1322 pit_type begPit = cur.selectionBegin().pit();
1323 pit_type endPit = cur.selectionEnd().pit();
1325 pos_type begPos = cur.selectionBegin().pos();
1326 pos_type endPos = cur.selectionEnd().pos();
1328 // keep selection info, because endPos becomes invalid after the first loop
1329 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1331 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1332 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1333 pos_type parSize = pars_[pit].size();
1335 // ignore empty paragraphs; otherwise, an assertion will fail for
1336 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1340 // do not consider first paragraph if the cursor starts at pos size()
1341 if (pit == begPit && begPos == parSize)
1344 // do not consider last paragraph if the cursor ends at pos 0
1345 if (pit == endPit && endPos == 0)
1346 break; // last iteration anyway
1348 pos_type left = (pit == begPit ? begPos : 0);
1349 pos_type right = (pit == endPit ? endPos : parSize);
1352 // there is no change here
1356 pars_[pit].acceptChanges(left, right);
1358 pars_[pit].rejectChanges(left, right);
1362 // next, accept/reject imaginary end-of-par characters
1364 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1365 pos_type pos = pars_[pit].size();
1367 // skip if the selection ends before the end-of-par
1368 if (pit == endPit && endsBeforeEndOfPar)
1369 break; // last iteration anyway
1371 // skip if this is not the last paragraph of the document
1372 // note: the user should be able to accept/reject the par break of the last par!
1373 if (pit == endPit && pit + 1 != int(pars_.size()))
1374 break; // last iteration anway
1377 if (pars_[pit].isInserted(pos)) {
1378 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1379 } else if (pars_[pit].isDeleted(pos)) {
1380 if (pit + 1 == int(pars_.size())) {
1381 // we cannot remove a par break at the end of the last paragraph;
1382 // instead, we mark it unchanged
1383 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1385 mergeParagraph(cur.buffer()->params(), pars_, pit);
1391 if (pars_[pit].isDeleted(pos)) {
1392 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1393 } else if (pars_[pit].isInserted(pos)) {
1394 if (pit + 1 == int(pars_.size())) {
1395 // we mark the par break at the end of the last paragraph unchanged
1396 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1398 mergeParagraph(cur.buffer()->params(), pars_, pit);
1406 // finally, invoke the DEPM
1407 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().track_changes);
1410 cur.clearSelection();
1411 setCursorIntern(cur, begPit, begPos);
1412 cur.screenUpdateFlags(Update::Force);
1413 cur.forceBufferUpdate();
1417 void Text::acceptChanges()
1419 BufferParams const & bparams = owner_->buffer().params();
1420 lyx::acceptChanges(pars_, bparams);
1421 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.track_changes);
1425 void Text::rejectChanges()
1427 BufferParams const & bparams = owner_->buffer().params();
1428 pit_type pars_size = static_cast<pit_type>(pars_.size());
1430 // first, reject changes within each individual paragraph
1431 // (do not consider end-of-par)
1432 for (pit_type pit = 0; pit < pars_size; ++pit) {
1433 if (!pars_[pit].empty()) // prevent assertion failure
1434 pars_[pit].rejectChanges(0, pars_[pit].size());
1437 // next, reject imaginary end-of-par characters
1438 for (pit_type pit = 0; pit < pars_size; ++pit) {
1439 pos_type pos = pars_[pit].size();
1441 if (pars_[pit].isDeleted(pos)) {
1442 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1443 } else if (pars_[pit].isInserted(pos)) {
1444 if (pit == pars_size - 1) {
1445 // we mark the par break at the end of the last
1446 // paragraph unchanged
1447 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1449 mergeParagraph(bparams, pars_, pit);
1456 // finally, invoke the DEPM
1457 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.track_changes);
1461 void Text::deleteWordForward(Cursor & cur)
1463 LBUFERR(this == cur.text());
1464 if (cur.lastpos() == 0)
1468 cur.setSelection(true);
1469 cursorForwardOneWord(cur);
1471 cutSelection(cur, true, false);
1472 cur.checkBufferStructure();
1477 void Text::deleteWordBackward(Cursor & cur)
1479 LBUFERR(this == cur.text());
1480 if (cur.lastpos() == 0)
1481 cursorBackward(cur);
1484 cur.setSelection(true);
1485 cursorBackwardOneWord(cur);
1487 cutSelection(cur, true, false);
1488 cur.checkBufferStructure();
1493 // Kill to end of line.
1494 void Text::changeCase(Cursor & cur, TextCase action)
1496 LBUFERR(this == cur.text());
1500 bool gotsel = false;
1501 if (cur.selection()) {
1502 from = cur.selBegin();
1507 getWord(from, to, PARTIAL_WORD);
1508 cursorForwardOneWord(cur);
1511 cur.recordUndoSelection();
1513 pit_type begPit = from.pit();
1514 pit_type endPit = to.pit();
1516 pos_type begPos = from.pos();
1517 pos_type endPos = to.pos();
1519 pos_type right = 0; // needed after the for loop
1521 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1522 Paragraph & par = pars_[pit];
1523 pos_type const pos = (pit == begPit ? begPos : 0);
1524 right = (pit == endPit ? endPos : par.size());
1525 par.changeCase(cur.buffer()->params(), pos, right, action);
1528 // the selection may have changed due to logically-only deleted chars
1530 setCursor(cur, begPit, begPos);
1532 setCursor(cur, endPit, right);
1535 setCursor(cur, endPit, right);
1537 cur.checkBufferStructure();
1541 bool Text::handleBibitems(Cursor & cur)
1543 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1549 BufferParams const & bufparams = cur.buffer()->params();
1550 Paragraph const & par = cur.paragraph();
1551 Cursor prevcur = cur;
1552 if (cur.pit() > 0) {
1554 prevcur.pos() = prevcur.lastpos();
1556 Paragraph const & prevpar = prevcur.paragraph();
1558 // if a bibitem is deleted, merge with previous paragraph
1559 // if this is a bibliography item as well
1560 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1561 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1562 mergeParagraph(bufparams, cur.text()->paragraphs(),
1564 cur.forceBufferUpdate();
1565 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1566 cur.screenUpdateFlags(Update::Force);
1570 // otherwise reset to default
1571 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1576 bool Text::erase(Cursor & cur)
1578 LASSERT(this == cur.text(), return false);
1579 bool needsUpdate = false;
1580 Paragraph & par = cur.paragraph();
1582 if (cur.pos() != cur.lastpos()) {
1583 // this is the code for a normal delete, not pasting
1585 cur.recordUndo(DELETE_UNDO);
1586 bool const was_inset = cur.paragraph().isInset(cur.pos());
1587 if(!par.eraseChar(cur.pos(), cur.buffer()->params().track_changes))
1588 // the character has been logically deleted only => skip it
1589 cur.top().forwardPos();
1592 cur.forceBufferUpdate();
1594 cur.checkBufferStructure();
1597 if (cur.pit() == cur.lastpit())
1598 return dissolveInset(cur);
1600 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1601 par.setChange(cur.pos(), Change(Change::DELETED));
1605 setCursorIntern(cur, cur.pit() + 1, 0);
1606 needsUpdate = backspacePos0(cur);
1610 needsUpdate |= handleBibitems(cur);
1613 // Make sure the cursor is correct. Is this really needed?
1614 // No, not really... at least not here!
1615 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1616 cur.checkBufferStructure();
1623 bool Text::backspacePos0(Cursor & cur)
1625 LBUFERR(this == cur.text());
1629 bool needsUpdate = false;
1631 BufferParams const & bufparams = cur.buffer()->params();
1632 DocumentClass const & tclass = bufparams.documentClass();
1633 ParagraphList & plist = cur.text()->paragraphs();
1634 Paragraph const & par = cur.paragraph();
1635 Cursor prevcur = cur;
1637 prevcur.pos() = prevcur.lastpos();
1638 Paragraph const & prevpar = prevcur.paragraph();
1640 // is it an empty paragraph?
1641 if (cur.lastpos() == 0
1642 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1643 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1644 plist.erase(boost::next(plist.begin(), cur.pit()));
1647 // is previous par empty?
1648 else if (prevcur.lastpos() == 0
1649 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1650 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1651 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1654 // Pasting is not allowed, if the paragraphs have different
1655 // layouts. I think it is a real bug of all other
1656 // word processors to allow it. It confuses the user.
1657 // Correction: Pasting is always allowed with standard-layout
1658 // or the empty layout.
1659 else if (par.layout() == prevpar.layout()
1660 || tclass.isDefaultLayout(par.layout())
1661 || tclass.isPlainLayout(par.layout())) {
1662 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1663 mergeParagraph(bufparams, plist, prevcur.pit());
1668 cur.forceBufferUpdate();
1669 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1676 bool Text::backspace(Cursor & cur)
1678 LBUFERR(this == cur.text());
1679 bool needsUpdate = false;
1680 if (cur.pos() == 0) {
1682 return dissolveInset(cur);
1684 Cursor prev_cur = cur;
1687 if (!prev_cur.paragraph().isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1688 cur.recordUndo(ATOMIC_UNDO, prev_cur.pit(), prev_cur.pit());
1689 prev_cur.paragraph().setChange(prev_cur.lastpos(), Change(Change::DELETED));
1690 setCursorIntern(cur, prev_cur.pit(), prev_cur.lastpos());
1693 // The cursor is at the beginning of a paragraph, so
1694 // the backspace will collapse two paragraphs into one.
1695 needsUpdate = backspacePos0(cur);
1698 // this is the code for a normal backspace, not pasting
1700 cur.recordUndo(DELETE_UNDO);
1701 // We used to do cursorBackwardIntern() here, but it is
1702 // not a good idea since it triggers the auto-delete
1703 // mechanism. So we do a cursorBackwardIntern()-lite,
1704 // without the dreaded mechanism. (JMarc)
1705 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1706 false, cur.boundary());
1707 bool const was_inset = cur.paragraph().isInset(cur.pos());
1708 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().track_changes);
1710 cur.forceBufferUpdate();
1712 cur.checkBufferStructure();
1715 if (cur.pos() == cur.lastpos())
1716 cur.setCurrentFont();
1718 needsUpdate |= handleBibitems(cur);
1720 // A singlePar update is not enough in this case.
1721 // cur.screenUpdateFlags(Update::Force);
1722 setCursor(cur.top(), cur.pit(), cur.pos());
1728 bool Text::dissolveInset(Cursor & cur)
1730 LASSERT(this == cur.text(), return false);
1732 if (isMainText() || cur.inset().nargs() != 1)
1735 cur.recordUndoInset();
1737 cur.selHandle(false);
1739 pos_type spos = cur.pos();
1740 pit_type spit = cur.pit();
1741 ParagraphList plist;
1742 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1743 plist = paragraphs();
1745 // store cursor offset
1749 Buffer & b = *cur.buffer();
1750 cur.paragraph().eraseChar(cur.pos(), b.params().track_changes);
1752 if (!plist.empty()) {
1754 // we clear the cache so that we won't get conflicts with labels
1755 // that get pasted into the buffer. we should update this before
1756 // its being empty matters. if not (i.e., if we encounter bugs),
1757 // then this should instead be:
1758 // cur.buffer().updateBuffer();
1759 // but we'll try the cheaper solution here.
1760 cur.buffer()->clearReferenceCache();
1762 // ERT paragraphs have the Language latex_language.
1763 // This is invalid outside of ERT, so we need to
1764 // change it to the buffer language.
1765 ParagraphList::iterator it = plist.begin();
1766 ParagraphList::iterator it_end = plist.end();
1767 for (; it != it_end; ++it)
1768 it->changeLanguage(b.params(), latex_language, b.language());
1770 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1771 b.errorList("Paste"));
1773 cur.pit() = min(cur.lastpit(), spit);
1774 cur.pos() = min(cur.lastpos(), spos);
1777 cur.forceBufferUpdate();
1779 // Ensure the current language is set correctly (bug 6292)
1780 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1781 cur.clearSelection();
1787 void Text::getWord(CursorSlice & from, CursorSlice & to,
1788 word_location const loc) const
1791 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1795 void Text::write(ostream & os) const
1797 Buffer const & buf = owner_->buffer();
1798 ParagraphList::const_iterator pit = paragraphs().begin();
1799 ParagraphList::const_iterator end = paragraphs().end();
1801 for (; pit != end; ++pit)
1802 pit->write(os, buf.params(), dth);
1804 // Close begin_deeper
1805 for(; dth > 0; --dth)
1806 os << "\n\\end_deeper";
1810 bool Text::read(Lexer & lex,
1811 ErrorList & errorList, InsetText * insetPtr)
1813 Buffer const & buf = owner_->buffer();
1814 depth_type depth = 0;
1817 while (lex.isOK()) {
1819 string const token = lex.getString();
1824 if (token == "\\end_inset")
1827 if (token == "\\end_body")
1830 if (token == "\\begin_body")
1833 if (token == "\\end_document") {
1838 if (token == "\\begin_layout") {
1839 lex.pushToken(token);
1842 par.setInsetOwner(insetPtr);
1843 par.params().depth(depth);
1844 par.setFont(0, Font(inherit_font, buf.params().language));
1845 pars_.push_back(par);
1846 readParagraph(pars_.back(), lex, errorList);
1848 // register the words in the global word list
1849 pars_.back().updateWords();
1850 } else if (token == "\\begin_deeper") {
1852 } else if (token == "\\end_deeper") {
1854 lex.printError("\\end_deeper: " "depth is already null");
1858 LYXERR0("Handling unknown body token: `" << token << '\'');
1862 // avoid a crash on weird documents (bug 4859)
1863 if (pars_.empty()) {
1865 par.setInsetOwner(insetPtr);
1866 par.params().depth(depth);
1867 par.setFont(0, Font(inherit_font,
1868 buf.params().language));
1869 par.setPlainOrDefaultLayout(buf.params().documentClass());
1870 pars_.push_back(par);
1877 // Returns the current font and depth as a message.
1878 docstring Text::currentState(Cursor const & cur) const
1880 LBUFERR(this == cur.text());
1881 Buffer & buf = *cur.buffer();
1882 Paragraph const & par = cur.paragraph();
1883 odocstringstream os;
1885 if (buf.params().track_changes)
1886 os << _("[Change Tracking] ");
1888 Change change = par.lookupChange(cur.pos());
1890 if (change.changed()) {
1891 Author const & a = buf.params().authors().get(change.author);
1892 os << _("Change: ") << a.name();
1893 if (!a.email().empty())
1894 os << " (" << a.email() << ")";
1895 // FIXME ctime is english, we should translate that
1896 os << _(" at ") << ctime(&change.changetime);
1900 // I think we should only show changes from the default
1902 // No, from the document font (MV)
1903 Font font = cur.real_current_font;
1904 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1906 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1908 // The paragraph depth
1909 int depth = cur.paragraph().getDepth();
1911 os << bformat(_(", Depth: %1$d"), depth);
1913 // The paragraph spacing, but only if different from
1915 Spacing const & spacing = par.params().spacing();
1916 if (!spacing.isDefault()) {
1917 os << _(", Spacing: ");
1918 switch (spacing.getSpace()) {
1919 case Spacing::Single:
1922 case Spacing::Onehalf:
1925 case Spacing::Double:
1928 case Spacing::Other:
1929 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1931 case Spacing::Default:
1932 // should never happen, do nothing
1937 #ifdef DEVEL_VERSION
1938 os << _(", Inset: ") << &cur.inset();
1939 os << _(", Paragraph: ") << cur.pit();
1940 os << _(", Id: ") << par.id();
1941 os << _(", Position: ") << cur.pos();
1942 // FIXME: Why is the check for par.size() needed?
1943 // We are called with cur.pos() == par.size() quite often.
1944 if (!par.empty() && cur.pos() < par.size()) {
1945 // Force output of code point, not character
1946 size_t const c = par.getChar(cur.pos());
1947 os << _(", Char: 0x") << hex << c;
1949 os << _(", Boundary: ") << cur.boundary();
1950 // Row & row = cur.textRow();
1951 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1957 docstring Text::getPossibleLabel(Cursor const & cur) const
1959 pit_type pit = cur.pit();
1961 Layout const * layout = &(pars_[pit].layout());
1964 docstring par_text = pars_[pit].asString();
1966 // The return string of math matrices might contain linebreaks
1967 par_text = subst(par_text, '\n', '-');
1968 int const numwords = 3;
1969 for (int i = 0; i < numwords; ++i) {
1970 if (par_text.empty())
1973 par_text = split(par_text, head, ' ');
1974 // Is it legal to use spaces in labels ?
1980 // Make sure it isn't too long
1981 unsigned int const max_label_length = 32;
1982 if (text.size() > max_label_length)
1983 text.resize(max_label_length);
1985 // Will contain the label prefix.
1988 // For section, subsection, etc...
1989 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1990 Layout const * layout2 = &(pars_[pit - 1].layout());
1991 if (layout2->latextype != LATEX_PARAGRAPH) {
1996 if (layout->latextype != LATEX_PARAGRAPH)
1997 name = layout->refprefix;
1999 // For captions, we just take the caption type
2000 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
2001 if (caption_inset) {
2002 string const & ftype = static_cast<InsetCaption *>(caption_inset)->floattype();
2003 FloatList const & fl = cur.buffer()->params().documentClass().floats();
2004 if (fl.typeExist(ftype)) {
2005 Floating const & flt = fl.getType(ftype);
2006 name = from_utf8(flt.refPrefix());
2009 name = from_utf8(ftype.substr(0,3));
2012 // If none of the above worked, see if the inset knows.
2014 InsetLayout const & il = cur.inset().getLayout();
2015 name = il.refprefix();
2019 text = name + ':' + text;
2021 // We need a unique label
2022 docstring label = text;
2024 while (cur.buffer()->insetLabel(label)) {
2025 label = text + '-' + convert<docstring>(i);
2033 docstring Text::asString(int options) const
2035 return asString(0, pars_.size(), options);
2039 docstring Text::asString(pit_type beg, pit_type end, int options) const
2041 size_t i = size_t(beg);
2042 docstring str = pars_[i].asString(options);
2043 for (++i; i != size_t(end); ++i) {
2045 str += pars_[i].asString(options);
2051 void Text::forOutliner(docstring & os, size_t maxlen, bool shorten) const
2054 maxlen = std::numeric_limits<std::size_t>::max();
2056 LASSERT(maxlen >= 8, maxlen = TOC_ENTRY_LENGTH);
2057 for (size_t i = 0; i != pars_.size() && os.length() < maxlen; ++i)
2058 pars_[i].forOutliner(os, maxlen);
2059 if (shorten && os.length() >= maxlen)
2060 os = os.substr(0, maxlen - 3) + from_ascii("...");
2064 void Text::charsTranspose(Cursor & cur)
2066 LBUFERR(this == cur.text());
2068 pos_type pos = cur.pos();
2070 // If cursor is at beginning or end of paragraph, do nothing.
2071 if (pos == cur.lastpos() || pos == 0)
2074 Paragraph & par = cur.paragraph();
2076 // Get the positions of the characters to be transposed.
2077 pos_type pos1 = pos - 1;
2078 pos_type pos2 = pos;
2080 // In change tracking mode, ignore deleted characters.
2081 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2083 if (pos2 == cur.lastpos())
2086 while (pos1 >= 0 && par.isDeleted(pos1))
2091 // Don't do anything if one of the "characters" is not regular text.
2092 if (par.isInset(pos1) || par.isInset(pos2))
2095 // Store the characters to be transposed (including font information).
2096 char_type const char1 = par.getChar(pos1);
2098 par.getFontSettings(cur.buffer()->params(), pos1);
2100 char_type const char2 = par.getChar(pos2);
2102 par.getFontSettings(cur.buffer()->params(), pos2);
2104 // And finally, we are ready to perform the transposition.
2105 // Track the changes if Change Tracking is enabled.
2106 bool const trackChanges = cur.buffer()->params().track_changes;
2110 par.eraseChar(pos2, trackChanges);
2111 par.eraseChar(pos1, trackChanges);
2112 par.insertChar(pos1, char2, font2, trackChanges);
2113 par.insertChar(pos2, char1, font1, trackChanges);
2115 cur.checkBufferStructure();
2117 // After the transposition, move cursor to after the transposition.
2118 setCursor(cur, cur.pit(), pos2);
2123 DocIterator Text::macrocontextPosition() const
2125 return macrocontext_position_;
2129 void Text::setMacrocontextPosition(DocIterator const & pos)
2131 macrocontext_position_ = pos;
2135 docstring Text::previousWord(CursorSlice const & sl) const
2137 CursorSlice from = sl;
2138 CursorSlice to = sl;
2139 getWord(from, to, PREVIOUS_WORD);
2140 if (sl == from || to == from)
2143 Paragraph const & par = sl.paragraph();
2144 return par.asString(from.pos(), to.pos());
2148 bool Text::completionSupported(Cursor const & cur) const
2150 Paragraph const & par = cur.paragraph();
2151 return cur.pos() > 0
2152 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2153 && !par.isWordSeparator(cur.pos() - 1);
2157 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2159 WordList const * list = theWordList(cur.getFont().language()->lang());
2160 return new TextCompletionList(cur, list);
2164 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2166 LBUFERR(cur.bv().cursor() == cur);
2168 cur.bv().cursor() = cur;
2169 if (!(cur.result().screenUpdate() & Update::Force))
2170 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2175 docstring Text::completionPrefix(Cursor const & cur) const
2177 return previousWord(cur.top());