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"
33 #include "ErrorList.h"
34 #include "FuncRequest.h"
36 #include "InsetList.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48 #include "WordLangTuple.h"
51 #include "insets/InsetText.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetCaption.h"
54 #include "insets/InsetNewline.h"
55 #include "insets/InsetNewpage.h"
56 #include "insets/InsetArgument.h"
57 #include "insets/InsetIPAMacro.h"
58 #include "insets/InsetSpace.h"
59 #include "insets/InsetSpecialChar.h"
60 #include "insets/InsetTabular.h"
62 #include "support/convert.h"
63 #include "support/debug.h"
64 #include "support/docstream.h"
65 #include "support/gettext.h"
66 #include "support/lassert.h"
67 #include "support/lstrings.h"
68 #include "support/textutils.h"
70 #include <boost/next_prior.hpp>
76 // TODO: replace if in Text::readParToken() with compile time switch
79 #include "support/metahash.h"
81 typedef boost::mpl::string<'\\end','_lay','out'> end_layout;
82 typedef boost::mpl::string<'\\end','in','set'> end_inset;
86 std::string token = "\\end_layout";
88 switch (boost::hash_value(token)) {
89 case lyx::support::hash_string<end_layout>::value:
91 case lyx::support::hash_string<end_inset>::value:
101 using namespace lyx::support;
105 using cap::cutSelection;
106 using cap::pasteParagraphList;
108 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
109 Paragraph & toPar, pos_type toPos, BufferParams const & params)
111 // Note: moveItem() does not honour change tracking!
112 // Therefore, it should only be used for breaking and merging paragraphs
114 // We need a copy here because the character at fromPos is going to be erased.
115 Font const tmpFont = fromPar.getFontSettings(params, fromPos);
116 Change const tmpChange = fromPar.lookupChange(fromPos);
118 if (Inset * tmpInset = fromPar.getInset(fromPos)) {
119 fromPar.releaseInset(fromPos);
120 // The inset is not in fromPar any more.
121 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
128 char_type const tmpChar = fromPar.getChar(fromPos);
129 fromPar.eraseChar(fromPos, false);
130 toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
135 void breakParagraphConservative(BufferParams const & bparams,
136 ParagraphList & pars, pit_type par_offset, pos_type pos)
138 // create a new paragraph
139 Paragraph & tmp = *pars.insert(boost::next(pars.begin(), par_offset + 1),
141 Paragraph & par = pars[par_offset];
143 tmp.setInsetOwner(&par.inInset());
144 tmp.makeSameLayout(par);
146 LASSERT(pos <= par.size(), /**/);
148 if (pos < par.size()) {
149 // move everything behind the break position to the new paragraph
150 pos_type pos_end = par.size() - 1;
152 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
153 if (moveItem(par, pos, tmp, j, bparams)) {
157 // Move over the end-of-par change information
158 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
159 par.setChange(par.size(), Change(bparams.trackChanges ?
160 Change::INSERTED : Change::UNCHANGED));
165 void mergeParagraph(BufferParams const & bparams,
166 ParagraphList & pars, pit_type par_offset)
168 Paragraph & next = pars[par_offset + 1];
169 Paragraph & par = pars[par_offset];
171 pos_type pos_end = next.size() - 1;
172 pos_type pos_insert = par.size();
174 // the imaginary end-of-paragraph character (at par.size()) has to be
175 // marked as unmodified. Otherwise, its change is adopted by the first
176 // character of the next paragraph.
177 if (par.isChanged(par.size())) {
178 LYXERR(Debug::CHANGES,
179 "merging par with inserted/deleted end-of-par character");
180 par.setChange(par.size(), Change(Change::UNCHANGED));
183 Change change = next.lookupChange(next.size());
185 // move the content of the second paragraph to the end of the first one
186 for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
187 if (moveItem(next, 0, par, j, bparams)) {
192 // move the change of the end-of-paragraph character
193 par.setChange(par.size(), change);
195 pars.erase(boost::next(pars.begin(), par_offset + 1));
199 Text::Text(InsetText * owner, bool use_default_layout)
200 : owner_(owner), autoBreakRows_(false), undo_counter_(0)
202 pars_.push_back(Paragraph());
203 Paragraph & par = pars_.back();
204 par.setInsetOwner(owner);
205 DocumentClass const & dc = owner->buffer().params().documentClass();
206 if (use_default_layout)
207 par.setDefaultLayout(dc);
209 par.setPlainLayout(dc);
213 Text::Text(InsetText * owner, Text const & text)
214 : owner_(owner), autoBreakRows_(text.autoBreakRows_), undo_counter_(0)
217 ParagraphList::iterator const end = pars_.end();
218 ParagraphList::iterator it = pars_.begin();
219 for (; it != end; ++it)
220 it->setInsetOwner(owner);
224 pit_type Text::depthHook(pit_type pit, depth_type depth) const
226 pit_type newpit = pit;
231 while (newpit != 0 && pars_[newpit].getDepth() > depth)
234 if (pars_[newpit].getDepth() > depth)
241 pit_type Text::outerHook(pit_type par_offset) const
243 Paragraph const & par = pars_[par_offset];
245 if (par.getDepth() == 0)
247 return depthHook(par_offset, depth_type(par.getDepth() - 1));
251 bool Text::isFirstInSequence(pit_type par_offset) const
253 Paragraph const & par = pars_[par_offset];
255 pit_type dhook_offset = depthHook(par_offset, par.getDepth());
257 if (dhook_offset == par_offset)
260 Paragraph const & dhook = pars_[dhook_offset];
262 return dhook.layout() != par.layout()
263 || dhook.getDepth() != par.getDepth();
267 int Text::getTocLevel(pit_type par_offset) const
269 Paragraph const & par = pars_[par_offset];
271 if (par.layout().isEnvironment() && !isFirstInSequence(par_offset))
272 return Layout::NOT_IN_TOC;
274 return par.layout().toclevel;
278 Font const Text::outerFont(pit_type par_offset) const
280 depth_type par_depth = pars_[par_offset].getDepth();
281 FontInfo tmpfont = inherit_font;
282 depth_type prev_par_depth = 0;
283 // Resolve against environment font information
284 while (par_offset != pit_type(pars_.size())
285 && par_depth != prev_par_depth
287 && !tmpfont.resolved()) {
288 prev_par_depth = par_depth;
289 par_offset = outerHook(par_offset);
290 if (par_offset != pit_type(pars_.size())) {
291 tmpfont.realize(pars_[par_offset].layout().font);
292 par_depth = pars_[par_offset].getDepth();
296 return Font(tmpfont);
300 static void acceptOrRejectChanges(ParagraphList & pars,
301 BufferParams const & bparams, Text::ChangeOp op)
303 pit_type pars_size = static_cast<pit_type>(pars.size());
305 // first, accept or reject changes within each individual
306 // paragraph (do not consider end-of-par)
307 for (pit_type pit = 0; pit < pars_size; ++pit) {
308 // prevent assertion failure
309 if (!pars[pit].empty()) {
310 if (op == Text::ACCEPT)
311 pars[pit].acceptChanges(0, pars[pit].size());
313 pars[pit].rejectChanges(0, pars[pit].size());
317 // next, accept or reject imaginary end-of-par characters
318 for (pit_type pit = 0; pit < pars_size; ++pit) {
319 pos_type pos = pars[pit].size();
320 if (pars[pit].isChanged(pos)) {
321 // keep the end-of-par char if it is inserted and accepted
322 // or when it is deleted and rejected.
323 if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
324 pars[pit].setChange(pos, Change(Change::UNCHANGED));
326 if (pit == pars_size - 1) {
327 // we cannot remove a par break at the end of the last
328 // paragraph; instead, we mark it unchanged
329 pars[pit].setChange(pos, Change(Change::UNCHANGED));
331 mergeParagraph(bparams, pars, pit);
341 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
343 acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
347 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
349 acceptOrRejectChanges(pars, bparams, Text::REJECT);
353 InsetText const & Text::inset() const
360 void Text::readParToken(Paragraph & par, Lexer & lex,
361 string const & token, Font & font, Change & change, ErrorList & errorList)
363 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
364 BufferParams const & bp = buf->params();
366 if (token[0] != '\\') {
367 docstring dstr = lex.getDocString();
368 par.appendString(dstr, font, change);
370 } else if (token == "\\begin_layout") {
372 docstring layoutname = lex.getDocString();
374 font = Font(inherit_font, bp.language);
375 change = Change(Change::UNCHANGED);
377 DocumentClass const & tclass = bp.documentClass();
379 if (layoutname.empty())
380 layoutname = tclass.defaultLayoutName();
382 if (owner_->forcePlainLayout()) {
383 // in this case only the empty layout is allowed
384 layoutname = tclass.plainLayoutName();
385 } else if (par.usePlainLayout()) {
386 // in this case, default layout maps to empty layout
387 if (layoutname == tclass.defaultLayoutName())
388 layoutname = tclass.plainLayoutName();
390 // otherwise, the empty layout maps to the default
391 if (layoutname == tclass.plainLayoutName())
392 layoutname = tclass.defaultLayoutName();
395 // When we apply an unknown layout to a document, we add this layout to the textclass
396 // of this document. For example, when you apply class article to a beamer document,
397 // all unknown layouts such as frame will be added to document class article so that
398 // these layouts can keep their original names.
399 bool const added_one = tclass.addLayoutIfNeeded(layoutname);
402 docstring const s = bformat(_("Layout `%1$s' was not found."), layoutname);
404 ErrorItem(_("Layout Not Found"), s, par.id(), 0, par.size()));
407 par.setLayout(bp.documentClass()[layoutname]);
409 // Test whether the layout is obsolete.
410 Layout const & layout = par.layout();
411 if (!layout.obsoleted_by().empty())
412 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
414 par.params().read(lex);
416 } else if (token == "\\end_layout") {
417 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
418 << "Missing \\begin_layout ?");
419 } else if (token == "\\end_inset") {
420 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
421 << "Missing \\begin_inset ?");
422 } else if (token == "\\begin_inset") {
423 Inset * inset = readInset(lex, buf);
425 par.insertInset(par.size(), inset, font, change);
428 docstring line = lex.getDocString();
429 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
430 par.id(), 0, par.size()));
432 } else if (token == "\\family") {
434 setLyXFamily(lex.getString(), font.fontInfo());
435 } else if (token == "\\series") {
437 setLyXSeries(lex.getString(), font.fontInfo());
438 } else if (token == "\\shape") {
440 setLyXShape(lex.getString(), font.fontInfo());
441 } else if (token == "\\size") {
443 setLyXSize(lex.getString(), font.fontInfo());
444 } else if (token == "\\lang") {
446 string const tok = lex.getString();
447 Language const * lang = languages.getLanguage(tok);
449 font.setLanguage(lang);
451 font.setLanguage(bp.language);
452 lex.printError("Unknown language `$$Token'");
454 } else if (token == "\\numeric") {
456 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
457 } else if (token == "\\emph") {
459 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
460 } else if (token == "\\bar") {
462 string const tok = lex.getString();
465 font.fontInfo().setUnderbar(FONT_ON);
466 else if (tok == "no")
467 font.fontInfo().setUnderbar(FONT_OFF);
468 else if (tok == "default")
469 font.fontInfo().setUnderbar(FONT_INHERIT);
471 lex.printError("Unknown bar font flag "
473 } else if (token == "\\strikeout") {
475 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
476 } else if (token == "\\uuline") {
478 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
479 } else if (token == "\\uwave") {
481 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
482 } else if (token == "\\noun") {
484 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
485 } else if (token == "\\color") {
487 setLyXColor(lex.getString(), font.fontInfo());
488 } else if (token == "\\SpecialChar") {
489 auto_ptr<Inset> inset;
490 inset.reset(new InsetSpecialChar);
492 inset->setBuffer(*buf);
493 par.insertInset(par.size(), inset.release(), font, change);
494 } else if (token == "\\IPAChar") {
495 auto_ptr<Inset> inset;
496 inset.reset(new InsetIPAChar);
498 inset->setBuffer(*buf);
499 par.insertInset(par.size(), inset.release(), font, change);
500 } else if (token == "\\backslash") {
501 par.appendChar('\\', font, change);
502 } else if (token == "\\LyXTable") {
503 auto_ptr<Inset> inset(new InsetTabular(buf));
505 par.insertInset(par.size(), inset.release(), font, change);
506 } else if (token == "\\change_unchanged") {
507 change = Change(Change::UNCHANGED);
508 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
510 istringstream is(lex.getString());
514 BufferParams::AuthorMap const & am = bp.author_map;
515 if (am.find(aid) == am.end()) {
516 errorList.push_back(ErrorItem(_("Change tracking error"),
517 bformat(_("Unknown author index for change: %1$d\n"), aid),
518 par.id(), 0, par.size()));
519 change = Change(Change::UNCHANGED);
521 if (token == "\\change_inserted")
522 change = Change(Change::INSERTED, am.find(aid)->second, ct);
524 change = Change(Change::DELETED, am.find(aid)->second, ct);
528 errorList.push_back(ErrorItem(_("Unknown token"),
529 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
531 par.id(), 0, par.size()));
536 void Text::readParagraph(Paragraph & par, Lexer & lex,
537 ErrorList & errorList)
540 string token = lex.getString();
542 Change change(Change::UNCHANGED);
545 readParToken(par, lex, token, font, change, errorList);
548 token = lex.getString();
553 if (token == "\\end_layout") {
554 //Ok, paragraph finished
558 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
559 if (token == "\\begin_layout" || token == "\\end_document"
560 || token == "\\end_inset" || token == "\\begin_deeper"
561 || token == "\\end_deeper") {
562 lex.pushToken(token);
563 lyxerr << "Paragraph ended in line "
564 << lex.lineNumber() << "\n"
565 << "Missing \\end_layout.\n";
569 // Final change goes to paragraph break:
570 par.setChange(par.size(), change);
572 // Initialize begin_of_body_ on load; redoParagraph maintains
573 par.setBeginOfBody();
575 // mark paragraph for spell checking on load
576 // par.requestSpellCheck();
580 class TextCompletionList : public CompletionList
584 TextCompletionList(Cursor const & cur, WordList const * list)
585 : buffer_(cur.buffer()), pos_(0), list_(list)
588 virtual ~TextCompletionList() {}
591 virtual bool sorted() const { return true; }
593 virtual size_t size() const
595 return list_->size();
598 virtual docstring const & data(size_t idx) const
600 return list_->word(idx);
605 Buffer const * buffer_;
609 WordList const * list_;
613 bool Text::empty() const
615 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
616 // FIXME: Should we consider the labeled type as empty too?
617 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
621 double Text::spacing(Paragraph const & par) const
623 if (par.params().spacing().isDefault())
624 return owner_->buffer().params().spacing().getValue();
625 return par.params().spacing().getValue();
630 * This breaks a paragraph at the specified position.
631 * The new paragraph will:
632 * - Decrease depth by one (or change layout to default layout) when
633 * keep_layout == false
634 * - keep current depth and layout when keep_layout == true
636 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
639 BufferParams const & bparams = text.inset().buffer().params();
640 ParagraphList & pars = text.paragraphs();
641 // create a new paragraph, and insert into the list
642 ParagraphList::iterator tmp =
643 pars.insert(boost::next(pars.begin(), par_offset + 1),
646 Paragraph & par = pars[par_offset];
648 // remember to set the inset_owner
649 tmp->setInsetOwner(&par.inInset());
650 // without doing that we get a crash when typing <Return> at the
651 // end of a paragraph
652 tmp->setPlainOrDefaultLayout(bparams.documentClass());
655 tmp->setLayout(par.layout());
656 tmp->setLabelWidthString(par.params().labelWidthString());
657 tmp->params().depth(par.params().depth());
658 } else if (par.params().depth() > 0) {
659 Paragraph const & hook = pars[text.outerHook(par_offset)];
660 tmp->setLayout(hook.layout());
661 // not sure the line below is useful
662 tmp->setLabelWidthString(par.params().labelWidthString());
663 tmp->params().depth(hook.params().depth());
666 bool const isempty = (par.allowEmpty() && par.empty());
668 if (!isempty && (par.size() > pos || par.empty())) {
669 tmp->setLayout(par.layout());
670 tmp->params().align(par.params().align());
671 tmp->setLabelWidthString(par.params().labelWidthString());
673 tmp->params().depth(par.params().depth());
674 tmp->params().noindent(par.params().noindent());
676 // move everything behind the break position
677 // to the new paragraph
679 /* Note: if !keepempty, empty() == true, then we reach
680 * here with size() == 0. So pos_end becomes - 1. This
681 * doesn't cause problems because both loops below
682 * enforce pos <= pos_end and 0 <= pos
684 pos_type pos_end = par.size() - 1;
686 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
687 if (moveItem(par, pos, *tmp, j, bparams)) {
693 // Move over the end-of-par change information
694 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
695 par.setChange(par.size(), Change(bparams.trackChanges ?
696 Change::INSERTED : Change::UNCHANGED));
699 // Make sure that we keep the language when
700 // breaking paragraph.
702 Font changed = tmp->getFirstFontSettings(bparams);
703 Font const & old = par.getFontSettings(bparams, par.size());
704 changed.setLanguage(old.language());
705 tmp->setFont(0, changed);
712 bool const soa = par.params().startOfAppendix();
713 par.params().clear();
714 // do not lose start of appendix marker (bug 4212)
715 par.params().startOfAppendix(soa);
716 par.setPlainOrDefaultLayout(bparams.documentClass());
720 par.setLayout(tmp->layout());
721 par.setLabelWidthString(tmp->params().labelWidthString());
722 par.params().depth(tmp->params().depth());
727 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
729 LASSERT(this == cur.text(), /**/);
731 Paragraph & cpar = cur.paragraph();
732 pit_type cpit = cur.pit();
734 DocumentClass const & tclass = cur.buffer()->params().documentClass();
735 Layout const & layout = cpar.layout();
737 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
738 if (changeDepthAllowed(cur, DEC_DEPTH))
739 changeDepth(cur, DEC_DEPTH);
741 setLayout(cur, tclass.defaultLayoutName());
747 // Always break behind a space
748 // It is better to erase the space (Dekel)
749 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
750 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
752 // What should the layout for the new paragraph be?
753 bool keep_layout = layout.isEnvironment()
754 || (layout.isParagraph() && layout.parbreak_is_newline);
756 keep_layout = !keep_layout;
758 // We need to remember this before we break the paragraph, because
759 // that invalidates the layout variable
760 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
762 // we need to set this before we insert the paragraph.
763 bool const isempty = cpar.allowEmpty() && cpar.empty();
765 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
767 // After this, neither paragraph contains any rows!
770 pit_type next_par = cpit + 1;
772 // well this is the caption hack since one caption is really enough
775 // set to standard-layout
776 //FIXME Check if this should be plainLayout() in some cases
777 pars_[cpit].applyLayout(tclass.defaultLayout());
779 // set to standard-layout
780 //FIXME Check if this should be plainLayout() in some cases
781 pars_[next_par].applyLayout(tclass.defaultLayout());
784 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
785 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
786 break; // the character couldn't be deleted physically due to change tracking
789 // A singlePar update is not enough in this case.
790 cur.screenUpdateFlags(Update::Force);
791 cur.forceBufferUpdate();
793 // This check is necessary. Otherwise the new empty paragraph will
794 // be deleted automatically. And it is more friendly for the user!
795 if (cur.pos() != 0 || isempty)
796 setCursor(cur, cur.pit() + 1, 0);
798 setCursor(cur, cur.pit(), 0);
802 // needed to insert the selection
803 void Text::insertStringAsLines(Cursor & cur, docstring const & str,
806 BufferParams const & bparams = owner_->buffer().params();
807 pit_type pit = cur.pit();
808 pos_type pos = cur.pos();
810 // insert the string, don't insert doublespace
811 bool space_inserted = true;
812 for (docstring::const_iterator cit = str.begin();
813 cit != str.end(); ++cit) {
814 Paragraph & par = pars_[pit];
816 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
817 lyx::breakParagraph(*this, pit, pos,
818 par.layout().isEnvironment());
821 space_inserted = true;
825 // do not insert consecutive spaces if !free_spacing
826 } else if ((*cit == ' ' || *cit == '\t') &&
827 space_inserted && !par.isFreeSpacing()) {
829 } else if (*cit == '\t') {
830 if (!par.isFreeSpacing()) {
831 // tabs are like spaces here
832 par.insertChar(pos, ' ', font, bparams.trackChanges);
834 space_inserted = true;
836 par.insertChar(pos, *cit, font, bparams.trackChanges);
838 space_inserted = true;
840 } else if (!isPrintable(*cit)) {
841 // Ignore unprintables
844 // just insert the character
845 par.insertChar(pos, *cit, font, bparams.trackChanges);
847 space_inserted = (*cit == ' ');
850 setCursor(cur, pit, pos);
854 // turn double CR to single CR, others are converted into one
855 // blank. Then insertStringAsLines is called
856 void Text::insertStringAsParagraphs(Cursor & cur, docstring const & str,
859 docstring linestr = str;
860 bool newline_inserted = false;
862 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
863 if (linestr[i] == '\n') {
864 if (newline_inserted) {
865 // we know that \r will be ignored by
866 // insertStringAsLines. Of course, it is a dirty
867 // trick, but it works...
868 linestr[i - 1] = '\r';
872 newline_inserted = true;
874 } else if (isPrintable(linestr[i])) {
875 newline_inserted = false;
878 insertStringAsLines(cur, linestr, font);
882 // insert a character, moves all the following breaks in the
883 // same Paragraph one to the right and make a rebreak
884 void Text::insertChar(Cursor & cur, char_type c)
886 LASSERT(this == cur.text(), /**/);
888 cur.recordUndo(INSERT_UNDO);
890 TextMetrics const & tm = cur.bv().textMetrics(this);
891 Buffer const & buffer = *cur.buffer();
892 Paragraph & par = cur.paragraph();
893 // try to remove this
894 pit_type const pit = cur.pit();
896 bool const freeSpacing = par.layout().free_spacing ||
899 if (lyxrc.auto_number) {
900 static docstring const number_operators = from_ascii("+-/*");
901 static docstring const number_unary_operators = from_ascii("+-");
902 static docstring const number_seperators = from_ascii(".,:");
904 if (cur.current_font.fontInfo().number() == FONT_ON) {
905 if (!isDigitASCII(c) && !contains(number_operators, c) &&
906 !(contains(number_seperators, c) &&
908 cur.pos() != cur.lastpos() &&
909 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
910 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
912 number(cur); // Set current_font.number to OFF
913 } else if (isDigitASCII(c) &&
914 cur.real_current_font.isVisibleRightToLeft()) {
915 number(cur); // Set current_font.number to ON
917 if (cur.pos() != 0) {
918 char_type const c = par.getChar(cur.pos() - 1);
919 if (contains(number_unary_operators, c) &&
921 || par.isSeparator(cur.pos() - 2)
922 || par.isNewline(cur.pos() - 2))
924 setCharFont(pit, cur.pos() - 1, cur.current_font,
926 } else if (contains(number_seperators, c)
928 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
929 setCharFont(pit, cur.pos() - 1, cur.current_font,
936 // In Bidi text, we want spaces to be treated in a special way: spaces
937 // which are between words in different languages should get the
938 // paragraph's language; otherwise, spaces should keep the language
939 // they were originally typed in. This is only in effect while typing;
940 // after the text is already typed in, the user can always go back and
941 // explicitly set the language of a space as desired. But 99.9% of the
942 // time, what we're doing here is what the user actually meant.
944 // The following cases are the ones in which the language of the space
945 // should be changed to match that of the containing paragraph. In the
946 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
947 // represents a space, pipe (|) represents the cursor position (so the
948 // character before it is the one just typed in). The different cases
949 // are depicted logically (not visually), from left to right:
954 // Theoretically, there are other situations that we should, perhaps, deal
955 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
956 // point (to understand why, just try to create this situation...).
958 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
959 // get font in front and behind the space in question. But do NOT
960 // use getFont(cur.pos()) because the character c is not inserted yet
961 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
962 Font const & post_space_font = cur.real_current_font;
963 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
964 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
966 if (pre_space_rtl != post_space_rtl) {
967 // Set the space's language to match the language of the
968 // adjacent character whose direction is the paragraph's
969 // direction; don't touch other properties of the font
970 Language const * lang =
971 (pre_space_rtl == par.isRTL(buffer.params())) ?
972 pre_space_font.language() : post_space_font.language();
974 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
975 space_font.setLanguage(lang);
976 par.setFont(cur.pos() - 1, space_font);
980 // Next check, if there will be two blanks together or a blank at
981 // the beginning of a paragraph.
982 // I decided to handle blanks like normal characters, the main
983 // difference are the special checks when calculating the row.fill
984 // (blank does not count at the end of a row) and the check here
986 // When the free-spacing option is set for the current layout,
987 // disable the double-space checking
988 if (!freeSpacing && isLineSeparatorChar(c)) {
989 if (cur.pos() == 0) {
991 "You cannot insert a space at the "
992 "beginning of a paragraph. Please read the Tutorial."));
995 LASSERT(cur.pos() > 0, /**/);
996 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
997 && !par.isDeleted(cur.pos() - 1)) {
999 "You cannot type two spaces this way. "
1000 "Please read the Tutorial."));
1005 par.insertChar(cur.pos(), c, cur.current_font,
1006 cur.buffer()->params().trackChanges);
1007 cur.checkBufferStructure();
1009 // cur.screenUpdateFlags(Update::Force);
1010 bool boundary = cur.boundary()
1011 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
1012 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
1017 void Text::charInserted(Cursor & cur)
1019 Paragraph & par = cur.paragraph();
1021 // Here we call finishUndo for every 20 characters inserted.
1022 // This is from my experience how emacs does it. (Lgb)
1023 if (undo_counter_ < 20) {
1030 // register word if a non-letter was entered
1032 && !par.isWordSeparator(cur.pos() - 2)
1033 && par.isWordSeparator(cur.pos() - 1)) {
1034 // get the word in front of cursor
1035 LASSERT(this == cur.text(), /**/);
1036 cur.paragraph().updateWords();
1041 // the cursor set functions have a special mechanism. When they
1042 // realize, that you left an empty paragraph, they will delete it.
1044 bool Text::cursorForwardOneWord(Cursor & cur)
1046 LASSERT(this == cur.text(), /**/);
1048 pos_type const lastpos = cur.lastpos();
1049 pit_type pit = cur.pit();
1050 pos_type pos = cur.pos();
1051 Paragraph const & par = cur.paragraph();
1053 // Paragraph boundary is a word boundary
1054 if (pos == lastpos) {
1055 if (pit != cur.lastpit())
1056 return setCursor(cur, pit + 1, 0);
1061 if (lyxrc.mac_like_word_movement) {
1062 // Skip through trailing punctuation and spaces.
1063 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1066 // Skip over either a non-char inset or a full word
1067 if (pos != lastpos && par.isWordSeparator(pos))
1069 else while (pos != lastpos && !par.isWordSeparator(pos))
1072 LASSERT(pos < lastpos, /**/); // see above
1073 if (!par.isWordSeparator(pos))
1074 while (pos != lastpos && !par.isWordSeparator(pos))
1076 else if (par.isChar(pos))
1077 while (pos != lastpos && par.isChar(pos))
1079 else if (!par.isSpace(pos)) // non-char inset
1082 // Skip over white space
1083 while (pos != lastpos && par.isSpace(pos))
1087 return setCursor(cur, pit, pos);
1091 bool Text::cursorBackwardOneWord(Cursor & cur)
1093 LASSERT(this == cur.text(), /**/);
1095 pit_type pit = cur.pit();
1096 pos_type pos = cur.pos();
1097 Paragraph & par = cur.paragraph();
1099 // Paragraph boundary is a word boundary
1100 if (pos == 0 && pit != 0)
1101 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1103 if (lyxrc.mac_like_word_movement) {
1104 // Skip through punctuation and spaces.
1105 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1108 // Skip over either a non-char inset or a full word
1109 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1111 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1114 // Skip over white space
1115 while (pos != 0 && par.isSpace(pos - 1))
1118 if (pos != 0 && !par.isWordSeparator(pos - 1))
1119 while (pos != 0 && !par.isWordSeparator(pos - 1))
1121 else if (pos != 0 && par.isChar(pos - 1))
1122 while (pos != 0 && par.isChar(pos - 1))
1124 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1128 return setCursor(cur, pit, pos);
1132 bool Text::cursorVisLeftOneWord(Cursor & cur)
1134 LASSERT(this == cur.text(), /**/);
1136 pos_type left_pos, right_pos;
1137 bool left_is_letter, right_is_letter;
1139 Cursor temp_cur = cur;
1141 // always try to move at least once...
1142 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1144 // collect some information about current cursor position
1145 temp_cur.getSurroundingPos(left_pos, right_pos);
1147 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1149 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1151 // if we're not at a letter/non-letter boundary, continue moving
1152 if (left_is_letter == right_is_letter)
1155 // we should stop when we have an LTR word on our right or an RTL word
1157 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1158 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1159 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1160 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1164 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1165 true, temp_cur.boundary());
1169 bool Text::cursorVisRightOneWord(Cursor & cur)
1171 LASSERT(this == cur.text(), /**/);
1173 pos_type left_pos, right_pos;
1174 bool left_is_letter, right_is_letter;
1176 Cursor temp_cur = cur;
1178 // always try to move at least once...
1179 while (temp_cur.posVisRight(true /* skip_inset */)) {
1181 // collect some information about current cursor position
1182 temp_cur.getSurroundingPos(left_pos, right_pos);
1184 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1186 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1188 // if we're not at a letter/non-letter boundary, continue moving
1189 if (left_is_letter == right_is_letter)
1192 // we should stop when we have an LTR word on our right or an RTL word
1194 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1195 temp_cur.buffer()->params(),
1196 left_pos).isRightToLeft())
1197 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1198 temp_cur.buffer()->params(),
1199 right_pos).isRightToLeft()))
1203 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1204 true, temp_cur.boundary());
1208 void Text::selectWord(Cursor & cur, word_location loc)
1210 LASSERT(this == cur.text(), /**/);
1211 CursorSlice from = cur.top();
1212 CursorSlice to = cur.top();
1213 getWord(from, to, loc);
1214 if (cur.top() != from)
1215 setCursor(cur, from.pit(), from.pos());
1218 if (!cur.selection())
1220 setCursor(cur, to.pit(), to.pos());
1222 cur.setWordSelection(true);
1226 void Text::selectAll(Cursor & cur)
1228 LASSERT(this == cur.text(), /**/);
1229 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1231 // If the cursor is at the beginning, make sure the cursor ends there
1232 if (cur.pit() == 0 && cur.pos() == 0) {
1233 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1235 setCursor(cur, 0, 0);
1237 setCursor(cur, 0, 0);
1239 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1245 // Select the word currently under the cursor when no
1246 // selection is currently set
1247 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1249 LASSERT(this == cur.text(), /**/);
1250 if (cur.selection())
1252 selectWord(cur, loc);
1253 return cur.selection();
1257 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1259 LASSERT(this == cur.text(), /**/);
1261 if (!cur.selection()) {
1262 bool const changed = cur.paragraph().isChanged(cur.pos());
1263 if (!(changed && findNextChange(&cur.bv())))
1267 cur.recordUndoSelection();
1269 pit_type begPit = cur.selectionBegin().pit();
1270 pit_type endPit = cur.selectionEnd().pit();
1272 pos_type begPos = cur.selectionBegin().pos();
1273 pos_type endPos = cur.selectionEnd().pos();
1275 // keep selection info, because endPos becomes invalid after the first loop
1276 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1278 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1280 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1281 pos_type parSize = pars_[pit].size();
1283 // ignore empty paragraphs; otherwise, an assertion will fail for
1284 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1288 // do not consider first paragraph if the cursor starts at pos size()
1289 if (pit == begPit && begPos == parSize)
1292 // do not consider last paragraph if the cursor ends at pos 0
1293 if (pit == endPit && endPos == 0)
1294 break; // last iteration anyway
1296 pos_type left = (pit == begPit ? begPos : 0);
1297 pos_type right = (pit == endPit ? endPos : parSize);
1300 // there is no change here
1304 pars_[pit].acceptChanges(left, right);
1306 pars_[pit].rejectChanges(left, right);
1310 // next, accept/reject imaginary end-of-par characters
1312 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1313 pos_type pos = pars_[pit].size();
1315 // skip if the selection ends before the end-of-par
1316 if (pit == endPit && endsBeforeEndOfPar)
1317 break; // last iteration anyway
1319 // skip if this is not the last paragraph of the document
1320 // note: the user should be able to accept/reject the par break of the last par!
1321 if (pit == endPit && pit + 1 != int(pars_.size()))
1322 break; // last iteration anway
1325 if (pars_[pit].isInserted(pos)) {
1326 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1327 } else if (pars_[pit].isDeleted(pos)) {
1328 if (pit + 1 == int(pars_.size())) {
1329 // we cannot remove a par break at the end of the last paragraph;
1330 // instead, we mark it unchanged
1331 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1333 mergeParagraph(cur.buffer()->params(), pars_, pit);
1339 if (pars_[pit].isDeleted(pos)) {
1340 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1341 } else if (pars_[pit].isInserted(pos)) {
1342 if (pit + 1 == int(pars_.size())) {
1343 // we mark the par break at the end of the last paragraph unchanged
1344 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1346 mergeParagraph(cur.buffer()->params(), pars_, pit);
1354 // finally, invoke the DEPM
1356 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1361 cur.clearSelection();
1362 setCursorIntern(cur, begPit, begPos);
1363 cur.screenUpdateFlags(Update::Force);
1364 cur.forceBufferUpdate();
1368 void Text::acceptChanges()
1370 BufferParams const & bparams = owner_->buffer().params();
1371 lyx::acceptChanges(pars_, bparams);
1372 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1376 void Text::rejectChanges()
1378 BufferParams const & bparams = owner_->buffer().params();
1379 pit_type pars_size = static_cast<pit_type>(pars_.size());
1381 // first, reject changes within each individual paragraph
1382 // (do not consider end-of-par)
1383 for (pit_type pit = 0; pit < pars_size; ++pit) {
1384 if (!pars_[pit].empty()) // prevent assertion failure
1385 pars_[pit].rejectChanges(0, pars_[pit].size());
1388 // next, reject imaginary end-of-par characters
1389 for (pit_type pit = 0; pit < pars_size; ++pit) {
1390 pos_type pos = pars_[pit].size();
1392 if (pars_[pit].isDeleted(pos)) {
1393 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1394 } else if (pars_[pit].isInserted(pos)) {
1395 if (pit == pars_size - 1) {
1396 // we mark the par break at the end of the last
1397 // paragraph unchanged
1398 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1400 mergeParagraph(bparams, pars_, pit);
1407 // finally, invoke the DEPM
1408 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1412 void Text::deleteWordForward(Cursor & cur)
1414 LASSERT(this == cur.text(), /**/);
1415 if (cur.lastpos() == 0)
1419 cur.setSelection(true);
1420 cursorForwardOneWord(cur);
1422 cutSelection(cur, true, false);
1423 cur.checkBufferStructure();
1428 void Text::deleteWordBackward(Cursor & cur)
1430 LASSERT(this == cur.text(), /**/);
1431 if (cur.lastpos() == 0)
1432 cursorBackward(cur);
1435 cur.setSelection(true);
1436 cursorBackwardOneWord(cur);
1438 cutSelection(cur, true, false);
1439 cur.checkBufferStructure();
1444 // Kill to end of line.
1445 void Text::changeCase(Cursor & cur, TextCase action)
1447 LASSERT(this == cur.text(), /**/);
1451 bool gotsel = false;
1452 if (cur.selection()) {
1453 from = cur.selBegin();
1458 getWord(from, to, PARTIAL_WORD);
1459 cursorForwardOneWord(cur);
1462 cur.recordUndoSelection();
1464 pit_type begPit = from.pit();
1465 pit_type endPit = to.pit();
1467 pos_type begPos = from.pos();
1468 pos_type endPos = to.pos();
1470 pos_type right = 0; // needed after the for loop
1472 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1473 Paragraph & par = pars_[pit];
1474 pos_type const pos = (pit == begPit ? begPos : 0);
1475 right = (pit == endPit ? endPos : par.size());
1476 par.changeCase(cur.buffer()->params(), pos, right, action);
1479 // the selection may have changed due to logically-only deleted chars
1481 setCursor(cur, begPit, begPos);
1483 setCursor(cur, endPit, right);
1486 setCursor(cur, endPit, right);
1488 cur.checkBufferStructure();
1492 bool Text::handleBibitems(Cursor & cur)
1494 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1500 BufferParams const & bufparams = cur.buffer()->params();
1501 Paragraph const & par = cur.paragraph();
1502 Cursor prevcur = cur;
1503 if (cur.pit() > 0) {
1505 prevcur.pos() = prevcur.lastpos();
1507 Paragraph const & prevpar = prevcur.paragraph();
1509 // if a bibitem is deleted, merge with previous paragraph
1510 // if this is a bibliography item as well
1511 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1512 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1513 mergeParagraph(bufparams, cur.text()->paragraphs(),
1515 cur.forceBufferUpdate();
1516 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1517 cur.screenUpdateFlags(Update::Force);
1521 // otherwise reset to default
1522 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1527 bool Text::erase(Cursor & cur)
1529 LASSERT(this == cur.text(), return false);
1530 bool needsUpdate = false;
1531 Paragraph & par = cur.paragraph();
1533 if (cur.pos() != cur.lastpos()) {
1534 // this is the code for a normal delete, not pasting
1536 cur.recordUndo(DELETE_UNDO);
1537 bool const was_inset = cur.paragraph().isInset(cur.pos());
1538 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1539 // the character has been logically deleted only => skip it
1540 cur.top().forwardPos();
1543 cur.forceBufferUpdate();
1545 cur.checkBufferStructure();
1548 if (cur.pit() == cur.lastpit())
1549 return dissolveInset(cur);
1551 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1552 par.setChange(cur.pos(), Change(Change::DELETED));
1556 setCursorIntern(cur, cur.pit() + 1, 0);
1557 needsUpdate = backspacePos0(cur);
1561 needsUpdate |= handleBibitems(cur);
1564 // Make sure the cursor is correct. Is this really needed?
1565 // No, not really... at least not here!
1566 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1567 cur.checkBufferStructure();
1574 bool Text::backspacePos0(Cursor & cur)
1576 LASSERT(this == cur.text(), /**/);
1580 bool needsUpdate = false;
1582 BufferParams const & bufparams = cur.buffer()->params();
1583 DocumentClass const & tclass = bufparams.documentClass();
1584 ParagraphList & plist = cur.text()->paragraphs();
1585 Paragraph const & par = cur.paragraph();
1586 Cursor prevcur = cur;
1588 prevcur.pos() = prevcur.lastpos();
1589 Paragraph const & prevpar = prevcur.paragraph();
1591 // is it an empty paragraph?
1592 if (cur.lastpos() == 0
1593 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1594 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1595 plist.erase(boost::next(plist.begin(), cur.pit()));
1598 // is previous par empty?
1599 else if (prevcur.lastpos() == 0
1600 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1601 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1602 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1605 // Pasting is not allowed, if the paragraphs have different
1606 // layouts. I think it is a real bug of all other
1607 // word processors to allow it. It confuses the user.
1608 // Correction: Pasting is always allowed with standard-layout
1609 // or the empty layout.
1610 else if (par.layout() == prevpar.layout()
1611 || tclass.isDefaultLayout(par.layout())
1612 || tclass.isPlainLayout(par.layout())) {
1613 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1614 mergeParagraph(bufparams, plist, prevcur.pit());
1619 cur.forceBufferUpdate();
1620 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1627 bool Text::backspace(Cursor & cur)
1629 LASSERT(this == cur.text(), /**/);
1630 bool needsUpdate = false;
1631 if (cur.pos() == 0) {
1633 return dissolveInset(cur);
1635 Paragraph & prev_par = pars_[cur.pit() - 1];
1637 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1638 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1639 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1642 // The cursor is at the beginning of a paragraph, so
1643 // the backspace will collapse two paragraphs into one.
1644 needsUpdate = backspacePos0(cur);
1647 // this is the code for a normal backspace, not pasting
1649 cur.recordUndo(DELETE_UNDO);
1650 // We used to do cursorBackwardIntern() here, but it is
1651 // not a good idea since it triggers the auto-delete
1652 // mechanism. So we do a cursorBackwardIntern()-lite,
1653 // without the dreaded mechanism. (JMarc)
1654 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1655 false, cur.boundary());
1656 bool const was_inset = cur.paragraph().isInset(cur.pos());
1657 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1659 cur.forceBufferUpdate();
1661 cur.checkBufferStructure();
1664 if (cur.pos() == cur.lastpos())
1665 cur.setCurrentFont();
1667 needsUpdate |= handleBibitems(cur);
1669 // A singlePar update is not enough in this case.
1670 // cur.screenUpdateFlags(Update::Force);
1671 setCursor(cur.top(), cur.pit(), cur.pos());
1677 bool Text::dissolveInset(Cursor & cur)
1679 LASSERT(this == cur.text(), return false);
1681 if (isMainText() || cur.inset().nargs() != 1)
1684 cur.recordUndoInset();
1686 cur.selHandle(false);
1688 pos_type spos = cur.pos();
1689 pit_type spit = cur.pit();
1690 ParagraphList plist;
1691 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1692 plist = paragraphs();
1694 // store cursor offset
1698 Buffer & b = *cur.buffer();
1699 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1701 if (!plist.empty()) {
1703 // we clear the cache so that we won't get conflicts with labels
1704 // that get pasted into the buffer. we should update this before
1705 // its being empty matters. if not (i.e., if we encounter bugs),
1706 // then this should instead be:
1707 // cur.buffer().updateBuffer();
1708 // but we'll try the cheaper solution here.
1709 cur.buffer()->clearReferenceCache();
1711 // ERT paragraphs have the Language latex_language.
1712 // This is invalid outside of ERT, so we need to
1713 // change it to the buffer language.
1714 ParagraphList::iterator it = plist.begin();
1715 ParagraphList::iterator it_end = plist.end();
1716 for (; it != it_end; ++it)
1717 it->changeLanguage(b.params(), latex_language, b.language());
1719 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1720 b.errorList("Paste"));
1722 cur.pit() = min(cur.lastpit(), spit);
1723 cur.pos() = min(cur.lastpos(), spos);
1726 cur.forceBufferUpdate();
1728 // Ensure the current language is set correctly (bug 6292)
1729 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1730 cur.clearSelection();
1736 void Text::getWord(CursorSlice & from, CursorSlice & to,
1737 word_location const loc) const
1740 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1744 void Text::write(ostream & os) const
1746 Buffer const & buf = owner_->buffer();
1747 ParagraphList::const_iterator pit = paragraphs().begin();
1748 ParagraphList::const_iterator end = paragraphs().end();
1750 for (; pit != end; ++pit)
1751 pit->write(os, buf.params(), dth);
1753 // Close begin_deeper
1754 for(; dth > 0; --dth)
1755 os << "\n\\end_deeper";
1759 bool Text::read(Lexer & lex,
1760 ErrorList & errorList, InsetText * insetPtr)
1762 Buffer const & buf = owner_->buffer();
1763 depth_type depth = 0;
1766 while (lex.isOK()) {
1768 string const token = lex.getString();
1773 if (token == "\\end_inset")
1776 if (token == "\\end_body")
1779 if (token == "\\begin_body")
1782 if (token == "\\end_document") {
1787 if (token == "\\begin_layout") {
1788 lex.pushToken(token);
1791 par.setInsetOwner(insetPtr);
1792 par.params().depth(depth);
1793 par.setFont(0, Font(inherit_font, buf.params().language));
1794 pars_.push_back(par);
1795 readParagraph(pars_.back(), lex, errorList);
1797 // register the words in the global word list
1798 pars_.back().updateWords();
1799 } else if (token == "\\begin_deeper") {
1801 } else if (token == "\\end_deeper") {
1803 lex.printError("\\end_deeper: " "depth is already null");
1807 LYXERR0("Handling unknown body token: `" << token << '\'');
1811 // avoid a crash on weird documents (bug 4859)
1812 if (pars_.empty()) {
1814 par.setInsetOwner(insetPtr);
1815 par.params().depth(depth);
1816 par.setFont(0, Font(inherit_font,
1817 buf.params().language));
1818 par.setPlainOrDefaultLayout(buf.params().documentClass());
1819 pars_.push_back(par);
1826 // Returns the current font and depth as a message.
1827 docstring Text::currentState(Cursor const & cur) const
1829 LASSERT(this == cur.text(), /**/);
1830 Buffer & buf = *cur.buffer();
1831 Paragraph const & par = cur.paragraph();
1832 odocstringstream os;
1834 if (buf.params().trackChanges)
1835 os << _("[Change Tracking] ");
1837 Change change = par.lookupChange(cur.pos());
1839 if (change.changed()) {
1840 Author const & a = buf.params().authors().get(change.author);
1841 os << _("Change: ") << a.name();
1842 if (!a.email().empty())
1843 os << " (" << a.email() << ")";
1844 // FIXME ctime is english, we should translate that
1845 os << _(" at ") << ctime(&change.changetime);
1849 // I think we should only show changes from the default
1851 // No, from the document font (MV)
1852 Font font = cur.real_current_font;
1853 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1855 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1857 // The paragraph depth
1858 int depth = cur.paragraph().getDepth();
1860 os << bformat(_(", Depth: %1$d"), depth);
1862 // The paragraph spacing, but only if different from
1864 Spacing const & spacing = par.params().spacing();
1865 if (!spacing.isDefault()) {
1866 os << _(", Spacing: ");
1867 switch (spacing.getSpace()) {
1868 case Spacing::Single:
1871 case Spacing::Onehalf:
1874 case Spacing::Double:
1877 case Spacing::Other:
1878 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1880 case Spacing::Default:
1881 // should never happen, do nothing
1886 #ifdef DEVEL_VERSION
1887 os << _(", Inset: ") << &cur.inset();
1888 os << _(", Paragraph: ") << cur.pit();
1889 os << _(", Id: ") << par.id();
1890 os << _(", Position: ") << cur.pos();
1891 // FIXME: Why is the check for par.size() needed?
1892 // We are called with cur.pos() == par.size() quite often.
1893 if (!par.empty() && cur.pos() < par.size()) {
1894 // Force output of code point, not character
1895 size_t const c = par.getChar(cur.pos());
1896 os << _(", Char: 0x") << hex << c;
1898 os << _(", Boundary: ") << cur.boundary();
1899 // Row & row = cur.textRow();
1900 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1906 docstring Text::getPossibleLabel(Cursor const & cur) const
1908 pit_type pit = cur.pit();
1910 Layout const * layout = &(pars_[pit].layout());
1913 docstring par_text = pars_[pit].asString();
1915 // The return string of math matrices might contain linebreaks
1916 par_text = subst(par_text, '\n', '-');
1917 int const numwords = 3;
1918 for (int i = 0; i < numwords; ++i) {
1919 if (par_text.empty())
1922 par_text = split(par_text, head, ' ');
1923 // Is it legal to use spaces in labels ?
1929 // Make sure it isn't too long
1930 unsigned int const max_label_length = 32;
1931 if (text.size() > max_label_length)
1932 text.resize(max_label_length);
1934 // Will contain the label prefix.
1937 // For section, subsection, etc...
1938 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1939 Layout const * layout2 = &(pars_[pit - 1].layout());
1940 if (layout2->latextype != LATEX_PARAGRAPH) {
1945 if (layout->latextype != LATEX_PARAGRAPH)
1946 name = layout->refprefix;
1948 // For captions, we just take the caption type
1949 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1950 if (caption_inset) {
1951 string const & ftype = static_cast<InsetCaption *>(caption_inset)->floattype();
1952 FloatList const & fl = cur.buffer()->params().documentClass().floats();
1953 if (fl.typeExist(ftype)) {
1954 Floating const & flt = fl.getType(ftype);
1955 name = from_utf8(flt.refPrefix());
1958 name = from_utf8(ftype.substr(0,3));
1961 // If none of the above worked, see if the inset knows.
1963 InsetLayout const & il = cur.inset().getLayout();
1964 name = il.refprefix();
1968 text = name + ':' + text;
1970 // We need a unique label
1971 docstring label = text;
1973 while (cur.buffer()->insetLabel(label)) {
1974 label = text + '-' + convert<docstring>(i);
1982 docstring Text::asString(int options) const
1984 return asString(0, pars_.size(), options);
1988 docstring Text::asString(pit_type beg, pit_type end, int options) const
1990 size_t i = size_t(beg);
1991 docstring str = pars_[i].asString(options);
1992 for (++i; i != size_t(end); ++i) {
1994 str += pars_[i].asString(options);
2000 void Text::forToc(docstring & os, size_t maxlen, bool shorten) const
2003 maxlen = std::numeric_limits<std::size_t>::max();
2005 LASSERT(maxlen >= 8, maxlen = TOC_ENTRY_LENGTH);
2006 for (size_t i = 0; i != pars_.size() && os.length() < maxlen; ++i)
2007 pars_[i].forToc(os, maxlen);
2008 if (shorten && os.length() >= maxlen)
2009 os = os.substr(0, maxlen - 3) + from_ascii("...");
2013 void Text::charsTranspose(Cursor & cur)
2015 LASSERT(this == cur.text(), /**/);
2017 pos_type pos = cur.pos();
2019 // If cursor is at beginning or end of paragraph, do nothing.
2020 if (pos == cur.lastpos() || pos == 0)
2023 Paragraph & par = cur.paragraph();
2025 // Get the positions of the characters to be transposed.
2026 pos_type pos1 = pos - 1;
2027 pos_type pos2 = pos;
2029 // In change tracking mode, ignore deleted characters.
2030 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2032 if (pos2 == cur.lastpos())
2035 while (pos1 >= 0 && par.isDeleted(pos1))
2040 // Don't do anything if one of the "characters" is not regular text.
2041 if (par.isInset(pos1) || par.isInset(pos2))
2044 // Store the characters to be transposed (including font information).
2045 char_type const char1 = par.getChar(pos1);
2047 par.getFontSettings(cur.buffer()->params(), pos1);
2049 char_type const char2 = par.getChar(pos2);
2051 par.getFontSettings(cur.buffer()->params(), pos2);
2053 // And finally, we are ready to perform the transposition.
2054 // Track the changes if Change Tracking is enabled.
2055 bool const trackChanges = cur.buffer()->params().trackChanges;
2059 par.eraseChar(pos2, trackChanges);
2060 par.eraseChar(pos1, trackChanges);
2061 par.insertChar(pos1, char2, font2, trackChanges);
2062 par.insertChar(pos2, char1, font1, trackChanges);
2064 cur.checkBufferStructure();
2066 // After the transposition, move cursor to after the transposition.
2067 setCursor(cur, cur.pit(), pos2);
2072 DocIterator Text::macrocontextPosition() const
2074 return macrocontext_position_;
2078 void Text::setMacrocontextPosition(DocIterator const & pos)
2080 macrocontext_position_ = pos;
2084 docstring Text::previousWord(CursorSlice const & sl) const
2086 CursorSlice from = sl;
2087 CursorSlice to = sl;
2088 getWord(from, to, PREVIOUS_WORD);
2089 if (sl == from || to == from)
2092 Paragraph const & par = sl.paragraph();
2093 return par.asString(from.pos(), to.pos());
2097 bool Text::completionSupported(Cursor const & cur) const
2099 Paragraph const & par = cur.paragraph();
2100 return cur.pos() > 0
2101 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2102 && !par.isWordSeparator(cur.pos() - 1);
2106 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2108 WordList const * list = theWordList(*cur.getFont().language());
2109 return new TextCompletionList(cur, list);
2113 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2115 LASSERT(cur.bv().cursor() == cur, /**/);
2117 cur.bv().cursor() = cur;
2118 if (!(cur.result().screenUpdate() & Update::Force))
2119 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2124 docstring Text::completionPrefix(Cursor const & cur) const
2126 return previousWord(cur.top());