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/InsetSpace.h"
59 #include "insets/InsetSpecialChar.h"
60 #include "insets/InsetTabular.h"
62 #include "support/debug.h"
63 #include "support/docstream.h"
64 #include "support/gettext.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/textutils.h"
69 #include <boost/next_prior.hpp>
75 // TODO: replace if in Text::readParToken() with compile time switch
78 #include "support/metahash.h"
80 typedef boost::mpl::string<'\\end','_lay','out'> end_layout;
81 typedef boost::mpl::string<'\\end','in','set'> end_inset;
85 std::string token = "\\end_layout";
87 switch (boost::hash_value(token)) {
88 case lyx::support::hash_string<end_layout>::value:
90 case lyx::support::hash_string<end_inset>::value:
100 using namespace lyx::support;
104 using cap::cutSelection;
105 using cap::pasteParagraphList;
107 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
108 Paragraph & toPar, pos_type toPos, BufferParams const & params)
110 // Note: moveItem() does not honour change tracking!
111 // Therefore, it should only be used for breaking and merging paragraphs
113 // We need a copy here because the character at fromPos is going to be erased.
114 Font const tmpFont = fromPar.getFontSettings(params, fromPos);
115 Change const tmpChange = fromPar.lookupChange(fromPos);
117 if (Inset * tmpInset = fromPar.getInset(fromPos)) {
118 fromPar.releaseInset(fromPos);
119 // The inset is not in fromPar any more.
120 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
127 char_type const tmpChar = fromPar.getChar(fromPos);
128 fromPar.eraseChar(fromPos, false);
129 toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
134 void breakParagraphConservative(BufferParams const & bparams,
135 ParagraphList & pars, pit_type par_offset, pos_type pos)
137 // create a new paragraph
138 Paragraph & tmp = *pars.insert(boost::next(pars.begin(), par_offset + 1),
140 Paragraph & par = pars[par_offset];
142 tmp.setInsetOwner(&par.inInset());
143 tmp.makeSameLayout(par);
145 LASSERT(pos <= par.size(), /**/);
147 if (pos < par.size()) {
148 // move everything behind the break position to the new paragraph
149 pos_type pos_end = par.size() - 1;
151 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
152 if (moveItem(par, pos, tmp, j, bparams)) {
156 // Move over the end-of-par change information
157 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
158 par.setChange(par.size(), Change(bparams.trackChanges ?
159 Change::INSERTED : Change::UNCHANGED));
164 void mergeParagraph(BufferParams const & bparams,
165 ParagraphList & pars, pit_type par_offset)
167 Paragraph & next = pars[par_offset + 1];
168 Paragraph & par = pars[par_offset];
170 pos_type pos_end = next.size() - 1;
171 pos_type pos_insert = par.size();
173 // the imaginary end-of-paragraph character (at par.size()) has to be
174 // marked as unmodified. Otherwise, its change is adopted by the first
175 // character of the next paragraph.
176 if (par.isChanged(par.size())) {
177 LYXERR(Debug::CHANGES,
178 "merging par with inserted/deleted end-of-par character");
179 par.setChange(par.size(), Change(Change::UNCHANGED));
182 Change change = next.lookupChange(next.size());
184 // move the content of the second paragraph to the end of the first one
185 for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
186 if (moveItem(next, 0, par, j, bparams)) {
191 // move the change of the end-of-paragraph character
192 par.setChange(par.size(), change);
194 pars.erase(boost::next(pars.begin(), par_offset + 1));
198 Text::Text(InsetText * owner, bool use_default_layout)
199 : owner_(owner), autoBreakRows_(false), undo_counter_(0)
201 pars_.push_back(Paragraph());
202 Paragraph & par = pars_.back();
203 par.setInsetOwner(owner);
204 DocumentClass const & dc = owner->buffer().params().documentClass();
205 if (use_default_layout)
206 par.setDefaultLayout(dc);
208 par.setPlainLayout(dc);
212 Text::Text(InsetText * owner, Text const & text)
213 : owner_(owner), autoBreakRows_(text.autoBreakRows_), undo_counter_(0)
216 ParagraphList::iterator const end = pars_.end();
217 ParagraphList::iterator it = pars_.begin();
218 for (; it != end; ++it)
219 it->setInsetOwner(owner);
223 pit_type Text::depthHook(pit_type pit, depth_type depth) const
225 pit_type newpit = pit;
230 while (newpit != 0 && pars_[newpit].getDepth() > depth)
233 if (pars_[newpit].getDepth() > depth)
240 pit_type Text::outerHook(pit_type par_offset) const
242 Paragraph const & par = pars_[par_offset];
244 if (par.getDepth() == 0)
246 return depthHook(par_offset, depth_type(par.getDepth() - 1));
250 bool Text::isFirstInSequence(pit_type par_offset) const
252 Paragraph const & par = pars_[par_offset];
254 pit_type dhook_offset = depthHook(par_offset, par.getDepth());
256 if (dhook_offset == par_offset)
259 Paragraph const & dhook = pars_[dhook_offset];
261 return dhook.layout() != par.layout()
262 || dhook.getDepth() != par.getDepth();
266 Font const Text::outerFont(pit_type par_offset) const
268 depth_type par_depth = pars_[par_offset].getDepth();
269 FontInfo tmpfont = inherit_font;
271 // Resolve against environment font information
272 while (par_offset != pit_type(pars_.size())
274 && !tmpfont.resolved()) {
275 par_offset = outerHook(par_offset);
276 if (par_offset != pit_type(pars_.size())) {
277 tmpfont.realize(pars_[par_offset].layout().font);
278 par_depth = pars_[par_offset].getDepth();
282 return Font(tmpfont);
286 static void acceptOrRejectChanges(ParagraphList & pars,
287 BufferParams const & bparams, Text::ChangeOp op)
289 pit_type pars_size = static_cast<pit_type>(pars.size());
291 // first, accept or reject changes within each individual
292 // paragraph (do not consider end-of-par)
293 for (pit_type pit = 0; pit < pars_size; ++pit) {
294 // prevent assertion failure
295 if (!pars[pit].empty()) {
296 if (op == Text::ACCEPT)
297 pars[pit].acceptChanges(0, pars[pit].size());
299 pars[pit].rejectChanges(0, pars[pit].size());
303 // next, accept or reject imaginary end-of-par characters
304 for (pit_type pit = 0; pit < pars_size; ++pit) {
305 pos_type pos = pars[pit].size();
306 if (pars[pit].isChanged(pos)) {
307 // keep the end-of-par char if it is inserted and accepted
308 // or when it is deleted and rejected.
309 if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
310 pars[pit].setChange(pos, Change(Change::UNCHANGED));
312 if (pit == pars_size - 1) {
313 // we cannot remove a par break at the end of the last
314 // paragraph; instead, we mark it unchanged
315 pars[pit].setChange(pos, Change(Change::UNCHANGED));
317 mergeParagraph(bparams, pars, pit);
327 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
329 acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
333 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
335 acceptOrRejectChanges(pars, bparams, Text::REJECT);
339 InsetText const & Text::inset() const
346 void Text::readParToken(Paragraph & par, Lexer & lex,
347 string const & token, Font & font, Change & change, ErrorList & errorList)
349 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
350 BufferParams const & bp = buf->params();
352 if (token[0] != '\\') {
353 docstring dstr = lex.getDocString();
354 par.appendString(dstr, font, change);
356 } else if (token == "\\begin_layout") {
358 docstring layoutname = lex.getDocString();
360 font = Font(inherit_font, bp.language);
361 change = Change(Change::UNCHANGED);
363 DocumentClass const & tclass = bp.documentClass();
365 if (layoutname.empty())
366 layoutname = tclass.defaultLayoutName();
368 if (owner_->forcePlainLayout()) {
369 // in this case only the empty layout is allowed
370 layoutname = tclass.plainLayoutName();
371 } else if (par.usePlainLayout()) {
372 // in this case, default layout maps to empty layout
373 if (layoutname == tclass.defaultLayoutName())
374 layoutname = tclass.plainLayoutName();
376 // otherwise, the empty layout maps to the default
377 if (layoutname == tclass.plainLayoutName())
378 layoutname = tclass.defaultLayoutName();
381 // When we apply an unknown layout to a document, we add this layout to the textclass
382 // of this document. For example, when you apply class article to a beamer document,
383 // all unknown layouts such as frame will be added to document class article so that
384 // these layouts can keep their original names.
385 bool const added_one = tclass.addLayoutIfNeeded(layoutname);
388 docstring const s = bformat(_("Layout `%1$s' was not found."), layoutname);
390 ErrorItem(_("Layout Not Found"), s, par.id(), 0, par.size()));
393 par.setLayout(bp.documentClass()[layoutname]);
395 // Test whether the layout is obsolete.
396 Layout const & layout = par.layout();
397 if (!layout.obsoleted_by().empty())
398 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
400 par.params().read(lex);
402 } else if (token == "\\end_layout") {
403 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
404 << "Missing \\begin_layout ?");
405 } else if (token == "\\end_inset") {
406 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
407 << "Missing \\begin_inset ?");
408 } else if (token == "\\begin_inset") {
409 Inset * inset = readInset(lex, buf);
411 par.insertInset(par.size(), inset, font, change);
414 docstring line = lex.getDocString();
415 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
416 par.id(), 0, par.size()));
418 } else if (token == "\\family") {
420 setLyXFamily(lex.getString(), font.fontInfo());
421 } else if (token == "\\series") {
423 setLyXSeries(lex.getString(), font.fontInfo());
424 } else if (token == "\\shape") {
426 setLyXShape(lex.getString(), font.fontInfo());
427 } else if (token == "\\size") {
429 setLyXSize(lex.getString(), font.fontInfo());
430 } else if (token == "\\lang") {
432 string const tok = lex.getString();
433 Language const * lang = languages.getLanguage(tok);
435 font.setLanguage(lang);
437 font.setLanguage(bp.language);
438 lex.printError("Unknown language `$$Token'");
440 } else if (token == "\\numeric") {
442 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
443 } else if (token == "\\emph") {
445 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
446 } else if (token == "\\bar") {
448 string const tok = lex.getString();
451 font.fontInfo().setUnderbar(FONT_ON);
452 else if (tok == "no")
453 font.fontInfo().setUnderbar(FONT_OFF);
454 else if (tok == "default")
455 font.fontInfo().setUnderbar(FONT_INHERIT);
457 lex.printError("Unknown bar font flag "
459 } else if (token == "\\strikeout") {
461 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
462 } else if (token == "\\uuline") {
464 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
465 } else if (token == "\\uwave") {
467 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
468 } else if (token == "\\noun") {
470 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
471 } else if (token == "\\color") {
473 setLyXColor(lex.getString(), font.fontInfo());
474 } else if (token == "\\SpecialChar") {
475 auto_ptr<Inset> inset;
476 inset.reset(new InsetSpecialChar);
478 inset->setBuffer(*buf);
479 par.insertInset(par.size(), inset.release(), font, change);
480 } else if (token == "\\backslash") {
481 par.appendChar('\\', font, change);
482 } else if (token == "\\LyXTable") {
483 auto_ptr<Inset> inset(new InsetTabular(buf));
485 par.insertInset(par.size(), inset.release(), font, change);
486 } else if (token == "\\change_unchanged") {
487 change = Change(Change::UNCHANGED);
488 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
490 istringstream is(lex.getString());
494 BufferParams::AuthorMap const & am = bp.author_map;
495 if (am.find(aid) == am.end()) {
496 errorList.push_back(ErrorItem(_("Change tracking error"),
497 bformat(_("Unknown author index for change: %1$d\n"), aid),
498 par.id(), 0, par.size()));
499 change = Change(Change::UNCHANGED);
501 if (token == "\\change_inserted")
502 change = Change(Change::INSERTED, am.find(aid)->second, ct);
504 change = Change(Change::DELETED, am.find(aid)->second, ct);
508 errorList.push_back(ErrorItem(_("Unknown token"),
509 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
511 par.id(), 0, par.size()));
516 void Text::readParagraph(Paragraph & par, Lexer & lex,
517 ErrorList & errorList)
520 string token = lex.getString();
522 Change change(Change::UNCHANGED);
525 readParToken(par, lex, token, font, change, errorList);
528 token = lex.getString();
533 if (token == "\\end_layout") {
534 //Ok, paragraph finished
538 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
539 if (token == "\\begin_layout" || token == "\\end_document"
540 || token == "\\end_inset" || token == "\\begin_deeper"
541 || token == "\\end_deeper") {
542 lex.pushToken(token);
543 lyxerr << "Paragraph ended in line "
544 << lex.lineNumber() << "\n"
545 << "Missing \\end_layout.\n";
549 // Final change goes to paragraph break:
550 par.setChange(par.size(), change);
552 // Initialize begin_of_body_ on load; redoParagraph maintains
553 par.setBeginOfBody();
555 // mark paragraph for spell checking on load
556 // par.requestSpellCheck();
560 class TextCompletionList : public CompletionList
564 TextCompletionList(Cursor const & cur, WordList const * list)
565 : buffer_(cur.buffer()), pos_(0), list_(list)
568 virtual ~TextCompletionList() {}
571 virtual bool sorted() const { return true; }
573 virtual size_t size() const
575 return list_->size();
578 virtual docstring const & data(size_t idx) const
580 return list_->word(idx);
585 Buffer const * buffer_;
589 WordList const * list_;
593 bool Text::empty() const
595 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
596 // FIXME: Should we consider the labeled type as empty too?
597 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
601 double Text::spacing(Paragraph const & par) const
603 if (par.params().spacing().isDefault())
604 return owner_->buffer().params().spacing().getValue();
605 return par.params().spacing().getValue();
610 * This breaks a paragraph at the specified position.
611 * The new paragraph will:
612 * - Decrease depth by one (or change layout to default layout) when
613 * keep_layout == false
614 * - keep current depth and layout when keep_layout == true
616 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
619 BufferParams const & bparams = text.inset().buffer().params();
620 ParagraphList & pars = text.paragraphs();
621 // create a new paragraph, and insert into the list
622 ParagraphList::iterator tmp =
623 pars.insert(boost::next(pars.begin(), par_offset + 1),
626 Paragraph & par = pars[par_offset];
628 // remember to set the inset_owner
629 tmp->setInsetOwner(&par.inInset());
630 // without doing that we get a crash when typing <Return> at the
631 // end of a paragraph
632 tmp->setPlainOrDefaultLayout(bparams.documentClass());
635 tmp->setLayout(par.layout());
636 tmp->setLabelWidthString(par.params().labelWidthString());
637 tmp->params().depth(par.params().depth());
638 } else if (par.params().depth() > 0) {
639 Paragraph const & hook = pars[text.outerHook(par_offset)];
640 tmp->setLayout(hook.layout());
641 // not sure the line below is useful
642 tmp->setLabelWidthString(par.params().labelWidthString());
643 tmp->params().depth(hook.params().depth());
646 bool const isempty = (par.allowEmpty() && par.empty());
648 if (!isempty && (par.size() > pos || par.empty())) {
649 tmp->setLayout(par.layout());
650 tmp->params().align(par.params().align());
651 tmp->setLabelWidthString(par.params().labelWidthString());
653 tmp->params().depth(par.params().depth());
654 tmp->params().noindent(par.params().noindent());
656 // move everything behind the break position
657 // to the new paragraph
659 /* Note: if !keepempty, empty() == true, then we reach
660 * here with size() == 0. So pos_end becomes - 1. This
661 * doesn't cause problems because both loops below
662 * enforce pos <= pos_end and 0 <= pos
664 pos_type pos_end = par.size() - 1;
666 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
667 if (moveItem(par, pos, *tmp, j, bparams)) {
673 // Move over the end-of-par change information
674 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
675 par.setChange(par.size(), Change(bparams.trackChanges ?
676 Change::INSERTED : Change::UNCHANGED));
679 // Make sure that we keep the language when
680 // breaking paragraph.
682 Font changed = tmp->getFirstFontSettings(bparams);
683 Font const & old = par.getFontSettings(bparams, par.size());
684 changed.setLanguage(old.language());
685 tmp->setFont(0, changed);
692 bool const soa = par.params().startOfAppendix();
693 par.params().clear();
694 // do not lose start of appendix marker (bug 4212)
695 par.params().startOfAppendix(soa);
696 par.setPlainOrDefaultLayout(bparams.documentClass());
700 par.setLayout(tmp->layout());
701 par.setLabelWidthString(tmp->params().labelWidthString());
702 par.params().depth(tmp->params().depth());
707 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
709 LASSERT(this == cur.text(), /**/);
711 Paragraph & cpar = cur.paragraph();
712 pit_type cpit = cur.pit();
714 DocumentClass const & tclass = cur.buffer()->params().documentClass();
715 Layout const & layout = cpar.layout();
717 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
718 if (changeDepthAllowed(cur, DEC_DEPTH))
719 changeDepth(cur, DEC_DEPTH);
721 setLayout(cur, tclass.defaultLayoutName());
725 // a layout change may affect also the following paragraph
726 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
728 // Always break behind a space
729 // It is better to erase the space (Dekel)
730 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
731 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
733 // What should the layout for the new paragraph be?
734 bool keep_layout = layout.isEnvironment()
735 || (layout.isParagraph() && layout.parbreak_is_newline);
737 keep_layout = !keep_layout;
739 // We need to remember this before we break the paragraph, because
740 // that invalidates the layout variable
741 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
743 // we need to set this before we insert the paragraph.
744 bool const isempty = cpar.allowEmpty() && cpar.empty();
746 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
748 // After this, neither paragraph contains any rows!
751 pit_type next_par = cpit + 1;
753 // well this is the caption hack since one caption is really enough
756 // set to standard-layout
757 //FIXME Check if this should be plainLayout() in some cases
758 pars_[cpit].applyLayout(tclass.defaultLayout());
760 // set to standard-layout
761 //FIXME Check if this should be plainLayout() in some cases
762 pars_[next_par].applyLayout(tclass.defaultLayout());
765 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
766 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
767 break; // the character couldn't be deleted physically due to change tracking
770 // A singlePar update is not enough in this case.
771 cur.screenUpdateFlags(Update::Force);
772 cur.forceBufferUpdate();
774 // This check is necessary. Otherwise the new empty paragraph will
775 // be deleted automatically. And it is more friendly for the user!
776 if (cur.pos() != 0 || isempty)
777 setCursor(cur, cur.pit() + 1, 0);
779 setCursor(cur, cur.pit(), 0);
783 // needed to insert the selection
784 void Text::insertStringAsLines(Cursor & cur, docstring const & str,
787 BufferParams const & bparams = owner_->buffer().params();
788 pit_type pit = cur.pit();
789 pos_type pos = cur.pos();
791 // insert the string, don't insert doublespace
792 bool space_inserted = true;
793 for (docstring::const_iterator cit = str.begin();
794 cit != str.end(); ++cit) {
795 Paragraph & par = pars_[pit];
797 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
798 lyx::breakParagraph(*this, pit, pos,
799 par.layout().isEnvironment());
802 space_inserted = true;
806 // do not insert consecutive spaces if !free_spacing
807 } else if ((*cit == ' ' || *cit == '\t') &&
808 space_inserted && !par.isFreeSpacing()) {
810 } else if (*cit == '\t') {
811 if (!par.isFreeSpacing()) {
812 // tabs are like spaces here
813 par.insertChar(pos, ' ', font, bparams.trackChanges);
815 space_inserted = true;
817 par.insertChar(pos, *cit, font, bparams.trackChanges);
819 space_inserted = true;
821 } else if (!isPrintable(*cit)) {
822 // Ignore unprintables
825 // just insert the character
826 par.insertChar(pos, *cit, font, bparams.trackChanges);
828 space_inserted = (*cit == ' ');
831 setCursor(cur, pit, pos);
835 // turn double CR to single CR, others are converted into one
836 // blank. Then insertStringAsLines is called
837 void Text::insertStringAsParagraphs(Cursor & cur, docstring const & str,
840 docstring linestr = str;
841 bool newline_inserted = false;
843 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
844 if (linestr[i] == '\n') {
845 if (newline_inserted) {
846 // we know that \r will be ignored by
847 // insertStringAsLines. Of course, it is a dirty
848 // trick, but it works...
849 linestr[i - 1] = '\r';
853 newline_inserted = true;
855 } else if (isPrintable(linestr[i])) {
856 newline_inserted = false;
859 insertStringAsLines(cur, linestr, font);
863 // insert a character, moves all the following breaks in the
864 // same Paragraph one to the right and make a rebreak
865 void Text::insertChar(Cursor & cur, char_type c)
867 LASSERT(this == cur.text(), /**/);
869 cur.recordUndo(INSERT_UNDO);
871 TextMetrics const & tm = cur.bv().textMetrics(this);
872 Buffer const & buffer = *cur.buffer();
873 Paragraph & par = cur.paragraph();
874 // try to remove this
875 pit_type const pit = cur.pit();
877 bool const freeSpacing = par.layout().free_spacing ||
880 if (lyxrc.auto_number) {
881 static docstring const number_operators = from_ascii("+-/*");
882 static docstring const number_unary_operators = from_ascii("+-");
883 static docstring const number_seperators = from_ascii(".,:");
885 if (cur.current_font.fontInfo().number() == FONT_ON) {
886 if (!isDigitASCII(c) && !contains(number_operators, c) &&
887 !(contains(number_seperators, c) &&
889 cur.pos() != cur.lastpos() &&
890 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
891 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
893 number(cur); // Set current_font.number to OFF
894 } else if (isDigitASCII(c) &&
895 cur.real_current_font.isVisibleRightToLeft()) {
896 number(cur); // Set current_font.number to ON
898 if (cur.pos() != 0) {
899 char_type const c = par.getChar(cur.pos() - 1);
900 if (contains(number_unary_operators, c) &&
902 || par.isSeparator(cur.pos() - 2)
903 || par.isNewline(cur.pos() - 2))
905 setCharFont(pit, cur.pos() - 1, cur.current_font,
907 } else if (contains(number_seperators, c)
909 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
910 setCharFont(pit, cur.pos() - 1, cur.current_font,
917 // In Bidi text, we want spaces to be treated in a special way: spaces
918 // which are between words in different languages should get the
919 // paragraph's language; otherwise, spaces should keep the language
920 // they were originally typed in. This is only in effect while typing;
921 // after the text is already typed in, the user can always go back and
922 // explicitly set the language of a space as desired. But 99.9% of the
923 // time, what we're doing here is what the user actually meant.
925 // The following cases are the ones in which the language of the space
926 // should be changed to match that of the containing paragraph. In the
927 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
928 // represents a space, pipe (|) represents the cursor position (so the
929 // character before it is the one just typed in). The different cases
930 // are depicted logically (not visually), from left to right:
935 // Theoretically, there are other situations that we should, perhaps, deal
936 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
937 // point (to understand why, just try to create this situation...).
939 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
940 // get font in front and behind the space in question. But do NOT
941 // use getFont(cur.pos()) because the character c is not inserted yet
942 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
943 Font const & post_space_font = cur.real_current_font;
944 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
945 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
947 if (pre_space_rtl != post_space_rtl) {
948 // Set the space's language to match the language of the
949 // adjacent character whose direction is the paragraph's
950 // direction; don't touch other properties of the font
951 Language const * lang =
952 (pre_space_rtl == par.isRTL(buffer.params())) ?
953 pre_space_font.language() : post_space_font.language();
955 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
956 space_font.setLanguage(lang);
957 par.setFont(cur.pos() - 1, space_font);
961 // Next check, if there will be two blanks together or a blank at
962 // the beginning of a paragraph.
963 // I decided to handle blanks like normal characters, the main
964 // difference are the special checks when calculating the row.fill
965 // (blank does not count at the end of a row) and the check here
967 // When the free-spacing option is set for the current layout,
968 // disable the double-space checking
969 if (!freeSpacing && isLineSeparatorChar(c)) {
970 if (cur.pos() == 0) {
972 "You cannot insert a space at the "
973 "beginning of a paragraph. Please read the Tutorial."));
976 LASSERT(cur.pos() > 0, /**/);
977 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
978 && !par.isDeleted(cur.pos() - 1)) {
980 "You cannot type two spaces this way. "
981 "Please read the Tutorial."));
986 par.insertChar(cur.pos(), c, cur.current_font,
987 cur.buffer()->params().trackChanges);
988 cur.checkBufferStructure();
990 // cur.screenUpdateFlags(Update::Force);
991 bool boundary = cur.boundary()
992 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
993 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
998 void Text::charInserted(Cursor & cur)
1000 Paragraph & par = cur.paragraph();
1002 // Here we call finishUndo for every 20 characters inserted.
1003 // This is from my experience how emacs does it. (Lgb)
1004 if (undo_counter_ < 20) {
1011 // register word if a non-letter was entered
1013 && !par.isWordSeparator(cur.pos() - 2)
1014 && par.isWordSeparator(cur.pos() - 1)) {
1015 // get the word in front of cursor
1016 LASSERT(this == cur.text(), /**/);
1017 cur.paragraph().updateWords();
1022 // the cursor set functions have a special mechanism. When they
1023 // realize, that you left an empty paragraph, they will delete it.
1025 bool Text::cursorForwardOneWord(Cursor & cur)
1027 LASSERT(this == cur.text(), /**/);
1029 pos_type const lastpos = cur.lastpos();
1030 pit_type pit = cur.pit();
1031 pos_type pos = cur.pos();
1032 Paragraph const & par = cur.paragraph();
1034 // Paragraph boundary is a word boundary
1035 if (pos == lastpos) {
1036 if (pit != cur.lastpit())
1037 return setCursor(cur, pit + 1, 0);
1042 if (lyxrc.mac_like_word_movement) {
1043 // Skip through trailing punctuation and spaces.
1044 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1047 // Skip over either a non-char inset or a full word
1048 if (pos != lastpos && par.isWordSeparator(pos))
1050 else while (pos != lastpos && !par.isWordSeparator(pos))
1053 LASSERT(pos < lastpos, /**/); // see above
1054 if (!par.isWordSeparator(pos))
1055 while (pos != lastpos && !par.isWordSeparator(pos))
1057 else if (par.isChar(pos))
1058 while (pos != lastpos && par.isChar(pos))
1060 else if (!par.isSpace(pos)) // non-char inset
1063 // Skip over white space
1064 while (pos != lastpos && par.isSpace(pos))
1068 return setCursor(cur, pit, pos);
1072 bool Text::cursorBackwardOneWord(Cursor & cur)
1074 LASSERT(this == cur.text(), /**/);
1076 pit_type pit = cur.pit();
1077 pos_type pos = cur.pos();
1078 Paragraph & par = cur.paragraph();
1080 // Paragraph boundary is a word boundary
1081 if (pos == 0 && pit != 0)
1082 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1084 if (lyxrc.mac_like_word_movement) {
1085 // Skip through punctuation and spaces.
1086 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1089 // Skip over either a non-char inset or a full word
1090 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1092 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1095 // Skip over white space
1096 while (pos != 0 && par.isSpace(pos - 1))
1099 if (pos != 0 && !par.isWordSeparator(pos - 1))
1100 while (pos != 0 && !par.isWordSeparator(pos - 1))
1102 else if (pos != 0 && par.isChar(pos - 1))
1103 while (pos != 0 && par.isChar(pos - 1))
1105 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1109 return setCursor(cur, pit, pos);
1113 bool Text::cursorVisLeftOneWord(Cursor & cur)
1115 LASSERT(this == cur.text(), /**/);
1117 pos_type left_pos, right_pos;
1118 bool left_is_letter, right_is_letter;
1120 Cursor temp_cur = cur;
1122 // always try to move at least once...
1123 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1125 // collect some information about current cursor position
1126 temp_cur.getSurroundingPos(left_pos, right_pos);
1128 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1130 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1132 // if we're not at a letter/non-letter boundary, continue moving
1133 if (left_is_letter == right_is_letter)
1136 // we should stop when we have an LTR word on our right or an RTL word
1138 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1139 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1140 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1141 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1145 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1146 true, temp_cur.boundary());
1150 bool Text::cursorVisRightOneWord(Cursor & cur)
1152 LASSERT(this == cur.text(), /**/);
1154 pos_type left_pos, right_pos;
1155 bool left_is_letter, right_is_letter;
1157 Cursor temp_cur = cur;
1159 // always try to move at least once...
1160 while (temp_cur.posVisRight(true /* skip_inset */)) {
1162 // collect some information about current cursor position
1163 temp_cur.getSurroundingPos(left_pos, right_pos);
1165 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1167 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1169 // if we're not at a letter/non-letter boundary, continue moving
1170 if (left_is_letter == right_is_letter)
1173 // we should stop when we have an LTR word on our right or an RTL word
1175 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1176 temp_cur.buffer()->params(),
1177 left_pos).isRightToLeft())
1178 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1179 temp_cur.buffer()->params(),
1180 right_pos).isRightToLeft()))
1184 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1185 true, temp_cur.boundary());
1189 void Text::selectWord(Cursor & cur, word_location loc)
1191 LASSERT(this == cur.text(), /**/);
1192 CursorSlice from = cur.top();
1193 CursorSlice to = cur.top();
1194 getWord(from, to, loc);
1195 if (cur.top() != from)
1196 setCursor(cur, from.pit(), from.pos());
1199 if (!cur.selection())
1201 setCursor(cur, to.pit(), to.pos());
1203 cur.setWordSelection(true);
1207 void Text::selectAll(Cursor & cur)
1209 LASSERT(this == cur.text(), /**/);
1210 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1212 // If the cursor is at the beginning, make sure the cursor ends there
1213 if (cur.pit() == 0 && cur.pos() == 0) {
1214 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1216 setCursor(cur, 0, 0);
1218 setCursor(cur, 0, 0);
1220 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1226 // Select the word currently under the cursor when no
1227 // selection is currently set
1228 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1230 LASSERT(this == cur.text(), /**/);
1231 if (cur.selection())
1233 selectWord(cur, loc);
1234 return cur.selection();
1238 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1240 LASSERT(this == cur.text(), /**/);
1242 if (!cur.selection()) {
1243 bool const changed = cur.paragraph().isChanged(cur.pos());
1244 if (!(changed && findNextChange(&cur.bv())))
1248 cur.recordUndoSelection();
1250 pit_type begPit = cur.selectionBegin().pit();
1251 pit_type endPit = cur.selectionEnd().pit();
1253 pos_type begPos = cur.selectionBegin().pos();
1254 pos_type endPos = cur.selectionEnd().pos();
1256 // keep selection info, because endPos becomes invalid after the first loop
1257 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1259 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1261 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1262 pos_type parSize = pars_[pit].size();
1264 // ignore empty paragraphs; otherwise, an assertion will fail for
1265 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1269 // do not consider first paragraph if the cursor starts at pos size()
1270 if (pit == begPit && begPos == parSize)
1273 // do not consider last paragraph if the cursor ends at pos 0
1274 if (pit == endPit && endPos == 0)
1275 break; // last iteration anyway
1277 pos_type left = (pit == begPit ? begPos : 0);
1278 pos_type right = (pit == endPit ? endPos : parSize);
1281 // there is no change here
1285 pars_[pit].acceptChanges(left, right);
1287 pars_[pit].rejectChanges(left, right);
1291 // next, accept/reject imaginary end-of-par characters
1293 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1294 pos_type pos = pars_[pit].size();
1296 // skip if the selection ends before the end-of-par
1297 if (pit == endPit && endsBeforeEndOfPar)
1298 break; // last iteration anyway
1300 // skip if this is not the last paragraph of the document
1301 // note: the user should be able to accept/reject the par break of the last par!
1302 if (pit == endPit && pit + 1 != int(pars_.size()))
1303 break; // last iteration anway
1306 if (pars_[pit].isInserted(pos)) {
1307 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1308 } else if (pars_[pit].isDeleted(pos)) {
1309 if (pit + 1 == int(pars_.size())) {
1310 // we cannot remove a par break at the end of the last paragraph;
1311 // instead, we mark it unchanged
1312 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1314 mergeParagraph(cur.buffer()->params(), pars_, pit);
1320 if (pars_[pit].isDeleted(pos)) {
1321 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1322 } else if (pars_[pit].isInserted(pos)) {
1323 if (pit + 1 == int(pars_.size())) {
1324 // we mark the par break at the end of the last paragraph unchanged
1325 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1327 mergeParagraph(cur.buffer()->params(), pars_, pit);
1335 // finally, invoke the DEPM
1337 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1342 cur.clearSelection();
1343 setCursorIntern(cur, begPit, begPos);
1344 cur.screenUpdateFlags(Update::Force);
1345 cur.forceBufferUpdate();
1349 void Text::acceptChanges()
1351 BufferParams const & bparams = owner_->buffer().params();
1352 lyx::acceptChanges(pars_, bparams);
1353 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1357 void Text::rejectChanges()
1359 BufferParams const & bparams = owner_->buffer().params();
1360 pit_type pars_size = static_cast<pit_type>(pars_.size());
1362 // first, reject changes within each individual paragraph
1363 // (do not consider end-of-par)
1364 for (pit_type pit = 0; pit < pars_size; ++pit) {
1365 if (!pars_[pit].empty()) // prevent assertion failure
1366 pars_[pit].rejectChanges(0, pars_[pit].size());
1369 // next, reject imaginary end-of-par characters
1370 for (pit_type pit = 0; pit < pars_size; ++pit) {
1371 pos_type pos = pars_[pit].size();
1373 if (pars_[pit].isDeleted(pos)) {
1374 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1375 } else if (pars_[pit].isInserted(pos)) {
1376 if (pit == pars_size - 1) {
1377 // we mark the par break at the end of the last
1378 // paragraph unchanged
1379 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1381 mergeParagraph(bparams, pars_, pit);
1388 // finally, invoke the DEPM
1389 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1393 void Text::deleteWordForward(Cursor & cur)
1395 LASSERT(this == cur.text(), /**/);
1396 if (cur.lastpos() == 0)
1400 cur.setSelection(true);
1401 cursorForwardOneWord(cur);
1403 cutSelection(cur, true, false);
1404 cur.checkBufferStructure();
1409 void Text::deleteWordBackward(Cursor & cur)
1411 LASSERT(this == cur.text(), /**/);
1412 if (cur.lastpos() == 0)
1413 cursorBackward(cur);
1416 cur.setSelection(true);
1417 cursorBackwardOneWord(cur);
1419 cutSelection(cur, true, false);
1420 cur.checkBufferStructure();
1425 // Kill to end of line.
1426 void Text::changeCase(Cursor & cur, TextCase action)
1428 LASSERT(this == cur.text(), /**/);
1432 bool gotsel = false;
1433 if (cur.selection()) {
1434 from = cur.selBegin();
1439 getWord(from, to, PARTIAL_WORD);
1440 cursorForwardOneWord(cur);
1443 cur.recordUndoSelection();
1445 pit_type begPit = from.pit();
1446 pit_type endPit = to.pit();
1448 pos_type begPos = from.pos();
1449 pos_type endPos = to.pos();
1451 pos_type right = 0; // needed after the for loop
1453 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1454 Paragraph & par = pars_[pit];
1455 pos_type const pos = (pit == begPit ? begPos : 0);
1456 right = (pit == endPit ? endPos : par.size());
1457 par.changeCase(cur.buffer()->params(), pos, right, action);
1460 // the selection may have changed due to logically-only deleted chars
1462 setCursor(cur, begPit, begPos);
1464 setCursor(cur, endPit, right);
1467 setCursor(cur, endPit, right);
1469 cur.checkBufferStructure();
1473 bool Text::handleBibitems(Cursor & cur)
1475 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1481 BufferParams const & bufparams = cur.buffer()->params();
1482 Paragraph const & par = cur.paragraph();
1483 Cursor prevcur = cur;
1484 if (cur.pit() > 0) {
1486 prevcur.pos() = prevcur.lastpos();
1488 Paragraph const & prevpar = prevcur.paragraph();
1490 // if a bibitem is deleted, merge with previous paragraph
1491 // if this is a bibliography item as well
1492 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1493 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1494 mergeParagraph(bufparams, cur.text()->paragraphs(),
1496 cur.forceBufferUpdate();
1497 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1498 cur.screenUpdateFlags(Update::Force);
1502 // otherwise reset to default
1503 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1508 bool Text::erase(Cursor & cur)
1510 LASSERT(this == cur.text(), return false);
1511 bool needsUpdate = false;
1512 Paragraph & par = cur.paragraph();
1514 if (cur.pos() != cur.lastpos()) {
1515 // this is the code for a normal delete, not pasting
1517 cur.recordUndo(DELETE_UNDO);
1518 bool const was_inset = cur.paragraph().isInset(cur.pos());
1519 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1520 // the character has been logically deleted only => skip it
1521 cur.top().forwardPos();
1524 cur.forceBufferUpdate();
1526 cur.checkBufferStructure();
1529 if (cur.pit() == cur.lastpit())
1530 return dissolveInset(cur);
1532 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1533 par.setChange(cur.pos(), Change(Change::DELETED));
1537 setCursorIntern(cur, cur.pit() + 1, 0);
1538 needsUpdate = backspacePos0(cur);
1542 needsUpdate |= handleBibitems(cur);
1545 // Make sure the cursor is correct. Is this really needed?
1546 // No, not really... at least not here!
1547 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1548 cur.checkBufferStructure();
1555 bool Text::backspacePos0(Cursor & cur)
1557 LASSERT(this == cur.text(), /**/);
1561 bool needsUpdate = false;
1563 BufferParams const & bufparams = cur.buffer()->params();
1564 DocumentClass const & tclass = bufparams.documentClass();
1565 ParagraphList & plist = cur.text()->paragraphs();
1566 Paragraph const & par = cur.paragraph();
1567 Cursor prevcur = cur;
1569 prevcur.pos() = prevcur.lastpos();
1570 Paragraph const & prevpar = prevcur.paragraph();
1572 // is it an empty paragraph?
1573 if (cur.lastpos() == 0
1574 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1575 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1576 plist.erase(boost::next(plist.begin(), cur.pit()));
1579 // is previous par empty?
1580 else if (prevcur.lastpos() == 0
1581 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1582 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1583 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1586 // Pasting is not allowed, if the paragraphs have different
1587 // layouts. I think it is a real bug of all other
1588 // word processors to allow it. It confuses the user.
1589 // Correction: Pasting is always allowed with standard-layout
1590 // or the empty layout.
1591 else if (par.layout() == prevpar.layout()
1592 || tclass.isDefaultLayout(par.layout())
1593 || tclass.isPlainLayout(par.layout())) {
1594 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1595 mergeParagraph(bufparams, plist, prevcur.pit());
1600 cur.forceBufferUpdate();
1601 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1608 bool Text::backspace(Cursor & cur)
1610 LASSERT(this == cur.text(), /**/);
1611 bool needsUpdate = false;
1612 if (cur.pos() == 0) {
1614 return dissolveInset(cur);
1616 Paragraph & prev_par = pars_[cur.pit() - 1];
1618 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1619 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1620 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1623 // The cursor is at the beginning of a paragraph, so
1624 // the backspace will collapse two paragraphs into one.
1625 needsUpdate = backspacePos0(cur);
1628 // this is the code for a normal backspace, not pasting
1630 cur.recordUndo(DELETE_UNDO);
1631 // We used to do cursorBackwardIntern() here, but it is
1632 // not a good idea since it triggers the auto-delete
1633 // mechanism. So we do a cursorBackwardIntern()-lite,
1634 // without the dreaded mechanism. (JMarc)
1635 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1636 false, cur.boundary());
1637 bool const was_inset = cur.paragraph().isInset(cur.pos());
1638 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1640 cur.forceBufferUpdate();
1642 cur.checkBufferStructure();
1645 if (cur.pos() == cur.lastpos())
1646 cur.setCurrentFont();
1648 needsUpdate |= handleBibitems(cur);
1650 // A singlePar update is not enough in this case.
1651 // cur.screenUpdateFlags(Update::Force);
1652 setCursor(cur.top(), cur.pit(), cur.pos());
1658 bool Text::dissolveInset(Cursor & cur)
1660 LASSERT(this == cur.text(), return false);
1662 if (isMainText() || cur.inset().nargs() != 1)
1665 cur.recordUndoInset();
1667 cur.selHandle(false);
1669 pos_type spos = cur.pos();
1670 pit_type spit = cur.pit();
1671 ParagraphList plist;
1672 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1673 plist = paragraphs();
1675 // store cursor offset
1679 Buffer & b = *cur.buffer();
1680 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1682 if (!plist.empty()) {
1684 // we clear the cache so that we won't get conflicts with labels
1685 // that get pasted into the buffer. we should update this before
1686 // its being empty matters. if not (i.e., if we encounter bugs),
1687 // then this should instead be:
1688 // cur.buffer().updateBuffer();
1689 // but we'll try the cheaper solution here.
1690 cur.buffer()->clearReferenceCache();
1692 // ERT paragraphs have the Language latex_language.
1693 // This is invalid outside of ERT, so we need to
1694 // change it to the buffer language.
1695 ParagraphList::iterator it = plist.begin();
1696 ParagraphList::iterator it_end = plist.end();
1697 for (; it != it_end; it++)
1698 it->changeLanguage(b.params(), latex_language, b.language());
1700 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1701 b.errorList("Paste"));
1703 cur.pit() = min(cur.lastpit(), spit);
1704 cur.pos() = min(cur.lastpos(), spos);
1707 cur.forceBufferUpdate();
1709 // Ensure the current language is set correctly (bug 6292)
1710 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1711 cur.clearSelection();
1717 void Text::getWord(CursorSlice & from, CursorSlice & to,
1718 word_location const loc) const
1721 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1725 void Text::write(ostream & os) const
1727 Buffer const & buf = owner_->buffer();
1728 ParagraphList::const_iterator pit = paragraphs().begin();
1729 ParagraphList::const_iterator end = paragraphs().end();
1731 for (; pit != end; ++pit)
1732 pit->write(os, buf.params(), dth);
1734 // Close begin_deeper
1735 for(; dth > 0; --dth)
1736 os << "\n\\end_deeper";
1740 bool Text::read(Lexer & lex,
1741 ErrorList & errorList, InsetText * insetPtr)
1743 Buffer const & buf = owner_->buffer();
1744 depth_type depth = 0;
1747 while (lex.isOK()) {
1749 string const token = lex.getString();
1754 if (token == "\\end_inset")
1757 if (token == "\\end_body")
1760 if (token == "\\begin_body")
1763 if (token == "\\end_document") {
1768 if (token == "\\begin_layout") {
1769 lex.pushToken(token);
1772 par.setInsetOwner(insetPtr);
1773 par.params().depth(depth);
1774 par.setFont(0, Font(inherit_font, buf.params().language));
1775 pars_.push_back(par);
1776 readParagraph(pars_.back(), lex, errorList);
1778 // register the words in the global word list
1779 pars_.back().updateWords();
1780 } else if (token == "\\begin_deeper") {
1782 } else if (token == "\\end_deeper") {
1784 lex.printError("\\end_deeper: " "depth is already null");
1788 LYXERR0("Handling unknown body token: `" << token << '\'');
1792 // avoid a crash on weird documents (bug 4859)
1793 if (pars_.empty()) {
1795 par.setInsetOwner(insetPtr);
1796 par.params().depth(depth);
1797 par.setFont(0, Font(inherit_font,
1798 buf.params().language));
1799 par.setPlainOrDefaultLayout(buf.params().documentClass());
1800 pars_.push_back(par);
1806 // Returns the current font and depth as a message.
1807 docstring Text::currentState(Cursor const & cur) const
1809 LASSERT(this == cur.text(), /**/);
1810 Buffer & buf = *cur.buffer();
1811 Paragraph const & par = cur.paragraph();
1812 odocstringstream os;
1814 if (buf.params().trackChanges)
1815 os << _("[Change Tracking] ");
1817 Change change = par.lookupChange(cur.pos());
1819 if (change.changed()) {
1820 Author const & a = buf.params().authors().get(change.author);
1821 os << _("Change: ") << a.name();
1822 if (!a.email().empty())
1823 os << " (" << a.email() << ")";
1824 // FIXME ctime is english, we should translate that
1825 os << _(" at ") << ctime(&change.changetime);
1829 // I think we should only show changes from the default
1831 // No, from the document font (MV)
1832 Font font = cur.real_current_font;
1833 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1835 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1837 // The paragraph depth
1838 int depth = cur.paragraph().getDepth();
1840 os << bformat(_(", Depth: %1$d"), depth);
1842 // The paragraph spacing, but only if different from
1844 Spacing const & spacing = par.params().spacing();
1845 if (!spacing.isDefault()) {
1846 os << _(", Spacing: ");
1847 switch (spacing.getSpace()) {
1848 case Spacing::Single:
1851 case Spacing::Onehalf:
1854 case Spacing::Double:
1857 case Spacing::Other:
1858 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1860 case Spacing::Default:
1861 // should never happen, do nothing
1866 #ifdef DEVEL_VERSION
1867 os << _(", Inset: ") << &cur.inset();
1868 os << _(", Paragraph: ") << cur.pit();
1869 os << _(", Id: ") << par.id();
1870 os << _(", Position: ") << cur.pos();
1871 // FIXME: Why is the check for par.size() needed?
1872 // We are called with cur.pos() == par.size() quite often.
1873 if (!par.empty() && cur.pos() < par.size()) {
1874 // Force output of code point, not character
1875 size_t const c = par.getChar(cur.pos());
1876 os << _(", Char: 0x") << hex << c;
1878 os << _(", Boundary: ") << cur.boundary();
1879 // Row & row = cur.textRow();
1880 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1886 docstring Text::getPossibleLabel(Cursor const & cur) const
1888 pit_type pit = cur.pit();
1890 Layout const * layout = &(pars_[pit].layout());
1893 docstring par_text = pars_[pit].asString();
1895 // The return string of math matrices might contain linebreaks
1896 par_text = subst(par_text, '\n', '-');
1897 int const numwords = 3;
1898 for (int i = 0; i < numwords; ++i) {
1899 if (par_text.empty())
1902 par_text = split(par_text, head, ' ');
1903 // Is it legal to use spaces in labels ?
1909 // Make sure it isn't too long
1910 unsigned int const max_label_length = 32;
1911 if (text.size() > max_label_length)
1912 text.resize(max_label_length);
1914 // Will contain the label prefix.
1917 // For section, subsection, etc...
1918 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1919 Layout const * layout2 = &(pars_[pit - 1].layout());
1920 if (layout2->latextype != LATEX_PARAGRAPH) {
1925 if (layout->latextype != LATEX_PARAGRAPH)
1926 name = layout->refprefix;
1928 // For captions, we just take the caption type
1929 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1930 if (caption_inset) {
1931 string const & ftype = static_cast<InsetCaption *>(caption_inset)->type();
1932 FloatList const & fl = cur.buffer()->params().documentClass().floats();
1933 if (fl.typeExist(ftype)) {
1934 Floating const & flt = fl.getType(ftype);
1935 name = from_utf8(flt.refPrefix());
1938 name = from_utf8(ftype.substr(0,3));
1941 // If none of the above worked, see if the inset knows.
1943 InsetLayout const & il = cur.inset().getLayout();
1944 name = il.refprefix();
1948 text = name + ':' + text;
1954 docstring Text::asString(int options) const
1956 return asString(0, pars_.size(), options);
1960 docstring Text::asString(pit_type beg, pit_type end, int options) const
1962 size_t i = size_t(beg);
1963 docstring str = pars_[i].asString(options);
1964 for (++i; i != size_t(end); ++i) {
1966 str += pars_[i].asString(options);
1972 void Text::forToc(docstring & os, size_t maxlen, bool shorten) const
1975 maxlen = std::numeric_limits<std::size_t>::max();
1977 LASSERT(maxlen >= 8, maxlen = TOC_ENTRY_LENGTH);
1978 for (size_t i = 0; i != pars_.size() && os.length() < maxlen; ++i)
1979 pars_[i].forToc(os, maxlen);
1980 if (shorten && os.length() >= maxlen)
1981 os = os.substr(0, maxlen - 3) + from_ascii("...");
1985 void Text::charsTranspose(Cursor & cur)
1987 LASSERT(this == cur.text(), /**/);
1989 pos_type pos = cur.pos();
1991 // If cursor is at beginning or end of paragraph, do nothing.
1992 if (pos == cur.lastpos() || pos == 0)
1995 Paragraph & par = cur.paragraph();
1997 // Get the positions of the characters to be transposed.
1998 pos_type pos1 = pos - 1;
1999 pos_type pos2 = pos;
2001 // In change tracking mode, ignore deleted characters.
2002 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2004 if (pos2 == cur.lastpos())
2007 while (pos1 >= 0 && par.isDeleted(pos1))
2012 // Don't do anything if one of the "characters" is not regular text.
2013 if (par.isInset(pos1) || par.isInset(pos2))
2016 // Store the characters to be transposed (including font information).
2017 char_type const char1 = par.getChar(pos1);
2019 par.getFontSettings(cur.buffer()->params(), pos1);
2021 char_type const char2 = par.getChar(pos2);
2023 par.getFontSettings(cur.buffer()->params(), pos2);
2025 // And finally, we are ready to perform the transposition.
2026 // Track the changes if Change Tracking is enabled.
2027 bool const trackChanges = cur.buffer()->params().trackChanges;
2031 par.eraseChar(pos2, trackChanges);
2032 par.eraseChar(pos1, trackChanges);
2033 par.insertChar(pos1, char2, font2, trackChanges);
2034 par.insertChar(pos2, char1, font1, trackChanges);
2036 cur.checkBufferStructure();
2038 // After the transposition, move cursor to after the transposition.
2039 setCursor(cur, cur.pit(), pos2);
2044 DocIterator Text::macrocontextPosition() const
2046 return macrocontext_position_;
2050 void Text::setMacrocontextPosition(DocIterator const & pos)
2052 macrocontext_position_ = pos;
2056 docstring Text::previousWord(CursorSlice const & sl) const
2058 CursorSlice from = sl;
2059 CursorSlice to = sl;
2060 getWord(from, to, PREVIOUS_WORD);
2061 if (sl == from || to == from)
2064 Paragraph const & par = sl.paragraph();
2065 return par.asString(from.pos(), to.pos());
2069 bool Text::completionSupported(Cursor const & cur) const
2071 Paragraph const & par = cur.paragraph();
2072 return cur.pos() > 0
2073 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2074 && !par.isWordSeparator(cur.pos() - 1);
2078 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2080 WordList const * list = theWordList(*cur.getFont().language());
2081 return new TextCompletionList(cur, list);
2085 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2087 LASSERT(cur.bv().cursor() == cur, /**/);
2089 cur.bv().cursor() = cur;
2090 if (!(cur.result().screenUpdate() & Update::Force))
2091 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2096 docstring Text::completionPrefix(Cursor const & cur) const
2098 return previousWord(cur.top());