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/InsetNewline.h"
57 #include "insets/InsetNewpage.h"
58 #include "insets/InsetArgument.h"
59 #include "insets/InsetSpace.h"
60 #include "insets/InsetSpecialChar.h"
61 #include "insets/InsetTabular.h"
63 #include "support/debug.h"
64 #include "support/docstream.h"
65 #include "support/gettext.h"
66 #include "support/lassert.h"
67 #include "support/lstrings.h"
68 #include "support/textutils.h"
70 #include <boost/next_prior.hpp>
75 using namespace lyx::support;
79 using cap::cutSelection;
80 using cap::pasteParagraphList;
82 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
83 Paragraph & toPar, pos_type toPos, BufferParams const & params)
85 // Note: moveItem() does not honour change tracking!
86 // Therefore, it should only be used for breaking and merging paragraphs
88 // We need a copy here because the character at fromPos is going to be erased.
89 Font const tmpFont = fromPar.getFontSettings(params, fromPos);
90 Change const tmpChange = fromPar.lookupChange(fromPos);
92 if (Inset * tmpInset = fromPar.getInset(fromPos)) {
93 fromPar.releaseInset(fromPos);
94 // The inset is not in fromPar any more.
95 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
102 char_type const tmpChar = fromPar.getChar(fromPos);
103 fromPar.eraseChar(fromPos, false);
104 toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
109 void breakParagraphConservative(BufferParams const & bparams,
110 ParagraphList & pars, pit_type par_offset, pos_type pos)
112 // create a new paragraph
113 Paragraph & tmp = *pars.insert(boost::next(pars.begin(), par_offset + 1),
115 Paragraph & par = pars[par_offset];
117 tmp.setInsetOwner(&par.inInset());
118 tmp.makeSameLayout(par);
120 LASSERT(pos <= par.size(), /**/);
122 if (pos < par.size()) {
123 // move everything behind the break position to the new paragraph
124 pos_type pos_end = par.size() - 1;
126 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
127 if (moveItem(par, pos, tmp, j, bparams)) {
131 // Move over the end-of-par change information
132 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
133 par.setChange(par.size(), Change(bparams.trackChanges ?
134 Change::INSERTED : Change::UNCHANGED));
139 void mergeParagraph(BufferParams const & bparams,
140 ParagraphList & pars, pit_type par_offset)
142 Paragraph & next = pars[par_offset + 1];
143 Paragraph & par = pars[par_offset];
145 pos_type pos_end = next.size() - 1;
146 pos_type pos_insert = par.size();
148 // the imaginary end-of-paragraph character (at par.size()) has to be
149 // marked as unmodified. Otherwise, its change is adopted by the first
150 // character of the next paragraph.
151 if (par.isChanged(par.size())) {
152 LYXERR(Debug::CHANGES,
153 "merging par with inserted/deleted end-of-par character");
154 par.setChange(par.size(), Change(Change::UNCHANGED));
157 Change change = next.lookupChange(next.size());
159 // move the content of the second paragraph to the end of the first one
160 for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
161 if (moveItem(next, 0, par, j, bparams)) {
166 // move the change of the end-of-paragraph character
167 par.setChange(par.size(), change);
169 pars.erase(boost::next(pars.begin(), par_offset + 1));
173 Text::Text(InsetText * owner, bool use_default_layout)
174 : owner_(owner), autoBreakRows_(false), undo_counter_(0)
176 pars_.push_back(Paragraph());
177 Paragraph & par = pars_.back();
178 par.setInsetOwner(owner);
179 DocumentClass const & dc = owner->buffer().params().documentClass();
180 if (use_default_layout)
181 par.setDefaultLayout(dc);
183 par.setPlainLayout(dc);
187 Text::Text(InsetText * owner, Text const & text)
188 : owner_(owner), autoBreakRows_(text.autoBreakRows_), undo_counter_(0)
191 ParagraphList::iterator const end = pars_.end();
192 ParagraphList::iterator it = pars_.begin();
193 for (; it != end; ++it)
194 it->setInsetOwner(owner);
198 pit_type Text::depthHook(pit_type pit, depth_type depth) const
200 pit_type newpit = pit;
205 while (newpit != 0 && pars_[newpit].getDepth() > depth)
208 if (pars_[newpit].getDepth() > depth)
215 pit_type Text::outerHook(pit_type par_offset) const
217 Paragraph const & par = pars_[par_offset];
219 if (par.getDepth() == 0)
221 return depthHook(par_offset, depth_type(par.getDepth() - 1));
225 bool Text::isFirstInSequence(pit_type par_offset) const
227 Paragraph const & par = pars_[par_offset];
229 pit_type dhook_offset = depthHook(par_offset, par.getDepth());
231 if (dhook_offset == par_offset)
234 Paragraph const & dhook = pars_[dhook_offset];
236 return dhook.layout() != par.layout()
237 || dhook.getDepth() != par.getDepth();
241 Font const Text::outerFont(pit_type par_offset) const
243 depth_type par_depth = pars_[par_offset].getDepth();
244 FontInfo tmpfont = inherit_font;
246 // Resolve against environment font information
247 while (par_offset != pit_type(pars_.size())
249 && !tmpfont.resolved()) {
250 par_offset = outerHook(par_offset);
251 if (par_offset != pit_type(pars_.size())) {
252 tmpfont.realize(pars_[par_offset].layout().font);
253 par_depth = pars_[par_offset].getDepth();
257 return Font(tmpfont);
261 static void acceptOrRejectChanges(ParagraphList & pars,
262 BufferParams const & bparams, Text::ChangeOp op)
264 pit_type pars_size = static_cast<pit_type>(pars.size());
266 // first, accept or reject changes within each individual
267 // paragraph (do not consider end-of-par)
268 for (pit_type pit = 0; pit < pars_size; ++pit) {
269 // prevent assertion failure
270 if (!pars[pit].empty()) {
271 if (op == Text::ACCEPT)
272 pars[pit].acceptChanges(0, pars[pit].size());
274 pars[pit].rejectChanges(0, pars[pit].size());
278 // next, accept or reject imaginary end-of-par characters
279 for (pit_type pit = 0; pit < pars_size; ++pit) {
280 pos_type pos = pars[pit].size();
281 if (pars[pit].isChanged(pos)) {
282 // keep the end-of-par char if it is inserted and accepted
283 // or when it is deleted and rejected.
284 if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
285 pars[pit].setChange(pos, Change(Change::UNCHANGED));
287 if (pit == pars_size - 1) {
288 // we cannot remove a par break at the end of the last
289 // paragraph; instead, we mark it unchanged
290 pars[pit].setChange(pos, Change(Change::UNCHANGED));
292 mergeParagraph(bparams, pars, pit);
302 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
304 acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
308 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
310 acceptOrRejectChanges(pars, bparams, Text::REJECT);
314 InsetText const & Text::inset() const
320 void Text::readParToken(Paragraph & par, Lexer & lex,
321 string const & token, Font & font, Change & change, ErrorList & errorList)
323 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
324 BufferParams const & bp = buf->params();
326 if (token[0] != '\\') {
327 docstring dstr = lex.getDocString();
328 par.appendString(dstr, font, change);
330 } else if (token == "\\begin_layout") {
332 docstring layoutname = lex.getDocString();
334 font = Font(inherit_font, bp.language);
335 change = Change(Change::UNCHANGED);
337 DocumentClass const & tclass = bp.documentClass();
339 if (layoutname.empty())
340 layoutname = tclass.defaultLayoutName();
342 if (owner_->forcePlainLayout()) {
343 // in this case only the empty layout is allowed
344 layoutname = tclass.plainLayoutName();
345 } else if (par.usePlainLayout()) {
346 // in this case, default layout maps to empty layout
347 if (layoutname == tclass.defaultLayoutName())
348 layoutname = tclass.plainLayoutName();
350 // otherwise, the empty layout maps to the default
351 if (layoutname == tclass.plainLayoutName())
352 layoutname = tclass.defaultLayoutName();
355 // When we apply an unknown layout to a document, we add this layout to the textclass
356 // of this document. For example, when you apply class article to a beamer document,
357 // all unknown layouts such as frame will be added to document class article so that
358 // these layouts can keep their original names.
359 tclass.addLayoutIfNeeded(layoutname);
361 par.setLayout(bp.documentClass()[layoutname]);
363 // Test whether the layout is obsolete.
364 Layout const & layout = par.layout();
365 if (!layout.obsoleted_by().empty())
366 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
368 par.params().read(lex);
370 } else if (token == "\\end_layout") {
371 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
372 << "Missing \\begin_layout ?");
373 } else if (token == "\\end_inset") {
374 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
375 << "Missing \\begin_inset ?");
376 } else if (token == "\\begin_inset") {
377 Inset * inset = readInset(lex, buf);
379 par.insertInset(par.size(), inset, font, change);
382 docstring line = lex.getDocString();
383 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
384 par.id(), 0, par.size()));
386 } else if (token == "\\family") {
388 setLyXFamily(lex.getString(), font.fontInfo());
389 } else if (token == "\\series") {
391 setLyXSeries(lex.getString(), font.fontInfo());
392 } else if (token == "\\shape") {
394 setLyXShape(lex.getString(), font.fontInfo());
395 } else if (token == "\\size") {
397 setLyXSize(lex.getString(), font.fontInfo());
398 } else if (token == "\\lang") {
400 string const tok = lex.getString();
401 Language const * lang = languages.getLanguage(tok);
403 font.setLanguage(lang);
405 font.setLanguage(bp.language);
406 lex.printError("Unknown language `$$Token'");
408 } else if (token == "\\numeric") {
410 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
411 } else if (token == "\\emph") {
413 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
414 } else if (token == "\\bar") {
416 string const tok = lex.getString();
419 font.fontInfo().setUnderbar(FONT_ON);
420 else if (tok == "no")
421 font.fontInfo().setUnderbar(FONT_OFF);
422 else if (tok == "default")
423 font.fontInfo().setUnderbar(FONT_INHERIT);
425 lex.printError("Unknown bar font flag "
427 } else if (token == "\\strikeout") {
429 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
430 } else if (token == "\\uuline") {
432 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
433 } else if (token == "\\uwave") {
435 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
436 } else if (token == "\\noun") {
438 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
439 } else if (token == "\\color") {
441 setLyXColor(lex.getString(), font.fontInfo());
442 } else if (token == "\\SpecialChar") {
443 auto_ptr<Inset> inset;
444 inset.reset(new InsetSpecialChar);
446 inset->setBuffer(*buf);
447 par.insertInset(par.size(), inset.release(), font, change);
448 } else if (token == "\\backslash") {
449 par.appendChar('\\', font, change);
450 } else if (token == "\\LyXTable") {
451 auto_ptr<Inset> inset(new InsetTabular(buf));
453 par.insertInset(par.size(), inset.release(), font, change);
454 } else if (token == "\\change_unchanged") {
455 change = Change(Change::UNCHANGED);
456 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
458 istringstream is(lex.getString());
462 map<unsigned int, int> const & am = bp.author_map;
463 if (am.find(aid) == am.end()) {
464 errorList.push_back(ErrorItem(_("Change tracking error"),
465 bformat(_("Unknown author index for change: %1$d\n"), aid),
466 par.id(), 0, par.size()));
467 change = Change(Change::UNCHANGED);
469 if (token == "\\change_inserted")
470 change = Change(Change::INSERTED, am.find(aid)->second, ct);
472 change = Change(Change::DELETED, am.find(aid)->second, ct);
476 errorList.push_back(ErrorItem(_("Unknown token"),
477 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
479 par.id(), 0, par.size()));
484 void Text::readParagraph(Paragraph & par, Lexer & lex,
485 ErrorList & errorList)
488 string token = lex.getString();
490 Change change(Change::UNCHANGED);
493 readParToken(par, lex, token, font, change, errorList);
496 token = lex.getString();
501 if (token == "\\end_layout") {
502 //Ok, paragraph finished
506 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
507 if (token == "\\begin_layout" || token == "\\end_document"
508 || token == "\\end_inset" || token == "\\begin_deeper"
509 || token == "\\end_deeper") {
510 lex.pushToken(token);
511 lyxerr << "Paragraph ended in line "
512 << lex.lineNumber() << "\n"
513 << "Missing \\end_layout.\n";
517 // Final change goes to paragraph break:
518 par.setChange(par.size(), change);
520 // Initialize begin_of_body_ on load; redoParagraph maintains
521 par.setBeginOfBody();
523 // mark paragraph for spell checking on load
524 // par.requestSpellCheck();
528 class TextCompletionList : public CompletionList
532 TextCompletionList(Cursor const & cur, WordList const * list)
533 : buffer_(cur.buffer()), pos_(0), list_(list)
536 virtual ~TextCompletionList() {}
539 virtual bool sorted() const { return true; }
541 virtual size_t size() const
543 return list_->size();
546 virtual docstring const & data(size_t idx) const
548 return list_->word(idx);
553 Buffer const * buffer_;
557 WordList const * list_;
561 bool Text::empty() const
563 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
564 // FIXME: Should we consider the labeled type as empty too?
565 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
569 double Text::spacing(Paragraph const & par) const
571 if (par.params().spacing().isDefault())
572 return owner_->buffer().params().spacing().getValue();
573 return par.params().spacing().getValue();
578 * This breaks a paragraph at the specified position.
579 * The new paragraph will:
580 * - Decrease depth by one (or change layout to default layout) when
581 * keep_layout == false
582 * - keep current depth and layout when keep_layout == true
584 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
587 BufferParams const & bparams = text.inset().buffer().params();
588 ParagraphList & pars = text.paragraphs();
589 // create a new paragraph, and insert into the list
590 ParagraphList::iterator tmp =
591 pars.insert(boost::next(pars.begin(), par_offset + 1),
594 Paragraph & par = pars[par_offset];
596 // remember to set the inset_owner
597 tmp->setInsetOwner(&par.inInset());
598 // without doing that we get a crash when typing <Return> at the
599 // end of a paragraph
600 tmp->setPlainOrDefaultLayout(bparams.documentClass());
602 // layout stays the same with latex-environments
604 tmp->setLayout(par.layout());
605 tmp->setLabelWidthString(par.params().labelWidthString());
606 tmp->params().depth(par.params().depth());
607 } else if (par.params().depth() > 0) {
608 Paragraph const & hook = pars[text.outerHook(par_offset)];
609 tmp->setLayout(hook.layout());
610 // not sure the line below is useful
611 tmp->setLabelWidthString(par.params().labelWidthString());
612 tmp->params().depth(hook.params().depth());
615 bool const isempty = (par.allowEmpty() && par.empty());
617 if (!isempty && (par.size() > pos || par.empty())) {
618 tmp->setLayout(par.layout());
619 tmp->params().align(par.params().align());
620 tmp->setLabelWidthString(par.params().labelWidthString());
622 tmp->params().depth(par.params().depth());
623 tmp->params().noindent(par.params().noindent());
625 // move everything behind the break position
626 // to the new paragraph
628 /* Note: if !keepempty, empty() == true, then we reach
629 * here with size() == 0. So pos_end becomes - 1. This
630 * doesn't cause problems because both loops below
631 * enforce pos <= pos_end and 0 <= pos
633 pos_type pos_end = par.size() - 1;
635 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
636 if (moveItem(par, pos, *tmp, j, bparams)) {
642 // Move over the end-of-par change information
643 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
644 par.setChange(par.size(), Change(bparams.trackChanges ?
645 Change::INSERTED : Change::UNCHANGED));
648 // Make sure that we keep the language when
649 // breaking paragraph.
651 Font changed = tmp->getFirstFontSettings(bparams);
652 Font const & old = par.getFontSettings(bparams, par.size());
653 changed.setLanguage(old.language());
654 tmp->setFont(0, changed);
661 bool const soa = par.params().startOfAppendix();
662 par.params().clear();
663 // do not lose start of appendix marker (bug 4212)
664 par.params().startOfAppendix(soa);
665 par.setPlainOrDefaultLayout(bparams.documentClass());
668 // layout stays the same with latex-environments
670 par.setLayout(tmp->layout());
671 par.setLabelWidthString(tmp->params().labelWidthString());
672 par.params().depth(tmp->params().depth());
677 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
679 LASSERT(this == cur.text(), /**/);
681 Paragraph & cpar = cur.paragraph();
682 pit_type cpit = cur.pit();
684 DocumentClass const & tclass = cur.buffer()->params().documentClass();
685 Layout const & layout = cpar.layout();
687 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
688 if (changeDepthAllowed(cur, DEC_DEPTH))
689 changeDepth(cur, DEC_DEPTH);
691 setLayout(cur, tclass.defaultLayoutName());
695 // a layout change may affect also the following paragraph
696 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
698 // Always break behind a space
699 // It is better to erase the space (Dekel)
700 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
701 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
703 // What should the layout for the new paragraph be?
704 bool keep_layout = inverse_logic ?
705 !layout.isEnvironment()
706 : layout.isEnvironment();
708 // We need to remember this before we break the paragraph, because
709 // that invalidates the layout variable
710 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
712 // we need to set this before we insert the paragraph.
713 bool const isempty = cpar.allowEmpty() && cpar.empty();
715 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
717 // After this, neither paragraph contains any rows!
720 pit_type next_par = cpit + 1;
722 // well this is the caption hack since one caption is really enough
725 // set to standard-layout
726 //FIXME Check if this should be plainLayout() in some cases
727 pars_[cpit].applyLayout(tclass.defaultLayout());
729 // set to standard-layout
730 //FIXME Check if this should be plainLayout() in some cases
731 pars_[next_par].applyLayout(tclass.defaultLayout());
734 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
735 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
736 break; // the character couldn't be deleted physically due to change tracking
739 // A singlePar update is not enough in this case.
740 cur.screenUpdateFlags(Update::Force);
741 cur.forceBufferUpdate();
743 // This check is necessary. Otherwise the new empty paragraph will
744 // be deleted automatically. And it is more friendly for the user!
745 if (cur.pos() != 0 || isempty)
746 setCursor(cur, cur.pit() + 1, 0);
748 setCursor(cur, cur.pit(), 0);
752 // needed to insert the selection
753 void Text::insertStringAsLines(DocIterator const & dit, docstring const & str,
756 BufferParams const & bparams = owner_->buffer().params();
757 pit_type pit = dit.pit();
758 pos_type pos = dit.pos();
760 // insert the string, don't insert doublespace
761 bool space_inserted = true;
762 for (docstring::const_iterator cit = str.begin();
763 cit != str.end(); ++cit) {
764 Paragraph & par = pars_[pit];
766 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
767 lyx::breakParagraph(*this, pit, pos,
768 par.layout().isEnvironment());
771 space_inserted = true;
775 // do not insert consecutive spaces if !free_spacing
776 } else if ((*cit == ' ' || *cit == '\t') &&
777 space_inserted && !par.isFreeSpacing()) {
779 } else if (*cit == '\t') {
780 if (!par.isFreeSpacing()) {
781 // tabs are like spaces here
782 par.insertChar(pos, ' ', font, bparams.trackChanges);
784 space_inserted = true;
786 par.insertChar(pos, *cit, font, bparams.trackChanges);
788 space_inserted = true;
790 } else if (!isPrintable(*cit)) {
791 // Ignore unprintables
794 // just insert the character
795 par.insertChar(pos, *cit, font, bparams.trackChanges);
797 space_inserted = (*cit == ' ');
803 // turn double CR to single CR, others are converted into one
804 // blank. Then insertStringAsLines is called
805 void Text::insertStringAsParagraphs(DocIterator const & dit, docstring const & str,
808 docstring linestr = str;
809 bool newline_inserted = false;
811 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
812 if (linestr[i] == '\n') {
813 if (newline_inserted) {
814 // we know that \r will be ignored by
815 // insertStringAsLines. Of course, it is a dirty
816 // trick, but it works...
817 linestr[i - 1] = '\r';
821 newline_inserted = true;
823 } else if (isPrintable(linestr[i])) {
824 newline_inserted = false;
827 insertStringAsLines(dit, linestr, font);
831 // insert a character, moves all the following breaks in the
832 // same Paragraph one to the right and make a rebreak
833 void Text::insertChar(Cursor & cur, char_type c)
835 LASSERT(this == cur.text(), /**/);
837 cur.recordUndo(INSERT_UNDO);
839 TextMetrics const & tm = cur.bv().textMetrics(this);
840 Buffer const & buffer = *cur.buffer();
841 Paragraph & par = cur.paragraph();
842 // try to remove this
843 pit_type const pit = cur.pit();
845 bool const freeSpacing = par.layout().free_spacing ||
848 if (lyxrc.auto_number) {
849 static docstring const number_operators = from_ascii("+-/*");
850 static docstring const number_unary_operators = from_ascii("+-");
851 static docstring const number_seperators = from_ascii(".,:");
853 if (cur.current_font.fontInfo().number() == FONT_ON) {
854 if (!isDigit(c) && !contains(number_operators, c) &&
855 !(contains(number_seperators, c) &&
857 cur.pos() != cur.lastpos() &&
858 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
859 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
861 number(cur); // Set current_font.number to OFF
862 } else if (isDigit(c) &&
863 cur.real_current_font.isVisibleRightToLeft()) {
864 number(cur); // Set current_font.number to ON
866 if (cur.pos() != 0) {
867 char_type const c = par.getChar(cur.pos() - 1);
868 if (contains(number_unary_operators, c) &&
870 || par.isSeparator(cur.pos() - 2)
871 || par.isNewline(cur.pos() - 2))
873 setCharFont(pit, cur.pos() - 1, cur.current_font,
875 } else if (contains(number_seperators, c)
877 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
878 setCharFont(pit, cur.pos() - 1, cur.current_font,
885 // In Bidi text, we want spaces to be treated in a special way: spaces
886 // which are between words in different languages should get the
887 // paragraph's language; otherwise, spaces should keep the language
888 // they were originally typed in. This is only in effect while typing;
889 // after the text is already typed in, the user can always go back and
890 // explicitly set the language of a space as desired. But 99.9% of the
891 // time, what we're doing here is what the user actually meant.
893 // The following cases are the ones in which the language of the space
894 // should be changed to match that of the containing paragraph. In the
895 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
896 // represents a space, pipe (|) represents the cursor position (so the
897 // character before it is the one just typed in). The different cases
898 // are depicted logically (not visually), from left to right:
903 // Theoretically, there are other situations that we should, perhaps, deal
904 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
905 // point (to understand why, just try to create this situation...).
907 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
908 // get font in front and behind the space in question. But do NOT
909 // use getFont(cur.pos()) because the character c is not inserted yet
910 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
911 Font const & post_space_font = cur.real_current_font;
912 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
913 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
915 if (pre_space_rtl != post_space_rtl) {
916 // Set the space's language to match the language of the
917 // adjacent character whose direction is the paragraph's
918 // direction; don't touch other properties of the font
919 Language const * lang =
920 (pre_space_rtl == par.isRTL(buffer.params())) ?
921 pre_space_font.language() : post_space_font.language();
923 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
924 space_font.setLanguage(lang);
925 par.setFont(cur.pos() - 1, space_font);
929 // Next check, if there will be two blanks together or a blank at
930 // the beginning of a paragraph.
931 // I decided to handle blanks like normal characters, the main
932 // difference are the special checks when calculating the row.fill
933 // (blank does not count at the end of a row) and the check here
935 // When the free-spacing option is set for the current layout,
936 // disable the double-space checking
937 if (!freeSpacing && isLineSeparatorChar(c)) {
938 if (cur.pos() == 0) {
939 static bool sent_space_message = false;
940 if (!sent_space_message) {
941 cur.message(_("You cannot insert a space at the "
942 "beginning of a paragraph. Please read the Tutorial."));
943 sent_space_message = true;
947 LASSERT(cur.pos() > 0, /**/);
948 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
949 && !par.isDeleted(cur.pos() - 1)) {
950 static bool sent_space_message = false;
951 if (!sent_space_message) {
952 cur.message(_("You cannot type two spaces this way. "
953 "Please read the Tutorial."));
954 sent_space_message = true;
960 par.insertChar(cur.pos(), c, cur.current_font,
961 cur.buffer()->params().trackChanges);
962 cur.checkBufferStructure();
964 // cur.screenUpdateFlags(Update::Force);
965 bool boundary = cur.boundary()
966 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
967 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
972 void Text::charInserted(Cursor & cur)
974 Paragraph & par = cur.paragraph();
976 // Here we call finishUndo for every 20 characters inserted.
977 // This is from my experience how emacs does it. (Lgb)
978 if (undo_counter_ < 20) {
985 // register word if a non-letter was entered
987 && !par.isWordSeparator(cur.pos() - 2)
988 && par.isWordSeparator(cur.pos() - 1)) {
989 // get the word in front of cursor
990 LASSERT(this == cur.text(), /**/);
991 cur.paragraph().updateWords();
996 // the cursor set functions have a special mechanism. When they
997 // realize, that you left an empty paragraph, they will delete it.
999 bool Text::cursorForwardOneWord(Cursor & cur)
1001 LASSERT(this == cur.text(), /**/);
1003 pos_type const lastpos = cur.lastpos();
1004 pit_type pit = cur.pit();
1005 pos_type pos = cur.pos();
1006 Paragraph const & par = cur.paragraph();
1008 // Paragraph boundary is a word boundary
1009 if (pos == lastpos) {
1010 if (pit != cur.lastpit())
1011 return setCursor(cur, pit + 1, 0);
1016 if (lyxrc.mac_like_word_movement) {
1017 // Skip through trailing punctuation and spaces.
1018 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1021 // Skip over either a non-char inset or a full word
1022 if (pos != lastpos && par.isWordSeparator(pos))
1024 else while (pos != lastpos && !par.isWordSeparator(pos))
1027 LASSERT(pos < lastpos, /**/); // see above
1028 if (!par.isWordSeparator(pos))
1029 while (pos != lastpos && !par.isWordSeparator(pos))
1031 else if (par.isChar(pos))
1032 while (pos != lastpos && par.isChar(pos))
1034 else if (!par.isSpace(pos)) // non-char inset
1037 // Skip over white space
1038 while (pos != lastpos && par.isSpace(pos))
1042 return setCursor(cur, pit, pos);
1046 bool Text::cursorBackwardOneWord(Cursor & cur)
1048 LASSERT(this == cur.text(), /**/);
1050 pit_type pit = cur.pit();
1051 pos_type pos = cur.pos();
1052 Paragraph & par = cur.paragraph();
1054 // Paragraph boundary is a word boundary
1055 if (pos == 0 && pit != 0)
1056 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1058 if (lyxrc.mac_like_word_movement) {
1059 // Skip through punctuation and spaces.
1060 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1063 // Skip over either a non-char inset or a full word
1064 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1066 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1069 // Skip over white space
1070 while (pos != 0 && par.isSpace(pos - 1))
1073 if (pos != 0 && !par.isWordSeparator(pos - 1))
1074 while (pos != 0 && !par.isWordSeparator(pos - 1))
1076 else if (pos != 0 && par.isChar(pos - 1))
1077 while (pos != 0 && par.isChar(pos - 1))
1079 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1083 return setCursor(cur, pit, pos);
1087 bool Text::cursorVisLeftOneWord(Cursor & cur)
1089 LASSERT(this == cur.text(), /**/);
1091 pos_type left_pos, right_pos;
1092 bool left_is_letter, right_is_letter;
1094 Cursor temp_cur = cur;
1096 // always try to move at least once...
1097 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1099 // collect some information about current cursor position
1100 temp_cur.getSurroundingPos(left_pos, right_pos);
1102 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1104 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1106 // if we're not at a letter/non-letter boundary, continue moving
1107 if (left_is_letter == right_is_letter)
1110 // we should stop when we have an LTR word on our right or an RTL word
1112 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1113 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1114 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1115 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1119 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1120 true, temp_cur.boundary());
1124 bool Text::cursorVisRightOneWord(Cursor & cur)
1126 LASSERT(this == cur.text(), /**/);
1128 pos_type left_pos, right_pos;
1129 bool left_is_letter, right_is_letter;
1131 Cursor temp_cur = cur;
1133 // always try to move at least once...
1134 while (temp_cur.posVisRight(true /* skip_inset */)) {
1136 // collect some information about current cursor position
1137 temp_cur.getSurroundingPos(left_pos, right_pos);
1139 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1141 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1143 // if we're not at a letter/non-letter boundary, continue moving
1144 if (left_is_letter == right_is_letter)
1147 // we should stop when we have an LTR word on our right or an RTL word
1149 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1150 temp_cur.buffer()->params(),
1151 left_pos).isRightToLeft())
1152 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1153 temp_cur.buffer()->params(),
1154 right_pos).isRightToLeft()))
1158 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1159 true, temp_cur.boundary());
1163 void Text::selectWord(Cursor & cur, word_location loc)
1165 LASSERT(this == cur.text(), /**/);
1166 CursorSlice from = cur.top();
1167 CursorSlice to = cur.top();
1168 getWord(from, to, loc);
1169 if (cur.top() != from)
1170 setCursor(cur, from.pit(), from.pos());
1173 if (!cur.selection())
1175 setCursor(cur, to.pit(), to.pos());
1177 cur.setWordSelection(true);
1181 void Text::selectAll(Cursor & cur)
1183 LASSERT(this == cur.text(), /**/);
1184 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1186 // If the cursor is at the beginning, make sure the cursor ends there
1187 if (cur.pit() == 0 && cur.pos() == 0) {
1188 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1190 setCursor(cur, 0, 0);
1192 setCursor(cur, 0, 0);
1194 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1200 // Select the word currently under the cursor when no
1201 // selection is currently set
1202 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1204 LASSERT(this == cur.text(), /**/);
1205 if (cur.selection())
1207 selectWord(cur, loc);
1208 return cur.selection();
1212 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1214 LASSERT(this == cur.text(), /**/);
1216 if (!cur.selection()) {
1217 bool const changed = cur.paragraph().isChanged(cur.pos());
1218 if (!(changed && findNextChange(&cur.bv())))
1222 cur.recordUndoSelection();
1224 pit_type begPit = cur.selectionBegin().pit();
1225 pit_type endPit = cur.selectionEnd().pit();
1227 pos_type begPos = cur.selectionBegin().pos();
1228 pos_type endPos = cur.selectionEnd().pos();
1230 // keep selection info, because endPos becomes invalid after the first loop
1231 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1233 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1235 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1236 pos_type parSize = pars_[pit].size();
1238 // ignore empty paragraphs; otherwise, an assertion will fail for
1239 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1243 // do not consider first paragraph if the cursor starts at pos size()
1244 if (pit == begPit && begPos == parSize)
1247 // do not consider last paragraph if the cursor ends at pos 0
1248 if (pit == endPit && endPos == 0)
1249 break; // last iteration anyway
1251 pos_type left = (pit == begPit ? begPos : 0);
1252 pos_type right = (pit == endPit ? endPos : parSize);
1255 pars_[pit].acceptChanges(left, right);
1257 pars_[pit].rejectChanges(left, right);
1261 // next, accept/reject imaginary end-of-par characters
1263 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1264 pos_type pos = pars_[pit].size();
1266 // skip if the selection ends before the end-of-par
1267 if (pit == endPit && endsBeforeEndOfPar)
1268 break; // last iteration anyway
1270 // skip if this is not the last paragraph of the document
1271 // note: the user should be able to accept/reject the par break of the last par!
1272 if (pit == endPit && pit + 1 != int(pars_.size()))
1273 break; // last iteration anway
1276 if (pars_[pit].isInserted(pos)) {
1277 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1278 } else if (pars_[pit].isDeleted(pos)) {
1279 if (pit + 1 == int(pars_.size())) {
1280 // we cannot remove a par break at the end of the last paragraph;
1281 // instead, we mark it unchanged
1282 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1284 mergeParagraph(cur.buffer()->params(), pars_, pit);
1290 if (pars_[pit].isDeleted(pos)) {
1291 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1292 } else if (pars_[pit].isInserted(pos)) {
1293 if (pit + 1 == int(pars_.size())) {
1294 // we mark the par break at the end of the last paragraph unchanged
1295 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1297 mergeParagraph(cur.buffer()->params(), pars_, pit);
1305 // finally, invoke the DEPM
1307 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1312 cur.clearSelection();
1313 setCursorIntern(cur, begPit, begPos);
1314 cur.screenUpdateFlags(Update::Force);
1315 cur.forceBufferUpdate();
1319 void Text::acceptChanges()
1321 BufferParams const & bparams = owner_->buffer().params();
1322 lyx::acceptChanges(pars_, bparams);
1323 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1327 void Text::rejectChanges()
1329 BufferParams const & bparams = owner_->buffer().params();
1330 pit_type pars_size = static_cast<pit_type>(pars_.size());
1332 // first, reject changes within each individual paragraph
1333 // (do not consider end-of-par)
1334 for (pit_type pit = 0; pit < pars_size; ++pit) {
1335 if (!pars_[pit].empty()) // prevent assertion failure
1336 pars_[pit].rejectChanges(0, pars_[pit].size());
1339 // next, reject imaginary end-of-par characters
1340 for (pit_type pit = 0; pit < pars_size; ++pit) {
1341 pos_type pos = pars_[pit].size();
1343 if (pars_[pit].isDeleted(pos)) {
1344 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1345 } else if (pars_[pit].isInserted(pos)) {
1346 if (pit == pars_size - 1) {
1347 // we mark the par break at the end of the last
1348 // paragraph unchanged
1349 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1351 mergeParagraph(bparams, pars_, pit);
1358 // finally, invoke the DEPM
1359 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1363 void Text::deleteWordForward(Cursor & cur)
1365 LASSERT(this == cur.text(), /**/);
1366 if (cur.lastpos() == 0)
1370 cur.setSelection(true);
1371 cursorForwardOneWord(cur);
1373 cutSelection(cur, true, false);
1374 cur.checkBufferStructure();
1379 void Text::deleteWordBackward(Cursor & cur)
1381 LASSERT(this == cur.text(), /**/);
1382 if (cur.lastpos() == 0)
1383 cursorBackward(cur);
1386 cur.setSelection(true);
1387 cursorBackwardOneWord(cur);
1389 cutSelection(cur, true, false);
1390 cur.checkBufferStructure();
1395 // Kill to end of line.
1396 void Text::changeCase(Cursor & cur, TextCase action)
1398 LASSERT(this == cur.text(), /**/);
1402 bool gotsel = false;
1403 if (cur.selection()) {
1404 from = cur.selBegin();
1409 getWord(from, to, PARTIAL_WORD);
1410 cursorForwardOneWord(cur);
1413 cur.recordUndoSelection();
1415 pit_type begPit = from.pit();
1416 pit_type endPit = to.pit();
1418 pos_type begPos = from.pos();
1419 pos_type endPos = to.pos();
1421 pos_type right = 0; // needed after the for loop
1423 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1424 Paragraph & par = pars_[pit];
1425 pos_type const pos = (pit == begPit ? begPos : 0);
1426 right = (pit == endPit ? endPos : par.size());
1427 par.changeCase(cur.buffer()->params(), pos, right, action);
1430 // the selection may have changed due to logically-only deleted chars
1432 setCursor(cur, begPit, begPos);
1434 setCursor(cur, endPit, right);
1437 setCursor(cur, endPit, right);
1439 cur.checkBufferStructure();
1443 bool Text::handleBibitems(Cursor & cur)
1445 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1451 BufferParams const & bufparams = cur.buffer()->params();
1452 Paragraph const & par = cur.paragraph();
1453 Cursor prevcur = cur;
1454 if (cur.pit() > 0) {
1456 prevcur.pos() = prevcur.lastpos();
1458 Paragraph const & prevpar = prevcur.paragraph();
1460 // if a bibitem is deleted, merge with previous paragraph
1461 // if this is a bibliography item as well
1462 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1463 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1464 mergeParagraph(bufparams, cur.text()->paragraphs(),
1466 cur.forceBufferUpdate();
1467 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1468 cur.screenUpdateFlags(Update::Force);
1472 // otherwise reset to default
1473 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1478 bool Text::erase(Cursor & cur)
1480 LASSERT(this == cur.text(), return false);
1481 bool needsUpdate = false;
1482 Paragraph & par = cur.paragraph();
1484 if (cur.pos() != cur.lastpos()) {
1485 // this is the code for a normal delete, not pasting
1487 cur.recordUndo(DELETE_UNDO);
1488 bool const was_inset = cur.paragraph().isInset(cur.pos());
1489 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1490 // the character has been logically deleted only => skip it
1491 cur.top().forwardPos();
1494 cur.forceBufferUpdate();
1496 cur.checkBufferStructure();
1499 if (cur.pit() == cur.lastpit())
1500 return dissolveInset(cur);
1502 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1503 par.setChange(cur.pos(), Change(Change::DELETED));
1507 setCursorIntern(cur, cur.pit() + 1, 0);
1508 needsUpdate = backspacePos0(cur);
1512 needsUpdate |= handleBibitems(cur);
1515 // Make sure the cursor is correct. Is this really needed?
1516 // No, not really... at least not here!
1517 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1518 cur.checkBufferStructure();
1525 bool Text::backspacePos0(Cursor & cur)
1527 LASSERT(this == cur.text(), /**/);
1531 bool needsUpdate = false;
1533 BufferParams const & bufparams = cur.buffer()->params();
1534 DocumentClass const & tclass = bufparams.documentClass();
1535 ParagraphList & plist = cur.text()->paragraphs();
1536 Paragraph const & par = cur.paragraph();
1537 Cursor prevcur = cur;
1539 prevcur.pos() = prevcur.lastpos();
1540 Paragraph const & prevpar = prevcur.paragraph();
1542 // is it an empty paragraph?
1543 if (cur.lastpos() == 0
1544 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1545 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1546 plist.erase(boost::next(plist.begin(), cur.pit()));
1549 // is previous par empty?
1550 else if (prevcur.lastpos() == 0
1551 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1552 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1553 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1556 // Pasting is not allowed, if the paragraphs have different
1557 // layouts. I think it is a real bug of all other
1558 // word processors to allow it. It confuses the user.
1559 // Correction: Pasting is always allowed with standard-layout
1560 // or the empty layout.
1561 else if (par.layout() == prevpar.layout()
1562 || tclass.isDefaultLayout(par.layout())
1563 || tclass.isPlainLayout(par.layout())) {
1564 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1565 mergeParagraph(bufparams, plist, prevcur.pit());
1570 cur.forceBufferUpdate();
1571 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1578 bool Text::backspace(Cursor & cur)
1580 LASSERT(this == cur.text(), /**/);
1581 bool needsUpdate = false;
1582 if (cur.pos() == 0) {
1584 return dissolveInset(cur);
1586 Paragraph & prev_par = pars_[cur.pit() - 1];
1588 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1589 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1590 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1593 // The cursor is at the beginning of a paragraph, so
1594 // the backspace will collapse two paragraphs into one.
1595 needsUpdate = backspacePos0(cur);
1598 // this is the code for a normal backspace, not pasting
1600 cur.recordUndo(DELETE_UNDO);
1601 // We used to do cursorBackwardIntern() here, but it is
1602 // not a good idea since it triggers the auto-delete
1603 // mechanism. So we do a cursorBackwardIntern()-lite,
1604 // without the dreaded mechanism. (JMarc)
1605 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1606 false, cur.boundary());
1607 bool const was_inset = cur.paragraph().isInset(cur.pos());
1608 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1610 cur.forceBufferUpdate();
1612 cur.checkBufferStructure();
1615 if (cur.pos() == cur.lastpos())
1616 cur.setCurrentFont();
1618 needsUpdate |= handleBibitems(cur);
1620 // A singlePar update is not enough in this case.
1621 // cur.screenUpdateFlags(Update::Force);
1622 setCursor(cur.top(), cur.pit(), cur.pos());
1628 bool Text::dissolveInset(Cursor & cur)
1630 LASSERT(this == cur.text(), return false);
1632 if (isMainText() || cur.inset().nargs() != 1)
1635 cur.recordUndoInset();
1637 cur.selHandle(false);
1639 pos_type spos = cur.pos();
1640 pit_type spit = cur.pit();
1641 ParagraphList plist;
1642 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1643 plist = paragraphs();
1645 // store cursor offset
1649 Buffer & b = *cur.buffer();
1650 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1651 if (!plist.empty()) {
1652 // ERT paragraphs have the Language latex_language.
1653 // This is invalid outside of ERT, so we need to
1654 // change it to the buffer language.
1655 ParagraphList::iterator it = plist.begin();
1656 ParagraphList::iterator it_end = plist.end();
1657 for (; it != it_end; it++)
1658 it->changeLanguage(b.params(), latex_language, b.language());
1660 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1661 b.errorList("Paste"));
1663 cur.pit() = min(cur.lastpit(), spit);
1664 cur.pos() = min(cur.lastpos(), spos);
1666 cur.forceBufferUpdate();
1668 // Ensure the current language is set correctly (bug 6292)
1669 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1670 cur.clearSelection();
1676 void Text::getWord(CursorSlice & from, CursorSlice & to,
1677 word_location const loc) const
1680 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1684 void Text::write(ostream & os) const
1686 Buffer const & buf = owner_->buffer();
1687 ParagraphList::const_iterator pit = paragraphs().begin();
1688 ParagraphList::const_iterator end = paragraphs().end();
1690 for (; pit != end; ++pit)
1691 pit->write(os, buf.params(), dth);
1693 // Close begin_deeper
1694 for(; dth > 0; --dth)
1695 os << "\n\\end_deeper";
1699 bool Text::read(Lexer & lex,
1700 ErrorList & errorList, InsetText * insetPtr)
1702 Buffer const & buf = owner_->buffer();
1703 depth_type depth = 0;
1706 while (lex.isOK()) {
1708 string const token = lex.getString();
1713 if (token == "\\end_inset")
1716 if (token == "\\end_body")
1719 if (token == "\\begin_body")
1722 if (token == "\\end_document") {
1727 if (token == "\\begin_layout") {
1728 lex.pushToken(token);
1731 par.setInsetOwner(insetPtr);
1732 par.params().depth(depth);
1733 par.setFont(0, Font(inherit_font, buf.params().language));
1734 pars_.push_back(par);
1735 readParagraph(pars_.back(), lex, errorList);
1737 // register the words in the global word list
1738 pars_.back().updateWords();
1739 } else if (token == "\\begin_deeper") {
1741 } else if (token == "\\end_deeper") {
1743 lex.printError("\\end_deeper: " "depth is already null");
1747 LYXERR0("Handling unknown body token: `" << token << '\'');
1751 // avoid a crash on weird documents (bug 4859)
1752 if (pars_.empty()) {
1754 par.setInsetOwner(insetPtr);
1755 par.params().depth(depth);
1756 par.setFont(0, Font(inherit_font,
1757 buf.params().language));
1758 par.setPlainOrDefaultLayout(buf.params().documentClass());
1759 pars_.push_back(par);
1765 // Returns the current font and depth as a message.
1766 docstring Text::currentState(Cursor const & cur) const
1768 LASSERT(this == cur.text(), /**/);
1769 Buffer & buf = *cur.buffer();
1770 Paragraph const & par = cur.paragraph();
1771 odocstringstream os;
1773 if (buf.params().trackChanges)
1774 os << _("[Change Tracking] ");
1776 Change change = par.lookupChange(cur.pos());
1778 if (change.changed()) {
1779 Author const & a = buf.params().authors().get(change.author);
1780 os << _("Change: ") << a.name();
1781 if (!a.email().empty())
1782 os << " (" << a.email() << ")";
1783 // FIXME ctime is english, we should translate that
1784 os << _(" at ") << ctime(&change.changetime);
1788 // I think we should only show changes from the default
1790 // No, from the document font (MV)
1791 Font font = cur.real_current_font;
1792 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1794 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1796 // The paragraph depth
1797 int depth = cur.paragraph().getDepth();
1799 os << bformat(_(", Depth: %1$d"), depth);
1801 // The paragraph spacing, but only if different from
1803 Spacing const & spacing = par.params().spacing();
1804 if (!spacing.isDefault()) {
1805 os << _(", Spacing: ");
1806 switch (spacing.getSpace()) {
1807 case Spacing::Single:
1810 case Spacing::Onehalf:
1813 case Spacing::Double:
1816 case Spacing::Other:
1817 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1819 case Spacing::Default:
1820 // should never happen, do nothing
1825 #ifdef DEVEL_VERSION
1826 os << _(", Inset: ") << &cur.inset();
1827 os << _(", Paragraph: ") << cur.pit();
1828 os << _(", Id: ") << par.id();
1829 os << _(", Position: ") << cur.pos();
1830 // FIXME: Why is the check for par.size() needed?
1831 // We are called with cur.pos() == par.size() quite often.
1832 if (!par.empty() && cur.pos() < par.size()) {
1833 // Force output of code point, not character
1834 size_t const c = par.getChar(cur.pos());
1835 os << _(", Char: 0x") << hex << c;
1837 os << _(", Boundary: ") << cur.boundary();
1838 // Row & row = cur.textRow();
1839 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1845 docstring Text::getPossibleLabel(Cursor const & cur) const
1847 pit_type pit = cur.pit();
1849 Layout const * layout = &(pars_[pit].layout());
1852 docstring par_text = pars_[pit].asString();
1854 // The return string of math matrices might contain linebreaks
1855 par_text = subst(par_text, '\n', '-');
1856 int const numwords = 3;
1857 for (int i = 0; i < numwords; ++i) {
1858 if (par_text.empty())
1861 par_text = split(par_text, head, ' ');
1862 // Is it legal to use spaces in labels ?
1868 // Make sure it isn't too long
1869 unsigned int const max_label_length = 32;
1870 if (text.size() > max_label_length)
1871 text.resize(max_label_length);
1873 // Will contain the label prefix.
1876 // For section, subsection, etc...
1877 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1878 Layout const * layout2 = &(pars_[pit - 1].layout());
1879 if (layout2->latextype != LATEX_PARAGRAPH) {
1884 if (layout->latextype != LATEX_PARAGRAPH)
1885 name = layout->refprefix;
1887 // For captions, we just take the caption type
1888 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1889 if (caption_inset) {
1890 string const & ftype = static_cast<InsetCaption *>(caption_inset)->type();
1891 FloatList const & fl = cur.buffer()->params().documentClass().floats();
1892 if (fl.typeExist(ftype)) {
1893 Floating const & flt = fl.getType(ftype);
1894 name = from_utf8(flt.refPrefix());
1897 name = from_utf8(ftype.substr(0,3));
1900 // If none of the above worked, see if the inset knows.
1902 InsetLayout const & il = cur.inset().getLayout();
1903 name = il.refprefix();
1908 // We should allow customization of the separator or else change it
1909 text = name + ':' + text;
1915 docstring Text::asString(int options) const
1917 return asString(0, pars_.size(), options);
1921 docstring Text::asString(pit_type beg, pit_type end, int options) const
1923 size_t i = size_t(beg);
1924 docstring str = pars_[i].asString(options);
1925 for (++i; i != size_t(end); ++i) {
1927 str += pars_[i].asString(options);
1934 void Text::charsTranspose(Cursor & cur)
1936 LASSERT(this == cur.text(), /**/);
1938 pos_type pos = cur.pos();
1940 // If cursor is at beginning or end of paragraph, do nothing.
1941 if (pos == cur.lastpos() || pos == 0)
1944 Paragraph & par = cur.paragraph();
1946 // Get the positions of the characters to be transposed.
1947 pos_type pos1 = pos - 1;
1948 pos_type pos2 = pos;
1950 // In change tracking mode, ignore deleted characters.
1951 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1953 if (pos2 == cur.lastpos())
1956 while (pos1 >= 0 && par.isDeleted(pos1))
1961 // Don't do anything if one of the "characters" is not regular text.
1962 if (par.isInset(pos1) || par.isInset(pos2))
1965 // Store the characters to be transposed (including font information).
1966 char_type const char1 = par.getChar(pos1);
1968 par.getFontSettings(cur.buffer()->params(), pos1);
1970 char_type const char2 = par.getChar(pos2);
1972 par.getFontSettings(cur.buffer()->params(), pos2);
1974 // And finally, we are ready to perform the transposition.
1975 // Track the changes if Change Tracking is enabled.
1976 bool const trackChanges = cur.buffer()->params().trackChanges;
1980 par.eraseChar(pos2, trackChanges);
1981 par.eraseChar(pos1, trackChanges);
1982 par.insertChar(pos1, char2, font2, trackChanges);
1983 par.insertChar(pos2, char1, font1, trackChanges);
1985 cur.checkBufferStructure();
1987 // After the transposition, move cursor to after the transposition.
1988 setCursor(cur, cur.pit(), pos2);
1993 DocIterator Text::macrocontextPosition() const
1995 return macrocontext_position_;
1999 void Text::setMacrocontextPosition(DocIterator const & pos)
2001 macrocontext_position_ = pos;
2005 docstring Text::previousWord(CursorSlice const & sl) const
2007 CursorSlice from = sl;
2008 CursorSlice to = sl;
2009 getWord(from, to, PREVIOUS_WORD);
2010 if (sl == from || to == from)
2013 Paragraph const & par = sl.paragraph();
2014 return par.asString(from.pos(), to.pos());
2018 bool Text::completionSupported(Cursor const & cur) const
2020 Paragraph const & par = cur.paragraph();
2021 return cur.pos() > 0
2022 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2023 && !par.isWordSeparator(cur.pos() - 1);
2027 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2029 WordList const * list = theWordList(*cur.getFont().language());
2030 return new TextCompletionList(cur, list);
2034 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2036 LASSERT(cur.bv().cursor() == cur, /**/);
2038 cur.bv().cursor() = cur;
2039 if (!(cur.result().update() & Update::Force))
2040 cur.screenUpdateFlags(cur.result().update() | Update::SinglePar);
2045 docstring Text::completionPrefix(Cursor const & cur) const
2047 return previousWord(cur.top());