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;
270 depth_type prev_par_depth = 0;
271 // Resolve against environment font information
272 while (par_offset != pit_type(pars_.size())
273 && par_depth != prev_par_depth
275 && !tmpfont.resolved()) {
276 prev_par_depth = par_depth;
277 par_offset = outerHook(par_offset);
278 if (par_offset != pit_type(pars_.size())) {
279 tmpfont.realize(pars_[par_offset].layout().font);
280 par_depth = pars_[par_offset].getDepth();
284 return Font(tmpfont);
288 static void acceptOrRejectChanges(ParagraphList & pars,
289 BufferParams const & bparams, Text::ChangeOp op)
291 pit_type pars_size = static_cast<pit_type>(pars.size());
293 // first, accept or reject changes within each individual
294 // paragraph (do not consider end-of-par)
295 for (pit_type pit = 0; pit < pars_size; ++pit) {
296 // prevent assertion failure
297 if (!pars[pit].empty()) {
298 if (op == Text::ACCEPT)
299 pars[pit].acceptChanges(0, pars[pit].size());
301 pars[pit].rejectChanges(0, pars[pit].size());
305 // next, accept or reject imaginary end-of-par characters
306 for (pit_type pit = 0; pit < pars_size; ++pit) {
307 pos_type pos = pars[pit].size();
308 if (pars[pit].isChanged(pos)) {
309 // keep the end-of-par char if it is inserted and accepted
310 // or when it is deleted and rejected.
311 if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
312 pars[pit].setChange(pos, Change(Change::UNCHANGED));
314 if (pit == pars_size - 1) {
315 // we cannot remove a par break at the end of the last
316 // paragraph; instead, we mark it unchanged
317 pars[pit].setChange(pos, Change(Change::UNCHANGED));
319 mergeParagraph(bparams, pars, pit);
329 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
331 acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
335 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
337 acceptOrRejectChanges(pars, bparams, Text::REJECT);
341 InsetText const & Text::inset() const
348 void Text::readParToken(Paragraph & par, Lexer & lex,
349 string const & token, Font & font, Change & change, ErrorList & errorList)
351 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
352 BufferParams const & bp = buf->params();
354 if (token[0] != '\\') {
355 docstring dstr = lex.getDocString();
356 par.appendString(dstr, font, change);
358 } else if (token == "\\begin_layout") {
360 docstring layoutname = lex.getDocString();
362 font = Font(inherit_font, bp.language);
363 change = Change(Change::UNCHANGED);
365 DocumentClass const & tclass = bp.documentClass();
367 if (layoutname.empty())
368 layoutname = tclass.defaultLayoutName();
370 if (owner_->forcePlainLayout()) {
371 // in this case only the empty layout is allowed
372 layoutname = tclass.plainLayoutName();
373 } else if (par.usePlainLayout()) {
374 // in this case, default layout maps to empty layout
375 if (layoutname == tclass.defaultLayoutName())
376 layoutname = tclass.plainLayoutName();
378 // otherwise, the empty layout maps to the default
379 if (layoutname == tclass.plainLayoutName())
380 layoutname = tclass.defaultLayoutName();
383 // When we apply an unknown layout to a document, we add this layout to the textclass
384 // of this document. For example, when you apply class article to a beamer document,
385 // all unknown layouts such as frame will be added to document class article so that
386 // these layouts can keep their original names.
387 bool const added_one = tclass.addLayoutIfNeeded(layoutname);
390 docstring const s = bformat(_("Layout `%1$s' was not found."), layoutname);
392 ErrorItem(_("Layout Not Found"), s, par.id(), 0, par.size()));
395 par.setLayout(bp.documentClass()[layoutname]);
397 // Test whether the layout is obsolete.
398 Layout const & layout = par.layout();
399 if (!layout.obsoleted_by().empty())
400 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
402 par.params().read(lex);
404 } else if (token == "\\end_layout") {
405 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
406 << "Missing \\begin_layout ?");
407 } else if (token == "\\end_inset") {
408 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
409 << "Missing \\begin_inset ?");
410 } else if (token == "\\begin_inset") {
411 Inset * inset = readInset(lex, buf);
413 par.insertInset(par.size(), inset, font, change);
416 docstring line = lex.getDocString();
417 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
418 par.id(), 0, par.size()));
420 } else if (token == "\\family") {
422 setLyXFamily(lex.getString(), font.fontInfo());
423 } else if (token == "\\series") {
425 setLyXSeries(lex.getString(), font.fontInfo());
426 } else if (token == "\\shape") {
428 setLyXShape(lex.getString(), font.fontInfo());
429 } else if (token == "\\size") {
431 setLyXSize(lex.getString(), font.fontInfo());
432 } else if (token == "\\lang") {
434 string const tok = lex.getString();
435 Language const * lang = languages.getLanguage(tok);
437 font.setLanguage(lang);
439 font.setLanguage(bp.language);
440 lex.printError("Unknown language `$$Token'");
442 } else if (token == "\\numeric") {
444 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
445 } else if (token == "\\emph") {
447 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
448 } else if (token == "\\bar") {
450 string const tok = lex.getString();
453 font.fontInfo().setUnderbar(FONT_ON);
454 else if (tok == "no")
455 font.fontInfo().setUnderbar(FONT_OFF);
456 else if (tok == "default")
457 font.fontInfo().setUnderbar(FONT_INHERIT);
459 lex.printError("Unknown bar font flag "
461 } else if (token == "\\strikeout") {
463 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
464 } else if (token == "\\uuline") {
466 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
467 } else if (token == "\\uwave") {
469 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
470 } else if (token == "\\noun") {
472 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
473 } else if (token == "\\color") {
475 setLyXColor(lex.getString(), font.fontInfo());
476 } else if (token == "\\SpecialChar") {
477 auto_ptr<Inset> inset;
478 inset.reset(new InsetSpecialChar);
480 inset->setBuffer(*buf);
481 par.insertInset(par.size(), inset.release(), font, change);
482 } else if (token == "\\backslash") {
483 par.appendChar('\\', font, change);
484 } else if (token == "\\LyXTable") {
485 auto_ptr<Inset> inset(new InsetTabular(buf));
487 par.insertInset(par.size(), inset.release(), font, change);
488 } else if (token == "\\change_unchanged") {
489 change = Change(Change::UNCHANGED);
490 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
492 istringstream is(lex.getString());
496 BufferParams::AuthorMap const & am = bp.author_map;
497 if (am.find(aid) == am.end()) {
498 errorList.push_back(ErrorItem(_("Change tracking error"),
499 bformat(_("Unknown author index for change: %1$d\n"), aid),
500 par.id(), 0, par.size()));
501 change = Change(Change::UNCHANGED);
503 if (token == "\\change_inserted")
504 change = Change(Change::INSERTED, am.find(aid)->second, ct);
506 change = Change(Change::DELETED, am.find(aid)->second, ct);
510 errorList.push_back(ErrorItem(_("Unknown token"),
511 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
513 par.id(), 0, par.size()));
518 void Text::readParagraph(Paragraph & par, Lexer & lex,
519 ErrorList & errorList)
522 string token = lex.getString();
524 Change change(Change::UNCHANGED);
527 readParToken(par, lex, token, font, change, errorList);
530 token = lex.getString();
535 if (token == "\\end_layout") {
536 //Ok, paragraph finished
540 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
541 if (token == "\\begin_layout" || token == "\\end_document"
542 || token == "\\end_inset" || token == "\\begin_deeper"
543 || token == "\\end_deeper") {
544 lex.pushToken(token);
545 lyxerr << "Paragraph ended in line "
546 << lex.lineNumber() << "\n"
547 << "Missing \\end_layout.\n";
551 // Final change goes to paragraph break:
552 par.setChange(par.size(), change);
554 // Initialize begin_of_body_ on load; redoParagraph maintains
555 par.setBeginOfBody();
557 // mark paragraph for spell checking on load
558 // par.requestSpellCheck();
562 class TextCompletionList : public CompletionList
566 TextCompletionList(Cursor const & cur, WordList const * list)
567 : buffer_(cur.buffer()), pos_(0), list_(list)
570 virtual ~TextCompletionList() {}
573 virtual bool sorted() const { return true; }
575 virtual size_t size() const
577 return list_->size();
580 virtual docstring const & data(size_t idx) const
582 return list_->word(idx);
587 Buffer const * buffer_;
591 WordList const * list_;
595 bool Text::empty() const
597 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
598 // FIXME: Should we consider the labeled type as empty too?
599 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
603 double Text::spacing(Paragraph const & par) const
605 if (par.params().spacing().isDefault())
606 return owner_->buffer().params().spacing().getValue();
607 return par.params().spacing().getValue();
612 * This breaks a paragraph at the specified position.
613 * The new paragraph will:
614 * - Decrease depth by one (or change layout to default layout) when
615 * keep_layout == false
616 * - keep current depth and layout when keep_layout == true
618 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
621 BufferParams const & bparams = text.inset().buffer().params();
622 ParagraphList & pars = text.paragraphs();
623 // create a new paragraph, and insert into the list
624 ParagraphList::iterator tmp =
625 pars.insert(boost::next(pars.begin(), par_offset + 1),
628 Paragraph & par = pars[par_offset];
630 // remember to set the inset_owner
631 tmp->setInsetOwner(&par.inInset());
632 // without doing that we get a crash when typing <Return> at the
633 // end of a paragraph
634 tmp->setPlainOrDefaultLayout(bparams.documentClass());
637 tmp->setLayout(par.layout());
638 tmp->setLabelWidthString(par.params().labelWidthString());
639 tmp->params().depth(par.params().depth());
640 } else if (par.params().depth() > 0) {
641 Paragraph const & hook = pars[text.outerHook(par_offset)];
642 tmp->setLayout(hook.layout());
643 // not sure the line below is useful
644 tmp->setLabelWidthString(par.params().labelWidthString());
645 tmp->params().depth(hook.params().depth());
648 bool const isempty = (par.allowEmpty() && par.empty());
650 if (!isempty && (par.size() > pos || par.empty())) {
651 tmp->setLayout(par.layout());
652 tmp->params().align(par.params().align());
653 tmp->setLabelWidthString(par.params().labelWidthString());
655 tmp->params().depth(par.params().depth());
656 tmp->params().noindent(par.params().noindent());
658 // move everything behind the break position
659 // to the new paragraph
661 /* Note: if !keepempty, empty() == true, then we reach
662 * here with size() == 0. So pos_end becomes - 1. This
663 * doesn't cause problems because both loops below
664 * enforce pos <= pos_end and 0 <= pos
666 pos_type pos_end = par.size() - 1;
668 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
669 if (moveItem(par, pos, *tmp, j, bparams)) {
675 // Move over the end-of-par change information
676 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
677 par.setChange(par.size(), Change(bparams.trackChanges ?
678 Change::INSERTED : Change::UNCHANGED));
681 // Make sure that we keep the language when
682 // breaking paragraph.
684 Font changed = tmp->getFirstFontSettings(bparams);
685 Font const & old = par.getFontSettings(bparams, par.size());
686 changed.setLanguage(old.language());
687 tmp->setFont(0, changed);
694 bool const soa = par.params().startOfAppendix();
695 par.params().clear();
696 // do not lose start of appendix marker (bug 4212)
697 par.params().startOfAppendix(soa);
698 par.setPlainOrDefaultLayout(bparams.documentClass());
702 par.setLayout(tmp->layout());
703 par.setLabelWidthString(tmp->params().labelWidthString());
704 par.params().depth(tmp->params().depth());
709 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
711 LASSERT(this == cur.text(), /**/);
713 Paragraph & cpar = cur.paragraph();
714 pit_type cpit = cur.pit();
716 DocumentClass const & tclass = cur.buffer()->params().documentClass();
717 Layout const & layout = cpar.layout();
719 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
720 if (changeDepthAllowed(cur, DEC_DEPTH))
721 changeDepth(cur, DEC_DEPTH);
723 setLayout(cur, tclass.defaultLayoutName());
729 // Always break behind a space
730 // It is better to erase the space (Dekel)
731 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
732 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
734 // What should the layout for the new paragraph be?
735 bool keep_layout = layout.isEnvironment()
736 || (layout.isParagraph() && layout.parbreak_is_newline);
738 keep_layout = !keep_layout;
740 // We need to remember this before we break the paragraph, because
741 // that invalidates the layout variable
742 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
744 // we need to set this before we insert the paragraph.
745 bool const isempty = cpar.allowEmpty() && cpar.empty();
747 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
749 // After this, neither paragraph contains any rows!
752 pit_type next_par = cpit + 1;
754 // well this is the caption hack since one caption is really enough
757 // set to standard-layout
758 //FIXME Check if this should be plainLayout() in some cases
759 pars_[cpit].applyLayout(tclass.defaultLayout());
761 // set to standard-layout
762 //FIXME Check if this should be plainLayout() in some cases
763 pars_[next_par].applyLayout(tclass.defaultLayout());
766 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
767 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
768 break; // the character couldn't be deleted physically due to change tracking
771 // A singlePar update is not enough in this case.
772 cur.screenUpdateFlags(Update::Force);
773 cur.forceBufferUpdate();
775 // This check is necessary. Otherwise the new empty paragraph will
776 // be deleted automatically. And it is more friendly for the user!
777 if (cur.pos() != 0 || isempty)
778 setCursor(cur, cur.pit() + 1, 0);
780 setCursor(cur, cur.pit(), 0);
784 // needed to insert the selection
785 void Text::insertStringAsLines(Cursor & cur, docstring const & str,
788 BufferParams const & bparams = owner_->buffer().params();
789 pit_type pit = cur.pit();
790 pos_type pos = cur.pos();
792 // insert the string, don't insert doublespace
793 bool space_inserted = true;
794 for (docstring::const_iterator cit = str.begin();
795 cit != str.end(); ++cit) {
796 Paragraph & par = pars_[pit];
798 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
799 lyx::breakParagraph(*this, pit, pos,
800 par.layout().isEnvironment());
803 space_inserted = true;
807 // do not insert consecutive spaces if !free_spacing
808 } else if ((*cit == ' ' || *cit == '\t') &&
809 space_inserted && !par.isFreeSpacing()) {
811 } else if (*cit == '\t') {
812 if (!par.isFreeSpacing()) {
813 // tabs are like spaces here
814 par.insertChar(pos, ' ', font, bparams.trackChanges);
816 space_inserted = true;
818 par.insertChar(pos, *cit, font, bparams.trackChanges);
820 space_inserted = true;
822 } else if (!isPrintable(*cit)) {
823 // Ignore unprintables
826 // just insert the character
827 par.insertChar(pos, *cit, font, bparams.trackChanges);
829 space_inserted = (*cit == ' ');
832 setCursor(cur, pit, pos);
836 // turn double CR to single CR, others are converted into one
837 // blank. Then insertStringAsLines is called
838 void Text::insertStringAsParagraphs(Cursor & cur, docstring const & str,
841 docstring linestr = str;
842 bool newline_inserted = false;
844 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
845 if (linestr[i] == '\n') {
846 if (newline_inserted) {
847 // we know that \r will be ignored by
848 // insertStringAsLines. Of course, it is a dirty
849 // trick, but it works...
850 linestr[i - 1] = '\r';
854 newline_inserted = true;
856 } else if (isPrintable(linestr[i])) {
857 newline_inserted = false;
860 insertStringAsLines(cur, linestr, font);
864 // insert a character, moves all the following breaks in the
865 // same Paragraph one to the right and make a rebreak
866 void Text::insertChar(Cursor & cur, char_type c)
868 LASSERT(this == cur.text(), /**/);
870 cur.recordUndo(INSERT_UNDO);
872 TextMetrics const & tm = cur.bv().textMetrics(this);
873 Buffer const & buffer = *cur.buffer();
874 Paragraph & par = cur.paragraph();
875 // try to remove this
876 pit_type const pit = cur.pit();
878 bool const freeSpacing = par.layout().free_spacing ||
881 if (lyxrc.auto_number) {
882 static docstring const number_operators = from_ascii("+-/*");
883 static docstring const number_unary_operators = from_ascii("+-");
884 static docstring const number_seperators = from_ascii(".,:");
886 if (cur.current_font.fontInfo().number() == FONT_ON) {
887 if (!isDigitASCII(c) && !contains(number_operators, c) &&
888 !(contains(number_seperators, c) &&
890 cur.pos() != cur.lastpos() &&
891 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
892 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
894 number(cur); // Set current_font.number to OFF
895 } else if (isDigitASCII(c) &&
896 cur.real_current_font.isVisibleRightToLeft()) {
897 number(cur); // Set current_font.number to ON
899 if (cur.pos() != 0) {
900 char_type const c = par.getChar(cur.pos() - 1);
901 if (contains(number_unary_operators, c) &&
903 || par.isSeparator(cur.pos() - 2)
904 || par.isNewline(cur.pos() - 2))
906 setCharFont(pit, cur.pos() - 1, cur.current_font,
908 } else if (contains(number_seperators, c)
910 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
911 setCharFont(pit, cur.pos() - 1, cur.current_font,
918 // In Bidi text, we want spaces to be treated in a special way: spaces
919 // which are between words in different languages should get the
920 // paragraph's language; otherwise, spaces should keep the language
921 // they were originally typed in. This is only in effect while typing;
922 // after the text is already typed in, the user can always go back and
923 // explicitly set the language of a space as desired. But 99.9% of the
924 // time, what we're doing here is what the user actually meant.
926 // The following cases are the ones in which the language of the space
927 // should be changed to match that of the containing paragraph. In the
928 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
929 // represents a space, pipe (|) represents the cursor position (so the
930 // character before it is the one just typed in). The different cases
931 // are depicted logically (not visually), from left to right:
936 // Theoretically, there are other situations that we should, perhaps, deal
937 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
938 // point (to understand why, just try to create this situation...).
940 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
941 // get font in front and behind the space in question. But do NOT
942 // use getFont(cur.pos()) because the character c is not inserted yet
943 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
944 Font const & post_space_font = cur.real_current_font;
945 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
946 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
948 if (pre_space_rtl != post_space_rtl) {
949 // Set the space's language to match the language of the
950 // adjacent character whose direction is the paragraph's
951 // direction; don't touch other properties of the font
952 Language const * lang =
953 (pre_space_rtl == par.isRTL(buffer.params())) ?
954 pre_space_font.language() : post_space_font.language();
956 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
957 space_font.setLanguage(lang);
958 par.setFont(cur.pos() - 1, space_font);
962 // Next check, if there will be two blanks together or a blank at
963 // the beginning of a paragraph.
964 // I decided to handle blanks like normal characters, the main
965 // difference are the special checks when calculating the row.fill
966 // (blank does not count at the end of a row) and the check here
968 // When the free-spacing option is set for the current layout,
969 // disable the double-space checking
970 if (!freeSpacing && isLineSeparatorChar(c)) {
971 if (cur.pos() == 0) {
973 "You cannot insert a space at the "
974 "beginning of a paragraph. Please read the Tutorial."));
977 LASSERT(cur.pos() > 0, /**/);
978 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
979 && !par.isDeleted(cur.pos() - 1)) {
981 "You cannot type two spaces this way. "
982 "Please read the Tutorial."));
987 par.insertChar(cur.pos(), c, cur.current_font,
988 cur.buffer()->params().trackChanges);
989 cur.checkBufferStructure();
991 // cur.screenUpdateFlags(Update::Force);
992 bool boundary = cur.boundary()
993 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
994 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
999 void Text::charInserted(Cursor & cur)
1001 Paragraph & par = cur.paragraph();
1003 // Here we call finishUndo for every 20 characters inserted.
1004 // This is from my experience how emacs does it. (Lgb)
1005 if (undo_counter_ < 20) {
1012 // register word if a non-letter was entered
1014 && !par.isWordSeparator(cur.pos() - 2)
1015 && par.isWordSeparator(cur.pos() - 1)) {
1016 // get the word in front of cursor
1017 LASSERT(this == cur.text(), /**/);
1018 cur.paragraph().updateWords();
1023 // the cursor set functions have a special mechanism. When they
1024 // realize, that you left an empty paragraph, they will delete it.
1026 bool Text::cursorForwardOneWord(Cursor & cur)
1028 LASSERT(this == cur.text(), /**/);
1030 pos_type const lastpos = cur.lastpos();
1031 pit_type pit = cur.pit();
1032 pos_type pos = cur.pos();
1033 Paragraph const & par = cur.paragraph();
1035 // Paragraph boundary is a word boundary
1036 if (pos == lastpos) {
1037 if (pit != cur.lastpit())
1038 return setCursor(cur, pit + 1, 0);
1043 if (lyxrc.mac_like_word_movement) {
1044 // Skip through trailing punctuation and spaces.
1045 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1048 // Skip over either a non-char inset or a full word
1049 if (pos != lastpos && par.isWordSeparator(pos))
1051 else while (pos != lastpos && !par.isWordSeparator(pos))
1054 LASSERT(pos < lastpos, /**/); // see above
1055 if (!par.isWordSeparator(pos))
1056 while (pos != lastpos && !par.isWordSeparator(pos))
1058 else if (par.isChar(pos))
1059 while (pos != lastpos && par.isChar(pos))
1061 else if (!par.isSpace(pos)) // non-char inset
1064 // Skip over white space
1065 while (pos != lastpos && par.isSpace(pos))
1069 return setCursor(cur, pit, pos);
1073 bool Text::cursorBackwardOneWord(Cursor & cur)
1075 LASSERT(this == cur.text(), /**/);
1077 pit_type pit = cur.pit();
1078 pos_type pos = cur.pos();
1079 Paragraph & par = cur.paragraph();
1081 // Paragraph boundary is a word boundary
1082 if (pos == 0 && pit != 0)
1083 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1085 if (lyxrc.mac_like_word_movement) {
1086 // Skip through punctuation and spaces.
1087 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1090 // Skip over either a non-char inset or a full word
1091 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1093 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1096 // Skip over white space
1097 while (pos != 0 && par.isSpace(pos - 1))
1100 if (pos != 0 && !par.isWordSeparator(pos - 1))
1101 while (pos != 0 && !par.isWordSeparator(pos - 1))
1103 else if (pos != 0 && par.isChar(pos - 1))
1104 while (pos != 0 && par.isChar(pos - 1))
1106 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1110 return setCursor(cur, pit, pos);
1114 bool Text::cursorVisLeftOneWord(Cursor & cur)
1116 LASSERT(this == cur.text(), /**/);
1118 pos_type left_pos, right_pos;
1119 bool left_is_letter, right_is_letter;
1121 Cursor temp_cur = cur;
1123 // always try to move at least once...
1124 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1126 // collect some information about current cursor position
1127 temp_cur.getSurroundingPos(left_pos, right_pos);
1129 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1131 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1133 // if we're not at a letter/non-letter boundary, continue moving
1134 if (left_is_letter == right_is_letter)
1137 // we should stop when we have an LTR word on our right or an RTL word
1139 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1140 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1141 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1142 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1146 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1147 true, temp_cur.boundary());
1151 bool Text::cursorVisRightOneWord(Cursor & cur)
1153 LASSERT(this == cur.text(), /**/);
1155 pos_type left_pos, right_pos;
1156 bool left_is_letter, right_is_letter;
1158 Cursor temp_cur = cur;
1160 // always try to move at least once...
1161 while (temp_cur.posVisRight(true /* skip_inset */)) {
1163 // collect some information about current cursor position
1164 temp_cur.getSurroundingPos(left_pos, right_pos);
1166 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1168 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1170 // if we're not at a letter/non-letter boundary, continue moving
1171 if (left_is_letter == right_is_letter)
1174 // we should stop when we have an LTR word on our right or an RTL word
1176 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1177 temp_cur.buffer()->params(),
1178 left_pos).isRightToLeft())
1179 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1180 temp_cur.buffer()->params(),
1181 right_pos).isRightToLeft()))
1185 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1186 true, temp_cur.boundary());
1190 void Text::selectWord(Cursor & cur, word_location loc)
1192 LASSERT(this == cur.text(), /**/);
1193 CursorSlice from = cur.top();
1194 CursorSlice to = cur.top();
1195 getWord(from, to, loc);
1196 if (cur.top() != from)
1197 setCursor(cur, from.pit(), from.pos());
1200 if (!cur.selection())
1202 setCursor(cur, to.pit(), to.pos());
1204 cur.setWordSelection(true);
1208 void Text::selectAll(Cursor & cur)
1210 LASSERT(this == cur.text(), /**/);
1211 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1213 // If the cursor is at the beginning, make sure the cursor ends there
1214 if (cur.pit() == 0 && cur.pos() == 0) {
1215 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1217 setCursor(cur, 0, 0);
1219 setCursor(cur, 0, 0);
1221 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1227 // Select the word currently under the cursor when no
1228 // selection is currently set
1229 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1231 LASSERT(this == cur.text(), /**/);
1232 if (cur.selection())
1234 selectWord(cur, loc);
1235 return cur.selection();
1239 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1241 LASSERT(this == cur.text(), /**/);
1243 if (!cur.selection()) {
1244 bool const changed = cur.paragraph().isChanged(cur.pos());
1245 if (!(changed && findNextChange(&cur.bv())))
1249 cur.recordUndoSelection();
1251 pit_type begPit = cur.selectionBegin().pit();
1252 pit_type endPit = cur.selectionEnd().pit();
1254 pos_type begPos = cur.selectionBegin().pos();
1255 pos_type endPos = cur.selectionEnd().pos();
1257 // keep selection info, because endPos becomes invalid after the first loop
1258 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1260 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1262 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1263 pos_type parSize = pars_[pit].size();
1265 // ignore empty paragraphs; otherwise, an assertion will fail for
1266 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1270 // do not consider first paragraph if the cursor starts at pos size()
1271 if (pit == begPit && begPos == parSize)
1274 // do not consider last paragraph if the cursor ends at pos 0
1275 if (pit == endPit && endPos == 0)
1276 break; // last iteration anyway
1278 pos_type left = (pit == begPit ? begPos : 0);
1279 pos_type right = (pit == endPit ? endPos : parSize);
1282 // there is no change here
1286 pars_[pit].acceptChanges(left, right);
1288 pars_[pit].rejectChanges(left, right);
1292 // next, accept/reject imaginary end-of-par characters
1294 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1295 pos_type pos = pars_[pit].size();
1297 // skip if the selection ends before the end-of-par
1298 if (pit == endPit && endsBeforeEndOfPar)
1299 break; // last iteration anyway
1301 // skip if this is not the last paragraph of the document
1302 // note: the user should be able to accept/reject the par break of the last par!
1303 if (pit == endPit && pit + 1 != int(pars_.size()))
1304 break; // last iteration anway
1307 if (pars_[pit].isInserted(pos)) {
1308 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1309 } else if (pars_[pit].isDeleted(pos)) {
1310 if (pit + 1 == int(pars_.size())) {
1311 // we cannot remove a par break at the end of the last paragraph;
1312 // instead, we mark it unchanged
1313 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1315 mergeParagraph(cur.buffer()->params(), pars_, pit);
1321 if (pars_[pit].isDeleted(pos)) {
1322 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1323 } else if (pars_[pit].isInserted(pos)) {
1324 if (pit + 1 == int(pars_.size())) {
1325 // we mark the par break at the end of the last paragraph unchanged
1326 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1328 mergeParagraph(cur.buffer()->params(), pars_, pit);
1336 // finally, invoke the DEPM
1338 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1343 cur.clearSelection();
1344 setCursorIntern(cur, begPit, begPos);
1345 cur.screenUpdateFlags(Update::Force);
1346 cur.forceBufferUpdate();
1350 void Text::acceptChanges()
1352 BufferParams const & bparams = owner_->buffer().params();
1353 lyx::acceptChanges(pars_, bparams);
1354 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1358 void Text::rejectChanges()
1360 BufferParams const & bparams = owner_->buffer().params();
1361 pit_type pars_size = static_cast<pit_type>(pars_.size());
1363 // first, reject changes within each individual paragraph
1364 // (do not consider end-of-par)
1365 for (pit_type pit = 0; pit < pars_size; ++pit) {
1366 if (!pars_[pit].empty()) // prevent assertion failure
1367 pars_[pit].rejectChanges(0, pars_[pit].size());
1370 // next, reject imaginary end-of-par characters
1371 for (pit_type pit = 0; pit < pars_size; ++pit) {
1372 pos_type pos = pars_[pit].size();
1374 if (pars_[pit].isDeleted(pos)) {
1375 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1376 } else if (pars_[pit].isInserted(pos)) {
1377 if (pit == pars_size - 1) {
1378 // we mark the par break at the end of the last
1379 // paragraph unchanged
1380 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1382 mergeParagraph(bparams, pars_, pit);
1389 // finally, invoke the DEPM
1390 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1394 void Text::deleteWordForward(Cursor & cur)
1396 LASSERT(this == cur.text(), /**/);
1397 if (cur.lastpos() == 0)
1401 cur.setSelection(true);
1402 cursorForwardOneWord(cur);
1404 cutSelection(cur, true, false);
1405 cur.checkBufferStructure();
1410 void Text::deleteWordBackward(Cursor & cur)
1412 LASSERT(this == cur.text(), /**/);
1413 if (cur.lastpos() == 0)
1414 cursorBackward(cur);
1417 cur.setSelection(true);
1418 cursorBackwardOneWord(cur);
1420 cutSelection(cur, true, false);
1421 cur.checkBufferStructure();
1426 // Kill to end of line.
1427 void Text::changeCase(Cursor & cur, TextCase action)
1429 LASSERT(this == cur.text(), /**/);
1433 bool gotsel = false;
1434 if (cur.selection()) {
1435 from = cur.selBegin();
1440 getWord(from, to, PARTIAL_WORD);
1441 cursorForwardOneWord(cur);
1444 cur.recordUndoSelection();
1446 pit_type begPit = from.pit();
1447 pit_type endPit = to.pit();
1449 pos_type begPos = from.pos();
1450 pos_type endPos = to.pos();
1452 pos_type right = 0; // needed after the for loop
1454 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1455 Paragraph & par = pars_[pit];
1456 pos_type const pos = (pit == begPit ? begPos : 0);
1457 right = (pit == endPit ? endPos : par.size());
1458 par.changeCase(cur.buffer()->params(), pos, right, action);
1461 // the selection may have changed due to logically-only deleted chars
1463 setCursor(cur, begPit, begPos);
1465 setCursor(cur, endPit, right);
1468 setCursor(cur, endPit, right);
1470 cur.checkBufferStructure();
1474 bool Text::handleBibitems(Cursor & cur)
1476 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1482 BufferParams const & bufparams = cur.buffer()->params();
1483 Paragraph const & par = cur.paragraph();
1484 Cursor prevcur = cur;
1485 if (cur.pit() > 0) {
1487 prevcur.pos() = prevcur.lastpos();
1489 Paragraph const & prevpar = prevcur.paragraph();
1491 // if a bibitem is deleted, merge with previous paragraph
1492 // if this is a bibliography item as well
1493 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1494 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1495 mergeParagraph(bufparams, cur.text()->paragraphs(),
1497 cur.forceBufferUpdate();
1498 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1499 cur.screenUpdateFlags(Update::Force);
1503 // otherwise reset to default
1504 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1509 bool Text::erase(Cursor & cur)
1511 LASSERT(this == cur.text(), return false);
1512 bool needsUpdate = false;
1513 Paragraph & par = cur.paragraph();
1515 if (cur.pos() != cur.lastpos()) {
1516 // this is the code for a normal delete, not pasting
1518 cur.recordUndo(DELETE_UNDO);
1519 bool const was_inset = cur.paragraph().isInset(cur.pos());
1520 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1521 // the character has been logically deleted only => skip it
1522 cur.top().forwardPos();
1525 cur.forceBufferUpdate();
1527 cur.checkBufferStructure();
1530 if (cur.pit() == cur.lastpit())
1531 return dissolveInset(cur);
1533 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1534 par.setChange(cur.pos(), Change(Change::DELETED));
1538 setCursorIntern(cur, cur.pit() + 1, 0);
1539 needsUpdate = backspacePos0(cur);
1543 needsUpdate |= handleBibitems(cur);
1546 // Make sure the cursor is correct. Is this really needed?
1547 // No, not really... at least not here!
1548 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1549 cur.checkBufferStructure();
1556 bool Text::backspacePos0(Cursor & cur)
1558 LASSERT(this == cur.text(), /**/);
1562 bool needsUpdate = false;
1564 BufferParams const & bufparams = cur.buffer()->params();
1565 DocumentClass const & tclass = bufparams.documentClass();
1566 ParagraphList & plist = cur.text()->paragraphs();
1567 Paragraph const & par = cur.paragraph();
1568 Cursor prevcur = cur;
1570 prevcur.pos() = prevcur.lastpos();
1571 Paragraph const & prevpar = prevcur.paragraph();
1573 // is it an empty paragraph?
1574 if (cur.lastpos() == 0
1575 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1576 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1577 plist.erase(boost::next(plist.begin(), cur.pit()));
1580 // is previous par empty?
1581 else if (prevcur.lastpos() == 0
1582 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1583 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1584 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1587 // Pasting is not allowed, if the paragraphs have different
1588 // layouts. I think it is a real bug of all other
1589 // word processors to allow it. It confuses the user.
1590 // Correction: Pasting is always allowed with standard-layout
1591 // or the empty layout.
1592 else if (par.layout() == prevpar.layout()
1593 || tclass.isDefaultLayout(par.layout())
1594 || tclass.isPlainLayout(par.layout())) {
1595 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1596 mergeParagraph(bufparams, plist, prevcur.pit());
1601 cur.forceBufferUpdate();
1602 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1609 bool Text::backspace(Cursor & cur)
1611 LASSERT(this == cur.text(), /**/);
1612 bool needsUpdate = false;
1613 if (cur.pos() == 0) {
1615 return dissolveInset(cur);
1617 Paragraph & prev_par = pars_[cur.pit() - 1];
1619 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1620 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1621 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1624 // The cursor is at the beginning of a paragraph, so
1625 // the backspace will collapse two paragraphs into one.
1626 needsUpdate = backspacePos0(cur);
1629 // this is the code for a normal backspace, not pasting
1631 cur.recordUndo(DELETE_UNDO);
1632 // We used to do cursorBackwardIntern() here, but it is
1633 // not a good idea since it triggers the auto-delete
1634 // mechanism. So we do a cursorBackwardIntern()-lite,
1635 // without the dreaded mechanism. (JMarc)
1636 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1637 false, cur.boundary());
1638 bool const was_inset = cur.paragraph().isInset(cur.pos());
1639 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1641 cur.forceBufferUpdate();
1643 cur.checkBufferStructure();
1646 if (cur.pos() == cur.lastpos())
1647 cur.setCurrentFont();
1649 needsUpdate |= handleBibitems(cur);
1651 // A singlePar update is not enough in this case.
1652 // cur.screenUpdateFlags(Update::Force);
1653 setCursor(cur.top(), cur.pit(), cur.pos());
1659 bool Text::dissolveInset(Cursor & cur)
1661 LASSERT(this == cur.text(), return false);
1663 if (isMainText() || cur.inset().nargs() != 1)
1666 cur.recordUndoInset();
1668 cur.selHandle(false);
1670 pos_type spos = cur.pos();
1671 pit_type spit = cur.pit();
1672 ParagraphList plist;
1673 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1674 plist = paragraphs();
1676 // store cursor offset
1680 Buffer & b = *cur.buffer();
1681 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1683 if (!plist.empty()) {
1685 // we clear the cache so that we won't get conflicts with labels
1686 // that get pasted into the buffer. we should update this before
1687 // its being empty matters. if not (i.e., if we encounter bugs),
1688 // then this should instead be:
1689 // cur.buffer().updateBuffer();
1690 // but we'll try the cheaper solution here.
1691 cur.buffer()->clearReferenceCache();
1693 // ERT paragraphs have the Language latex_language.
1694 // This is invalid outside of ERT, so we need to
1695 // change it to the buffer language.
1696 ParagraphList::iterator it = plist.begin();
1697 ParagraphList::iterator it_end = plist.end();
1698 for (; it != it_end; ++it)
1699 it->changeLanguage(b.params(), latex_language, b.language());
1701 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1702 b.errorList("Paste"));
1704 cur.pit() = min(cur.lastpit(), spit);
1705 cur.pos() = min(cur.lastpos(), spos);
1708 cur.forceBufferUpdate();
1710 // Ensure the current language is set correctly (bug 6292)
1711 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1712 cur.clearSelection();
1718 void Text::getWord(CursorSlice & from, CursorSlice & to,
1719 word_location const loc) const
1722 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1726 void Text::write(ostream & os) const
1728 Buffer const & buf = owner_->buffer();
1729 ParagraphList::const_iterator pit = paragraphs().begin();
1730 ParagraphList::const_iterator end = paragraphs().end();
1732 for (; pit != end; ++pit)
1733 pit->write(os, buf.params(), dth);
1735 // Close begin_deeper
1736 for(; dth > 0; --dth)
1737 os << "\n\\end_deeper";
1741 bool Text::read(Lexer & lex,
1742 ErrorList & errorList, InsetText * insetPtr)
1744 Buffer const & buf = owner_->buffer();
1745 depth_type depth = 0;
1748 while (lex.isOK()) {
1750 string const token = lex.getString();
1755 if (token == "\\end_inset")
1758 if (token == "\\end_body")
1761 if (token == "\\begin_body")
1764 if (token == "\\end_document") {
1769 if (token == "\\begin_layout") {
1770 lex.pushToken(token);
1773 par.setInsetOwner(insetPtr);
1774 par.params().depth(depth);
1775 par.setFont(0, Font(inherit_font, buf.params().language));
1776 pars_.push_back(par);
1777 readParagraph(pars_.back(), lex, errorList);
1779 // register the words in the global word list
1780 pars_.back().updateWords();
1781 } else if (token == "\\begin_deeper") {
1783 } else if (token == "\\end_deeper") {
1785 lex.printError("\\end_deeper: " "depth is already null");
1789 LYXERR0("Handling unknown body token: `" << token << '\'');
1793 // avoid a crash on weird documents (bug 4859)
1794 if (pars_.empty()) {
1796 par.setInsetOwner(insetPtr);
1797 par.params().depth(depth);
1798 par.setFont(0, Font(inherit_font,
1799 buf.params().language));
1800 par.setPlainOrDefaultLayout(buf.params().documentClass());
1801 pars_.push_back(par);
1807 // Returns the current font and depth as a message.
1808 docstring Text::currentState(Cursor const & cur) const
1810 LASSERT(this == cur.text(), /**/);
1811 Buffer & buf = *cur.buffer();
1812 Paragraph const & par = cur.paragraph();
1813 odocstringstream os;
1815 if (buf.params().trackChanges)
1816 os << _("[Change Tracking] ");
1818 Change change = par.lookupChange(cur.pos());
1820 if (change.changed()) {
1821 Author const & a = buf.params().authors().get(change.author);
1822 os << _("Change: ") << a.name();
1823 if (!a.email().empty())
1824 os << " (" << a.email() << ")";
1825 // FIXME ctime is english, we should translate that
1826 os << _(" at ") << ctime(&change.changetime);
1830 // I think we should only show changes from the default
1832 // No, from the document font (MV)
1833 Font font = cur.real_current_font;
1834 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1836 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1838 // The paragraph depth
1839 int depth = cur.paragraph().getDepth();
1841 os << bformat(_(", Depth: %1$d"), depth);
1843 // The paragraph spacing, but only if different from
1845 Spacing const & spacing = par.params().spacing();
1846 if (!spacing.isDefault()) {
1847 os << _(", Spacing: ");
1848 switch (spacing.getSpace()) {
1849 case Spacing::Single:
1852 case Spacing::Onehalf:
1855 case Spacing::Double:
1858 case Spacing::Other:
1859 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1861 case Spacing::Default:
1862 // should never happen, do nothing
1867 #ifdef DEVEL_VERSION
1868 os << _(", Inset: ") << &cur.inset();
1869 os << _(", Paragraph: ") << cur.pit();
1870 os << _(", Id: ") << par.id();
1871 os << _(", Position: ") << cur.pos();
1872 // FIXME: Why is the check for par.size() needed?
1873 // We are called with cur.pos() == par.size() quite often.
1874 if (!par.empty() && cur.pos() < par.size()) {
1875 // Force output of code point, not character
1876 size_t const c = par.getChar(cur.pos());
1877 os << _(", Char: 0x") << hex << c;
1879 os << _(", Boundary: ") << cur.boundary();
1880 // Row & row = cur.textRow();
1881 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1887 docstring Text::getPossibleLabel(Cursor const & cur) const
1889 pit_type pit = cur.pit();
1891 Layout const * layout = &(pars_[pit].layout());
1894 docstring par_text = pars_[pit].asString();
1896 // The return string of math matrices might contain linebreaks
1897 par_text = subst(par_text, '\n', '-');
1898 int const numwords = 3;
1899 for (int i = 0; i < numwords; ++i) {
1900 if (par_text.empty())
1903 par_text = split(par_text, head, ' ');
1904 // Is it legal to use spaces in labels ?
1910 // Make sure it isn't too long
1911 unsigned int const max_label_length = 32;
1912 if (text.size() > max_label_length)
1913 text.resize(max_label_length);
1915 // Will contain the label prefix.
1918 // For section, subsection, etc...
1919 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1920 Layout const * layout2 = &(pars_[pit - 1].layout());
1921 if (layout2->latextype != LATEX_PARAGRAPH) {
1926 if (layout->latextype != LATEX_PARAGRAPH)
1927 name = layout->refprefix;
1929 // For captions, we just take the caption type
1930 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1931 if (caption_inset) {
1932 string const & ftype = static_cast<InsetCaption *>(caption_inset)->type();
1933 FloatList const & fl = cur.buffer()->params().documentClass().floats();
1934 if (fl.typeExist(ftype)) {
1935 Floating const & flt = fl.getType(ftype);
1936 name = from_utf8(flt.refPrefix());
1939 name = from_utf8(ftype.substr(0,3));
1942 // If none of the above worked, see if the inset knows.
1944 InsetLayout const & il = cur.inset().getLayout();
1945 name = il.refprefix();
1949 text = name + ':' + text;
1955 docstring Text::asString(int options) const
1957 return asString(0, pars_.size(), options);
1961 docstring Text::asString(pit_type beg, pit_type end, int options) const
1963 size_t i = size_t(beg);
1964 docstring str = pars_[i].asString(options);
1965 for (++i; i != size_t(end); ++i) {
1967 str += pars_[i].asString(options);
1973 void Text::forToc(docstring & os, size_t maxlen, bool shorten) const
1976 maxlen = std::numeric_limits<std::size_t>::max();
1978 LASSERT(maxlen >= 8, maxlen = TOC_ENTRY_LENGTH);
1979 for (size_t i = 0; i != pars_.size() && os.length() < maxlen; ++i)
1980 pars_[i].forToc(os, maxlen);
1981 if (shorten && os.length() >= maxlen)
1982 os = os.substr(0, maxlen - 3) + from_ascii("...");
1986 void Text::charsTranspose(Cursor & cur)
1988 LASSERT(this == cur.text(), /**/);
1990 pos_type pos = cur.pos();
1992 // If cursor is at beginning or end of paragraph, do nothing.
1993 if (pos == cur.lastpos() || pos == 0)
1996 Paragraph & par = cur.paragraph();
1998 // Get the positions of the characters to be transposed.
1999 pos_type pos1 = pos - 1;
2000 pos_type pos2 = pos;
2002 // In change tracking mode, ignore deleted characters.
2003 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2005 if (pos2 == cur.lastpos())
2008 while (pos1 >= 0 && par.isDeleted(pos1))
2013 // Don't do anything if one of the "characters" is not regular text.
2014 if (par.isInset(pos1) || par.isInset(pos2))
2017 // Store the characters to be transposed (including font information).
2018 char_type const char1 = par.getChar(pos1);
2020 par.getFontSettings(cur.buffer()->params(), pos1);
2022 char_type const char2 = par.getChar(pos2);
2024 par.getFontSettings(cur.buffer()->params(), pos2);
2026 // And finally, we are ready to perform the transposition.
2027 // Track the changes if Change Tracking is enabled.
2028 bool const trackChanges = cur.buffer()->params().trackChanges;
2032 par.eraseChar(pos2, trackChanges);
2033 par.eraseChar(pos1, trackChanges);
2034 par.insertChar(pos1, char2, font2, trackChanges);
2035 par.insertChar(pos2, char1, font1, trackChanges);
2037 cur.checkBufferStructure();
2039 // After the transposition, move cursor to after the transposition.
2040 setCursor(cur, cur.pit(), pos2);
2045 DocIterator Text::macrocontextPosition() const
2047 return macrocontext_position_;
2051 void Text::setMacrocontextPosition(DocIterator const & pos)
2053 macrocontext_position_ = pos;
2057 docstring Text::previousWord(CursorSlice const & sl) const
2059 CursorSlice from = sl;
2060 CursorSlice to = sl;
2061 getWord(from, to, PREVIOUS_WORD);
2062 if (sl == from || to == from)
2065 Paragraph const & par = sl.paragraph();
2066 return par.asString(from.pos(), to.pos());
2070 bool Text::completionSupported(Cursor const & cur) const
2072 Paragraph const & par = cur.paragraph();
2073 return cur.pos() > 0
2074 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2075 && !par.isWordSeparator(cur.pos() - 1);
2079 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2081 WordList const * list = theWordList(*cur.getFont().language());
2082 return new TextCompletionList(cur, list);
2086 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2088 LASSERT(cur.bv().cursor() == cur, /**/);
2090 cur.bv().cursor() = cur;
2091 if (!(cur.result().screenUpdate() & Update::Force))
2092 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2097 docstring Text::completionPrefix(Cursor const & cur) const
2099 return previousWord(cur.top());