3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Dov Feldstern
9 * \author Jean-Marc Lasgouttes
11 * \author André Pönitz
12 * \author Stefan Schimanski
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "CompletionList.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
37 #include "InsetList.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TextMetrics.h"
49 #include "WordLangTuple.h"
52 #include "insets/InsetText.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetCaption.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetNewpage.h"
57 #include "insets/InsetArgument.h"
58 #include "insets/InsetIPAMacro.h"
59 #include "insets/InsetSpace.h"
60 #include "insets/InsetSpecialChar.h"
61 #include "insets/InsetTabular.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
71 #include <boost/next_prior.hpp>
77 // TODO: replace if in Text::readParToken() with compile time switch
80 #include "support/metahash.h"
82 typedef boost::mpl::string<'\\end','_lay','out'> end_layout;
83 typedef boost::mpl::string<'\\end','in','set'> end_inset;
87 std::string token = "\\end_layout";
89 switch (boost::hash_value(token)) {
90 case lyx::support::hash_string<end_layout>::value:
92 case lyx::support::hash_string<end_inset>::value:
102 using namespace lyx::support;
106 using cap::cutSelection;
107 using cap::pasteParagraphList;
109 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
110 Paragraph & toPar, pos_type toPos, BufferParams const & params)
112 // Note: moveItem() does not honour change tracking!
113 // Therefore, it should only be used for breaking and merging paragraphs
115 // We need a copy here because the character at fromPos is going to be erased.
116 Font const tmpFont = fromPar.getFontSettings(params, fromPos);
117 Change const tmpChange = fromPar.lookupChange(fromPos);
119 if (Inset * tmpInset = fromPar.getInset(fromPos)) {
120 fromPar.releaseInset(fromPos);
121 // The inset is not in fromPar any more.
122 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
129 char_type const tmpChar = fromPar.getChar(fromPos);
130 fromPar.eraseChar(fromPos, false);
131 toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
136 void breakParagraphConservative(BufferParams const & bparams,
137 ParagraphList & pars, pit_type par_offset, pos_type pos)
139 // create a new paragraph
140 Paragraph & tmp = *pars.insert(boost::next(pars.begin(), par_offset + 1),
142 Paragraph & par = pars[par_offset];
144 tmp.setInsetOwner(&par.inInset());
145 tmp.makeSameLayout(par);
147 LASSERT(pos <= par.size(), /**/);
149 if (pos < par.size()) {
150 // move everything behind the break position to the new paragraph
151 pos_type pos_end = par.size() - 1;
153 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
154 if (moveItem(par, pos, tmp, j, bparams)) {
158 // Move over the end-of-par change information
159 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
160 par.setChange(par.size(), Change(bparams.trackChanges ?
161 Change::INSERTED : Change::UNCHANGED));
166 void mergeParagraph(BufferParams const & bparams,
167 ParagraphList & pars, pit_type par_offset)
169 Paragraph & next = pars[par_offset + 1];
170 Paragraph & par = pars[par_offset];
172 pos_type pos_end = next.size() - 1;
173 pos_type pos_insert = par.size();
175 // the imaginary end-of-paragraph character (at par.size()) has to be
176 // marked as unmodified. Otherwise, its change is adopted by the first
177 // character of the next paragraph.
178 if (par.isChanged(par.size())) {
179 LYXERR(Debug::CHANGES,
180 "merging par with inserted/deleted end-of-par character");
181 par.setChange(par.size(), Change(Change::UNCHANGED));
184 Change change = next.lookupChange(next.size());
186 // move the content of the second paragraph to the end of the first one
187 for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
188 if (moveItem(next, 0, par, j, bparams)) {
193 // move the change of the end-of-paragraph character
194 par.setChange(par.size(), change);
196 pars.erase(boost::next(pars.begin(), par_offset + 1));
200 Text::Text(InsetText * owner, bool use_default_layout)
201 : owner_(owner), autoBreakRows_(false), undo_counter_(0)
203 pars_.push_back(Paragraph());
204 Paragraph & par = pars_.back();
205 par.setInsetOwner(owner);
206 DocumentClass const & dc = owner->buffer().params().documentClass();
207 if (use_default_layout)
208 par.setDefaultLayout(dc);
210 par.setPlainLayout(dc);
214 Text::Text(InsetText * owner, Text const & text)
215 : owner_(owner), autoBreakRows_(text.autoBreakRows_), undo_counter_(0)
218 ParagraphList::iterator const end = pars_.end();
219 ParagraphList::iterator it = pars_.begin();
220 for (; it != end; ++it)
221 it->setInsetOwner(owner);
225 pit_type Text::depthHook(pit_type pit, depth_type depth) const
227 pit_type newpit = pit;
232 while (newpit != 0 && pars_[newpit].getDepth() > depth)
235 if (pars_[newpit].getDepth() > depth)
242 pit_type Text::outerHook(pit_type par_offset) const
244 Paragraph const & par = pars_[par_offset];
246 if (par.getDepth() == 0)
248 return depthHook(par_offset, depth_type(par.getDepth() - 1));
252 bool Text::isFirstInSequence(pit_type par_offset) const
254 Paragraph const & par = pars_[par_offset];
256 pit_type dhook_offset = depthHook(par_offset, par.getDepth());
258 if (dhook_offset == par_offset)
261 Paragraph const & dhook = pars_[dhook_offset];
263 return dhook.layout() != par.layout()
264 || dhook.getDepth() != par.getDepth();
268 Font const Text::outerFont(pit_type par_offset) const
270 depth_type par_depth = pars_[par_offset].getDepth();
271 FontInfo tmpfont = inherit_font;
272 depth_type prev_par_depth = 0;
273 // Resolve against environment font information
274 while (par_offset != pit_type(pars_.size())
275 && par_depth != prev_par_depth
277 && !tmpfont.resolved()) {
278 prev_par_depth = par_depth;
279 par_offset = outerHook(par_offset);
280 if (par_offset != pit_type(pars_.size())) {
281 tmpfont.realize(pars_[par_offset].layout().font);
282 par_depth = pars_[par_offset].getDepth();
286 return Font(tmpfont);
290 static void acceptOrRejectChanges(ParagraphList & pars,
291 BufferParams const & bparams, Text::ChangeOp op)
293 pit_type pars_size = static_cast<pit_type>(pars.size());
295 // first, accept or reject changes within each individual
296 // paragraph (do not consider end-of-par)
297 for (pit_type pit = 0; pit < pars_size; ++pit) {
298 // prevent assertion failure
299 if (!pars[pit].empty()) {
300 if (op == Text::ACCEPT)
301 pars[pit].acceptChanges(0, pars[pit].size());
303 pars[pit].rejectChanges(0, pars[pit].size());
307 // next, accept or reject imaginary end-of-par characters
308 for (pit_type pit = 0; pit < pars_size; ++pit) {
309 pos_type pos = pars[pit].size();
310 if (pars[pit].isChanged(pos)) {
311 // keep the end-of-par char if it is inserted and accepted
312 // or when it is deleted and rejected.
313 if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
314 pars[pit].setChange(pos, Change(Change::UNCHANGED));
316 if (pit == pars_size - 1) {
317 // we cannot remove a par break at the end of the last
318 // paragraph; instead, we mark it unchanged
319 pars[pit].setChange(pos, Change(Change::UNCHANGED));
321 mergeParagraph(bparams, pars, pit);
331 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
333 acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
337 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
339 acceptOrRejectChanges(pars, bparams, Text::REJECT);
343 InsetText const & Text::inset() const
350 void Text::readParToken(Paragraph & par, Lexer & lex,
351 string const & token, Font & font, Change & change, ErrorList & errorList)
353 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
354 BufferParams const & bp = buf->params();
356 if (token[0] != '\\') {
357 docstring dstr = lex.getDocString();
358 par.appendString(dstr, font, change);
360 } else if (token == "\\begin_layout") {
362 docstring layoutname = lex.getDocString();
364 font = Font(inherit_font, bp.language);
365 change = Change(Change::UNCHANGED);
367 DocumentClass const & tclass = bp.documentClass();
369 if (layoutname.empty())
370 layoutname = tclass.defaultLayoutName();
372 if (owner_->forcePlainLayout()) {
373 // in this case only the empty layout is allowed
374 layoutname = tclass.plainLayoutName();
375 } else if (par.usePlainLayout()) {
376 // in this case, default layout maps to empty layout
377 if (layoutname == tclass.defaultLayoutName())
378 layoutname = tclass.plainLayoutName();
380 // otherwise, the empty layout maps to the default
381 if (layoutname == tclass.plainLayoutName())
382 layoutname = tclass.defaultLayoutName();
385 // When we apply an unknown layout to a document, we add this layout to the textclass
386 // of this document. For example, when you apply class article to a beamer document,
387 // all unknown layouts such as frame will be added to document class article so that
388 // these layouts can keep their original names.
389 bool const added_one = tclass.addLayoutIfNeeded(layoutname);
392 docstring const s = bformat(_("Layout `%1$s' was not found."), layoutname);
394 ErrorItem(_("Layout Not Found"), s, par.id(), 0, par.size()));
397 par.setLayout(bp.documentClass()[layoutname]);
399 // Test whether the layout is obsolete.
400 Layout const & layout = par.layout();
401 if (!layout.obsoleted_by().empty())
402 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
404 par.params().read(lex);
406 } else if (token == "\\end_layout") {
407 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
408 << "Missing \\begin_layout ?");
409 } else if (token == "\\end_inset") {
410 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
411 << "Missing \\begin_inset ?");
412 } else if (token == "\\begin_inset") {
413 Inset * inset = readInset(lex, buf);
415 par.insertInset(par.size(), inset, font, change);
418 docstring line = lex.getDocString();
419 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
420 par.id(), 0, par.size()));
422 } else if (token == "\\family") {
424 setLyXFamily(lex.getString(), font.fontInfo());
425 } else if (token == "\\series") {
427 setLyXSeries(lex.getString(), font.fontInfo());
428 } else if (token == "\\shape") {
430 setLyXShape(lex.getString(), font.fontInfo());
431 } else if (token == "\\size") {
433 setLyXSize(lex.getString(), font.fontInfo());
434 } else if (token == "\\lang") {
436 string const tok = lex.getString();
437 Language const * lang = languages.getLanguage(tok);
439 font.setLanguage(lang);
441 font.setLanguage(bp.language);
442 lex.printError("Unknown language `$$Token'");
444 } else if (token == "\\numeric") {
446 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
447 } else if (token == "\\emph") {
449 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
450 } else if (token == "\\bar") {
452 string const tok = lex.getString();
455 font.fontInfo().setUnderbar(FONT_ON);
456 else if (tok == "no")
457 font.fontInfo().setUnderbar(FONT_OFF);
458 else if (tok == "default")
459 font.fontInfo().setUnderbar(FONT_INHERIT);
461 lex.printError("Unknown bar font flag "
463 } else if (token == "\\strikeout") {
465 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
466 } else if (token == "\\uuline") {
468 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
469 } else if (token == "\\uwave") {
471 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
472 } else if (token == "\\noun") {
474 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
475 } else if (token == "\\color") {
477 setLyXColor(lex.getString(), font.fontInfo());
478 } else if (token == "\\SpecialChar") {
479 auto_ptr<Inset> inset;
480 inset.reset(new InsetSpecialChar);
482 inset->setBuffer(*buf);
483 par.insertInset(par.size(), inset.release(), font, change);
484 } else if (token == "\\IPAChar") {
485 auto_ptr<Inset> inset;
486 inset.reset(new InsetIPAChar);
488 inset->setBuffer(*buf);
489 par.insertInset(par.size(), inset.release(), font, change);
490 } else if (token == "\\backslash") {
491 par.appendChar('\\', font, change);
492 } else if (token == "\\LyXTable") {
493 auto_ptr<Inset> inset(new InsetTabular(buf));
495 par.insertInset(par.size(), inset.release(), font, change);
496 } else if (token == "\\change_unchanged") {
497 change = Change(Change::UNCHANGED);
498 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
500 istringstream is(lex.getString());
504 BufferParams::AuthorMap const & am = bp.author_map;
505 if (am.find(aid) == am.end()) {
506 errorList.push_back(ErrorItem(_("Change tracking error"),
507 bformat(_("Unknown author index for change: %1$d\n"), aid),
508 par.id(), 0, par.size()));
509 change = Change(Change::UNCHANGED);
511 if (token == "\\change_inserted")
512 change = Change(Change::INSERTED, am.find(aid)->second, ct);
514 change = Change(Change::DELETED, am.find(aid)->second, ct);
518 errorList.push_back(ErrorItem(_("Unknown token"),
519 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
521 par.id(), 0, par.size()));
526 void Text::readParagraph(Paragraph & par, Lexer & lex,
527 ErrorList & errorList)
530 string token = lex.getString();
532 Change change(Change::UNCHANGED);
535 readParToken(par, lex, token, font, change, errorList);
538 token = lex.getString();
543 if (token == "\\end_layout") {
544 //Ok, paragraph finished
548 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
549 if (token == "\\begin_layout" || token == "\\end_document"
550 || token == "\\end_inset" || token == "\\begin_deeper"
551 || token == "\\end_deeper") {
552 lex.pushToken(token);
553 lyxerr << "Paragraph ended in line "
554 << lex.lineNumber() << "\n"
555 << "Missing \\end_layout.\n";
559 // Final change goes to paragraph break:
560 par.setChange(par.size(), change);
562 // Initialize begin_of_body_ on load; redoParagraph maintains
563 par.setBeginOfBody();
565 // mark paragraph for spell checking on load
566 // par.requestSpellCheck();
570 class TextCompletionList : public CompletionList
574 TextCompletionList(Cursor const & cur, WordList const * list)
575 : buffer_(cur.buffer()), pos_(0), list_(list)
578 virtual ~TextCompletionList() {}
581 virtual bool sorted() const { return true; }
583 virtual size_t size() const
585 return list_->size();
588 virtual docstring const & data(size_t idx) const
590 return list_->word(idx);
595 Buffer const * buffer_;
599 WordList const * list_;
603 bool Text::empty() const
605 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
606 // FIXME: Should we consider the labeled type as empty too?
607 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
611 double Text::spacing(Paragraph const & par) const
613 if (par.params().spacing().isDefault())
614 return owner_->buffer().params().spacing().getValue();
615 return par.params().spacing().getValue();
620 * This breaks a paragraph at the specified position.
621 * The new paragraph will:
622 * - Decrease depth by one (or change layout to default layout) when
623 * keep_layout == false
624 * - keep current depth and layout when keep_layout == true
626 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
629 BufferParams const & bparams = text.inset().buffer().params();
630 ParagraphList & pars = text.paragraphs();
631 // create a new paragraph, and insert into the list
632 ParagraphList::iterator tmp =
633 pars.insert(boost::next(pars.begin(), par_offset + 1),
636 Paragraph & par = pars[par_offset];
638 // remember to set the inset_owner
639 tmp->setInsetOwner(&par.inInset());
640 // without doing that we get a crash when typing <Return> at the
641 // end of a paragraph
642 tmp->setPlainOrDefaultLayout(bparams.documentClass());
645 tmp->setLayout(par.layout());
646 tmp->setLabelWidthString(par.params().labelWidthString());
647 tmp->params().depth(par.params().depth());
648 } else if (par.params().depth() > 0) {
649 Paragraph const & hook = pars[text.outerHook(par_offset)];
650 tmp->setLayout(hook.layout());
651 // not sure the line below is useful
652 tmp->setLabelWidthString(par.params().labelWidthString());
653 tmp->params().depth(hook.params().depth());
656 bool const isempty = (par.allowEmpty() && par.empty());
658 if (!isempty && (par.size() > pos || par.empty())) {
659 tmp->setLayout(par.layout());
660 tmp->params().align(par.params().align());
661 tmp->setLabelWidthString(par.params().labelWidthString());
663 tmp->params().depth(par.params().depth());
664 tmp->params().noindent(par.params().noindent());
666 // move everything behind the break position
667 // to the new paragraph
669 /* Note: if !keepempty, empty() == true, then we reach
670 * here with size() == 0. So pos_end becomes - 1. This
671 * doesn't cause problems because both loops below
672 * enforce pos <= pos_end and 0 <= pos
674 pos_type pos_end = par.size() - 1;
676 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
677 if (moveItem(par, pos, *tmp, j, bparams)) {
683 // Move over the end-of-par change information
684 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
685 par.setChange(par.size(), Change(bparams.trackChanges ?
686 Change::INSERTED : Change::UNCHANGED));
689 // Make sure that we keep the language when
690 // breaking paragraph.
692 Font changed = tmp->getFirstFontSettings(bparams);
693 Font const & old = par.getFontSettings(bparams, par.size());
694 changed.setLanguage(old.language());
695 tmp->setFont(0, changed);
702 bool const soa = par.params().startOfAppendix();
703 par.params().clear();
704 // do not lose start of appendix marker (bug 4212)
705 par.params().startOfAppendix(soa);
706 par.setPlainOrDefaultLayout(bparams.documentClass());
710 par.setLayout(tmp->layout());
711 par.setLabelWidthString(tmp->params().labelWidthString());
712 par.params().depth(tmp->params().depth());
717 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
719 LASSERT(this == cur.text(), /**/);
721 Paragraph & cpar = cur.paragraph();
722 pit_type cpit = cur.pit();
724 DocumentClass const & tclass = cur.buffer()->params().documentClass();
725 Layout const & layout = cpar.layout();
727 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
728 if (changeDepthAllowed(cur, DEC_DEPTH))
729 changeDepth(cur, DEC_DEPTH);
731 setLayout(cur, tclass.defaultLayoutName());
737 // Always break behind a space
738 // It is better to erase the space (Dekel)
739 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
740 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
742 // What should the layout for the new paragraph be?
743 bool keep_layout = layout.isEnvironment()
744 || (layout.isParagraph() && layout.parbreak_is_newline);
746 keep_layout = !keep_layout;
748 // We need to remember this before we break the paragraph, because
749 // that invalidates the layout variable
750 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
752 // we need to set this before we insert the paragraph.
753 bool const isempty = cpar.allowEmpty() && cpar.empty();
755 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
757 // After this, neither paragraph contains any rows!
760 pit_type next_par = cpit + 1;
762 // well this is the caption hack since one caption is really enough
765 // set to standard-layout
766 //FIXME Check if this should be plainLayout() in some cases
767 pars_[cpit].applyLayout(tclass.defaultLayout());
769 // set to standard-layout
770 //FIXME Check if this should be plainLayout() in some cases
771 pars_[next_par].applyLayout(tclass.defaultLayout());
774 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
775 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
776 break; // the character couldn't be deleted physically due to change tracking
779 // A singlePar update is not enough in this case.
780 cur.screenUpdateFlags(Update::Force);
781 cur.forceBufferUpdate();
783 // This check is necessary. Otherwise the new empty paragraph will
784 // be deleted automatically. And it is more friendly for the user!
785 if (cur.pos() != 0 || isempty)
786 setCursor(cur, cur.pit() + 1, 0);
788 setCursor(cur, cur.pit(), 0);
792 // needed to insert the selection
793 void Text::insertStringAsLines(Cursor & cur, docstring const & str,
796 BufferParams const & bparams = owner_->buffer().params();
797 pit_type pit = cur.pit();
798 pos_type pos = cur.pos();
800 // insert the string, don't insert doublespace
801 bool space_inserted = true;
802 for (docstring::const_iterator cit = str.begin();
803 cit != str.end(); ++cit) {
804 Paragraph & par = pars_[pit];
806 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
807 lyx::breakParagraph(*this, pit, pos,
808 par.layout().isEnvironment());
811 space_inserted = true;
815 // do not insert consecutive spaces if !free_spacing
816 } else if ((*cit == ' ' || *cit == '\t') &&
817 space_inserted && !par.isFreeSpacing()) {
819 } else if (*cit == '\t') {
820 if (!par.isFreeSpacing()) {
821 // tabs are like spaces here
822 par.insertChar(pos, ' ', font, bparams.trackChanges);
824 space_inserted = true;
826 par.insertChar(pos, *cit, font, bparams.trackChanges);
828 space_inserted = true;
830 } else if (!isPrintable(*cit)) {
831 // Ignore unprintables
834 // just insert the character
835 par.insertChar(pos, *cit, font, bparams.trackChanges);
837 space_inserted = (*cit == ' ');
840 setCursor(cur, pit, pos);
844 // turn double CR to single CR, others are converted into one
845 // blank. Then insertStringAsLines is called
846 void Text::insertStringAsParagraphs(Cursor & cur, docstring const & str,
849 docstring linestr = str;
850 bool newline_inserted = false;
852 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
853 if (linestr[i] == '\n') {
854 if (newline_inserted) {
855 // we know that \r will be ignored by
856 // insertStringAsLines. Of course, it is a dirty
857 // trick, but it works...
858 linestr[i - 1] = '\r';
862 newline_inserted = true;
864 } else if (isPrintable(linestr[i])) {
865 newline_inserted = false;
868 insertStringAsLines(cur, linestr, font);
872 // insert a character, moves all the following breaks in the
873 // same Paragraph one to the right and make a rebreak
874 void Text::insertChar(Cursor & cur, char_type c)
876 LASSERT(this == cur.text(), /**/);
878 cur.recordUndo(INSERT_UNDO);
880 TextMetrics const & tm = cur.bv().textMetrics(this);
881 Buffer const & buffer = *cur.buffer();
882 Paragraph & par = cur.paragraph();
883 // try to remove this
884 pit_type const pit = cur.pit();
886 bool const freeSpacing = par.layout().free_spacing ||
889 if (lyxrc.auto_number) {
890 static docstring const number_operators = from_ascii("+-/*");
891 static docstring const number_unary_operators = from_ascii("+-");
892 static docstring const number_seperators = from_ascii(".,:");
894 if (cur.current_font.fontInfo().number() == FONT_ON) {
895 if (!isDigitASCII(c) && !contains(number_operators, c) &&
896 !(contains(number_seperators, c) &&
898 cur.pos() != cur.lastpos() &&
899 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
900 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
902 number(cur); // Set current_font.number to OFF
903 } else if (isDigitASCII(c) &&
904 cur.real_current_font.isVisibleRightToLeft()) {
905 number(cur); // Set current_font.number to ON
907 if (cur.pos() != 0) {
908 char_type const c = par.getChar(cur.pos() - 1);
909 if (contains(number_unary_operators, c) &&
911 || par.isSeparator(cur.pos() - 2)
912 || par.isNewline(cur.pos() - 2))
914 setCharFont(pit, cur.pos() - 1, cur.current_font,
916 } else if (contains(number_seperators, c)
918 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
919 setCharFont(pit, cur.pos() - 1, cur.current_font,
926 // In Bidi text, we want spaces to be treated in a special way: spaces
927 // which are between words in different languages should get the
928 // paragraph's language; otherwise, spaces should keep the language
929 // they were originally typed in. This is only in effect while typing;
930 // after the text is already typed in, the user can always go back and
931 // explicitly set the language of a space as desired. But 99.9% of the
932 // time, what we're doing here is what the user actually meant.
934 // The following cases are the ones in which the language of the space
935 // should be changed to match that of the containing paragraph. In the
936 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
937 // represents a space, pipe (|) represents the cursor position (so the
938 // character before it is the one just typed in). The different cases
939 // are depicted logically (not visually), from left to right:
944 // Theoretically, there are other situations that we should, perhaps, deal
945 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
946 // point (to understand why, just try to create this situation...).
948 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
949 // get font in front and behind the space in question. But do NOT
950 // use getFont(cur.pos()) because the character c is not inserted yet
951 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
952 Font const & post_space_font = cur.real_current_font;
953 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
954 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
956 if (pre_space_rtl != post_space_rtl) {
957 // Set the space's language to match the language of the
958 // adjacent character whose direction is the paragraph's
959 // direction; don't touch other properties of the font
960 Language const * lang =
961 (pre_space_rtl == par.isRTL(buffer.params())) ?
962 pre_space_font.language() : post_space_font.language();
964 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
965 space_font.setLanguage(lang);
966 par.setFont(cur.pos() - 1, space_font);
970 // Next check, if there will be two blanks together or a blank at
971 // the beginning of a paragraph.
972 // I decided to handle blanks like normal characters, the main
973 // difference are the special checks when calculating the row.fill
974 // (blank does not count at the end of a row) and the check here
976 // When the free-spacing option is set for the current layout,
977 // disable the double-space checking
978 if (!freeSpacing && isLineSeparatorChar(c)) {
979 if (cur.pos() == 0) {
981 "You cannot insert a space at the "
982 "beginning of a paragraph. Please read the Tutorial."));
985 LASSERT(cur.pos() > 0, /**/);
986 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
987 && !par.isDeleted(cur.pos() - 1)) {
989 "You cannot type two spaces this way. "
990 "Please read the Tutorial."));
995 par.insertChar(cur.pos(), c, cur.current_font,
996 cur.buffer()->params().trackChanges);
997 cur.checkBufferStructure();
999 // cur.screenUpdateFlags(Update::Force);
1000 bool boundary = cur.boundary()
1001 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
1002 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
1007 void Text::charInserted(Cursor & cur)
1009 Paragraph & par = cur.paragraph();
1011 // Here we call finishUndo for every 20 characters inserted.
1012 // This is from my experience how emacs does it. (Lgb)
1013 if (undo_counter_ < 20) {
1020 // register word if a non-letter was entered
1022 && !par.isWordSeparator(cur.pos() - 2)
1023 && par.isWordSeparator(cur.pos() - 1)) {
1024 // get the word in front of cursor
1025 LASSERT(this == cur.text(), /**/);
1026 cur.paragraph().updateWords();
1031 // the cursor set functions have a special mechanism. When they
1032 // realize, that you left an empty paragraph, they will delete it.
1034 bool Text::cursorForwardOneWord(Cursor & cur)
1036 LASSERT(this == cur.text(), /**/);
1038 pos_type const lastpos = cur.lastpos();
1039 pit_type pit = cur.pit();
1040 pos_type pos = cur.pos();
1041 Paragraph const & par = cur.paragraph();
1043 // Paragraph boundary is a word boundary
1044 if (pos == lastpos) {
1045 if (pit != cur.lastpit())
1046 return setCursor(cur, pit + 1, 0);
1051 if (lyxrc.mac_like_word_movement) {
1052 // Skip through trailing punctuation and spaces.
1053 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1056 // Skip over either a non-char inset or a full word
1057 if (pos != lastpos && par.isWordSeparator(pos))
1059 else while (pos != lastpos && !par.isWordSeparator(pos))
1062 LASSERT(pos < lastpos, /**/); // see above
1063 if (!par.isWordSeparator(pos))
1064 while (pos != lastpos && !par.isWordSeparator(pos))
1066 else if (par.isChar(pos))
1067 while (pos != lastpos && par.isChar(pos))
1069 else if (!par.isSpace(pos)) // non-char inset
1072 // Skip over white space
1073 while (pos != lastpos && par.isSpace(pos))
1077 return setCursor(cur, pit, pos);
1081 bool Text::cursorBackwardOneWord(Cursor & cur)
1083 LASSERT(this == cur.text(), /**/);
1085 pit_type pit = cur.pit();
1086 pos_type pos = cur.pos();
1087 Paragraph & par = cur.paragraph();
1089 // Paragraph boundary is a word boundary
1090 if (pos == 0 && pit != 0)
1091 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1093 if (lyxrc.mac_like_word_movement) {
1094 // Skip through punctuation and spaces.
1095 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1098 // Skip over either a non-char inset or a full word
1099 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1101 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1104 // Skip over white space
1105 while (pos != 0 && par.isSpace(pos - 1))
1108 if (pos != 0 && !par.isWordSeparator(pos - 1))
1109 while (pos != 0 && !par.isWordSeparator(pos - 1))
1111 else if (pos != 0 && par.isChar(pos - 1))
1112 while (pos != 0 && par.isChar(pos - 1))
1114 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1118 return setCursor(cur, pit, pos);
1122 bool Text::cursorVisLeftOneWord(Cursor & cur)
1124 LASSERT(this == cur.text(), /**/);
1126 pos_type left_pos, right_pos;
1127 bool left_is_letter, right_is_letter;
1129 Cursor temp_cur = cur;
1131 // always try to move at least once...
1132 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1134 // collect some information about current cursor position
1135 temp_cur.getSurroundingPos(left_pos, right_pos);
1137 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1139 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1141 // if we're not at a letter/non-letter boundary, continue moving
1142 if (left_is_letter == right_is_letter)
1145 // we should stop when we have an LTR word on our right or an RTL word
1147 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1148 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1149 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1150 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1154 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1155 true, temp_cur.boundary());
1159 bool Text::cursorVisRightOneWord(Cursor & cur)
1161 LASSERT(this == cur.text(), /**/);
1163 pos_type left_pos, right_pos;
1164 bool left_is_letter, right_is_letter;
1166 Cursor temp_cur = cur;
1168 // always try to move at least once...
1169 while (temp_cur.posVisRight(true /* skip_inset */)) {
1171 // collect some information about current cursor position
1172 temp_cur.getSurroundingPos(left_pos, right_pos);
1174 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1176 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1178 // if we're not at a letter/non-letter boundary, continue moving
1179 if (left_is_letter == right_is_letter)
1182 // we should stop when we have an LTR word on our right or an RTL word
1184 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1185 temp_cur.buffer()->params(),
1186 left_pos).isRightToLeft())
1187 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1188 temp_cur.buffer()->params(),
1189 right_pos).isRightToLeft()))
1193 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1194 true, temp_cur.boundary());
1198 void Text::selectWord(Cursor & cur, word_location loc)
1200 LASSERT(this == cur.text(), /**/);
1201 CursorSlice from = cur.top();
1202 CursorSlice to = cur.top();
1203 getWord(from, to, loc);
1204 if (cur.top() != from)
1205 setCursor(cur, from.pit(), from.pos());
1208 if (!cur.selection())
1210 setCursor(cur, to.pit(), to.pos());
1212 cur.setWordSelection(true);
1216 void Text::selectAll(Cursor & cur)
1218 LASSERT(this == cur.text(), /**/);
1219 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1221 // If the cursor is at the beginning, make sure the cursor ends there
1222 if (cur.pit() == 0 && cur.pos() == 0) {
1223 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1225 setCursor(cur, 0, 0);
1227 setCursor(cur, 0, 0);
1229 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1235 // Select the word currently under the cursor when no
1236 // selection is currently set
1237 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1239 LASSERT(this == cur.text(), /**/);
1240 if (cur.selection())
1242 selectWord(cur, loc);
1243 return cur.selection();
1247 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1249 LASSERT(this == cur.text(), /**/);
1251 if (!cur.selection()) {
1252 bool const changed = cur.paragraph().isChanged(cur.pos());
1253 if (!(changed && findNextChange(&cur.bv())))
1257 cur.recordUndoSelection();
1259 pit_type begPit = cur.selectionBegin().pit();
1260 pit_type endPit = cur.selectionEnd().pit();
1262 pos_type begPos = cur.selectionBegin().pos();
1263 pos_type endPos = cur.selectionEnd().pos();
1265 // keep selection info, because endPos becomes invalid after the first loop
1266 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1268 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1270 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1271 pos_type parSize = pars_[pit].size();
1273 // ignore empty paragraphs; otherwise, an assertion will fail for
1274 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1278 // do not consider first paragraph if the cursor starts at pos size()
1279 if (pit == begPit && begPos == parSize)
1282 // do not consider last paragraph if the cursor ends at pos 0
1283 if (pit == endPit && endPos == 0)
1284 break; // last iteration anyway
1286 pos_type left = (pit == begPit ? begPos : 0);
1287 pos_type right = (pit == endPit ? endPos : parSize);
1290 // there is no change here
1294 pars_[pit].acceptChanges(left, right);
1296 pars_[pit].rejectChanges(left, right);
1300 // next, accept/reject imaginary end-of-par characters
1302 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1303 pos_type pos = pars_[pit].size();
1305 // skip if the selection ends before the end-of-par
1306 if (pit == endPit && endsBeforeEndOfPar)
1307 break; // last iteration anyway
1309 // skip if this is not the last paragraph of the document
1310 // note: the user should be able to accept/reject the par break of the last par!
1311 if (pit == endPit && pit + 1 != int(pars_.size()))
1312 break; // last iteration anway
1315 if (pars_[pit].isInserted(pos)) {
1316 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1317 } else if (pars_[pit].isDeleted(pos)) {
1318 if (pit + 1 == int(pars_.size())) {
1319 // we cannot remove a par break at the end of the last paragraph;
1320 // instead, we mark it unchanged
1321 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1323 mergeParagraph(cur.buffer()->params(), pars_, pit);
1329 if (pars_[pit].isDeleted(pos)) {
1330 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1331 } else if (pars_[pit].isInserted(pos)) {
1332 if (pit + 1 == int(pars_.size())) {
1333 // we mark the par break at the end of the last paragraph unchanged
1334 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1336 mergeParagraph(cur.buffer()->params(), pars_, pit);
1344 // finally, invoke the DEPM
1346 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1351 cur.clearSelection();
1352 setCursorIntern(cur, begPit, begPos);
1353 cur.screenUpdateFlags(Update::Force);
1354 cur.forceBufferUpdate();
1358 void Text::acceptChanges()
1360 BufferParams const & bparams = owner_->buffer().params();
1361 lyx::acceptChanges(pars_, bparams);
1362 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1366 void Text::rejectChanges()
1368 BufferParams const & bparams = owner_->buffer().params();
1369 pit_type pars_size = static_cast<pit_type>(pars_.size());
1371 // first, reject changes within each individual paragraph
1372 // (do not consider end-of-par)
1373 for (pit_type pit = 0; pit < pars_size; ++pit) {
1374 if (!pars_[pit].empty()) // prevent assertion failure
1375 pars_[pit].rejectChanges(0, pars_[pit].size());
1378 // next, reject imaginary end-of-par characters
1379 for (pit_type pit = 0; pit < pars_size; ++pit) {
1380 pos_type pos = pars_[pit].size();
1382 if (pars_[pit].isDeleted(pos)) {
1383 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1384 } else if (pars_[pit].isInserted(pos)) {
1385 if (pit == pars_size - 1) {
1386 // we mark the par break at the end of the last
1387 // paragraph unchanged
1388 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1390 mergeParagraph(bparams, pars_, pit);
1397 // finally, invoke the DEPM
1398 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1402 void Text::deleteWordForward(Cursor & cur)
1404 LASSERT(this == cur.text(), /**/);
1405 if (cur.lastpos() == 0)
1409 cur.setSelection(true);
1410 cursorForwardOneWord(cur);
1412 cutSelection(cur, true, false);
1413 cur.checkBufferStructure();
1418 void Text::deleteWordBackward(Cursor & cur)
1420 LASSERT(this == cur.text(), /**/);
1421 if (cur.lastpos() == 0)
1422 cursorBackward(cur);
1425 cur.setSelection(true);
1426 cursorBackwardOneWord(cur);
1428 cutSelection(cur, true, false);
1429 cur.checkBufferStructure();
1434 // Kill to end of line.
1435 void Text::changeCase(Cursor & cur, TextCase action)
1437 LASSERT(this == cur.text(), /**/);
1441 bool gotsel = false;
1442 if (cur.selection()) {
1443 from = cur.selBegin();
1448 getWord(from, to, PARTIAL_WORD);
1449 cursorForwardOneWord(cur);
1452 cur.recordUndoSelection();
1454 pit_type begPit = from.pit();
1455 pit_type endPit = to.pit();
1457 pos_type begPos = from.pos();
1458 pos_type endPos = to.pos();
1460 pos_type right = 0; // needed after the for loop
1462 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1463 Paragraph & par = pars_[pit];
1464 pos_type const pos = (pit == begPit ? begPos : 0);
1465 right = (pit == endPit ? endPos : par.size());
1466 par.changeCase(cur.buffer()->params(), pos, right, action);
1469 // the selection may have changed due to logically-only deleted chars
1471 setCursor(cur, begPit, begPos);
1473 setCursor(cur, endPit, right);
1476 setCursor(cur, endPit, right);
1478 cur.checkBufferStructure();
1482 bool Text::handleBibitems(Cursor & cur)
1484 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1490 BufferParams const & bufparams = cur.buffer()->params();
1491 Paragraph const & par = cur.paragraph();
1492 Cursor prevcur = cur;
1493 if (cur.pit() > 0) {
1495 prevcur.pos() = prevcur.lastpos();
1497 Paragraph const & prevpar = prevcur.paragraph();
1499 // if a bibitem is deleted, merge with previous paragraph
1500 // if this is a bibliography item as well
1501 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1502 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1503 mergeParagraph(bufparams, cur.text()->paragraphs(),
1505 cur.forceBufferUpdate();
1506 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1507 cur.screenUpdateFlags(Update::Force);
1511 // otherwise reset to default
1512 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1517 bool Text::erase(Cursor & cur)
1519 LASSERT(this == cur.text(), return false);
1520 bool needsUpdate = false;
1521 Paragraph & par = cur.paragraph();
1523 if (cur.pos() != cur.lastpos()) {
1524 // this is the code for a normal delete, not pasting
1526 cur.recordUndo(DELETE_UNDO);
1527 bool const was_inset = cur.paragraph().isInset(cur.pos());
1528 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1529 // the character has been logically deleted only => skip it
1530 cur.top().forwardPos();
1533 cur.forceBufferUpdate();
1535 cur.checkBufferStructure();
1538 if (cur.pit() == cur.lastpit())
1539 return dissolveInset(cur);
1541 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1542 par.setChange(cur.pos(), Change(Change::DELETED));
1546 setCursorIntern(cur, cur.pit() + 1, 0);
1547 needsUpdate = backspacePos0(cur);
1551 needsUpdate |= handleBibitems(cur);
1554 // Make sure the cursor is correct. Is this really needed?
1555 // No, not really... at least not here!
1556 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1557 cur.checkBufferStructure();
1564 bool Text::backspacePos0(Cursor & cur)
1566 LASSERT(this == cur.text(), /**/);
1570 bool needsUpdate = false;
1572 BufferParams const & bufparams = cur.buffer()->params();
1573 DocumentClass const & tclass = bufparams.documentClass();
1574 ParagraphList & plist = cur.text()->paragraphs();
1575 Paragraph const & par = cur.paragraph();
1576 Cursor prevcur = cur;
1578 prevcur.pos() = prevcur.lastpos();
1579 Paragraph const & prevpar = prevcur.paragraph();
1581 // is it an empty paragraph?
1582 if (cur.lastpos() == 0
1583 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1584 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1585 plist.erase(boost::next(plist.begin(), cur.pit()));
1588 // is previous par empty?
1589 else if (prevcur.lastpos() == 0
1590 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1591 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1592 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1595 // Pasting is not allowed, if the paragraphs have different
1596 // layouts. I think it is a real bug of all other
1597 // word processors to allow it. It confuses the user.
1598 // Correction: Pasting is always allowed with standard-layout
1599 // or the empty layout.
1600 else if (par.layout() == prevpar.layout()
1601 || tclass.isDefaultLayout(par.layout())
1602 || tclass.isPlainLayout(par.layout())) {
1603 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1604 mergeParagraph(bufparams, plist, prevcur.pit());
1609 cur.forceBufferUpdate();
1610 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1617 bool Text::backspace(Cursor & cur)
1619 LASSERT(this == cur.text(), /**/);
1620 bool needsUpdate = false;
1621 if (cur.pos() == 0) {
1623 return dissolveInset(cur);
1625 Paragraph & prev_par = pars_[cur.pit() - 1];
1627 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1628 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1629 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1632 // The cursor is at the beginning of a paragraph, so
1633 // the backspace will collapse two paragraphs into one.
1634 needsUpdate = backspacePos0(cur);
1637 // this is the code for a normal backspace, not pasting
1639 cur.recordUndo(DELETE_UNDO);
1640 // We used to do cursorBackwardIntern() here, but it is
1641 // not a good idea since it triggers the auto-delete
1642 // mechanism. So we do a cursorBackwardIntern()-lite,
1643 // without the dreaded mechanism. (JMarc)
1644 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1645 false, cur.boundary());
1646 bool const was_inset = cur.paragraph().isInset(cur.pos());
1647 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1649 cur.forceBufferUpdate();
1651 cur.checkBufferStructure();
1654 if (cur.pos() == cur.lastpos())
1655 cur.setCurrentFont();
1657 needsUpdate |= handleBibitems(cur);
1659 // A singlePar update is not enough in this case.
1660 // cur.screenUpdateFlags(Update::Force);
1661 setCursor(cur.top(), cur.pit(), cur.pos());
1667 bool Text::dissolveInset(Cursor & cur)
1669 LASSERT(this == cur.text(), return false);
1671 if (isMainText() || cur.inset().nargs() != 1)
1674 cur.recordUndoInset();
1676 cur.selHandle(false);
1678 pos_type spos = cur.pos();
1679 pit_type spit = cur.pit();
1680 ParagraphList plist;
1681 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1682 plist = paragraphs();
1684 // store cursor offset
1688 Buffer & b = *cur.buffer();
1689 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1691 if (!plist.empty()) {
1693 // we clear the cache so that we won't get conflicts with labels
1694 // that get pasted into the buffer. we should update this before
1695 // its being empty matters. if not (i.e., if we encounter bugs),
1696 // then this should instead be:
1697 // cur.buffer().updateBuffer();
1698 // but we'll try the cheaper solution here.
1699 cur.buffer()->clearReferenceCache();
1701 // ERT paragraphs have the Language latex_language.
1702 // This is invalid outside of ERT, so we need to
1703 // change it to the buffer language.
1704 ParagraphList::iterator it = plist.begin();
1705 ParagraphList::iterator it_end = plist.end();
1706 for (; it != it_end; ++it)
1707 it->changeLanguage(b.params(), latex_language, b.language());
1709 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1710 b.errorList("Paste"));
1712 cur.pit() = min(cur.lastpit(), spit);
1713 cur.pos() = min(cur.lastpos(), spos);
1716 cur.forceBufferUpdate();
1718 // Ensure the current language is set correctly (bug 6292)
1719 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1720 cur.clearSelection();
1726 void Text::getWord(CursorSlice & from, CursorSlice & to,
1727 word_location const loc) const
1730 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1734 void Text::write(ostream & os) const
1736 Buffer const & buf = owner_->buffer();
1737 ParagraphList::const_iterator pit = paragraphs().begin();
1738 ParagraphList::const_iterator end = paragraphs().end();
1740 for (; pit != end; ++pit)
1741 pit->write(os, buf.params(), dth);
1743 // Close begin_deeper
1744 for(; dth > 0; --dth)
1745 os << "\n\\end_deeper";
1749 bool Text::read(Lexer & lex,
1750 ErrorList & errorList, InsetText * insetPtr)
1752 Buffer const & buf = owner_->buffer();
1753 depth_type depth = 0;
1756 while (lex.isOK()) {
1758 string const token = lex.getString();
1763 if (token == "\\end_inset")
1766 if (token == "\\end_body")
1769 if (token == "\\begin_body")
1772 if (token == "\\end_document") {
1777 if (token == "\\begin_layout") {
1778 lex.pushToken(token);
1781 par.setInsetOwner(insetPtr);
1782 par.params().depth(depth);
1783 par.setFont(0, Font(inherit_font, buf.params().language));
1784 pars_.push_back(par);
1785 readParagraph(pars_.back(), lex, errorList);
1787 // register the words in the global word list
1788 pars_.back().updateWords();
1789 } else if (token == "\\begin_deeper") {
1791 } else if (token == "\\end_deeper") {
1793 lex.printError("\\end_deeper: " "depth is already null");
1797 LYXERR0("Handling unknown body token: `" << token << '\'');
1801 // avoid a crash on weird documents (bug 4859)
1802 if (pars_.empty()) {
1804 par.setInsetOwner(insetPtr);
1805 par.params().depth(depth);
1806 par.setFont(0, Font(inherit_font,
1807 buf.params().language));
1808 par.setPlainOrDefaultLayout(buf.params().documentClass());
1809 pars_.push_back(par);
1816 // Returns the current font and depth as a message.
1817 docstring Text::currentState(Cursor const & cur) const
1819 LASSERT(this == cur.text(), /**/);
1820 Buffer & buf = *cur.buffer();
1821 Paragraph const & par = cur.paragraph();
1822 odocstringstream os;
1824 if (buf.params().trackChanges)
1825 os << _("[Change Tracking] ");
1827 Change change = par.lookupChange(cur.pos());
1829 if (change.changed()) {
1830 Author const & a = buf.params().authors().get(change.author);
1831 os << _("Change: ") << a.name();
1832 if (!a.email().empty())
1833 os << " (" << a.email() << ")";
1834 // FIXME ctime is english, we should translate that
1835 os << _(" at ") << ctime(&change.changetime);
1839 // I think we should only show changes from the default
1841 // No, from the document font (MV)
1842 Font font = cur.real_current_font;
1843 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1845 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1847 // The paragraph depth
1848 int depth = cur.paragraph().getDepth();
1850 os << bformat(_(", Depth: %1$d"), depth);
1852 // The paragraph spacing, but only if different from
1854 Spacing const & spacing = par.params().spacing();
1855 if (!spacing.isDefault()) {
1856 os << _(", Spacing: ");
1857 switch (spacing.getSpace()) {
1858 case Spacing::Single:
1861 case Spacing::Onehalf:
1864 case Spacing::Double:
1867 case Spacing::Other:
1868 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1870 case Spacing::Default:
1871 // should never happen, do nothing
1876 #ifdef DEVEL_VERSION
1877 os << _(", Inset: ") << &cur.inset();
1878 os << _(", Paragraph: ") << cur.pit();
1879 os << _(", Id: ") << par.id();
1880 os << _(", Position: ") << cur.pos();
1881 // FIXME: Why is the check for par.size() needed?
1882 // We are called with cur.pos() == par.size() quite often.
1883 if (!par.empty() && cur.pos() < par.size()) {
1884 // Force output of code point, not character
1885 size_t const c = par.getChar(cur.pos());
1886 os << _(", Char: 0x") << hex << c;
1888 os << _(", Boundary: ") << cur.boundary();
1889 // Row & row = cur.textRow();
1890 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1896 docstring Text::getPossibleLabel(Cursor const & cur) const
1898 pit_type pit = cur.pit();
1900 Layout const * layout = &(pars_[pit].layout());
1903 docstring par_text = pars_[pit].asString();
1905 // The return string of math matrices might contain linebreaks
1906 par_text = subst(par_text, '\n', '-');
1907 int const numwords = 3;
1908 for (int i = 0; i < numwords; ++i) {
1909 if (par_text.empty())
1912 par_text = split(par_text, head, ' ');
1913 // Is it legal to use spaces in labels ?
1919 // Make sure it isn't too long
1920 unsigned int const max_label_length = 32;
1921 if (text.size() > max_label_length)
1922 text.resize(max_label_length);
1924 // Will contain the label prefix.
1927 // For section, subsection, etc...
1928 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1929 Layout const * layout2 = &(pars_[pit - 1].layout());
1930 if (layout2->latextype != LATEX_PARAGRAPH) {
1935 if (layout->latextype != LATEX_PARAGRAPH)
1936 name = layout->refprefix;
1938 // For captions, we just take the caption type
1939 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1940 if (caption_inset) {
1941 string const & ftype = static_cast<InsetCaption *>(caption_inset)->type();
1942 FloatList const & fl = cur.buffer()->params().documentClass().floats();
1943 if (fl.typeExist(ftype)) {
1944 Floating const & flt = fl.getType(ftype);
1945 name = from_utf8(flt.refPrefix());
1948 name = from_utf8(ftype.substr(0,3));
1951 // If none of the above worked, see if the inset knows.
1953 InsetLayout const & il = cur.inset().getLayout();
1954 name = il.refprefix();
1958 text = name + ':' + text;
1960 // We need a unique label
1961 docstring label = text;
1963 while (cur.buffer()->insetLabel(label)) {
1964 label = text + '-' + convert<docstring>(i);
1972 docstring Text::asString(int options) const
1974 return asString(0, pars_.size(), options);
1978 docstring Text::asString(pit_type beg, pit_type end, int options) const
1980 size_t i = size_t(beg);
1981 docstring str = pars_[i].asString(options);
1982 for (++i; i != size_t(end); ++i) {
1984 str += pars_[i].asString(options);
1990 void Text::forToc(docstring & os, size_t maxlen, bool shorten) const
1993 maxlen = std::numeric_limits<std::size_t>::max();
1995 LASSERT(maxlen >= 8, maxlen = TOC_ENTRY_LENGTH);
1996 for (size_t i = 0; i != pars_.size() && os.length() < maxlen; ++i)
1997 pars_[i].forToc(os, maxlen);
1998 if (shorten && os.length() >= maxlen)
1999 os = os.substr(0, maxlen - 3) + from_ascii("...");
2003 void Text::charsTranspose(Cursor & cur)
2005 LASSERT(this == cur.text(), /**/);
2007 pos_type pos = cur.pos();
2009 // If cursor is at beginning or end of paragraph, do nothing.
2010 if (pos == cur.lastpos() || pos == 0)
2013 Paragraph & par = cur.paragraph();
2015 // Get the positions of the characters to be transposed.
2016 pos_type pos1 = pos - 1;
2017 pos_type pos2 = pos;
2019 // In change tracking mode, ignore deleted characters.
2020 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2022 if (pos2 == cur.lastpos())
2025 while (pos1 >= 0 && par.isDeleted(pos1))
2030 // Don't do anything if one of the "characters" is not regular text.
2031 if (par.isInset(pos1) || par.isInset(pos2))
2034 // Store the characters to be transposed (including font information).
2035 char_type const char1 = par.getChar(pos1);
2037 par.getFontSettings(cur.buffer()->params(), pos1);
2039 char_type const char2 = par.getChar(pos2);
2041 par.getFontSettings(cur.buffer()->params(), pos2);
2043 // And finally, we are ready to perform the transposition.
2044 // Track the changes if Change Tracking is enabled.
2045 bool const trackChanges = cur.buffer()->params().trackChanges;
2049 par.eraseChar(pos2, trackChanges);
2050 par.eraseChar(pos1, trackChanges);
2051 par.insertChar(pos1, char2, font2, trackChanges);
2052 par.insertChar(pos2, char1, font1, trackChanges);
2054 cur.checkBufferStructure();
2056 // After the transposition, move cursor to after the transposition.
2057 setCursor(cur, cur.pit(), pos2);
2062 DocIterator Text::macrocontextPosition() const
2064 return macrocontext_position_;
2068 void Text::setMacrocontextPosition(DocIterator const & pos)
2070 macrocontext_position_ = pos;
2074 docstring Text::previousWord(CursorSlice const & sl) const
2076 CursorSlice from = sl;
2077 CursorSlice to = sl;
2078 getWord(from, to, PREVIOUS_WORD);
2079 if (sl == from || to == from)
2082 Paragraph const & par = sl.paragraph();
2083 return par.asString(from.pos(), to.pos());
2087 bool Text::completionSupported(Cursor const & cur) const
2089 Paragraph const & par = cur.paragraph();
2090 return cur.pos() > 0
2091 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2092 && !par.isWordSeparator(cur.pos() - 1);
2096 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2098 WordList const * list = theWordList(*cur.getFont().language());
2099 return new TextCompletionList(cur, list);
2103 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2105 LASSERT(cur.bv().cursor() == cur, /**/);
2107 cur.bv().cursor() = cur;
2108 if (!(cur.result().screenUpdate() & Update::Force))
2109 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2114 docstring Text::completionPrefix(Cursor const & cur) const
2116 return previousWord(cur.top());