3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Dov Feldstern
9 * \author Jean-Marc Lasgouttes
11 * \author André Pönitz
12 * \author Stefan Schimanski
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "CompletionList.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
37 #include "InsetList.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TextMetrics.h"
50 #include "WordLangTuple.h"
53 #include "insets/InsetText.h"
54 #include "insets/InsetBibitem.h"
55 #include "insets/InsetCaption.h"
56 #include "insets/InsetLine.h"
57 #include "insets/InsetNewline.h"
58 #include "insets/InsetNewpage.h"
59 #include "insets/InsetArgument.h"
60 #include "insets/InsetSpace.h"
61 #include "insets/InsetSpecialChar.h"
62 #include "insets/InsetTabular.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
71 #include <boost/next_prior.hpp>
76 using namespace lyx::support;
80 using cap::cutSelection;
81 using cap::pasteParagraphList;
83 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
84 Paragraph & toPar, pos_type toPos, BufferParams const & params)
86 // Note: moveItem() does not honour change tracking!
87 // Therefore, it should only be used for breaking and merging paragraphs
89 // We need a copy here because the character at fromPos is going to be erased.
90 Font const tmpFont = fromPar.getFontSettings(params, fromPos);
91 Change const tmpChange = fromPar.lookupChange(fromPos);
93 if (Inset * tmpInset = fromPar.getInset(fromPos)) {
94 fromPar.releaseInset(fromPos);
95 // The inset is not in fromPar any more.
96 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
103 char_type const tmpChar = fromPar.getChar(fromPos);
104 fromPar.eraseChar(fromPos, false);
105 toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
110 void breakParagraphConservative(BufferParams const & bparams,
111 ParagraphList & pars, pit_type par_offset, pos_type pos)
113 // create a new paragraph
114 Paragraph & tmp = *pars.insert(boost::next(pars.begin(), par_offset + 1),
116 Paragraph & par = pars[par_offset];
118 tmp.setInsetOwner(&par.inInset());
119 tmp.makeSameLayout(par);
121 LASSERT(pos <= par.size(), /**/);
123 if (pos < par.size()) {
124 // move everything behind the break position to the new paragraph
125 pos_type pos_end = par.size() - 1;
127 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
128 if (moveItem(par, pos, tmp, j, bparams)) {
132 // Move over the end-of-par change information
133 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
134 par.setChange(par.size(), Change(bparams.trackChanges ?
135 Change::INSERTED : Change::UNCHANGED));
140 void mergeParagraph(BufferParams const & bparams,
141 ParagraphList & pars, pit_type par_offset)
143 Paragraph & next = pars[par_offset + 1];
144 Paragraph & par = pars[par_offset];
146 pos_type pos_end = next.size() - 1;
147 pos_type pos_insert = par.size();
149 // the imaginary end-of-paragraph character (at par.size()) has to be
150 // marked as unmodified. Otherwise, its change is adopted by the first
151 // character of the next paragraph.
152 if (par.isChanged(par.size())) {
153 LYXERR(Debug::CHANGES,
154 "merging par with inserted/deleted end-of-par character");
155 par.setChange(par.size(), Change(Change::UNCHANGED));
158 Change change = next.lookupChange(next.size());
160 // move the content of the second paragraph to the end of the first one
161 for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
162 if (moveItem(next, 0, par, j, bparams)) {
167 // move the change of the end-of-paragraph character
168 par.setChange(par.size(), change);
170 pars.erase(boost::next(pars.begin(), par_offset + 1));
174 Text::Text(InsetText * owner, bool use_default_layout)
175 : owner_(owner), autoBreakRows_(false), undo_counter_(0)
177 pars_.push_back(Paragraph());
178 Paragraph & par = pars_.back();
179 par.setInsetOwner(owner);
180 DocumentClass const & dc = owner->buffer().params().documentClass();
181 if (use_default_layout)
182 par.setDefaultLayout(dc);
184 par.setPlainLayout(dc);
188 Text::Text(InsetText * owner, Text const & text)
189 : owner_(owner), autoBreakRows_(text.autoBreakRows_), undo_counter_(0)
192 ParagraphList::iterator const end = pars_.end();
193 ParagraphList::iterator it = pars_.begin();
194 for (; it != end; ++it)
195 it->setInsetOwner(owner);
199 pit_type Text::depthHook(pit_type pit, depth_type depth) const
201 pit_type newpit = pit;
206 while (newpit != 0 && pars_[newpit].getDepth() > depth)
209 if (pars_[newpit].getDepth() > depth)
216 pit_type Text::outerHook(pit_type par_offset) const
218 Paragraph const & par = pars_[par_offset];
220 if (par.getDepth() == 0)
222 return depthHook(par_offset, depth_type(par.getDepth() - 1));
226 bool Text::isFirstInSequence(pit_type par_offset) const
228 Paragraph const & par = pars_[par_offset];
230 pit_type dhook_offset = depthHook(par_offset, par.getDepth());
232 if (dhook_offset == par_offset)
235 Paragraph const & dhook = pars_[dhook_offset];
237 return dhook.layout() != par.layout()
238 || dhook.getDepth() != par.getDepth();
242 Font const Text::outerFont(pit_type par_offset) const
244 depth_type par_depth = pars_[par_offset].getDepth();
245 FontInfo tmpfont = inherit_font;
247 // Resolve against environment font information
248 while (par_offset != pit_type(pars_.size())
250 && !tmpfont.resolved()) {
251 par_offset = outerHook(par_offset);
252 if (par_offset != pit_type(pars_.size())) {
253 tmpfont.realize(pars_[par_offset].layout().font);
254 par_depth = pars_[par_offset].getDepth();
258 return Font(tmpfont);
262 static void acceptOrRejectChanges(ParagraphList & pars,
263 BufferParams const & bparams, Text::ChangeOp op)
265 pit_type pars_size = static_cast<pit_type>(pars.size());
267 // first, accept or reject changes within each individual
268 // paragraph (do not consider end-of-par)
269 for (pit_type pit = 0; pit < pars_size; ++pit) {
270 // prevent assertion failure
271 if (!pars[pit].empty()) {
272 if (op == Text::ACCEPT)
273 pars[pit].acceptChanges(0, pars[pit].size());
275 pars[pit].rejectChanges(0, pars[pit].size());
279 // next, accept or reject imaginary end-of-par characters
280 for (pit_type pit = 0; pit < pars_size; ++pit) {
281 pos_type pos = pars[pit].size();
282 if (pars[pit].isChanged(pos)) {
283 // keep the end-of-par char if it is inserted and accepted
284 // or when it is deleted and rejected.
285 if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
286 pars[pit].setChange(pos, Change(Change::UNCHANGED));
288 if (pit == pars_size - 1) {
289 // we cannot remove a par break at the end of the last
290 // paragraph; instead, we mark it unchanged
291 pars[pit].setChange(pos, Change(Change::UNCHANGED));
293 mergeParagraph(bparams, pars, pit);
303 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
305 acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
309 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
311 acceptOrRejectChanges(pars, bparams, Text::REJECT);
315 InsetText const & Text::inset() const
321 void Text::readParToken(Paragraph & par, Lexer & lex,
322 string const & token, Font & font, Change & change, ErrorList & errorList)
324 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
325 BufferParams const & bp = buf->params();
327 if (token[0] != '\\') {
328 docstring dstr = lex.getDocString();
329 par.appendString(dstr, font, change);
331 } else if (token == "\\begin_layout") {
333 docstring layoutname = lex.getDocString();
335 font = Font(inherit_font, bp.language);
336 change = Change(Change::UNCHANGED);
338 DocumentClass const & tclass = bp.documentClass();
340 if (layoutname.empty())
341 layoutname = tclass.defaultLayoutName();
343 if (owner_->forcePlainLayout()) {
344 // in this case only the empty layout is allowed
345 layoutname = tclass.plainLayoutName();
346 } else if (par.usePlainLayout()) {
347 // in this case, default layout maps to empty layout
348 if (layoutname == tclass.defaultLayoutName())
349 layoutname = tclass.plainLayoutName();
351 // otherwise, the empty layout maps to the default
352 if (layoutname == tclass.plainLayoutName())
353 layoutname = tclass.defaultLayoutName();
356 // When we apply an unknown layout to a document, we add this layout to the textclass
357 // of this document. For example, when you apply class article to a beamer document,
358 // all unknown layouts such as frame will be added to document class article so that
359 // these layouts can keep their original names.
360 tclass.addLayoutIfNeeded(layoutname);
362 par.setLayout(bp.documentClass()[layoutname]);
364 // Test whether the layout is obsolete.
365 Layout const & layout = par.layout();
366 if (!layout.obsoleted_by().empty())
367 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
369 par.params().read(lex);
371 } else if (token == "\\end_layout") {
372 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
373 << "Missing \\begin_layout ?");
374 } else if (token == "\\end_inset") {
375 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
376 << "Missing \\begin_inset ?");
377 } else if (token == "\\begin_inset") {
378 Inset * inset = readInset(lex, buf);
380 par.insertInset(par.size(), inset, font, change);
383 docstring line = lex.getDocString();
384 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
385 par.id(), 0, par.size()));
387 } else if (token == "\\family") {
389 setLyXFamily(lex.getString(), font.fontInfo());
390 } else if (token == "\\series") {
392 setLyXSeries(lex.getString(), font.fontInfo());
393 } else if (token == "\\shape") {
395 setLyXShape(lex.getString(), font.fontInfo());
396 } else if (token == "\\size") {
398 setLyXSize(lex.getString(), font.fontInfo());
399 } else if (token == "\\lang") {
401 string const tok = lex.getString();
402 Language const * lang = languages.getLanguage(tok);
404 font.setLanguage(lang);
406 font.setLanguage(bp.language);
407 lex.printError("Unknown language `$$Token'");
409 } else if (token == "\\numeric") {
411 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
412 } else if (token == "\\emph") {
414 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
415 } else if (token == "\\bar") {
417 string const tok = lex.getString();
420 font.fontInfo().setUnderbar(FONT_ON);
421 else if (tok == "no")
422 font.fontInfo().setUnderbar(FONT_OFF);
423 else if (tok == "default")
424 font.fontInfo().setUnderbar(FONT_INHERIT);
426 lex.printError("Unknown bar font flag "
428 } else if (token == "\\strikeout") {
430 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
431 } else if (token == "\\uuline") {
433 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
434 } else if (token == "\\uwave") {
436 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
437 } else if (token == "\\noun") {
439 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
440 } else if (token == "\\color") {
442 setLyXColor(lex.getString(), font.fontInfo());
443 } else if (token == "\\SpecialChar") {
444 auto_ptr<Inset> inset;
445 inset.reset(new InsetSpecialChar);
447 inset->setBuffer(*buf);
448 par.insertInset(par.size(), inset.release(), font, change);
449 } else if (token == "\\backslash") {
450 par.appendChar('\\', font, change);
451 } else if (token == "\\LyXTable") {
452 auto_ptr<Inset> inset(new InsetTabular(buf));
454 par.insertInset(par.size(), inset.release(), font, change);
455 } else if (token == "\\lyxline") {
456 auto_ptr<Inset> inset;
457 inset.reset(new InsetLine);
458 inset->setBuffer(*buf);
459 par.insertInset(par.size(), inset.release(), font, change);
460 } else if (token == "\\change_unchanged") {
461 change = Change(Change::UNCHANGED);
462 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
464 istringstream is(lex.getString());
468 map<unsigned int, int> const & am = bp.author_map;
469 if (am.find(aid) == am.end()) {
470 errorList.push_back(ErrorItem(_("Change tracking error"),
471 bformat(_("Unknown author index for change: %1$d\n"), aid),
472 par.id(), 0, par.size()));
473 change = Change(Change::UNCHANGED);
475 if (token == "\\change_inserted")
476 change = Change(Change::INSERTED, am.find(aid)->second, ct);
478 change = Change(Change::DELETED, am.find(aid)->second, ct);
482 errorList.push_back(ErrorItem(_("Unknown token"),
483 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
485 par.id(), 0, par.size()));
490 void Text::readParagraph(Paragraph & par, Lexer & lex,
491 ErrorList & errorList)
494 string token = lex.getString();
496 Change change(Change::UNCHANGED);
499 readParToken(par, lex, token, font, change, errorList);
502 token = lex.getString();
507 if (token == "\\end_layout") {
508 //Ok, paragraph finished
512 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
513 if (token == "\\begin_layout" || token == "\\end_document"
514 || token == "\\end_inset" || token == "\\begin_deeper"
515 || token == "\\end_deeper") {
516 lex.pushToken(token);
517 lyxerr << "Paragraph ended in line "
518 << lex.lineNumber() << "\n"
519 << "Missing \\end_layout.\n";
523 // Final change goes to paragraph break:
524 par.setChange(par.size(), change);
526 // Initialize begin_of_body_ on load; redoParagraph maintains
527 par.setBeginOfBody();
531 class TextCompletionList : public CompletionList
535 TextCompletionList(Cursor const & cur, WordList const * list)
536 : buffer_(cur.buffer()), pos_(0), list_(list)
539 virtual ~TextCompletionList() {}
542 virtual bool sorted() const { return true; }
544 virtual size_t size() const
546 return list_->size();
549 virtual docstring const & data(size_t idx) const
551 return list_->word(idx);
556 Buffer const * buffer_;
560 WordList const * list_;
564 bool Text::empty() const
566 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
567 // FIXME: Should we consider the labeled type as empty too?
568 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
572 double Text::spacing(Paragraph const & par) const
574 if (par.params().spacing().isDefault())
575 return owner_->buffer().params().spacing().getValue();
576 return par.params().spacing().getValue();
581 * This breaks a paragraph at the specified position.
582 * The new paragraph will:
583 * - Decrease depth by one (or change layout to default layout) when
584 * keep_layout == false
585 * - keep current depth and layout when keep_layout == true
587 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
590 BufferParams const & bparams = text.inset().buffer().params();
591 ParagraphList & pars = text.paragraphs();
592 // create a new paragraph, and insert into the list
593 ParagraphList::iterator tmp =
594 pars.insert(boost::next(pars.begin(), par_offset + 1),
597 Paragraph & par = pars[par_offset];
599 // remember to set the inset_owner
600 tmp->setInsetOwner(&par.inInset());
601 // without doing that we get a crash when typing <Return> at the
602 // end of a paragraph
603 tmp->setPlainOrDefaultLayout(bparams.documentClass());
605 // layout stays the same with latex-environments
607 tmp->setLayout(par.layout());
608 tmp->setLabelWidthString(par.params().labelWidthString());
609 tmp->params().depth(par.params().depth());
610 } else if (par.params().depth() > 0) {
611 Paragraph const & hook = pars[text.outerHook(par_offset)];
612 tmp->setLayout(hook.layout());
613 // not sure the line below is useful
614 tmp->setLabelWidthString(par.params().labelWidthString());
615 tmp->params().depth(hook.params().depth());
618 bool const isempty = (par.allowEmpty() && par.empty());
620 if (!isempty && (par.size() > pos || par.empty())) {
621 tmp->setLayout(par.layout());
622 tmp->params().align(par.params().align());
623 tmp->setLabelWidthString(par.params().labelWidthString());
625 tmp->params().depth(par.params().depth());
626 tmp->params().noindent(par.params().noindent());
628 // move everything behind the break position
629 // to the new paragraph
631 /* Note: if !keepempty, empty() == true, then we reach
632 * here with size() == 0. So pos_end becomes - 1. This
633 * doesn't cause problems because both loops below
634 * enforce pos <= pos_end and 0 <= pos
636 pos_type pos_end = par.size() - 1;
638 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
639 if (moveItem(par, pos, *tmp, j, bparams)) {
645 // Move over the end-of-par change information
646 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
647 par.setChange(par.size(), Change(bparams.trackChanges ?
648 Change::INSERTED : Change::UNCHANGED));
651 // Make sure that we keep the language when
652 // breaking paragraph.
654 Font changed = tmp->getFirstFontSettings(bparams);
655 Font const & old = par.getFontSettings(bparams, par.size());
656 changed.setLanguage(old.language());
657 tmp->setFont(0, changed);
664 bool const soa = par.params().startOfAppendix();
665 par.params().clear();
666 // do not lose start of appendix marker (bug 4212)
667 par.params().startOfAppendix(soa);
668 par.setPlainOrDefaultLayout(bparams.documentClass());
671 // layout stays the same with latex-environments
673 par.setLayout(tmp->layout());
674 par.setLabelWidthString(tmp->params().labelWidthString());
675 par.params().depth(tmp->params().depth());
680 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
682 LASSERT(this == cur.text(), /**/);
684 Paragraph & cpar = cur.paragraph();
685 pit_type cpit = cur.pit();
687 DocumentClass const & tclass = cur.buffer()->params().documentClass();
688 Layout const & layout = cpar.layout();
690 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
691 if (changeDepthAllowed(cur, DEC_DEPTH))
692 changeDepth(cur, DEC_DEPTH);
694 setLayout(cur, tclass.defaultLayoutName());
698 // a layout change may affect also the following paragraph
699 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
701 // Always break behind a space
702 // It is better to erase the space (Dekel)
703 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
704 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
706 // What should the layout for the new paragraph be?
707 bool keep_layout = inverse_logic ?
708 !layout.isEnvironment()
709 : layout.isEnvironment();
711 // We need to remember this before we break the paragraph, because
712 // that invalidates the layout variable
713 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
715 // we need to set this before we insert the paragraph.
716 bool const isempty = cpar.allowEmpty() && cpar.empty();
718 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
720 // After this, neither paragraph contains any rows!
723 pit_type next_par = cpit + 1;
725 // well this is the caption hack since one caption is really enough
728 // set to standard-layout
729 //FIXME Check if this should be plainLayout() in some cases
730 pars_[cpit].applyLayout(tclass.defaultLayout());
732 // set to standard-layout
733 //FIXME Check if this should be plainLayout() in some cases
734 pars_[next_par].applyLayout(tclass.defaultLayout());
737 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
738 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
739 break; // the character couldn't be deleted physically due to change tracking
742 // A singlePar update is not enough in this case.
743 cur.screenUpdateFlags(Update::Force);
744 cur.forceBufferUpdate();
746 // This check is necessary. Otherwise the new empty paragraph will
747 // be deleted automatically. And it is more friendly for the user!
748 if (cur.pos() != 0 || isempty)
749 setCursor(cur, cur.pit() + 1, 0);
751 setCursor(cur, cur.pit(), 0);
755 // needed to insert the selection
756 void Text::insertStringAsLines(DocIterator const & dit, docstring const & str,
759 BufferParams const & bparams = owner_->buffer().params();
760 pit_type pit = dit.pit();
761 pos_type pos = dit.pos();
763 // insert the string, don't insert doublespace
764 bool space_inserted = true;
765 for (docstring::const_iterator cit = str.begin();
766 cit != str.end(); ++cit) {
767 Paragraph & par = pars_[pit];
769 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
770 lyx::breakParagraph(*this, pit, pos,
771 par.layout().isEnvironment());
774 space_inserted = true;
778 // do not insert consecutive spaces if !free_spacing
779 } else if ((*cit == ' ' || *cit == '\t') &&
780 space_inserted && !par.isFreeSpacing()) {
782 } else if (*cit == '\t') {
783 if (!par.isFreeSpacing()) {
784 // tabs are like spaces here
785 par.insertChar(pos, ' ', font, bparams.trackChanges);
787 space_inserted = true;
789 par.insertChar(pos, *cit, font, bparams.trackChanges);
791 space_inserted = true;
793 } else if (!isPrintable(*cit)) {
794 // Ignore unprintables
797 // just insert the character
798 par.insertChar(pos, *cit, font, bparams.trackChanges);
800 space_inserted = (*cit == ' ');
806 // turn double CR to single CR, others are converted into one
807 // blank. Then insertStringAsLines is called
808 void Text::insertStringAsParagraphs(DocIterator const & dit, docstring const & str,
811 docstring linestr = str;
812 bool newline_inserted = false;
814 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
815 if (linestr[i] == '\n') {
816 if (newline_inserted) {
817 // we know that \r will be ignored by
818 // insertStringAsLines. Of course, it is a dirty
819 // trick, but it works...
820 linestr[i - 1] = '\r';
824 newline_inserted = true;
826 } else if (isPrintable(linestr[i])) {
827 newline_inserted = false;
830 insertStringAsLines(dit, linestr, font);
834 // insert a character, moves all the following breaks in the
835 // same Paragraph one to the right and make a rebreak
836 void Text::insertChar(Cursor & cur, char_type c)
838 LASSERT(this == cur.text(), /**/);
840 cur.recordUndo(INSERT_UNDO);
842 TextMetrics const & tm = cur.bv().textMetrics(this);
843 Buffer const & buffer = *cur.buffer();
844 Paragraph & par = cur.paragraph();
845 // try to remove this
846 pit_type const pit = cur.pit();
848 bool const freeSpacing = par.layout().free_spacing ||
851 if (lyxrc.auto_number) {
852 static docstring const number_operators = from_ascii("+-/*");
853 static docstring const number_unary_operators = from_ascii("+-");
854 static docstring const number_seperators = from_ascii(".,:");
856 if (cur.current_font.fontInfo().number() == FONT_ON) {
857 if (!isDigit(c) && !contains(number_operators, c) &&
858 !(contains(number_seperators, c) &&
860 cur.pos() != cur.lastpos() &&
861 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
862 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
864 number(cur); // Set current_font.number to OFF
865 } else if (isDigit(c) &&
866 cur.real_current_font.isVisibleRightToLeft()) {
867 number(cur); // Set current_font.number to ON
869 if (cur.pos() != 0) {
870 char_type const c = par.getChar(cur.pos() - 1);
871 if (contains(number_unary_operators, c) &&
873 || par.isSeparator(cur.pos() - 2)
874 || par.isNewline(cur.pos() - 2))
876 setCharFont(pit, cur.pos() - 1, cur.current_font,
878 } else if (contains(number_seperators, c)
880 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
881 setCharFont(pit, cur.pos() - 1, cur.current_font,
888 // In Bidi text, we want spaces to be treated in a special way: spaces
889 // which are between words in different languages should get the
890 // paragraph's language; otherwise, spaces should keep the language
891 // they were originally typed in. This is only in effect while typing;
892 // after the text is already typed in, the user can always go back and
893 // explicitly set the language of a space as desired. But 99.9% of the
894 // time, what we're doing here is what the user actually meant.
896 // The following cases are the ones in which the language of the space
897 // should be changed to match that of the containing paragraph. In the
898 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
899 // represents a space, pipe (|) represents the cursor position (so the
900 // character before it is the one just typed in). The different cases
901 // are depicted logically (not visually), from left to right:
906 // Theoretically, there are other situations that we should, perhaps, deal
907 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
908 // point (to understand why, just try to create this situation...).
910 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
911 // get font in front and behind the space in question. But do NOT
912 // use getFont(cur.pos()) because the character c is not inserted yet
913 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
914 Font const & post_space_font = cur.real_current_font;
915 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
916 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
918 if (pre_space_rtl != post_space_rtl) {
919 // Set the space's language to match the language of the
920 // adjacent character whose direction is the paragraph's
921 // direction; don't touch other properties of the font
922 Language const * lang =
923 (pre_space_rtl == par.isRTL(buffer.params())) ?
924 pre_space_font.language() : post_space_font.language();
926 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
927 space_font.setLanguage(lang);
928 par.setFont(cur.pos() - 1, space_font);
932 // Next check, if there will be two blanks together or a blank at
933 // the beginning of a paragraph.
934 // I decided to handle blanks like normal characters, the main
935 // difference are the special checks when calculating the row.fill
936 // (blank does not count at the end of a row) and the check here
938 // When the free-spacing option is set for the current layout,
939 // disable the double-space checking
940 if (!freeSpacing && isLineSeparatorChar(c)) {
941 if (cur.pos() == 0) {
942 static bool sent_space_message = false;
943 if (!sent_space_message) {
944 cur.message(_("You cannot insert a space at the "
945 "beginning of a paragraph. Please read the Tutorial."));
946 sent_space_message = true;
950 LASSERT(cur.pos() > 0, /**/);
951 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
952 && !par.isDeleted(cur.pos() - 1)) {
953 static bool sent_space_message = false;
954 if (!sent_space_message) {
955 cur.message(_("You cannot type two spaces this way. "
956 "Please read the Tutorial."));
957 sent_space_message = true;
963 par.insertChar(cur.pos(), c, cur.current_font,
964 cur.buffer()->params().trackChanges);
965 cur.checkBufferStructure();
967 // cur.screenUpdateFlags(Update::Force);
968 bool boundary = cur.boundary()
969 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
970 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
975 void Text::charInserted(Cursor & cur)
977 Paragraph & par = cur.paragraph();
979 // Here we call finishUndo for every 20 characters inserted.
980 // This is from my experience how emacs does it. (Lgb)
981 if (undo_counter_ < 20) {
988 // register word if a non-letter was entered
990 && !par.isWordSeparator(cur.pos() - 2)
991 && par.isWordSeparator(cur.pos() - 1)) {
992 // get the word in front of cursor
993 LASSERT(this == cur.text(), /**/);
994 cur.paragraph().updateWords();
999 // the cursor set functions have a special mechanism. When they
1000 // realize, that you left an empty paragraph, they will delete it.
1002 bool Text::cursorForwardOneWord(Cursor & cur)
1004 LASSERT(this == cur.text(), /**/);
1006 pos_type const lastpos = cur.lastpos();
1007 pit_type pit = cur.pit();
1008 pos_type pos = cur.pos();
1009 Paragraph const & par = cur.paragraph();
1011 // Paragraph boundary is a word boundary
1012 if (pos == lastpos) {
1013 if (pit != cur.lastpit())
1014 return setCursor(cur, pit + 1, 0);
1019 if (lyxrc.mac_like_word_movement) {
1020 // Skip through trailing punctuation and spaces.
1021 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1024 // Skip over either a non-char inset or a full word
1025 if (pos != lastpos && par.isWordSeparator(pos))
1027 else while (pos != lastpos && !par.isWordSeparator(pos))
1030 LASSERT(pos < lastpos, /**/); // see above
1031 if (!par.isWordSeparator(pos))
1032 while (pos != lastpos && !par.isWordSeparator(pos))
1034 else if (par.isChar(pos))
1035 while (pos != lastpos && par.isChar(pos))
1037 else if (!par.isSpace(pos)) // non-char inset
1040 // Skip over white space
1041 while (pos != lastpos && par.isSpace(pos))
1045 return setCursor(cur, pit, pos);
1049 bool Text::cursorBackwardOneWord(Cursor & cur)
1051 LASSERT(this == cur.text(), /**/);
1053 pit_type pit = cur.pit();
1054 pos_type pos = cur.pos();
1055 Paragraph & par = cur.paragraph();
1057 // Paragraph boundary is a word boundary
1058 if (pos == 0 && pit != 0)
1059 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1061 if (lyxrc.mac_like_word_movement) {
1062 // Skip through punctuation and spaces.
1063 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1066 // Skip over either a non-char inset or a full word
1067 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1069 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1072 // Skip over white space
1073 while (pos != 0 && par.isSpace(pos - 1))
1076 if (pos != 0 && !par.isWordSeparator(pos - 1))
1077 while (pos != 0 && !par.isWordSeparator(pos - 1))
1079 else if (pos != 0 && par.isChar(pos - 1))
1080 while (pos != 0 && par.isChar(pos - 1))
1082 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1086 return setCursor(cur, pit, pos);
1090 bool Text::cursorVisLeftOneWord(Cursor & cur)
1092 LASSERT(this == cur.text(), /**/);
1094 pos_type left_pos, right_pos;
1095 bool left_is_letter, right_is_letter;
1097 Cursor temp_cur = cur;
1099 // always try to move at least once...
1100 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1102 // collect some information about current cursor position
1103 temp_cur.getSurroundingPos(left_pos, right_pos);
1105 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1107 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1109 // if we're not at a letter/non-letter boundary, continue moving
1110 if (left_is_letter == right_is_letter)
1113 // we should stop when we have an LTR word on our right or an RTL word
1115 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1116 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1117 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1118 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1122 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1123 true, temp_cur.boundary());
1127 bool Text::cursorVisRightOneWord(Cursor & cur)
1129 LASSERT(this == cur.text(), /**/);
1131 pos_type left_pos, right_pos;
1132 bool left_is_letter, right_is_letter;
1134 Cursor temp_cur = cur;
1136 // always try to move at least once...
1137 while (temp_cur.posVisRight(true /* skip_inset */)) {
1139 // collect some information about current cursor position
1140 temp_cur.getSurroundingPos(left_pos, right_pos);
1142 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1144 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1146 // if we're not at a letter/non-letter boundary, continue moving
1147 if (left_is_letter == right_is_letter)
1150 // we should stop when we have an LTR word on our right or an RTL word
1152 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1153 temp_cur.buffer()->params(),
1154 left_pos).isRightToLeft())
1155 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1156 temp_cur.buffer()->params(),
1157 right_pos).isRightToLeft()))
1161 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1162 true, temp_cur.boundary());
1166 void Text::selectWord(Cursor & cur, word_location loc)
1168 LASSERT(this == cur.text(), /**/);
1169 CursorSlice from = cur.top();
1170 CursorSlice to = cur.top();
1171 getWord(from, to, loc);
1172 if (cur.top() != from)
1173 setCursor(cur, from.pit(), from.pos());
1176 if (!cur.selection())
1178 setCursor(cur, to.pit(), to.pos());
1180 cur.setWordSelection(true);
1184 void Text::selectAll(Cursor & cur)
1186 LASSERT(this == cur.text(), /**/);
1187 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1189 // If the cursor is at the beginning, make sure the cursor ends there
1190 if (cur.pit() == 0 && cur.pos() == 0) {
1191 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1193 setCursor(cur, 0, 0);
1195 setCursor(cur, 0, 0);
1197 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1203 // Select the word currently under the cursor when no
1204 // selection is currently set
1205 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1207 LASSERT(this == cur.text(), /**/);
1208 if (cur.selection())
1210 selectWord(cur, loc);
1211 return cur.selection();
1215 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1217 LASSERT(this == cur.text(), /**/);
1219 if (!cur.selection()) {
1220 bool const changed = cur.paragraph().isChanged(cur.pos());
1221 if (!(changed && findNextChange(&cur.bv())))
1225 cur.recordUndoSelection();
1227 pit_type begPit = cur.selectionBegin().pit();
1228 pit_type endPit = cur.selectionEnd().pit();
1230 pos_type begPos = cur.selectionBegin().pos();
1231 pos_type endPos = cur.selectionEnd().pos();
1233 // keep selection info, because endPos becomes invalid after the first loop
1234 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1236 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1238 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1239 pos_type parSize = pars_[pit].size();
1241 // ignore empty paragraphs; otherwise, an assertion will fail for
1242 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1246 // do not consider first paragraph if the cursor starts at pos size()
1247 if (pit == begPit && begPos == parSize)
1250 // do not consider last paragraph if the cursor ends at pos 0
1251 if (pit == endPit && endPos == 0)
1252 break; // last iteration anyway
1254 pos_type left = (pit == begPit ? begPos : 0);
1255 pos_type right = (pit == endPit ? endPos : parSize);
1258 pars_[pit].acceptChanges(left, right);
1260 pars_[pit].rejectChanges(left, right);
1264 // next, accept/reject imaginary end-of-par characters
1266 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1267 pos_type pos = pars_[pit].size();
1269 // skip if the selection ends before the end-of-par
1270 if (pit == endPit && endsBeforeEndOfPar)
1271 break; // last iteration anyway
1273 // skip if this is not the last paragraph of the document
1274 // note: the user should be able to accept/reject the par break of the last par!
1275 if (pit == endPit && pit + 1 != int(pars_.size()))
1276 break; // last iteration anway
1279 if (pars_[pit].isInserted(pos)) {
1280 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1281 } else if (pars_[pit].isDeleted(pos)) {
1282 if (pit + 1 == int(pars_.size())) {
1283 // we cannot remove a par break at the end of the last paragraph;
1284 // instead, we mark it unchanged
1285 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1287 mergeParagraph(cur.buffer()->params(), pars_, pit);
1293 if (pars_[pit].isDeleted(pos)) {
1294 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1295 } else if (pars_[pit].isInserted(pos)) {
1296 if (pit + 1 == int(pars_.size())) {
1297 // we mark the par break at the end of the last paragraph unchanged
1298 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1300 mergeParagraph(cur.buffer()->params(), pars_, pit);
1308 // finally, invoke the DEPM
1310 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1315 cur.clearSelection();
1316 setCursorIntern(cur, begPit, begPos);
1317 cur.screenUpdateFlags(Update::Force);
1318 cur.forceBufferUpdate();
1322 void Text::acceptChanges()
1324 BufferParams const & bparams = owner_->buffer().params();
1325 lyx::acceptChanges(pars_, bparams);
1326 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1330 void Text::rejectChanges()
1332 BufferParams const & bparams = owner_->buffer().params();
1333 pit_type pars_size = static_cast<pit_type>(pars_.size());
1335 // first, reject changes within each individual paragraph
1336 // (do not consider end-of-par)
1337 for (pit_type pit = 0; pit < pars_size; ++pit) {
1338 if (!pars_[pit].empty()) // prevent assertion failure
1339 pars_[pit].rejectChanges(0, pars_[pit].size());
1342 // next, reject imaginary end-of-par characters
1343 for (pit_type pit = 0; pit < pars_size; ++pit) {
1344 pos_type pos = pars_[pit].size();
1346 if (pars_[pit].isDeleted(pos)) {
1347 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1348 } else if (pars_[pit].isInserted(pos)) {
1349 if (pit == pars_size - 1) {
1350 // we mark the par break at the end of the last
1351 // paragraph unchanged
1352 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1354 mergeParagraph(bparams, pars_, pit);
1361 // finally, invoke the DEPM
1362 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1366 void Text::deleteWordForward(Cursor & cur)
1368 LASSERT(this == cur.text(), /**/);
1369 if (cur.lastpos() == 0)
1373 cur.setSelection(true);
1374 cursorForwardOneWord(cur);
1376 cutSelection(cur, true, false);
1377 cur.checkBufferStructure();
1382 void Text::deleteWordBackward(Cursor & cur)
1384 LASSERT(this == cur.text(), /**/);
1385 if (cur.lastpos() == 0)
1386 cursorBackward(cur);
1389 cur.setSelection(true);
1390 cursorBackwardOneWord(cur);
1392 cutSelection(cur, true, false);
1393 cur.checkBufferStructure();
1398 // Kill to end of line.
1399 void Text::changeCase(Cursor & cur, TextCase action)
1401 LASSERT(this == cur.text(), /**/);
1405 bool gotsel = false;
1406 if (cur.selection()) {
1407 from = cur.selBegin();
1412 getWord(from, to, PARTIAL_WORD);
1413 cursorForwardOneWord(cur);
1416 cur.recordUndoSelection();
1418 pit_type begPit = from.pit();
1419 pit_type endPit = to.pit();
1421 pos_type begPos = from.pos();
1422 pos_type endPos = to.pos();
1424 pos_type right = 0; // needed after the for loop
1426 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1427 Paragraph & par = pars_[pit];
1428 pos_type const pos = (pit == begPit ? begPos : 0);
1429 right = (pit == endPit ? endPos : par.size());
1430 par.changeCase(cur.buffer()->params(), pos, right, action);
1433 // the selection may have changed due to logically-only deleted chars
1435 setCursor(cur, begPit, begPos);
1437 setCursor(cur, endPit, right);
1440 setCursor(cur, endPit, right);
1442 cur.checkBufferStructure();
1446 bool Text::handleBibitems(Cursor & cur)
1448 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1454 BufferParams const & bufparams = cur.buffer()->params();
1455 Paragraph const & par = cur.paragraph();
1456 Cursor prevcur = cur;
1457 if (cur.pit() > 0) {
1459 prevcur.pos() = prevcur.lastpos();
1461 Paragraph const & prevpar = prevcur.paragraph();
1463 // if a bibitem is deleted, merge with previous paragraph
1464 // if this is a bibliography item as well
1465 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1466 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1467 mergeParagraph(bufparams, cur.text()->paragraphs(),
1469 cur.forceBufferUpdate();
1470 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1471 cur.screenUpdateFlags(Update::Force);
1475 // otherwise reset to default
1476 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1481 bool Text::erase(Cursor & cur)
1483 LASSERT(this == cur.text(), return false);
1484 bool needsUpdate = false;
1485 Paragraph & par = cur.paragraph();
1487 if (cur.pos() != cur.lastpos()) {
1488 // this is the code for a normal delete, not pasting
1490 cur.recordUndo(DELETE_UNDO);
1491 bool const was_inset = cur.paragraph().isInset(cur.pos());
1492 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1493 // the character has been logically deleted only => skip it
1494 cur.top().forwardPos();
1497 cur.forceBufferUpdate();
1499 cur.checkBufferStructure();
1502 if (cur.pit() == cur.lastpit())
1503 return dissolveInset(cur);
1505 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1506 par.setChange(cur.pos(), Change(Change::DELETED));
1510 setCursorIntern(cur, cur.pit() + 1, 0);
1511 needsUpdate = backspacePos0(cur);
1515 needsUpdate |= handleBibitems(cur);
1518 // Make sure the cursor is correct. Is this really needed?
1519 // No, not really... at least not here!
1520 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1521 cur.checkBufferStructure();
1528 bool Text::backspacePos0(Cursor & cur)
1530 LASSERT(this == cur.text(), /**/);
1534 bool needsUpdate = false;
1536 BufferParams const & bufparams = cur.buffer()->params();
1537 DocumentClass const & tclass = bufparams.documentClass();
1538 ParagraphList & plist = cur.text()->paragraphs();
1539 Paragraph const & par = cur.paragraph();
1540 Cursor prevcur = cur;
1542 prevcur.pos() = prevcur.lastpos();
1543 Paragraph const & prevpar = prevcur.paragraph();
1545 // is it an empty paragraph?
1546 if (cur.lastpos() == 0
1547 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1548 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1549 plist.erase(boost::next(plist.begin(), cur.pit()));
1552 // is previous par empty?
1553 else if (prevcur.lastpos() == 0
1554 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1555 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1556 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1559 // Pasting is not allowed, if the paragraphs have different
1560 // layouts. I think it is a real bug of all other
1561 // word processors to allow it. It confuses the user.
1562 // Correction: Pasting is always allowed with standard-layout
1563 // or the empty layout.
1564 else if (par.layout() == prevpar.layout()
1565 || tclass.isDefaultLayout(par.layout())
1566 || tclass.isPlainLayout(par.layout())) {
1567 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1568 mergeParagraph(bufparams, plist, prevcur.pit());
1573 cur.forceBufferUpdate();
1574 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1581 bool Text::backspace(Cursor & cur)
1583 LASSERT(this == cur.text(), /**/);
1584 bool needsUpdate = false;
1585 if (cur.pos() == 0) {
1587 return dissolveInset(cur);
1589 Paragraph & prev_par = pars_[cur.pit() - 1];
1591 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1592 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1593 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1596 // The cursor is at the beginning of a paragraph, so
1597 // the backspace will collapse two paragraphs into one.
1598 needsUpdate = backspacePos0(cur);
1601 // this is the code for a normal backspace, not pasting
1603 cur.recordUndo(DELETE_UNDO);
1604 // We used to do cursorBackwardIntern() here, but it is
1605 // not a good idea since it triggers the auto-delete
1606 // mechanism. So we do a cursorBackwardIntern()-lite,
1607 // without the dreaded mechanism. (JMarc)
1608 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1609 false, cur.boundary());
1610 bool const was_inset = cur.paragraph().isInset(cur.pos());
1611 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1613 cur.forceBufferUpdate();
1615 cur.checkBufferStructure();
1618 if (cur.pos() == cur.lastpos())
1619 cur.setCurrentFont();
1621 needsUpdate |= handleBibitems(cur);
1623 // A singlePar update is not enough in this case.
1624 // cur.screenUpdateFlags(Update::Force);
1625 setCursor(cur.top(), cur.pit(), cur.pos());
1631 bool Text::dissolveInset(Cursor & cur)
1633 LASSERT(this == cur.text(), return false);
1635 if (isMainText() || cur.inset().nargs() != 1)
1638 cur.recordUndoInset();
1640 cur.selHandle(false);
1642 pos_type spos = cur.pos();
1643 pit_type spit = cur.pit();
1644 ParagraphList plist;
1645 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1646 plist = paragraphs();
1648 // store cursor offset
1652 Buffer & b = *cur.buffer();
1653 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1654 if (!plist.empty()) {
1655 // ERT paragraphs have the Language latex_language.
1656 // This is invalid outside of ERT, so we need to
1657 // change it to the buffer language.
1658 ParagraphList::iterator it = plist.begin();
1659 ParagraphList::iterator it_end = plist.end();
1660 for (; it != it_end; it++)
1661 it->changeLanguage(b.params(), latex_language, b.language());
1663 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1664 b.errorList("Paste"));
1666 cur.pit() = min(cur.lastpit(), spit);
1667 cur.pos() = min(cur.lastpos(), spos);
1669 cur.forceBufferUpdate();
1671 // Ensure the current language is set correctly (bug 6292)
1672 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1673 cur.clearSelection();
1679 void Text::getWord(CursorSlice & from, CursorSlice & to,
1680 word_location const loc) const
1683 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1687 void Text::write(ostream & os) const
1689 Buffer const & buf = owner_->buffer();
1690 ParagraphList::const_iterator pit = paragraphs().begin();
1691 ParagraphList::const_iterator end = paragraphs().end();
1693 for (; pit != end; ++pit)
1694 pit->write(os, buf.params(), dth);
1696 // Close begin_deeper
1697 for(; dth > 0; --dth)
1698 os << "\n\\end_deeper";
1702 bool Text::read(Lexer & lex,
1703 ErrorList & errorList, InsetText * insetPtr)
1705 Buffer const & buf = owner_->buffer();
1706 depth_type depth = 0;
1709 while (lex.isOK()) {
1711 string const token = lex.getString();
1716 if (token == "\\end_inset")
1719 if (token == "\\end_body")
1722 if (token == "\\begin_body")
1725 if (token == "\\end_document") {
1730 if (token == "\\begin_layout") {
1731 lex.pushToken(token);
1734 par.setInsetOwner(insetPtr);
1735 par.params().depth(depth);
1736 par.setFont(0, Font(inherit_font, buf.params().language));
1737 pars_.push_back(par);
1738 readParagraph(pars_.back(), lex, errorList);
1740 // register the words in the global word list
1741 pars_.back().updateWords();
1742 } else if (token == "\\begin_deeper") {
1744 } else if (token == "\\end_deeper") {
1746 lex.printError("\\end_deeper: " "depth is already null");
1750 LYXERR0("Handling unknown body token: `" << token << '\'');
1754 // avoid a crash on weird documents (bug 4859)
1755 if (pars_.empty()) {
1757 par.setInsetOwner(insetPtr);
1758 par.params().depth(depth);
1759 par.setFont(0, Font(inherit_font,
1760 buf.params().language));
1761 par.setPlainOrDefaultLayout(buf.params().documentClass());
1762 pars_.push_back(par);
1768 // Returns the current font and depth as a message.
1769 docstring Text::currentState(Cursor const & cur) const
1771 LASSERT(this == cur.text(), /**/);
1772 Buffer & buf = *cur.buffer();
1773 Paragraph const & par = cur.paragraph();
1774 odocstringstream os;
1776 if (buf.params().trackChanges)
1777 os << _("[Change Tracking] ");
1779 Change change = par.lookupChange(cur.pos());
1781 if (change.changed()) {
1782 Author const & a = buf.params().authors().get(change.author);
1783 os << _("Change: ") << a.name();
1784 if (!a.email().empty())
1785 os << " (" << a.email() << ")";
1786 // FIXME ctime is english, we should translate that
1787 os << _(" at ") << ctime(&change.changetime);
1791 // I think we should only show changes from the default
1793 // No, from the document font (MV)
1794 Font font = cur.real_current_font;
1795 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1797 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1799 // The paragraph depth
1800 int depth = cur.paragraph().getDepth();
1802 os << bformat(_(", Depth: %1$d"), depth);
1804 // The paragraph spacing, but only if different from
1806 Spacing const & spacing = par.params().spacing();
1807 if (!spacing.isDefault()) {
1808 os << _(", Spacing: ");
1809 switch (spacing.getSpace()) {
1810 case Spacing::Single:
1813 case Spacing::Onehalf:
1816 case Spacing::Double:
1819 case Spacing::Other:
1820 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1822 case Spacing::Default:
1823 // should never happen, do nothing
1828 #ifdef DEVEL_VERSION
1829 os << _(", Inset: ") << &cur.inset();
1830 os << _(", Paragraph: ") << cur.pit();
1831 os << _(", Id: ") << par.id();
1832 os << _(", Position: ") << cur.pos();
1833 // FIXME: Why is the check for par.size() needed?
1834 // We are called with cur.pos() == par.size() quite often.
1835 if (!par.empty() && cur.pos() < par.size()) {
1836 // Force output of code point, not character
1837 size_t const c = par.getChar(cur.pos());
1838 os << _(", Char: 0x") << hex << c;
1840 os << _(", Boundary: ") << cur.boundary();
1841 // Row & row = cur.textRow();
1842 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1848 docstring Text::getPossibleLabel(Cursor const & cur) const
1850 pit_type pit = cur.pit();
1852 Layout const * layout = &(pars_[pit].layout());
1855 docstring par_text = pars_[pit].asString();
1857 // The return string of math matrices might contain linebreaks
1858 par_text = subst(par_text, '\n', '-');
1859 int const numwords = 3;
1860 for (int i = 0; i < numwords; ++i) {
1861 if (par_text.empty())
1864 par_text = split(par_text, head, ' ');
1865 // Is it legal to use spaces in labels ?
1871 // Make sure it isn't too long
1872 unsigned int const max_label_length = 32;
1873 if (text.size() > max_label_length)
1874 text.resize(max_label_length);
1876 // Will contain the label prefix.
1879 // For section, subsection, etc...
1880 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1881 Layout const * layout2 = &(pars_[pit - 1].layout());
1882 if (layout2->latextype != LATEX_PARAGRAPH) {
1887 if (layout->latextype != LATEX_PARAGRAPH)
1888 name = layout->refprefix;
1890 // For captions, we just take the caption type
1891 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1892 if (caption_inset) {
1893 string const & ftype = static_cast<InsetCaption *>(caption_inset)->type();
1894 FloatList const & fl = cur.buffer()->params().documentClass().floats();
1895 if (fl.typeExist(ftype)) {
1896 Floating const & flt = fl.getType(ftype);
1897 name = from_utf8(flt.refPrefix());
1900 name = from_utf8(ftype.substr(0,3));
1903 // If none of the above worked, see if the inset knows.
1905 InsetLayout const & il = cur.inset().getLayout();
1906 name = il.refprefix();
1911 // We should allow customization of the separator or else change it
1912 text = name + ':' + text;
1918 docstring Text::asString(int options) const
1920 return asString(0, pars_.size(), options);
1924 docstring Text::asString(pit_type beg, pit_type end, int options) const
1926 size_t i = size_t(beg);
1927 docstring str = pars_[i].asString(options);
1928 for (++i; i != size_t(end); ++i) {
1930 str += pars_[i].asString(options);
1937 void Text::charsTranspose(Cursor & cur)
1939 LASSERT(this == cur.text(), /**/);
1941 pos_type pos = cur.pos();
1943 // If cursor is at beginning or end of paragraph, do nothing.
1944 if (pos == cur.lastpos() || pos == 0)
1947 Paragraph & par = cur.paragraph();
1949 // Get the positions of the characters to be transposed.
1950 pos_type pos1 = pos - 1;
1951 pos_type pos2 = pos;
1953 // In change tracking mode, ignore deleted characters.
1954 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1956 if (pos2 == cur.lastpos())
1959 while (pos1 >= 0 && par.isDeleted(pos1))
1964 // Don't do anything if one of the "characters" is not regular text.
1965 if (par.isInset(pos1) || par.isInset(pos2))
1968 // Store the characters to be transposed (including font information).
1969 char_type const char1 = par.getChar(pos1);
1971 par.getFontSettings(cur.buffer()->params(), pos1);
1973 char_type const char2 = par.getChar(pos2);
1975 par.getFontSettings(cur.buffer()->params(), pos2);
1977 // And finally, we are ready to perform the transposition.
1978 // Track the changes if Change Tracking is enabled.
1979 bool const trackChanges = cur.buffer()->params().trackChanges;
1983 par.eraseChar(pos2, trackChanges);
1984 par.eraseChar(pos1, trackChanges);
1985 par.insertChar(pos1, char2, font2, trackChanges);
1986 par.insertChar(pos2, char1, font1, trackChanges);
1988 cur.checkBufferStructure();
1990 // After the transposition, move cursor to after the transposition.
1991 setCursor(cur, cur.pit(), pos2);
1996 DocIterator Text::macrocontextPosition() const
1998 return macrocontext_position_;
2002 void Text::setMacrocontextPosition(DocIterator const & pos)
2004 macrocontext_position_ = pos;
2008 docstring Text::previousWord(CursorSlice const & sl) const
2010 CursorSlice from = sl;
2011 CursorSlice to = sl;
2012 getWord(from, to, PREVIOUS_WORD);
2013 if (sl == from || to == from)
2016 Paragraph const & par = sl.paragraph();
2017 return par.asString(from.pos(), to.pos());
2021 bool Text::completionSupported(Cursor const & cur) const
2023 Paragraph const & par = cur.paragraph();
2024 return cur.pos() > 0
2025 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2026 && !par.isWordSeparator(cur.pos() - 1);
2030 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2032 WordList const * list = theWordList(*cur.getFont().language());
2033 return new TextCompletionList(cur, list);
2037 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2039 LASSERT(cur.bv().cursor() == cur, /**/);
2041 cur.bv().cursor() = cur;
2042 if (!(cur.result().update() & Update::Force))
2043 cur.screenUpdateFlags(cur.result().update() | Update::SinglePar);
2048 docstring Text::completionPrefix(Cursor const & cur) const
2050 return previousWord(cur.top());