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/InsetOptArg.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 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
264 pit_type pars_size = static_cast<pit_type>(pars.size());
266 // first, accept changes within each individual paragraph
267 // (do not consider end-of-par)
268 for (pit_type pit = 0; pit < pars_size; ++pit) {
269 if (!pars[pit].empty()) // prevent assertion failure
270 pars[pit].acceptChanges(0, pars[pit].size());
273 // next, accept imaginary end-of-par characters
274 for (pit_type pit = 0; pit < pars_size; ++pit) {
275 pos_type pos = pars[pit].size();
277 if (pars[pit].isInserted(pos)) {
278 pars[pit].setChange(pos, Change(Change::UNCHANGED));
279 } else if (pars[pit].isDeleted(pos)) {
280 if (pit == pars_size - 1) {
281 // we cannot remove a par break at the end of the last
282 // paragraph; instead, we mark it unchanged
283 pars[pit].setChange(pos, Change(Change::UNCHANGED));
285 mergeParagraph(bparams, pars, pit);
293 InsetText const & Text::inset() const
299 void Text::readParToken(Paragraph & par, Lexer & lex,
300 string const & token, Font & font, Change & change, ErrorList & errorList)
302 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
303 BufferParams const & bp = buf->params();
305 if (token[0] != '\\') {
306 docstring dstr = lex.getDocString();
307 par.appendString(dstr, font, change);
309 } else if (token == "\\begin_layout") {
311 docstring layoutname = lex.getDocString();
313 font = Font(inherit_font, bp.language);
314 change = Change(Change::UNCHANGED);
316 DocumentClass const & tclass = bp.documentClass();
318 if (layoutname.empty())
319 layoutname = tclass.defaultLayoutName();
321 if (owner_->forcePlainLayout()) {
322 // in this case only the empty layout is allowed
323 layoutname = tclass.plainLayoutName();
324 } else if (par.usePlainLayout()) {
325 // in this case, default layout maps to empty layout
326 if (layoutname == tclass.defaultLayoutName())
327 layoutname = tclass.plainLayoutName();
329 // otherwise, the empty layout maps to the default
330 if (layoutname == tclass.plainLayoutName())
331 layoutname = tclass.defaultLayoutName();
334 // When we apply an unknown layout to a document, we add this layout to the textclass
335 // of this document. For example, when you apply class article to a beamer document,
336 // all unknown layouts such as frame will be added to document class article so that
337 // these layouts can keep their original names.
338 tclass.addLayoutIfNeeded(layoutname);
340 par.setLayout(bp.documentClass()[layoutname]);
342 // Test whether the layout is obsolete.
343 Layout const & layout = par.layout();
344 if (!layout.obsoleted_by().empty())
345 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
347 par.params().read(lex);
349 } else if (token == "\\end_layout") {
350 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
351 << "Missing \\begin_layout ?");
352 } else if (token == "\\end_inset") {
353 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
354 << "Missing \\begin_inset ?");
355 } else if (token == "\\begin_inset") {
356 Inset * inset = readInset(lex, buf);
358 par.insertInset(par.size(), inset, font, change);
361 docstring line = lex.getDocString();
362 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
363 par.id(), 0, par.size()));
365 } else if (token == "\\family") {
367 setLyXFamily(lex.getString(), font.fontInfo());
368 } else if (token == "\\series") {
370 setLyXSeries(lex.getString(), font.fontInfo());
371 } else if (token == "\\shape") {
373 setLyXShape(lex.getString(), font.fontInfo());
374 } else if (token == "\\size") {
376 setLyXSize(lex.getString(), font.fontInfo());
377 } else if (token == "\\lang") {
379 string const tok = lex.getString();
380 Language const * lang = languages.getLanguage(tok);
382 font.setLanguage(lang);
384 font.setLanguage(bp.language);
385 lex.printError("Unknown language `$$Token'");
387 } else if (token == "\\numeric") {
389 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
390 } else if (token == "\\emph") {
392 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
393 } else if (token == "\\bar") {
395 string const tok = lex.getString();
398 font.fontInfo().setUnderbar(FONT_ON);
399 else if (tok == "no")
400 font.fontInfo().setUnderbar(FONT_OFF);
401 else if (tok == "default")
402 font.fontInfo().setUnderbar(FONT_INHERIT);
404 lex.printError("Unknown bar font flag "
406 } else if (token == "\\strikeout") {
408 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
409 } else if (token == "\\uuline") {
411 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
412 } else if (token == "\\uwave") {
414 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
415 } else if (token == "\\noun") {
417 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
418 } else if (token == "\\color") {
420 setLyXColor(lex.getString(), font.fontInfo());
421 } else if (token == "\\SpecialChar") {
422 auto_ptr<Inset> inset;
423 inset.reset(new InsetSpecialChar);
425 inset->setBuffer(*buf);
426 par.insertInset(par.size(), inset.release(), font, change);
427 } else if (token == "\\backslash") {
428 par.appendChar('\\', font, change);
429 } else if (token == "\\LyXTable") {
430 auto_ptr<Inset> inset(new InsetTabular(buf));
432 par.insertInset(par.size(), inset.release(), font, change);
433 } else if (token == "\\lyxline") {
434 auto_ptr<Inset> inset;
435 inset.reset(new InsetLine);
436 inset->setBuffer(*buf);
437 par.insertInset(par.size(), inset.release(), font, change);
438 } else if (token == "\\change_unchanged") {
439 change = Change(Change::UNCHANGED);
440 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
442 istringstream is(lex.getString());
446 map<unsigned int, int> const & am = bp.author_map;
447 if (am.find(aid) == am.end()) {
448 errorList.push_back(ErrorItem(_("Change tracking error"),
449 bformat(_("Unknown author index for change: %1$d\n"), aid),
450 par.id(), 0, par.size()));
451 change = Change(Change::UNCHANGED);
453 if (token == "\\change_inserted")
454 change = Change(Change::INSERTED, am.find(aid)->second, ct);
456 change = Change(Change::DELETED, am.find(aid)->second, ct);
460 errorList.push_back(ErrorItem(_("Unknown token"),
461 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
463 par.id(), 0, par.size()));
468 void Text::readParagraph(Paragraph & par, Lexer & lex,
469 ErrorList & errorList)
472 string token = lex.getString();
474 Change change(Change::UNCHANGED);
477 readParToken(par, lex, token, font, change, errorList);
480 token = lex.getString();
485 if (token == "\\end_layout") {
486 //Ok, paragraph finished
490 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
491 if (token == "\\begin_layout" || token == "\\end_document"
492 || token == "\\end_inset" || token == "\\begin_deeper"
493 || token == "\\end_deeper") {
494 lex.pushToken(token);
495 lyxerr << "Paragraph ended in line "
496 << lex.lineNumber() << "\n"
497 << "Missing \\end_layout.\n";
501 // Final change goes to paragraph break:
502 par.setChange(par.size(), change);
504 // Initialize begin_of_body_ on load; redoParagraph maintains
505 par.setBeginOfBody();
509 class TextCompletionList : public CompletionList
513 TextCompletionList(Cursor const & cur, WordList const * list)
514 : buffer_(cur.buffer()), pos_(0), list_(list)
517 virtual ~TextCompletionList() {}
520 virtual bool sorted() const { return true; }
522 virtual size_t size() const
524 return list_->size();
527 virtual docstring const & data(size_t idx) const
529 return list_->word(idx);
534 Buffer const * buffer_;
538 WordList const * list_;
542 bool Text::empty() const
544 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
545 // FIXME: Should we consider the labeled type as empty too?
546 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
550 double Text::spacing(Paragraph const & par) const
552 if (par.params().spacing().isDefault())
553 return owner_->buffer().params().spacing().getValue();
554 return par.params().spacing().getValue();
559 * This breaks a paragraph at the specified position.
560 * The new paragraph will:
561 * - Decrease depth by one (or change layout to default layout) when
562 * keep_layout == false
563 * - keep current depth and layout when keep_layout == true
565 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
568 BufferParams const & bparams = text.inset().buffer().params();
569 ParagraphList & pars = text.paragraphs();
570 // create a new paragraph, and insert into the list
571 ParagraphList::iterator tmp =
572 pars.insert(boost::next(pars.begin(), par_offset + 1),
575 Paragraph & par = pars[par_offset];
577 // remember to set the inset_owner
578 tmp->setInsetOwner(&par.inInset());
579 // without doing that we get a crash when typing <Return> at the
580 // end of a paragraph
581 tmp->setPlainOrDefaultLayout(bparams.documentClass());
583 // layout stays the same with latex-environments
585 tmp->setLayout(par.layout());
586 tmp->setLabelWidthString(par.params().labelWidthString());
587 tmp->params().depth(par.params().depth());
588 } else if (par.params().depth() > 0) {
589 Paragraph const & hook = pars[text.outerHook(par_offset)];
590 tmp->setLayout(hook.layout());
591 // not sure the line below is useful
592 tmp->setLabelWidthString(par.params().labelWidthString());
593 tmp->params().depth(hook.params().depth());
596 bool const isempty = (par.allowEmpty() && par.empty());
598 if (!isempty && (par.size() > pos || par.empty())) {
599 tmp->setLayout(par.layout());
600 tmp->params().align(par.params().align());
601 tmp->setLabelWidthString(par.params().labelWidthString());
603 tmp->params().depth(par.params().depth());
604 tmp->params().noindent(par.params().noindent());
606 // move everything behind the break position
607 // to the new paragraph
609 /* Note: if !keepempty, empty() == true, then we reach
610 * here with size() == 0. So pos_end becomes - 1. This
611 * doesn't cause problems because both loops below
612 * enforce pos <= pos_end and 0 <= pos
614 pos_type pos_end = par.size() - 1;
616 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
617 if (moveItem(par, pos, *tmp, j, bparams)) {
623 // Move over the end-of-par change information
624 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
625 par.setChange(par.size(), Change(bparams.trackChanges ?
626 Change::INSERTED : Change::UNCHANGED));
629 // Make sure that we keep the language when
630 // breaking paragraph.
632 Font changed = tmp->getFirstFontSettings(bparams);
633 Font const & old = par.getFontSettings(bparams, par.size());
634 changed.setLanguage(old.language());
635 tmp->setFont(0, changed);
642 bool const soa = par.params().startOfAppendix();
643 par.params().clear();
644 // do not lose start of appendix marker (bug 4212)
645 par.params().startOfAppendix(soa);
646 par.setPlainOrDefaultLayout(bparams.documentClass());
649 // layout stays the same with latex-environments
651 par.setLayout(tmp->layout());
652 par.setLabelWidthString(tmp->params().labelWidthString());
653 par.params().depth(tmp->params().depth());
658 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
660 LASSERT(this == cur.text(), /**/);
662 Paragraph & cpar = cur.paragraph();
663 pit_type cpit = cur.pit();
665 DocumentClass const & tclass = cur.buffer()->params().documentClass();
666 Layout const & layout = cpar.layout();
668 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
669 if (changeDepthAllowed(cur, DEC_DEPTH))
670 changeDepth(cur, DEC_DEPTH);
672 setLayout(cur, tclass.defaultLayoutName());
676 // a layout change may affect also the following paragraph
677 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
679 // Always break behind a space
680 // It is better to erase the space (Dekel)
681 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
682 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
684 // What should the layout for the new paragraph be?
685 bool keep_layout = inverse_logic ?
686 !layout.isEnvironment()
687 : layout.isEnvironment();
689 // We need to remember this before we break the paragraph, because
690 // that invalidates the layout variable
691 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
693 // we need to set this before we insert the paragraph.
694 bool const isempty = cpar.allowEmpty() && cpar.empty();
696 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
698 // After this, neither paragraph contains any rows!
701 pit_type next_par = cpit + 1;
703 // well this is the caption hack since one caption is really enough
706 // set to standard-layout
707 //FIXME Check if this should be plainLayout() in some cases
708 pars_[cpit].applyLayout(tclass.defaultLayout());
710 // set to standard-layout
711 //FIXME Check if this should be plainLayout() in some cases
712 pars_[next_par].applyLayout(tclass.defaultLayout());
715 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
716 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
717 break; // the character couldn't be deleted physically due to change tracking
720 cur.buffer()->updateLabels();
722 // A singlePar update is not enough in this case.
723 cur.updateFlags(Update::Force);
725 // This check is necessary. Otherwise the new empty paragraph will
726 // be deleted automatically. And it is more friendly for the user!
727 if (cur.pos() != 0 || isempty)
728 setCursor(cur, cur.pit() + 1, 0);
730 setCursor(cur, cur.pit(), 0);
734 // needed to insert the selection
735 void Text::insertStringAsLines(DocIterator const & dit, docstring const & str,
738 BufferParams const & bparams = owner_->buffer().params();
739 pit_type pit = dit.pit();
740 pos_type pos = dit.pos();
742 // insert the string, don't insert doublespace
743 bool space_inserted = true;
744 for (docstring::const_iterator cit = str.begin();
745 cit != str.end(); ++cit) {
746 Paragraph & par = pars_[pit];
748 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
749 lyx::breakParagraph(*this, pit, pos,
750 par.layout().isEnvironment());
753 space_inserted = true;
757 // do not insert consecutive spaces if !free_spacing
758 } else if ((*cit == ' ' || *cit == '\t') &&
759 space_inserted && !par.isFreeSpacing()) {
761 } else if (*cit == '\t') {
762 if (!par.isFreeSpacing()) {
763 // tabs are like spaces here
764 par.insertChar(pos, ' ', font, bparams.trackChanges);
766 space_inserted = true;
768 par.insertChar(pos, *cit, font, bparams.trackChanges);
770 space_inserted = true;
772 } else if (!isPrintable(*cit)) {
773 // Ignore unprintables
776 // just insert the character
777 par.insertChar(pos, *cit, font, bparams.trackChanges);
779 space_inserted = (*cit == ' ');
785 // turn double CR to single CR, others are converted into one
786 // blank. Then insertStringAsLines is called
787 void Text::insertStringAsParagraphs(DocIterator const & dit, docstring const & str,
790 docstring linestr = str;
791 bool newline_inserted = false;
793 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
794 if (linestr[i] == '\n') {
795 if (newline_inserted) {
796 // we know that \r will be ignored by
797 // insertStringAsLines. Of course, it is a dirty
798 // trick, but it works...
799 linestr[i - 1] = '\r';
803 newline_inserted = true;
805 } else if (isPrintable(linestr[i])) {
806 newline_inserted = false;
809 insertStringAsLines(dit, linestr, font);
813 // insert a character, moves all the following breaks in the
814 // same Paragraph one to the right and make a rebreak
815 void Text::insertChar(Cursor & cur, char_type c)
817 LASSERT(this == cur.text(), /**/);
819 cur.recordUndo(INSERT_UNDO);
821 TextMetrics const & tm = cur.bv().textMetrics(this);
822 Buffer const & buffer = *cur.buffer();
823 Paragraph & par = cur.paragraph();
824 // try to remove this
825 pit_type const pit = cur.pit();
827 bool const freeSpacing = par.layout().free_spacing ||
830 if (lyxrc.auto_number) {
831 static docstring const number_operators = from_ascii("+-/*");
832 static docstring const number_unary_operators = from_ascii("+-");
833 static docstring const number_seperators = from_ascii(".,:");
835 if (cur.current_font.fontInfo().number() == FONT_ON) {
836 if (!isDigit(c) && !contains(number_operators, c) &&
837 !(contains(number_seperators, c) &&
839 cur.pos() != cur.lastpos() &&
840 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
841 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
843 number(cur); // Set current_font.number to OFF
844 } else if (isDigit(c) &&
845 cur.real_current_font.isVisibleRightToLeft()) {
846 number(cur); // Set current_font.number to ON
848 if (cur.pos() != 0) {
849 char_type const c = par.getChar(cur.pos() - 1);
850 if (contains(number_unary_operators, c) &&
852 || par.isSeparator(cur.pos() - 2)
853 || par.isNewline(cur.pos() - 2))
855 setCharFont(pit, cur.pos() - 1, cur.current_font,
857 } else if (contains(number_seperators, c)
859 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
860 setCharFont(pit, cur.pos() - 1, cur.current_font,
867 // In Bidi text, we want spaces to be treated in a special way: spaces
868 // which are between words in different languages should get the
869 // paragraph's language; otherwise, spaces should keep the language
870 // they were originally typed in. This is only in effect while typing;
871 // after the text is already typed in, the user can always go back and
872 // explicitly set the language of a space as desired. But 99.9% of the
873 // time, what we're doing here is what the user actually meant.
875 // The following cases are the ones in which the language of the space
876 // should be changed to match that of the containing paragraph. In the
877 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
878 // represents a space, pipe (|) represents the cursor position (so the
879 // character before it is the one just typed in). The different cases
880 // are depicted logically (not visually), from left to right:
885 // Theoretically, there are other situations that we should, perhaps, deal
886 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
887 // point (to understand why, just try to create this situation...).
889 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
890 // get font in front and behind the space in question. But do NOT
891 // use getFont(cur.pos()) because the character c is not inserted yet
892 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
893 Font const & post_space_font = cur.real_current_font;
894 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
895 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
897 if (pre_space_rtl != post_space_rtl) {
898 // Set the space's language to match the language of the
899 // adjacent character whose direction is the paragraph's
900 // direction; don't touch other properties of the font
901 Language const * lang =
902 (pre_space_rtl == par.isRTL(buffer.params())) ?
903 pre_space_font.language() : post_space_font.language();
905 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
906 space_font.setLanguage(lang);
907 par.setFont(cur.pos() - 1, space_font);
911 // Next check, if there will be two blanks together or a blank at
912 // the beginning of a paragraph.
913 // I decided to handle blanks like normal characters, the main
914 // difference are the special checks when calculating the row.fill
915 // (blank does not count at the end of a row) and the check here
917 // When the free-spacing option is set for the current layout,
918 // disable the double-space checking
919 if (!freeSpacing && isLineSeparatorChar(c)) {
920 if (cur.pos() == 0) {
921 static bool sent_space_message = false;
922 if (!sent_space_message) {
923 cur.message(_("You cannot insert a space at the "
924 "beginning of a paragraph. Please read the Tutorial."));
925 sent_space_message = true;
929 LASSERT(cur.pos() > 0, /**/);
930 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
931 && !par.isDeleted(cur.pos() - 1)) {
932 static bool sent_space_message = false;
933 if (!sent_space_message) {
934 cur.message(_("You cannot type two spaces this way. "
935 "Please read the Tutorial."));
936 sent_space_message = true;
942 par.insertChar(cur.pos(), c, cur.current_font,
943 cur.buffer()->params().trackChanges);
944 cur.checkBufferStructure();
946 // cur.updateFlags(Update::Force);
947 bool boundary = cur.boundary()
948 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
949 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
954 void Text::charInserted(Cursor & cur)
956 Paragraph & par = cur.paragraph();
958 // Here we call finishUndo for every 20 characters inserted.
959 // This is from my experience how emacs does it. (Lgb)
960 if (undo_counter_ < 20) {
967 // register word if a non-letter was entered
969 && !par.isWordSeparator(cur.pos() - 2)
970 && par.isWordSeparator(cur.pos() - 1)) {
971 // get the word in front of cursor
972 LASSERT(this == cur.text(), /**/);
973 cur.paragraph().updateWords();
978 // the cursor set functions have a special mechanism. When they
979 // realize, that you left an empty paragraph, they will delete it.
981 bool Text::cursorForwardOneWord(Cursor & cur)
983 LASSERT(this == cur.text(), /**/);
985 pos_type const lastpos = cur.lastpos();
986 pit_type pit = cur.pit();
987 pos_type pos = cur.pos();
988 Paragraph const & par = cur.paragraph();
990 // Paragraph boundary is a word boundary
991 if (pos == lastpos) {
992 if (pit != cur.lastpit())
993 return setCursor(cur, pit + 1, 0);
998 if (lyxrc.mac_like_word_movement) {
999 // Skip through trailing punctuation and spaces.
1000 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1003 // Skip over either a non-char inset or a full word
1004 if (pos != lastpos && par.isWordSeparator(pos))
1006 else while (pos != lastpos && !par.isWordSeparator(pos))
1009 LASSERT(pos < lastpos, /**/); // see above
1010 if (!par.isWordSeparator(pos))
1011 while (pos != lastpos && !par.isWordSeparator(pos))
1013 else if (par.isChar(pos))
1014 while (pos != lastpos && par.isChar(pos))
1016 else if (!par.isSpace(pos)) // non-char inset
1019 // Skip over white space
1020 while (pos != lastpos && par.isSpace(pos))
1024 return setCursor(cur, pit, pos);
1028 bool Text::cursorBackwardOneWord(Cursor & cur)
1030 LASSERT(this == cur.text(), /**/);
1032 pit_type pit = cur.pit();
1033 pos_type pos = cur.pos();
1034 Paragraph & par = cur.paragraph();
1036 // Paragraph boundary is a word boundary
1037 if (pos == 0 && pit != 0)
1038 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1040 if (lyxrc.mac_like_word_movement) {
1041 // Skip through punctuation and spaces.
1042 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1045 // Skip over either a non-char inset or a full word
1046 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1048 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1051 // Skip over white space
1052 while (pos != 0 && par.isSpace(pos - 1))
1055 if (pos != 0 && !par.isWordSeparator(pos - 1))
1056 while (pos != 0 && !par.isWordSeparator(pos - 1))
1058 else if (pos != 0 && par.isChar(pos - 1))
1059 while (pos != 0 && par.isChar(pos - 1))
1061 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1065 return setCursor(cur, pit, pos);
1069 bool Text::cursorVisLeftOneWord(Cursor & cur)
1071 LASSERT(this == cur.text(), /**/);
1073 pos_type left_pos, right_pos;
1074 bool left_is_letter, right_is_letter;
1076 Cursor temp_cur = cur;
1078 // always try to move at least once...
1079 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1081 // collect some information about current cursor position
1082 temp_cur.getSurroundingPos(left_pos, right_pos);
1084 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1086 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1088 // if we're not at a letter/non-letter boundary, continue moving
1089 if (left_is_letter == right_is_letter)
1092 // we should stop when we have an LTR word on our right or an RTL word
1094 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1095 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1096 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1097 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1101 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1102 true, temp_cur.boundary());
1106 bool Text::cursorVisRightOneWord(Cursor & cur)
1108 LASSERT(this == cur.text(), /**/);
1110 pos_type left_pos, right_pos;
1111 bool left_is_letter, right_is_letter;
1113 Cursor temp_cur = cur;
1115 // always try to move at least once...
1116 while (temp_cur.posVisRight(true /* skip_inset */)) {
1118 // collect some information about current cursor position
1119 temp_cur.getSurroundingPos(left_pos, right_pos);
1121 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1123 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1125 // if we're not at a letter/non-letter boundary, continue moving
1126 if (left_is_letter == right_is_letter)
1129 // we should stop when we have an LTR word on our right or an RTL word
1131 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1132 temp_cur.buffer()->params(),
1133 left_pos).isRightToLeft())
1134 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1135 temp_cur.buffer()->params(),
1136 right_pos).isRightToLeft()))
1140 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1141 true, temp_cur.boundary());
1145 void Text::selectWord(Cursor & cur, word_location loc)
1147 LASSERT(this == cur.text(), /**/);
1148 CursorSlice from = cur.top();
1149 CursorSlice to = cur.top();
1150 getWord(from, to, loc);
1151 if (cur.top() != from)
1152 setCursor(cur, from.pit(), from.pos());
1155 if (!cur.selection())
1157 setCursor(cur, to.pit(), to.pos());
1159 cur.setWordSelection(true);
1163 void Text::selectAll(Cursor & cur)
1165 LASSERT(this == cur.text(), /**/);
1166 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1168 // If the cursor is at the beginning, make sure the cursor ends there
1169 if (cur.pit() == 0 && cur.pos() == 0) {
1170 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1172 setCursor(cur, 0, 0);
1174 setCursor(cur, 0, 0);
1176 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1182 // Select the word currently under the cursor when no
1183 // selection is currently set
1184 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1186 LASSERT(this == cur.text(), /**/);
1187 if (cur.selection())
1189 selectWord(cur, loc);
1190 return cur.selection();
1194 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1196 LASSERT(this == cur.text(), /**/);
1198 if (!cur.selection()) {
1199 bool const changed = cur.paragraph().isChanged(cur.pos());
1200 if (!(changed && findNextChange(&cur.bv())))
1204 cur.recordUndoSelection();
1206 pit_type begPit = cur.selectionBegin().pit();
1207 pit_type endPit = cur.selectionEnd().pit();
1209 pos_type begPos = cur.selectionBegin().pos();
1210 pos_type endPos = cur.selectionEnd().pos();
1212 // keep selection info, because endPos becomes invalid after the first loop
1213 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1215 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1217 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1218 pos_type parSize = pars_[pit].size();
1220 // ignore empty paragraphs; otherwise, an assertion will fail for
1221 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1225 // do not consider first paragraph if the cursor starts at pos size()
1226 if (pit == begPit && begPos == parSize)
1229 // do not consider last paragraph if the cursor ends at pos 0
1230 if (pit == endPit && endPos == 0)
1231 break; // last iteration anyway
1233 pos_type left = (pit == begPit ? begPos : 0);
1234 pos_type right = (pit == endPit ? endPos : parSize);
1237 pars_[pit].acceptChanges(left, right);
1239 pars_[pit].rejectChanges(left, right);
1243 // next, accept/reject imaginary end-of-par characters
1245 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1246 pos_type pos = pars_[pit].size();
1248 // skip if the selection ends before the end-of-par
1249 if (pit == endPit && endsBeforeEndOfPar)
1250 break; // last iteration anyway
1252 // skip if this is not the last paragraph of the document
1253 // note: the user should be able to accept/reject the par break of the last par!
1254 if (pit == endPit && pit + 1 != int(pars_.size()))
1255 break; // last iteration anway
1258 if (pars_[pit].isInserted(pos)) {
1259 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1260 } else if (pars_[pit].isDeleted(pos)) {
1261 if (pit + 1 == int(pars_.size())) {
1262 // we cannot remove a par break at the end of the last paragraph;
1263 // instead, we mark it unchanged
1264 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1266 mergeParagraph(cur.buffer()->params(), pars_, pit);
1272 if (pars_[pit].isDeleted(pos)) {
1273 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1274 } else if (pars_[pit].isInserted(pos)) {
1275 if (pit + 1 == int(pars_.size())) {
1276 // we mark the par break at the end of the last paragraph unchanged
1277 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1279 mergeParagraph(cur.buffer()->params(), pars_, pit);
1287 // finally, invoke the DEPM
1289 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1294 cur.clearSelection();
1295 setCursorIntern(cur, begPit, begPos);
1296 cur.updateFlags(Update::Force);
1297 cur.buffer()->updateLabels();
1301 void Text::acceptChanges()
1303 BufferParams const & bparams = owner_->buffer().params();
1304 lyx::acceptChanges(pars_, bparams);
1305 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1309 void Text::rejectChanges()
1311 BufferParams const & bparams = owner_->buffer().params();
1312 pit_type pars_size = static_cast<pit_type>(pars_.size());
1314 // first, reject changes within each individual paragraph
1315 // (do not consider end-of-par)
1316 for (pit_type pit = 0; pit < pars_size; ++pit) {
1317 if (!pars_[pit].empty()) // prevent assertion failure
1318 pars_[pit].rejectChanges(0, pars_[pit].size());
1321 // next, reject imaginary end-of-par characters
1322 for (pit_type pit = 0; pit < pars_size; ++pit) {
1323 pos_type pos = pars_[pit].size();
1325 if (pars_[pit].isDeleted(pos)) {
1326 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1327 } else if (pars_[pit].isInserted(pos)) {
1328 if (pit == pars_size - 1) {
1329 // we mark the par break at the end of the last
1330 // paragraph unchanged
1331 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1333 mergeParagraph(bparams, pars_, pit);
1340 // finally, invoke the DEPM
1341 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1345 void Text::deleteWordForward(Cursor & cur)
1347 LASSERT(this == cur.text(), /**/);
1348 if (cur.lastpos() == 0)
1352 cur.setSelection(true);
1353 cursorForwardOneWord(cur);
1355 cutSelection(cur, true, false);
1356 cur.checkBufferStructure();
1361 void Text::deleteWordBackward(Cursor & cur)
1363 LASSERT(this == cur.text(), /**/);
1364 if (cur.lastpos() == 0)
1365 cursorBackward(cur);
1368 cur.setSelection(true);
1369 cursorBackwardOneWord(cur);
1371 cutSelection(cur, true, false);
1372 cur.checkBufferStructure();
1377 // Kill to end of line.
1378 void Text::changeCase(Cursor & cur, TextCase action)
1380 LASSERT(this == cur.text(), /**/);
1384 bool gotsel = false;
1385 if (cur.selection()) {
1386 from = cur.selBegin();
1391 getWord(from, to, PARTIAL_WORD);
1392 cursorForwardOneWord(cur);
1395 cur.recordUndoSelection();
1397 pit_type begPit = from.pit();
1398 pit_type endPit = to.pit();
1400 pos_type begPos = from.pos();
1401 pos_type endPos = to.pos();
1403 pos_type right = 0; // needed after the for loop
1405 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1406 Paragraph & par = pars_[pit];
1407 pos_type const pos = (pit == begPit ? begPos : 0);
1408 right = (pit == endPit ? endPos : par.size());
1409 par.changeCase(cur.buffer()->params(), pos, right, action);
1412 // the selection may have changed due to logically-only deleted chars
1414 setCursor(cur, begPit, begPos);
1416 setCursor(cur, endPit, right);
1419 setCursor(cur, endPit, right);
1421 cur.checkBufferStructure();
1425 bool Text::handleBibitems(Cursor & cur)
1427 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1433 BufferParams const & bufparams = cur.buffer()->params();
1434 Paragraph const & par = cur.paragraph();
1435 Cursor prevcur = cur;
1436 if (cur.pit() > 0) {
1438 prevcur.pos() = prevcur.lastpos();
1440 Paragraph const & prevpar = prevcur.paragraph();
1442 // if a bibitem is deleted, merge with previous paragraph
1443 // if this is a bibliography item as well
1444 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1445 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1446 mergeParagraph(bufparams, cur.text()->paragraphs(),
1448 cur.buffer()->updateLabels();
1449 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1450 cur.updateFlags(Update::Force);
1454 // otherwise reset to default
1455 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1460 bool Text::erase(Cursor & cur)
1462 LASSERT(this == cur.text(), return false);
1463 bool needsUpdate = false;
1464 Paragraph & par = cur.paragraph();
1466 if (cur.pos() != cur.lastpos()) {
1467 // this is the code for a normal delete, not pasting
1469 cur.recordUndo(DELETE_UNDO);
1470 bool const was_inset = cur.paragraph().isInset(cur.pos());
1471 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1472 // the character has been logically deleted only => skip it
1473 cur.top().forwardPos();
1476 cur.buffer()->updateLabels();
1478 cur.checkBufferStructure();
1481 if (cur.pit() == cur.lastpit())
1482 return dissolveInset(cur);
1484 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1485 par.setChange(cur.pos(), Change(Change::DELETED));
1489 setCursorIntern(cur, cur.pit() + 1, 0);
1490 needsUpdate = backspacePos0(cur);
1494 needsUpdate |= handleBibitems(cur);
1497 // Make sure the cursor is correct. Is this really needed?
1498 // No, not really... at least not here!
1499 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1500 cur.checkBufferStructure();
1507 bool Text::backspacePos0(Cursor & cur)
1509 LASSERT(this == cur.text(), /**/);
1513 bool needsUpdate = false;
1515 BufferParams const & bufparams = cur.buffer()->params();
1516 DocumentClass const & tclass = bufparams.documentClass();
1517 ParagraphList & plist = cur.text()->paragraphs();
1518 Paragraph const & par = cur.paragraph();
1519 Cursor prevcur = cur;
1521 prevcur.pos() = prevcur.lastpos();
1522 Paragraph const & prevpar = prevcur.paragraph();
1524 // is it an empty paragraph?
1525 if (cur.lastpos() == 0
1526 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1527 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1528 plist.erase(boost::next(plist.begin(), cur.pit()));
1531 // is previous par empty?
1532 else if (prevcur.lastpos() == 0
1533 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1534 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1535 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1538 // Pasting is not allowed, if the paragraphs have different
1539 // layouts. I think it is a real bug of all other
1540 // word processors to allow it. It confuses the user.
1541 // Correction: Pasting is always allowed with standard-layout
1542 // or the empty layout.
1543 else if (par.layout() == prevpar.layout()
1544 || tclass.isDefaultLayout(par.layout())
1545 || tclass.isPlainLayout(par.layout())) {
1546 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1547 mergeParagraph(bufparams, plist, prevcur.pit());
1552 cur.buffer()->updateLabels();
1553 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1560 bool Text::backspace(Cursor & cur)
1562 LASSERT(this == cur.text(), /**/);
1563 bool needsUpdate = false;
1564 if (cur.pos() == 0) {
1566 return dissolveInset(cur);
1568 Paragraph & prev_par = pars_[cur.pit() - 1];
1570 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1571 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1572 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1575 // The cursor is at the beginning of a paragraph, so
1576 // the backspace will collapse two paragraphs into one.
1577 needsUpdate = backspacePos0(cur);
1580 // this is the code for a normal backspace, not pasting
1582 cur.recordUndo(DELETE_UNDO);
1583 // We used to do cursorBackwardIntern() here, but it is
1584 // not a good idea since it triggers the auto-delete
1585 // mechanism. So we do a cursorBackwardIntern()-lite,
1586 // without the dreaded mechanism. (JMarc)
1587 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1588 false, cur.boundary());
1589 bool const was_inset = cur.paragraph().isInset(cur.pos());
1590 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1592 cur.buffer()->updateLabels();
1594 cur.checkBufferStructure();
1597 if (cur.pos() == cur.lastpos())
1598 cur.setCurrentFont();
1600 needsUpdate |= handleBibitems(cur);
1602 // A singlePar update is not enough in this case.
1603 // cur.updateFlags(Update::Force);
1604 setCursor(cur.top(), cur.pit(), cur.pos());
1610 bool Text::dissolveInset(Cursor & cur)
1612 LASSERT(this == cur.text(), return false);
1614 if (isMainText() || cur.inset().nargs() != 1)
1617 cur.recordUndoInset();
1619 cur.selHandle(false);
1621 pos_type spos = cur.pos();
1622 pit_type spit = cur.pit();
1623 ParagraphList plist;
1624 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1625 plist = paragraphs();
1627 // store cursor offset
1631 Buffer & b = *cur.buffer();
1632 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1633 if (!plist.empty()) {
1634 // ERT paragraphs have the Language latex_language.
1635 // This is invalid outside of ERT, so we need to
1636 // change it to the buffer language.
1637 ParagraphList::iterator it = plist.begin();
1638 ParagraphList::iterator it_end = plist.end();
1639 for (; it != it_end; it++)
1640 it->changeLanguage(b.params(), latex_language, b.language());
1642 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1643 b.errorList("Paste"));
1645 cur.pit() = min(cur.lastpit(), spit);
1646 cur.pos() = min(cur.lastpos(), spos);
1648 // this is the least that needs to be done (bug 6003)
1649 // in the above case, pasteParagraphList handles this
1650 cur.buffer()->updateLabels();
1652 // Ensure the current language is set correctly (bug 6292)
1653 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1654 cur.clearSelection();
1660 void Text::getWord(CursorSlice & from, CursorSlice & to,
1661 word_location const loc) const
1664 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1668 void Text::write(ostream & os) const
1670 Buffer const & buf = owner_->buffer();
1671 ParagraphList::const_iterator pit = paragraphs().begin();
1672 ParagraphList::const_iterator end = paragraphs().end();
1674 for (; pit != end; ++pit)
1675 pit->write(os, buf.params(), dth);
1677 // Close begin_deeper
1678 for(; dth > 0; --dth)
1679 os << "\n\\end_deeper";
1683 bool Text::read(Lexer & lex,
1684 ErrorList & errorList, InsetText * insetPtr)
1686 Buffer const & buf = owner_->buffer();
1687 depth_type depth = 0;
1690 while (lex.isOK()) {
1692 string const token = lex.getString();
1697 if (token == "\\end_inset")
1700 if (token == "\\end_body")
1703 if (token == "\\begin_body")
1706 if (token == "\\end_document") {
1711 if (token == "\\begin_layout") {
1712 lex.pushToken(token);
1715 par.setInsetOwner(insetPtr);
1716 par.params().depth(depth);
1717 par.setFont(0, Font(inherit_font, buf.params().language));
1718 pars_.push_back(par);
1719 readParagraph(pars_.back(), lex, errorList);
1721 // register the words in the global word list
1722 pars_.back().updateWords();
1723 } else if (token == "\\begin_deeper") {
1725 } else if (token == "\\end_deeper") {
1727 lex.printError("\\end_deeper: " "depth is already null");
1731 LYXERR0("Handling unknown body token: `" << token << '\'');
1735 // avoid a crash on weird documents (bug 4859)
1736 if (pars_.empty()) {
1738 par.setInsetOwner(insetPtr);
1739 par.params().depth(depth);
1740 par.setFont(0, Font(inherit_font,
1741 buf.params().language));
1742 par.setPlainOrDefaultLayout(buf.params().documentClass());
1743 pars_.push_back(par);
1749 // Returns the current font and depth as a message.
1750 docstring Text::currentState(Cursor const & cur) const
1752 LASSERT(this == cur.text(), /**/);
1753 Buffer & buf = *cur.buffer();
1754 Paragraph const & par = cur.paragraph();
1755 odocstringstream os;
1757 if (buf.params().trackChanges)
1758 os << _("[Change Tracking] ");
1760 Change change = par.lookupChange(cur.pos());
1762 if (change.changed()) {
1763 Author const & a = buf.params().authors().get(change.author);
1764 os << _("Change: ") << a.name();
1765 if (!a.email().empty())
1766 os << " (" << a.email() << ")";
1767 // FIXME ctime is english, we should translate that
1768 os << _(" at ") << ctime(&change.changetime);
1772 // I think we should only show changes from the default
1774 // No, from the document font (MV)
1775 Font font = cur.real_current_font;
1776 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1778 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1780 // The paragraph depth
1781 int depth = cur.paragraph().getDepth();
1783 os << bformat(_(", Depth: %1$d"), depth);
1785 // The paragraph spacing, but only if different from
1787 Spacing const & spacing = par.params().spacing();
1788 if (!spacing.isDefault()) {
1789 os << _(", Spacing: ");
1790 switch (spacing.getSpace()) {
1791 case Spacing::Single:
1794 case Spacing::Onehalf:
1797 case Spacing::Double:
1800 case Spacing::Other:
1801 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1803 case Spacing::Default:
1804 // should never happen, do nothing
1809 #ifdef DEVEL_VERSION
1810 os << _(", Inset: ") << &cur.inset();
1811 os << _(", Paragraph: ") << cur.pit();
1812 os << _(", Id: ") << par.id();
1813 os << _(", Position: ") << cur.pos();
1814 // FIXME: Why is the check for par.size() needed?
1815 // We are called with cur.pos() == par.size() quite often.
1816 if (!par.empty() && cur.pos() < par.size()) {
1817 // Force output of code point, not character
1818 size_t const c = par.getChar(cur.pos());
1819 os << _(", Char: 0x") << hex << c;
1821 os << _(", Boundary: ") << cur.boundary();
1822 // Row & row = cur.textRow();
1823 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1829 docstring Text::getPossibleLabel(Cursor const & cur) const
1831 pit_type pit = cur.pit();
1833 Layout const * layout = &(pars_[pit].layout());
1836 docstring par_text = pars_[pit].asString();
1838 // the return string of math matrices might contain linebreaks
1839 par_text = subst(par_text, '\n', '-');
1840 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1841 if (par_text.empty())
1844 par_text = split(par_text, head, ' ');
1845 // Is it legal to use spaces in labels ?
1851 // No need for a prefix if the user said so.
1852 if (lyxrc.label_init_length <= 0)
1855 // Will contain the label type.
1858 // For section, subsection, etc...
1859 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1860 Layout const * layout2 = &(pars_[pit - 1].layout());
1861 if (layout2->latextype != LATEX_PARAGRAPH) {
1866 if (layout->latextype != LATEX_PARAGRAPH)
1867 name = from_ascii(layout->latexname());
1869 // for captions, we just take the caption type
1870 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1872 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1874 // If none of the above worked, we'll see if we're inside various
1875 // types of insets and take our abbreviation from them.
1877 InsetCode const codes[] = {
1882 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1883 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1885 name = float_inset->name();
1891 // Create a correct prefix for prettyref
1892 if (name == "theorem")
1893 name = from_ascii("thm");
1894 else if (name == "Foot")
1895 name = from_ascii("fn");
1896 else if (name == "listing")
1897 name = from_ascii("lst");
1900 text = name.substr(0, 3) + ':' + text;
1906 docstring Text::asString(int options) const
1908 return asString(0, pars_.size(), options);
1912 docstring Text::asString(pit_type beg, pit_type end, int options) const
1914 size_t i = size_t(beg);
1915 docstring str = pars_[i].asString(options);
1916 for (++i; i != size_t(end); ++i) {
1918 str += pars_[i].asString(options);
1925 void Text::charsTranspose(Cursor & cur)
1927 LASSERT(this == cur.text(), /**/);
1929 pos_type pos = cur.pos();
1931 // If cursor is at beginning or end of paragraph, do nothing.
1932 if (pos == cur.lastpos() || pos == 0)
1935 Paragraph & par = cur.paragraph();
1937 // Get the positions of the characters to be transposed.
1938 pos_type pos1 = pos - 1;
1939 pos_type pos2 = pos;
1941 // In change tracking mode, ignore deleted characters.
1942 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1944 if (pos2 == cur.lastpos())
1947 while (pos1 >= 0 && par.isDeleted(pos1))
1952 // Don't do anything if one of the "characters" is not regular text.
1953 if (par.isInset(pos1) || par.isInset(pos2))
1956 // Store the characters to be transposed (including font information).
1957 char_type const char1 = par.getChar(pos1);
1959 par.getFontSettings(cur.buffer()->params(), pos1);
1961 char_type const char2 = par.getChar(pos2);
1963 par.getFontSettings(cur.buffer()->params(), pos2);
1965 // And finally, we are ready to perform the transposition.
1966 // Track the changes if Change Tracking is enabled.
1967 bool const trackChanges = cur.buffer()->params().trackChanges;
1971 par.eraseChar(pos2, trackChanges);
1972 par.eraseChar(pos1, trackChanges);
1973 par.insertChar(pos1, char2, font2, trackChanges);
1974 par.insertChar(pos2, char1, font1, trackChanges);
1976 cur.checkBufferStructure();
1978 // After the transposition, move cursor to after the transposition.
1979 setCursor(cur, cur.pit(), pos2);
1984 DocIterator Text::macrocontextPosition() const
1986 return macrocontext_position_;
1990 void Text::setMacrocontextPosition(DocIterator const & pos)
1992 macrocontext_position_ = pos;
1996 docstring Text::previousWord(CursorSlice const & sl) const
1998 CursorSlice from = sl;
1999 CursorSlice to = sl;
2000 getWord(from, to, PREVIOUS_WORD);
2001 if (sl == from || to == from)
2004 Paragraph const & par = sl.paragraph();
2005 return par.asString(from.pos(), to.pos());
2009 bool Text::completionSupported(Cursor const & cur) const
2011 Paragraph const & par = cur.paragraph();
2012 return cur.pos() > 0
2013 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2014 && !par.isWordSeparator(cur.pos() - 1);
2018 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2020 WordList const * list = theWordList(*cur.getFont().language());
2021 return new TextCompletionList(cur, list);
2025 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2027 LASSERT(cur.bv().cursor() == cur, /**/);
2029 cur.bv().cursor() = cur;
2030 if (!(cur.disp_.update() & Update::Force))
2031 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2036 docstring Text::completionPrefix(Cursor const & cur) const
2038 return previousWord(cur.top());