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"
50 #include "WordLangTuple.h"
53 #include "insets/InsetText.h"
54 #include "insets/InsetBibitem.h"
55 #include "insets/InsetCaption.h"
56 #include "insets/InsetLine.h"
57 #include "insets/InsetNewline.h"
58 #include "insets/InsetNewpage.h"
59 #include "insets/InsetOptArg.h"
60 #include "insets/InsetSpace.h"
61 #include "insets/InsetSpecialChar.h"
62 #include "insets/InsetTabular.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>
76 using namespace lyx::support;
80 using cap::cutSelection;
81 using cap::pasteParagraphList;
83 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
84 Paragraph & toPar, pos_type toPos, BufferParams const & params)
86 // Note: moveItem() does not honour change tracking!
87 // Therefore, it should only be used for breaking and merging paragraphs
89 // We need a copy here because the character at fromPos is going to be erased.
90 Font const tmpFont = fromPar.getFontSettings(params, fromPos);
91 Change const tmpChange = fromPar.lookupChange(fromPos);
93 if (Inset * tmpInset = fromPar.getInset(fromPos)) {
94 fromPar.releaseInset(fromPos);
95 // The inset is not in fromPar any more.
96 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
103 char_type const tmpChar = fromPar.getChar(fromPos);
104 fromPar.eraseChar(fromPos, false);
105 toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
110 void breakParagraphConservative(BufferParams const & bparams,
111 ParagraphList & pars, pit_type par_offset, pos_type pos)
113 // create a new paragraph
114 Paragraph & tmp = *pars.insert(boost::next(pars.begin(), par_offset + 1),
116 Paragraph & par = pars[par_offset];
118 tmp.setInsetOwner(&par.inInset());
119 tmp.makeSameLayout(par);
121 LASSERT(pos <= par.size(), /**/);
123 if (pos < par.size()) {
124 // move everything behind the break position to the new paragraph
125 pos_type pos_end = par.size() - 1;
127 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
128 if (moveItem(par, pos, tmp, j, bparams)) {
132 // Move over the end-of-par change information
133 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
134 par.setChange(par.size(), Change(bparams.trackChanges ?
135 Change::INSERTED : Change::UNCHANGED));
140 void mergeParagraph(BufferParams const & bparams,
141 ParagraphList & pars, pit_type par_offset)
143 Paragraph & next = pars[par_offset + 1];
144 Paragraph & par = pars[par_offset];
146 pos_type pos_end = next.size() - 1;
147 pos_type pos_insert = par.size();
149 // the imaginary end-of-paragraph character (at par.size()) has to be
150 // marked as unmodified. Otherwise, its change is adopted by the first
151 // character of the next paragraph.
152 if (par.isChanged(par.size())) {
153 LYXERR(Debug::CHANGES,
154 "merging par with inserted/deleted end-of-par character");
155 par.setChange(par.size(), Change(Change::UNCHANGED));
158 Change change = next.lookupChange(next.size());
160 // move the content of the second paragraph to the end of the first one
161 for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
162 if (moveItem(next, 0, par, j, bparams)) {
167 // move the change of the end-of-paragraph character
168 par.setChange(par.size(), change);
170 pars.erase(boost::next(pars.begin(), par_offset + 1));
174 pit_type depthHook(pit_type pit, ParagraphList const & pars, depth_type depth)
176 pit_type newpit = pit;
181 while (newpit != 0 && pars[newpit].getDepth() > depth)
184 if (pars[newpit].getDepth() > depth)
191 pit_type outerHook(pit_type par_offset, ParagraphList const & pars)
193 Paragraph const & par = pars[par_offset];
195 if (par.getDepth() == 0)
197 return depthHook(par_offset, pars, depth_type(par.getDepth() - 1));
201 bool isFirstInSequence(pit_type par_offset, ParagraphList const & pars)
203 Paragraph const & par = pars[par_offset];
205 pit_type dhook_offset = depthHook(par_offset, pars, par.getDepth());
207 if (dhook_offset == par_offset)
210 Paragraph const & dhook = pars[dhook_offset];
212 return dhook.layout() != par.layout()
213 || dhook.getDepth() != par.getDepth();
217 void setLabelWidthStringToSequence(pit_type const par_offset,
218 ParagraphList & pars, docstring const & s)
220 pit_type offset = par_offset;
221 // Find first of same layout in sequence
222 while (!isFirstInSequence(offset, pars)) {
223 offset = depthHook(offset, pars, pars[offset].getDepth());
226 // now apply label width string to every par
228 pit_type const end = pars.size();
229 depth_type const depth = pars[offset].getDepth();
230 Layout const & layout = pars[offset].layout();
231 for (pit_type pit = offset; pit != end; ++pit) {
232 while (pars[pit].getDepth() > depth)
234 if (pars[pit].getDepth() < depth)
236 if (pars[pit].layout() != layout)
238 pars[pit].setLabelWidthString(s);
243 int getEndLabel(pit_type p, ParagraphList const & pars)
246 depth_type par_depth = pars[p].getDepth();
247 while (pit != pit_type(pars.size())) {
248 Layout const & layout = pars[pit].layout();
249 int const endlabeltype = layout.endlabeltype;
251 if (endlabeltype != END_LABEL_NO_LABEL) {
252 if (p + 1 == pit_type(pars.size()))
255 depth_type const next_depth =
256 pars[p + 1].getDepth();
257 if (par_depth > next_depth ||
258 (par_depth == next_depth && layout != pars[p + 1].layout()))
264 pit = outerHook(pit, pars);
265 if (pit != pit_type(pars.size()))
266 par_depth = pars[pit].getDepth();
268 return END_LABEL_NO_LABEL;
272 Font const outerFont(pit_type par_offset, ParagraphList const & pars)
274 depth_type par_depth = pars[par_offset].getDepth();
275 FontInfo tmpfont = inherit_font;
277 // Resolve against environment font information
278 while (par_offset != pit_type(pars.size())
280 && !tmpfont.resolved()) {
281 par_offset = outerHook(par_offset, pars);
282 if (par_offset != pit_type(pars.size())) {
283 tmpfont.realize(pars[par_offset].layout().font);
284 par_depth = pars[par_offset].getDepth();
288 return Font(tmpfont);
292 bool isFullyDeleted(ParagraphList const & pars)
294 pit_type const pars_size = static_cast<pit_type>(pars.size());
296 // check all paragraphs
297 for (pit_type pit = 0; pit < pars_size; ++pit) {
298 if (!pars[pit].empty()) // prevent assertion failure
299 if (!pars[pit].isDeleted(0, pars[pit].size()))
306 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
308 pit_type pars_size = static_cast<pit_type>(pars.size());
310 // first, accept changes within each individual paragraph
311 // (do not consider end-of-par)
312 for (pit_type pit = 0; pit < pars_size; ++pit) {
313 if (!pars[pit].empty()) // prevent assertion failure
314 pars[pit].acceptChanges(0, pars[pit].size());
317 // next, accept imaginary end-of-par characters
318 for (pit_type pit = 0; pit < pars_size; ++pit) {
319 pos_type pos = pars[pit].size();
321 if (pars[pit].isInserted(pos)) {
322 pars[pit].setChange(pos, Change(Change::UNCHANGED));
323 } else if (pars[pit].isDeleted(pos)) {
324 if (pit == pars_size - 1) {
325 // we cannot remove a par break at the end of the last
326 // paragraph; instead, we mark it unchanged
327 pars[pit].setChange(pos, Change(Change::UNCHANGED));
329 mergeParagraph(bparams, pars, pit);
337 InsetText const & Text::inset() const
343 void Text::readParToken(Paragraph & par, Lexer & lex,
344 string const & token, Font & font, Change & change, ErrorList & errorList)
346 Buffer const & buf = owner_->buffer();
347 BufferParams const & bp = buf.params();
349 if (token[0] != '\\') {
350 docstring dstr = lex.getDocString();
351 par.appendString(dstr, font, change);
353 } else if (token == "\\begin_layout") {
355 docstring layoutname = lex.getDocString();
357 font = Font(inherit_font, bp.language);
358 change = Change(Change::UNCHANGED);
360 DocumentClass const & tclass = bp.documentClass();
362 if (layoutname.empty())
363 layoutname = tclass.defaultLayoutName();
365 if (owner_->forcePlainLayout()) {
366 // in this case only the empty layout is allowed
367 layoutname = tclass.plainLayoutName();
368 } else if (par.usePlainLayout()) {
369 // in this case, default layout maps to empty layout
370 if (layoutname == tclass.defaultLayoutName())
371 layoutname = tclass.plainLayoutName();
373 // otherwise, the empty layout maps to the default
374 if (layoutname == tclass.plainLayoutName())
375 layoutname = tclass.defaultLayoutName();
378 // When we apply an unknown layout to a document, we add this layout to the textclass
379 // of this document. For example, when you apply class article to a beamer document,
380 // all unknown layouts such as frame will be added to document class article so that
381 // these layouts can keep their original names.
382 tclass.addLayoutIfNeeded(layoutname);
384 par.setLayout(bp.documentClass()[layoutname]);
386 // Test whether the layout is obsolete.
387 Layout const & layout = par.layout();
388 if (!layout.obsoleted_by().empty())
389 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
391 par.params().read(lex);
393 } else if (token == "\\end_layout") {
394 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
395 << "Missing \\begin_layout ?");
396 } else if (token == "\\end_inset") {
397 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
398 << "Missing \\begin_inset ?");
399 } else if (token == "\\begin_inset") {
400 Inset * inset = readInset(lex, buf);
402 par.insertInset(par.size(), inset, font, change);
405 docstring line = lex.getDocString();
406 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
407 par.id(), 0, par.size()));
409 } else if (token == "\\family") {
411 setLyXFamily(lex.getString(), font.fontInfo());
412 } else if (token == "\\series") {
414 setLyXSeries(lex.getString(), font.fontInfo());
415 } else if (token == "\\shape") {
417 setLyXShape(lex.getString(), font.fontInfo());
418 } else if (token == "\\size") {
420 setLyXSize(lex.getString(), font.fontInfo());
421 } else if (token == "\\lang") {
423 string const tok = lex.getString();
424 Language const * lang = languages.getLanguage(tok);
426 font.setLanguage(lang);
428 font.setLanguage(bp.language);
429 lex.printError("Unknown language `$$Token'");
431 } else if (token == "\\numeric") {
433 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
434 } else if (token == "\\emph") {
436 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
437 } else if (token == "\\bar") {
439 string const tok = lex.getString();
442 font.fontInfo().setUnderbar(FONT_ON);
443 else if (tok == "no")
444 font.fontInfo().setUnderbar(FONT_OFF);
445 else if (tok == "default")
446 font.fontInfo().setUnderbar(FONT_INHERIT);
448 lex.printError("Unknown bar font flag "
450 } else if (token == "\\strikeout") {
452 font.fontInfo().setStrikeout(font.setLyXMisc(lex.getString()));
453 } else if (token == "\\uuline") {
455 font.fontInfo().setUuline(font.setLyXMisc(lex.getString()));
456 } else if (token == "\\uwave") {
458 font.fontInfo().setUwave(font.setLyXMisc(lex.getString()));
459 } else if (token == "\\noun") {
461 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
462 } else if (token == "\\color") {
464 setLyXColor(lex.getString(), font.fontInfo());
465 } else if (token == "\\SpecialChar") {
466 auto_ptr<Inset> inset;
467 inset.reset(new InsetSpecialChar);
469 par.insertInset(par.size(), inset.release(),
471 } else if (token == "\\backslash") {
472 par.appendChar('\\', font, change);
473 } else if (token == "\\LyXTable") {
474 auto_ptr<Inset> inset(new InsetTabular(const_cast<Buffer &>(buf)));
476 par.insertInset(par.size(), inset.release(), font, change);
477 } else if (token == "\\lyxline") {
478 par.insertInset(par.size(), new InsetLine, font, change);
479 } else if (token == "\\change_unchanged") {
480 change = Change(Change::UNCHANGED);
481 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
483 istringstream is(lex.getString());
487 map<unsigned int, int> const & am = bp.author_map;
488 if (am.find(aid) == am.end()) {
489 errorList.push_back(ErrorItem(_("Change tracking error"),
490 bformat(_("Unknown author index for change: %1$d\n"), aid),
491 par.id(), 0, par.size()));
492 change = Change(Change::UNCHANGED);
494 if (token == "\\change_inserted")
495 change = Change(Change::INSERTED, am.find(aid)->second, ct);
497 change = Change(Change::DELETED, am.find(aid)->second, ct);
501 errorList.push_back(ErrorItem(_("Unknown token"),
502 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
504 par.id(), 0, par.size()));
509 void Text::readParagraph(Paragraph & par, Lexer & lex,
510 ErrorList & errorList)
513 string token = lex.getString();
515 Change change(Change::UNCHANGED);
518 readParToken(par, lex, token, font, change, errorList);
521 token = lex.getString();
526 if (token == "\\end_layout") {
527 //Ok, paragraph finished
531 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
532 if (token == "\\begin_layout" || token == "\\end_document"
533 || token == "\\end_inset" || token == "\\begin_deeper"
534 || token == "\\end_deeper") {
535 lex.pushToken(token);
536 lyxerr << "Paragraph ended in line "
537 << lex.lineNumber() << "\n"
538 << "Missing \\end_layout.\n";
542 // Final change goes to paragraph break:
543 par.setChange(par.size(), change);
545 // Initialize begin_of_body_ on load; redoParagraph maintains
546 par.setBeginOfBody();
550 class TextCompletionList : public CompletionList
554 TextCompletionList(Cursor const & cur)
555 : buffer_(cur.buffer()), pos_(0)
558 virtual ~TextCompletionList() {}
561 virtual bool sorted() const { return true; }
563 virtual size_t size() const
565 return theWordList().size();
568 virtual docstring const & data(size_t idx) const
570 return theWordList().word(idx);
575 Buffer const * buffer_;
581 bool Text::empty() const
583 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
584 // FIXME: Should we consider the labeled type as empty too?
585 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
589 double Text::spacing(Paragraph const & par) const
591 if (par.params().spacing().isDefault())
592 return owner_->buffer().params().spacing().getValue();
593 return par.params().spacing().getValue();
598 * This breaks a paragraph at the specified position.
599 * The new paragraph will:
600 * - Decrease depth by one (or change layout to default layout) when
601 * keep_layout == false
602 * - keep current depth and layout when keep_layout == true
604 static void breakParagraph(BufferParams const & bparams,
605 ParagraphList & pars, pit_type par_offset, pos_type pos,
608 // create a new paragraph, and insert into the list
609 ParagraphList::iterator tmp =
610 pars.insert(boost::next(pars.begin(), par_offset + 1),
613 Paragraph & par = pars[par_offset];
615 // remember to set the inset_owner
616 tmp->setInsetOwner(&par.inInset());
617 // without doing that we get a crash when typing <Return> at the
618 // end of a paragraph
619 tmp->setPlainOrDefaultLayout(bparams.documentClass());
621 // layout stays the same with latex-environments
623 tmp->setLayout(par.layout());
624 tmp->setLabelWidthString(par.params().labelWidthString());
625 tmp->params().depth(par.params().depth());
626 } else if (par.params().depth() > 0) {
627 Paragraph const & hook = pars[outerHook(par_offset, pars)];
628 tmp->setLayout(hook.layout());
629 // not sure the line below is useful
630 tmp->setLabelWidthString(par.params().labelWidthString());
631 tmp->params().depth(hook.params().depth());
634 bool const isempty = (par.allowEmpty() && par.empty());
636 if (!isempty && (par.size() > pos || par.empty())) {
637 tmp->setLayout(par.layout());
638 tmp->params().align(par.params().align());
639 tmp->setLabelWidthString(par.params().labelWidthString());
641 tmp->params().depth(par.params().depth());
642 tmp->params().noindent(par.params().noindent());
644 // move everything behind the break position
645 // to the new paragraph
647 /* Note: if !keepempty, empty() == true, then we reach
648 * here with size() == 0. So pos_end becomes - 1. This
649 * doesn't cause problems because both loops below
650 * enforce pos <= pos_end and 0 <= pos
652 pos_type pos_end = par.size() - 1;
654 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
655 if (moveItem(par, pos, *tmp, j, bparams)) {
661 // Move over the end-of-par change information
662 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
663 par.setChange(par.size(), Change(bparams.trackChanges ?
664 Change::INSERTED : Change::UNCHANGED));
667 // Make sure that we keep the language when
668 // breaking paragraph.
670 Font changed = tmp->getFirstFontSettings(bparams);
671 Font const & old = par.getFontSettings(bparams, par.size());
672 changed.setLanguage(old.language());
673 tmp->setFont(0, changed);
680 bool const soa = par.params().startOfAppendix();
681 par.params().clear();
682 // do not lose start of appendix marker (bug 4212)
683 par.params().startOfAppendix(soa);
684 par.setPlainOrDefaultLayout(bparams.documentClass());
687 // layout stays the same with latex-environments
689 par.setLayout(tmp->layout());
690 par.setLabelWidthString(tmp->params().labelWidthString());
691 par.params().depth(tmp->params().depth());
696 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
698 LASSERT(this == cur.text(), /**/);
700 Paragraph & cpar = cur.paragraph();
701 pit_type cpit = cur.pit();
703 DocumentClass const & tclass = cur.buffer()->params().documentClass();
704 Layout const & layout = cpar.layout();
706 // this is only allowed, if the current paragraph is not empty
707 // or caption and if it has not the keepempty flag active
708 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
709 layout.labeltype != LABEL_SENSITIVE)
712 // a layout change may affect also the following paragraph
713 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
715 // Always break behind a space
716 // It is better to erase the space (Dekel)
717 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
718 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
720 // What should the layout for the new paragraph be?
721 bool keep_layout = inverse_logic ?
722 !layout.isEnvironment()
723 : layout.isEnvironment();
725 // We need to remember this before we break the paragraph, because
726 // that invalidates the layout variable
727 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
729 // we need to set this before we insert the paragraph.
730 bool const isempty = cpar.allowEmpty() && cpar.empty();
732 lyx::breakParagraph(cur.buffer()->params(), paragraphs(), cpit,
733 cur.pos(), keep_layout);
735 // After this, neither paragraph contains any rows!
738 pit_type next_par = cpit + 1;
740 // well this is the caption hack since one caption is really enough
743 // set to standard-layout
744 //FIXME Check if this should be plainLayout() in some cases
745 pars_[cpit].applyLayout(tclass.defaultLayout());
747 // set to standard-layout
748 //FIXME Check if this should be plainLayout() in some cases
749 pars_[next_par].applyLayout(tclass.defaultLayout());
752 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
753 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
754 break; // the character couldn't be deleted physically due to change tracking
757 cur.buffer()->updateLabels();
759 // A singlePar update is not enough in this case.
760 cur.updateFlags(Update::Force);
762 // This check is necessary. Otherwise the new empty paragraph will
763 // be deleted automatically. And it is more friendly for the user!
764 if (cur.pos() != 0 || isempty)
765 setCursor(cur, cur.pit() + 1, 0);
767 setCursor(cur, cur.pit(), 0);
771 // needed to insert the selection
772 void Text::insertStringAsLines(DocIterator const & dit, docstring const & str,
775 BufferParams const & bparams = owner_->buffer().params();
776 pit_type pit = dit.pit();
777 pos_type pos = dit.pos();
779 // insert the string, don't insert doublespace
780 bool space_inserted = true;
781 for (docstring::const_iterator cit = str.begin();
782 cit != str.end(); ++cit) {
783 Paragraph & par = pars_[pit];
785 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
786 lyx::breakParagraph(bparams, pars_, pit, pos,
787 par.layout().isEnvironment());
790 space_inserted = true;
794 // do not insert consecutive spaces if !free_spacing
795 } else if ((*cit == ' ' || *cit == '\t') &&
796 space_inserted && !par.isFreeSpacing()) {
798 } else if (*cit == '\t') {
799 if (!par.isFreeSpacing()) {
800 // tabs are like spaces here
801 par.insertChar(pos, ' ', font, bparams.trackChanges);
803 space_inserted = true;
805 par.insertChar(pos, *cit, font, bparams.trackChanges);
807 space_inserted = true;
809 } else if (!isPrintable(*cit)) {
810 // Ignore unprintables
813 // just insert the character
814 par.insertChar(pos, *cit, font, bparams.trackChanges);
816 space_inserted = (*cit == ' ');
822 // turn double CR to single CR, others are converted into one
823 // blank. Then insertStringAsLines is called
824 void Text::insertStringAsParagraphs(DocIterator const & dit, docstring const & str,
827 docstring linestr = str;
828 bool newline_inserted = false;
830 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
831 if (linestr[i] == '\n') {
832 if (newline_inserted) {
833 // we know that \r will be ignored by
834 // insertStringAsLines. Of course, it is a dirty
835 // trick, but it works...
836 linestr[i - 1] = '\r';
840 newline_inserted = true;
842 } else if (isPrintable(linestr[i])) {
843 newline_inserted = false;
846 insertStringAsLines(dit, linestr, font);
850 // insert a character, moves all the following breaks in the
851 // same Paragraph one to the right and make a rebreak
852 void Text::insertChar(Cursor & cur, char_type c)
854 LASSERT(this == cur.text(), /**/);
856 cur.recordUndo(INSERT_UNDO);
858 TextMetrics const & tm = cur.bv().textMetrics(this);
859 Buffer const & buffer = *cur.buffer();
860 Paragraph & par = cur.paragraph();
861 // try to remove this
862 pit_type const pit = cur.pit();
864 bool const freeSpacing = par.layout().free_spacing ||
867 if (lyxrc.auto_number) {
868 static docstring const number_operators = from_ascii("+-/*");
869 static docstring const number_unary_operators = from_ascii("+-");
870 static docstring const number_seperators = from_ascii(".,:");
872 if (cur.current_font.fontInfo().number() == FONT_ON) {
873 if (!isDigit(c) && !contains(number_operators, c) &&
874 !(contains(number_seperators, c) &&
876 cur.pos() != cur.lastpos() &&
877 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
878 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
880 number(cur); // Set current_font.number to OFF
881 } else if (isDigit(c) &&
882 cur.real_current_font.isVisibleRightToLeft()) {
883 number(cur); // Set current_font.number to ON
885 if (cur.pos() != 0) {
886 char_type const c = par.getChar(cur.pos() - 1);
887 if (contains(number_unary_operators, c) &&
889 || par.isSeparator(cur.pos() - 2)
890 || par.isNewline(cur.pos() - 2))
892 setCharFont(pit, cur.pos() - 1, cur.current_font,
894 } else if (contains(number_seperators, c)
896 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
897 setCharFont(pit, cur.pos() - 1, cur.current_font,
904 // In Bidi text, we want spaces to be treated in a special way: spaces
905 // which are between words in different languages should get the
906 // paragraph's language; otherwise, spaces should keep the language
907 // they were originally typed in. This is only in effect while typing;
908 // after the text is already typed in, the user can always go back and
909 // explicitly set the language of a space as desired. But 99.9% of the
910 // time, what we're doing here is what the user actually meant.
912 // The following cases are the ones in which the language of the space
913 // should be changed to match that of the containing paragraph. In the
914 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
915 // represents a space, pipe (|) represents the cursor position (so the
916 // character before it is the one just typed in). The different cases
917 // are depicted logically (not visually), from left to right:
922 // Theoretically, there are other situations that we should, perhaps, deal
923 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
924 // point (to understand why, just try to create this situation...).
926 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
927 // get font in front and behind the space in question. But do NOT
928 // use getFont(cur.pos()) because the character c is not inserted yet
929 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
930 Font const & post_space_font = cur.real_current_font;
931 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
932 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
934 if (pre_space_rtl != post_space_rtl) {
935 // Set the space's language to match the language of the
936 // adjacent character whose direction is the paragraph's
937 // direction; don't touch other properties of the font
938 Language const * lang =
939 (pre_space_rtl == par.isRTL(buffer.params())) ?
940 pre_space_font.language() : post_space_font.language();
942 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
943 space_font.setLanguage(lang);
944 par.setFont(cur.pos() - 1, space_font);
948 // Next check, if there will be two blanks together or a blank at
949 // the beginning of a paragraph.
950 // I decided to handle blanks like normal characters, the main
951 // difference are the special checks when calculating the row.fill
952 // (blank does not count at the end of a row) and the check here
954 // When the free-spacing option is set for the current layout,
955 // disable the double-space checking
956 if (!freeSpacing && isLineSeparatorChar(c)) {
957 if (cur.pos() == 0) {
958 static bool sent_space_message = false;
959 if (!sent_space_message) {
960 cur.message(_("You cannot insert a space at the "
961 "beginning of a paragraph. Please read the Tutorial."));
962 sent_space_message = true;
966 LASSERT(cur.pos() > 0, /**/);
967 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
968 && !par.isDeleted(cur.pos() - 1)) {
969 static bool sent_space_message = false;
970 if (!sent_space_message) {
971 cur.message(_("You cannot type two spaces this way. "
972 "Please read the Tutorial."));
973 sent_space_message = true;
979 par.insertChar(cur.pos(), c, cur.current_font,
980 cur.buffer()->params().trackChanges);
981 cur.checkBufferStructure();
983 // cur.updateFlags(Update::Force);
984 bool boundary = tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
985 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
990 void Text::charInserted(Cursor & cur)
992 Paragraph & par = cur.paragraph();
994 // Here we call finishUndo for every 20 characters inserted.
995 // This is from my experience how emacs does it. (Lgb)
996 static unsigned int counter;
1004 // register word if a non-letter was entered
1006 && !par.isWordSeparator(cur.pos() - 2)
1007 && par.isWordSeparator(cur.pos() - 1)) {
1008 // get the word in front of cursor
1009 LASSERT(this == cur.text(), /**/);
1010 cur.paragraph().updateWords();
1015 // the cursor set functions have a special mechanism. When they
1016 // realize, that you left an empty paragraph, they will delete it.
1018 bool Text::cursorForwardOneWord(Cursor & cur)
1020 LASSERT(this == cur.text(), /**/);
1022 pos_type const lastpos = cur.lastpos();
1023 pit_type pit = cur.pit();
1024 pos_type pos = cur.pos();
1025 Paragraph const & par = cur.paragraph();
1027 // Paragraph boundary is a word boundary
1028 if (pos == lastpos) {
1029 if (pit != cur.lastpit())
1030 return setCursor(cur, pit + 1, 0);
1035 if (lyxrc.mac_like_word_movement) {
1036 // Skip through trailing punctuation and spaces.
1037 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1040 // Skip over either a non-char inset or a full word
1041 if (pos != lastpos && par.isWordSeparator(pos))
1043 else while (pos != lastpos && !par.isWordSeparator(pos))
1046 LASSERT(pos < lastpos, /**/); // see above
1047 if (!par.isWordSeparator(pos))
1048 while (pos != lastpos && !par.isWordSeparator(pos))
1050 else if (par.isChar(pos))
1051 while (pos != lastpos && par.isChar(pos))
1053 else if (!par.isSpace(pos)) // non-char inset
1056 // Skip over white space
1057 while (pos != lastpos && par.isSpace(pos))
1061 return setCursor(cur, pit, pos);
1065 bool Text::cursorBackwardOneWord(Cursor & cur)
1067 LASSERT(this == cur.text(), /**/);
1069 pit_type pit = cur.pit();
1070 pos_type pos = cur.pos();
1071 Paragraph & par = cur.paragraph();
1073 // Paragraph boundary is a word boundary
1074 if (pos == 0 && pit != 0)
1075 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1077 if (lyxrc.mac_like_word_movement) {
1078 // Skip through punctuation and spaces.
1079 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1082 // Skip over either a non-char inset or a full word
1083 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1085 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1088 // Skip over white space
1089 while (pos != 0 && par.isSpace(pos - 1))
1092 if (pos != 0 && !par.isWordSeparator(pos - 1))
1093 while (pos != 0 && !par.isWordSeparator(pos - 1))
1095 else if (pos != 0 && par.isChar(pos - 1))
1096 while (pos != 0 && par.isChar(pos - 1))
1098 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1102 return setCursor(cur, pit, pos);
1106 bool Text::cursorVisLeftOneWord(Cursor & cur)
1108 LASSERT(this == cur.text(), /**/);
1110 pos_type left_pos, right_pos;
1111 bool left_is_letter, right_is_letter;
1113 Cursor temp_cur = cur;
1115 // always try to move at least once...
1116 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1118 // collect some information about current cursor position
1119 temp_cur.getSurroundingPos(left_pos, right_pos);
1121 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1123 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1125 // if we're not at a letter/non-letter boundary, continue moving
1126 if (left_is_letter == right_is_letter)
1129 // we should stop when we have an LTR word on our right or an RTL word
1131 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1132 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1133 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1134 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1138 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1139 true, temp_cur.boundary());
1143 bool Text::cursorVisRightOneWord(Cursor & cur)
1145 LASSERT(this == cur.text(), /**/);
1147 pos_type left_pos, right_pos;
1148 bool left_is_letter, right_is_letter;
1150 Cursor temp_cur = cur;
1152 // always try to move at least once...
1153 while (temp_cur.posVisRight(true /* skip_inset */)) {
1155 // collect some information about current cursor position
1156 temp_cur.getSurroundingPos(left_pos, right_pos);
1158 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1160 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1162 // if we're not at a letter/non-letter boundary, continue moving
1163 if (left_is_letter == right_is_letter)
1166 // we should stop when we have an LTR word on our right or an RTL word
1168 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1169 temp_cur.buffer()->params(),
1170 left_pos).isRightToLeft())
1171 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1172 temp_cur.buffer()->params(),
1173 right_pos).isRightToLeft()))
1177 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1178 true, temp_cur.boundary());
1182 void Text::selectWord(Cursor & cur, word_location loc)
1184 LASSERT(this == cur.text(), /**/);
1185 CursorSlice from = cur.top();
1186 CursorSlice to = cur.top();
1187 getWord(from, to, loc);
1188 if (cur.top() != from)
1189 setCursor(cur, from.pit(), from.pos());
1193 setCursor(cur, to.pit(), to.pos());
1198 void Text::selectAll(Cursor & cur)
1200 LASSERT(this == cur.text(), /**/);
1201 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1203 // If the cursor is at the beginning, make sure the cursor ends there
1204 if (cur.pit() == 0 && cur.pos() == 0) {
1205 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1207 setCursor(cur, 0, 0);
1209 setCursor(cur, 0, 0);
1211 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1217 // Select the word currently under the cursor when no
1218 // selection is currently set
1219 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1221 LASSERT(this == cur.text(), /**/);
1222 if (cur.selection())
1224 selectWord(cur, loc);
1225 return cur.selection();
1229 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1231 LASSERT(this == cur.text(), /**/);
1233 if (!cur.selection()) {
1234 bool const changed = cur.paragraph().isChanged(cur.pos());
1235 if (!(changed && findNextChange(&cur.bv())))
1239 cur.recordUndoSelection();
1241 pit_type begPit = cur.selectionBegin().pit();
1242 pit_type endPit = cur.selectionEnd().pit();
1244 pos_type begPos = cur.selectionBegin().pos();
1245 pos_type endPos = cur.selectionEnd().pos();
1247 // keep selection info, because endPos becomes invalid after the first loop
1248 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1250 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1252 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1253 pos_type parSize = pars_[pit].size();
1255 // ignore empty paragraphs; otherwise, an assertion will fail for
1256 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1260 // do not consider first paragraph if the cursor starts at pos size()
1261 if (pit == begPit && begPos == parSize)
1264 // do not consider last paragraph if the cursor ends at pos 0
1265 if (pit == endPit && endPos == 0)
1266 break; // last iteration anyway
1268 pos_type left = (pit == begPit ? begPos : 0);
1269 pos_type right = (pit == endPit ? endPos : parSize);
1272 pars_[pit].acceptChanges(left, right);
1274 pars_[pit].rejectChanges(left, right);
1278 // next, accept/reject imaginary end-of-par characters
1280 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1281 pos_type pos = pars_[pit].size();
1283 // skip if the selection ends before the end-of-par
1284 if (pit == endPit && endsBeforeEndOfPar)
1285 break; // last iteration anyway
1287 // skip if this is not the last paragraph of the document
1288 // note: the user should be able to accept/reject the par break of the last par!
1289 if (pit == endPit && pit + 1 != int(pars_.size()))
1290 break; // last iteration anway
1293 if (pars_[pit].isInserted(pos)) {
1294 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1295 } else if (pars_[pit].isDeleted(pos)) {
1296 if (pit + 1 == int(pars_.size())) {
1297 // we cannot remove a par break at the end of the last paragraph;
1298 // instead, we mark it unchanged
1299 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1301 mergeParagraph(cur.buffer()->params(), pars_, pit);
1307 if (pars_[pit].isDeleted(pos)) {
1308 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1309 } else if (pars_[pit].isInserted(pos)) {
1310 if (pit + 1 == int(pars_.size())) {
1311 // we mark the par break at the end of the last paragraph unchanged
1312 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1314 mergeParagraph(cur.buffer()->params(), pars_, pit);
1322 // finally, invoke the DEPM
1324 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1329 cur.clearSelection();
1330 setCursorIntern(cur, begPit, begPos);
1331 cur.updateFlags(Update::Force);
1332 cur.buffer()->updateLabels();
1336 void Text::acceptChanges()
1338 BufferParams const & bparams = owner_->buffer().params();
1339 lyx::acceptChanges(pars_, bparams);
1340 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1344 void Text::rejectChanges()
1346 BufferParams const & bparams = owner_->buffer().params();
1347 pit_type pars_size = static_cast<pit_type>(pars_.size());
1349 // first, reject changes within each individual paragraph
1350 // (do not consider end-of-par)
1351 for (pit_type pit = 0; pit < pars_size; ++pit) {
1352 if (!pars_[pit].empty()) // prevent assertion failure
1353 pars_[pit].rejectChanges(0, pars_[pit].size());
1356 // next, reject imaginary end-of-par characters
1357 for (pit_type pit = 0; pit < pars_size; ++pit) {
1358 pos_type pos = pars_[pit].size();
1360 if (pars_[pit].isDeleted(pos)) {
1361 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1362 } else if (pars_[pit].isInserted(pos)) {
1363 if (pit == pars_size - 1) {
1364 // we mark the par break at the end of the last
1365 // paragraph unchanged
1366 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1368 mergeParagraph(bparams, pars_, pit);
1375 // finally, invoke the DEPM
1376 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1380 void Text::deleteWordForward(Cursor & cur)
1382 LASSERT(this == cur.text(), /**/);
1383 if (cur.lastpos() == 0)
1387 cur.setSelection(true);
1388 cursorForwardOneWord(cur);
1390 cutSelection(cur, true, false);
1391 cur.checkBufferStructure();
1396 void Text::deleteWordBackward(Cursor & cur)
1398 LASSERT(this == cur.text(), /**/);
1399 if (cur.lastpos() == 0)
1400 cursorBackward(cur);
1403 cur.setSelection(true);
1404 cursorBackwardOneWord(cur);
1406 cutSelection(cur, true, false);
1407 cur.checkBufferStructure();
1412 // Kill to end of line.
1413 void Text::changeCase(Cursor & cur, TextCase action)
1415 LASSERT(this == cur.text(), /**/);
1419 bool gotsel = false;
1420 if (cur.selection()) {
1421 from = cur.selBegin();
1426 getWord(from, to, PARTIAL_WORD);
1427 cursorForwardOneWord(cur);
1430 cur.recordUndoSelection();
1432 pit_type begPit = from.pit();
1433 pit_type endPit = to.pit();
1435 pos_type begPos = from.pos();
1436 pos_type endPos = to.pos();
1438 pos_type right = 0; // needed after the for loop
1440 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1441 Paragraph & par = pars_[pit];
1442 pos_type const pos = (pit == begPit ? begPos : 0);
1443 right = (pit == endPit ? endPos : par.size());
1444 par.changeCase(cur.buffer()->params(), pos, right, action);
1447 // the selection may have changed due to logically-only deleted chars
1449 setCursor(cur, begPit, begPos);
1451 setCursor(cur, endPit, right);
1454 setCursor(cur, endPit, right);
1456 cur.checkBufferStructure();
1460 bool Text::handleBibitems(Cursor & cur)
1462 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1468 BufferParams const & bufparams = cur.buffer()->params();
1469 Paragraph const & par = cur.paragraph();
1470 Cursor prevcur = cur;
1471 if (cur.pit() > 0) {
1473 prevcur.pos() = prevcur.lastpos();
1475 Paragraph const & prevpar = prevcur.paragraph();
1477 // if a bibitem is deleted, merge with previous paragraph
1478 // if this is a bibliography item as well
1479 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1480 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1481 mergeParagraph(bufparams, cur.text()->paragraphs(),
1483 cur.buffer()->updateLabels();
1484 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1485 cur.updateFlags(Update::Force);
1489 // otherwise reset to default
1490 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1495 bool Text::erase(Cursor & cur)
1497 LASSERT(this == cur.text(), return false);
1498 bool needsUpdate = false;
1499 Paragraph & par = cur.paragraph();
1501 if (cur.pos() != cur.lastpos()) {
1502 // this is the code for a normal delete, not pasting
1504 cur.recordUndo(DELETE_UNDO);
1505 bool const was_inset = cur.paragraph().isInset(cur.pos());
1506 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1507 // the character has been logically deleted only => skip it
1508 cur.top().forwardPos();
1511 cur.buffer()->updateLabels();
1513 cur.checkBufferStructure();
1516 if (cur.pit() == cur.lastpit())
1517 return dissolveInset(cur);
1519 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1520 par.setChange(cur.pos(), Change(Change::DELETED));
1524 setCursorIntern(cur, cur.pit() + 1, 0);
1525 needsUpdate = backspacePos0(cur);
1529 needsUpdate |= handleBibitems(cur);
1532 // Make sure the cursor is correct. Is this really needed?
1533 // No, not really... at least not here!
1534 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1535 cur.checkBufferStructure();
1542 bool Text::backspacePos0(Cursor & cur)
1544 LASSERT(this == cur.text(), /**/);
1548 bool needsUpdate = false;
1550 BufferParams const & bufparams = cur.buffer()->params();
1551 DocumentClass const & tclass = bufparams.documentClass();
1552 ParagraphList & plist = cur.text()->paragraphs();
1553 Paragraph const & par = cur.paragraph();
1554 Cursor prevcur = cur;
1556 prevcur.pos() = prevcur.lastpos();
1557 Paragraph const & prevpar = prevcur.paragraph();
1559 // is it an empty paragraph?
1560 if (cur.lastpos() == 0
1561 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1562 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1563 plist.erase(boost::next(plist.begin(), cur.pit()));
1566 // is previous par empty?
1567 else if (prevcur.lastpos() == 0
1568 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1569 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1570 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1573 // Pasting is not allowed, if the paragraphs have different
1574 // layouts. I think it is a real bug of all other
1575 // word processors to allow it. It confuses the user.
1576 // Correction: Pasting is always allowed with standard-layout
1577 // or the empty layout.
1578 else if (par.layout() == prevpar.layout()
1579 || tclass.isDefaultLayout(par.layout())
1580 || tclass.isPlainLayout(par.layout())) {
1581 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1582 mergeParagraph(bufparams, plist, prevcur.pit());
1587 cur.buffer()->updateLabels();
1588 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1595 bool Text::backspace(Cursor & cur)
1597 LASSERT(this == cur.text(), /**/);
1598 bool needsUpdate = false;
1599 if (cur.pos() == 0) {
1601 return dissolveInset(cur);
1603 Paragraph & prev_par = pars_[cur.pit() - 1];
1605 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1606 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1607 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1610 // The cursor is at the beginning of a paragraph, so
1611 // the backspace will collapse two paragraphs into one.
1612 needsUpdate = backspacePos0(cur);
1615 // this is the code for a normal backspace, not pasting
1617 cur.recordUndo(DELETE_UNDO);
1618 // We used to do cursorBackwardIntern() here, but it is
1619 // not a good idea since it triggers the auto-delete
1620 // mechanism. So we do a cursorBackwardIntern()-lite,
1621 // without the dreaded mechanism. (JMarc)
1622 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1623 false, cur.boundary());
1624 bool const was_inset = cur.paragraph().isInset(cur.pos());
1625 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1627 cur.buffer()->updateLabels();
1629 cur.checkBufferStructure();
1632 if (cur.pos() == cur.lastpos())
1633 cur.setCurrentFont();
1635 needsUpdate |= handleBibitems(cur);
1637 // A singlePar update is not enough in this case.
1638 // cur.updateFlags(Update::Force);
1639 setCursor(cur.top(), cur.pit(), cur.pos());
1645 bool Text::dissolveInset(Cursor & cur)
1647 LASSERT(this == cur.text(), return false);
1649 if (isMainText() || cur.inset().nargs() != 1)
1652 cur.recordUndoInset();
1654 cur.selHandle(false);
1656 pos_type spos = cur.pos();
1657 pit_type spit = cur.pit();
1658 ParagraphList plist;
1659 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1660 plist = paragraphs();
1662 // store cursor offset
1666 Buffer & b = *cur.buffer();
1667 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1668 if (!plist.empty()) {
1669 // ERT paragraphs have the Language latex_language.
1670 // This is invalid outside of ERT, so we need to
1671 // change it to the buffer language.
1672 ParagraphList::iterator it = plist.begin();
1673 ParagraphList::iterator it_end = plist.end();
1674 for (; it != it_end; it++)
1675 it->changeLanguage(b.params(), latex_language, b.language());
1677 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1678 b.errorList("Paste"));
1680 cur.pit() = min(cur.lastpit(), spit);
1681 cur.pos() = min(cur.lastpos(), spos);
1683 // this is the least that needs to be done (bug 6003)
1684 // in the above case, pasteParagraphList handles this
1685 cur.buffer()->updateLabels();
1686 cur.clearSelection();
1692 void Text::getWord(CursorSlice & from, CursorSlice & to,
1693 word_location const loc) const
1696 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1700 void Text::write(ostream & os) const
1702 Buffer const & buf = owner_->buffer();
1703 ParagraphList::const_iterator pit = paragraphs().begin();
1704 ParagraphList::const_iterator end = paragraphs().end();
1706 for (; pit != end; ++pit)
1707 pit->write(os, buf.params(), dth);
1709 // Close begin_deeper
1710 for(; dth > 0; --dth)
1711 os << "\n\\end_deeper";
1715 bool Text::read(Lexer & lex,
1716 ErrorList & errorList, InsetText * insetPtr)
1718 Buffer const & buf = owner_->buffer();
1719 depth_type depth = 0;
1722 while (lex.isOK()) {
1724 string const token = lex.getString();
1729 if (token == "\\end_inset")
1732 if (token == "\\end_body")
1735 if (token == "\\begin_body")
1738 if (token == "\\end_document") {
1743 if (token == "\\begin_layout") {
1744 lex.pushToken(token);
1747 par.setInsetOwner(insetPtr);
1748 par.params().depth(depth);
1749 par.setFont(0, Font(inherit_font, buf.params().language));
1750 pars_.push_back(par);
1751 readParagraph(pars_.back(), lex, errorList);
1753 // register the words in the global word list
1754 CursorSlice sl = CursorSlice(*insetPtr);
1755 sl.pit() = pars_.size() - 1;
1756 pars_.back().updateWords();
1757 } else if (token == "\\begin_deeper") {
1759 } else if (token == "\\end_deeper") {
1761 lex.printError("\\end_deeper: " "depth is already null");
1765 LYXERR0("Handling unknown body token: `" << token << '\'');
1769 // avoid a crash on weird documents (bug 4859)
1770 if (pars_.empty()) {
1772 par.setInsetOwner(insetPtr);
1773 par.params().depth(depth);
1774 par.setFont(0, Font(inherit_font,
1775 buf.params().language));
1776 par.setPlainOrDefaultLayout(buf.params().documentClass());
1777 pars_.push_back(par);
1783 // Returns the current font and depth as a message.
1784 docstring Text::currentState(Cursor const & cur) const
1786 LASSERT(this == cur.text(), /**/);
1787 Buffer & buf = *cur.buffer();
1788 Paragraph const & par = cur.paragraph();
1789 odocstringstream os;
1791 if (buf.params().trackChanges)
1792 os << _("[Change Tracking] ");
1794 Change change = par.lookupChange(cur.pos());
1796 if (change.changed()) {
1797 Author const & a = buf.params().authors().get(change.author);
1798 os << _("Change: ") << a.name();
1799 if (!a.email().empty())
1800 os << " (" << a.email() << ")";
1801 // FIXME ctime is english, we should translate that
1802 os << _(" at ") << ctime(&change.changetime);
1806 // I think we should only show changes from the default
1808 // No, from the document font (MV)
1809 Font font = cur.real_current_font;
1810 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1812 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1814 // The paragraph depth
1815 int depth = cur.paragraph().getDepth();
1817 os << bformat(_(", Depth: %1$d"), depth);
1819 // The paragraph spacing, but only if different from
1821 Spacing const & spacing = par.params().spacing();
1822 if (!spacing.isDefault()) {
1823 os << _(", Spacing: ");
1824 switch (spacing.getSpace()) {
1825 case Spacing::Single:
1828 case Spacing::Onehalf:
1831 case Spacing::Double:
1834 case Spacing::Other:
1835 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1837 case Spacing::Default:
1838 // should never happen, do nothing
1843 #ifdef DEVEL_VERSION
1844 os << _(", Inset: ") << &cur.inset();
1845 os << _(", Paragraph: ") << cur.pit();
1846 os << _(", Id: ") << par.id();
1847 os << _(", Position: ") << cur.pos();
1848 // FIXME: Why is the check for par.size() needed?
1849 // We are called with cur.pos() == par.size() quite often.
1850 if (!par.empty() && cur.pos() < par.size()) {
1851 // Force output of code point, not character
1852 size_t const c = par.getChar(cur.pos());
1853 os << _(", Char: 0x") << hex << c;
1855 os << _(", Boundary: ") << cur.boundary();
1856 // Row & row = cur.textRow();
1857 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1863 docstring Text::getPossibleLabel(Cursor const & cur) const
1865 pit_type pit = cur.pit();
1867 Layout const * layout = &(pars_[pit].layout());
1870 docstring par_text = pars_[pit].asString();
1872 // the return string of math matrices might contain linebreaks
1873 par_text = subst(par_text, '\n', '-');
1874 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1875 if (par_text.empty())
1878 par_text = split(par_text, head, ' ');
1879 // Is it legal to use spaces in labels ?
1885 // No need for a prefix if the user said so.
1886 if (lyxrc.label_init_length <= 0)
1889 // Will contain the label type.
1892 // For section, subsection, etc...
1893 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1894 Layout const * layout2 = &(pars_[pit - 1].layout());
1895 if (layout2->latextype != LATEX_PARAGRAPH) {
1900 if (layout->latextype != LATEX_PARAGRAPH)
1901 name = from_ascii(layout->latexname());
1903 // for captions, we just take the caption type
1904 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1906 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1908 // If none of the above worked, we'll see if we're inside various
1909 // types of insets and take our abbreviation from them.
1911 InsetCode const codes[] = {
1916 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1917 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1919 name = float_inset->name();
1925 // Create a correct prefix for prettyref
1926 if (name == "theorem")
1927 name = from_ascii("thm");
1928 else if (name == "Foot")
1929 name = from_ascii("fn");
1930 else if (name == "listing")
1931 name = from_ascii("lst");
1934 text = name.substr(0, 3) + ':' + text;
1940 docstring Text::asString(int options) const
1942 return asString(0, pars_.size(), options);
1946 docstring Text::asString(pit_type beg, pit_type end, int options) const
1948 size_t i = size_t(beg);
1949 docstring str = pars_[i].asString(options);
1950 for (++i; i != size_t(end); ++i) {
1952 str += pars_[i].asString(options);
1959 void Text::charsTranspose(Cursor & cur)
1961 LASSERT(this == cur.text(), /**/);
1963 pos_type pos = cur.pos();
1965 // If cursor is at beginning or end of paragraph, do nothing.
1966 if (pos == cur.lastpos() || pos == 0)
1969 Paragraph & par = cur.paragraph();
1971 // Get the positions of the characters to be transposed.
1972 pos_type pos1 = pos - 1;
1973 pos_type pos2 = pos;
1975 // In change tracking mode, ignore deleted characters.
1976 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1978 if (pos2 == cur.lastpos())
1981 while (pos1 >= 0 && par.isDeleted(pos1))
1986 // Don't do anything if one of the "characters" is not regular text.
1987 if (par.isInset(pos1) || par.isInset(pos2))
1990 // Store the characters to be transposed (including font information).
1991 char_type const char1 = par.getChar(pos1);
1993 par.getFontSettings(cur.buffer()->params(), pos1);
1995 char_type const char2 = par.getChar(pos2);
1997 par.getFontSettings(cur.buffer()->params(), pos2);
1999 // And finally, we are ready to perform the transposition.
2000 // Track the changes if Change Tracking is enabled.
2001 bool const trackChanges = cur.buffer()->params().trackChanges;
2005 par.eraseChar(pos2, trackChanges);
2006 par.eraseChar(pos1, trackChanges);
2007 par.insertChar(pos1, char2, font2, trackChanges);
2008 par.insertChar(pos2, char1, font1, trackChanges);
2010 cur.checkBufferStructure();
2012 // After the transposition, move cursor to after the transposition.
2013 setCursor(cur, cur.pit(), pos2);
2018 DocIterator Text::macrocontextPosition() const
2020 return macrocontext_position_;
2024 void Text::setMacrocontextPosition(DocIterator const & pos)
2026 macrocontext_position_ = pos;
2030 docstring Text::previousWord(CursorSlice const & sl) const
2032 CursorSlice from = sl;
2033 CursorSlice to = sl;
2034 getWord(from, to, PREVIOUS_WORD);
2035 if (sl == from || to == from)
2038 Paragraph const & par = sl.paragraph();
2039 return par.asString(from.pos(), to.pos());
2043 bool Text::completionSupported(Cursor const & cur) const
2045 Paragraph const & par = cur.paragraph();
2046 return cur.pos() > 0
2047 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2048 && !par.isWordSeparator(cur.pos() - 1);
2052 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2054 return new TextCompletionList(cur);
2058 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2060 LASSERT(cur.bv().cursor() == cur, /**/);
2062 cur.bv().cursor() = cur;
2063 if (!(cur.disp_.update() & Update::Force))
2064 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2069 docstring Text::completionPrefix(Cursor const & cur) const
2071 return previousWord(cur.top());