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();
525 class TextCompletionList : public CompletionList
529 TextCompletionList(Cursor const & cur, WordList const * list)
530 : buffer_(cur.buffer()), pos_(0), list_(list)
533 virtual ~TextCompletionList() {}
536 virtual bool sorted() const { return true; }
538 virtual size_t size() const
540 return list_->size();
543 virtual docstring const & data(size_t idx) const
545 return list_->word(idx);
550 Buffer const * buffer_;
554 WordList const * list_;
558 bool Text::empty() const
560 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
561 // FIXME: Should we consider the labeled type as empty too?
562 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
566 double Text::spacing(Paragraph const & par) const
568 if (par.params().spacing().isDefault())
569 return owner_->buffer().params().spacing().getValue();
570 return par.params().spacing().getValue();
575 * This breaks a paragraph at the specified position.
576 * The new paragraph will:
577 * - Decrease depth by one (or change layout to default layout) when
578 * keep_layout == false
579 * - keep current depth and layout when keep_layout == true
581 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
584 BufferParams const & bparams = text.inset().buffer().params();
585 ParagraphList & pars = text.paragraphs();
586 // create a new paragraph, and insert into the list
587 ParagraphList::iterator tmp =
588 pars.insert(boost::next(pars.begin(), par_offset + 1),
591 Paragraph & par = pars[par_offset];
593 // remember to set the inset_owner
594 tmp->setInsetOwner(&par.inInset());
595 // without doing that we get a crash when typing <Return> at the
596 // end of a paragraph
597 tmp->setPlainOrDefaultLayout(bparams.documentClass());
599 // layout stays the same with latex-environments
601 tmp->setLayout(par.layout());
602 tmp->setLabelWidthString(par.params().labelWidthString());
603 tmp->params().depth(par.params().depth());
604 } else if (par.params().depth() > 0) {
605 Paragraph const & hook = pars[text.outerHook(par_offset)];
606 tmp->setLayout(hook.layout());
607 // not sure the line below is useful
608 tmp->setLabelWidthString(par.params().labelWidthString());
609 tmp->params().depth(hook.params().depth());
612 bool const isempty = (par.allowEmpty() && par.empty());
614 if (!isempty && (par.size() > pos || par.empty())) {
615 tmp->setLayout(par.layout());
616 tmp->params().align(par.params().align());
617 tmp->setLabelWidthString(par.params().labelWidthString());
619 tmp->params().depth(par.params().depth());
620 tmp->params().noindent(par.params().noindent());
622 // move everything behind the break position
623 // to the new paragraph
625 /* Note: if !keepempty, empty() == true, then we reach
626 * here with size() == 0. So pos_end becomes - 1. This
627 * doesn't cause problems because both loops below
628 * enforce pos <= pos_end and 0 <= pos
630 pos_type pos_end = par.size() - 1;
632 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
633 if (moveItem(par, pos, *tmp, j, bparams)) {
639 // Move over the end-of-par change information
640 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
641 par.setChange(par.size(), Change(bparams.trackChanges ?
642 Change::INSERTED : Change::UNCHANGED));
645 // Make sure that we keep the language when
646 // breaking paragraph.
648 Font changed = tmp->getFirstFontSettings(bparams);
649 Font const & old = par.getFontSettings(bparams, par.size());
650 changed.setLanguage(old.language());
651 tmp->setFont(0, changed);
658 bool const soa = par.params().startOfAppendix();
659 par.params().clear();
660 // do not lose start of appendix marker (bug 4212)
661 par.params().startOfAppendix(soa);
662 par.setPlainOrDefaultLayout(bparams.documentClass());
665 // layout stays the same with latex-environments
667 par.setLayout(tmp->layout());
668 par.setLabelWidthString(tmp->params().labelWidthString());
669 par.params().depth(tmp->params().depth());
674 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
676 LASSERT(this == cur.text(), /**/);
678 Paragraph & cpar = cur.paragraph();
679 pit_type cpit = cur.pit();
681 DocumentClass const & tclass = cur.buffer()->params().documentClass();
682 Layout const & layout = cpar.layout();
684 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
685 if (changeDepthAllowed(cur, DEC_DEPTH))
686 changeDepth(cur, DEC_DEPTH);
688 setLayout(cur, tclass.defaultLayoutName());
692 // a layout change may affect also the following paragraph
693 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
695 // Always break behind a space
696 // It is better to erase the space (Dekel)
697 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
698 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
700 // What should the layout for the new paragraph be?
701 bool keep_layout = inverse_logic ?
702 !layout.isEnvironment()
703 : layout.isEnvironment();
705 // We need to remember this before we break the paragraph, because
706 // that invalidates the layout variable
707 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
709 // we need to set this before we insert the paragraph.
710 bool const isempty = cpar.allowEmpty() && cpar.empty();
712 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
714 // After this, neither paragraph contains any rows!
717 pit_type next_par = cpit + 1;
719 // well this is the caption hack since one caption is really enough
722 // set to standard-layout
723 //FIXME Check if this should be plainLayout() in some cases
724 pars_[cpit].applyLayout(tclass.defaultLayout());
726 // set to standard-layout
727 //FIXME Check if this should be plainLayout() in some cases
728 pars_[next_par].applyLayout(tclass.defaultLayout());
731 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
732 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
733 break; // the character couldn't be deleted physically due to change tracking
736 // A singlePar update is not enough in this case.
737 cur.screenUpdateFlags(Update::Force);
738 cur.forceBufferUpdate();
740 // This check is necessary. Otherwise the new empty paragraph will
741 // be deleted automatically. And it is more friendly for the user!
742 if (cur.pos() != 0 || isempty)
743 setCursor(cur, cur.pit() + 1, 0);
745 setCursor(cur, cur.pit(), 0);
749 // needed to insert the selection
750 void Text::insertStringAsLines(DocIterator const & dit, docstring const & str,
753 BufferParams const & bparams = owner_->buffer().params();
754 pit_type pit = dit.pit();
755 pos_type pos = dit.pos();
757 // insert the string, don't insert doublespace
758 bool space_inserted = true;
759 for (docstring::const_iterator cit = str.begin();
760 cit != str.end(); ++cit) {
761 Paragraph & par = pars_[pit];
763 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
764 lyx::breakParagraph(*this, pit, pos,
765 par.layout().isEnvironment());
768 space_inserted = true;
772 // do not insert consecutive spaces if !free_spacing
773 } else if ((*cit == ' ' || *cit == '\t') &&
774 space_inserted && !par.isFreeSpacing()) {
776 } else if (*cit == '\t') {
777 if (!par.isFreeSpacing()) {
778 // tabs are like spaces here
779 par.insertChar(pos, ' ', font, bparams.trackChanges);
781 space_inserted = true;
783 par.insertChar(pos, *cit, font, bparams.trackChanges);
785 space_inserted = true;
787 } else if (!isPrintable(*cit)) {
788 // Ignore unprintables
791 // just insert the character
792 par.insertChar(pos, *cit, font, bparams.trackChanges);
794 space_inserted = (*cit == ' ');
800 // turn double CR to single CR, others are converted into one
801 // blank. Then insertStringAsLines is called
802 void Text::insertStringAsParagraphs(DocIterator const & dit, docstring const & str,
805 docstring linestr = str;
806 bool newline_inserted = false;
808 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
809 if (linestr[i] == '\n') {
810 if (newline_inserted) {
811 // we know that \r will be ignored by
812 // insertStringAsLines. Of course, it is a dirty
813 // trick, but it works...
814 linestr[i - 1] = '\r';
818 newline_inserted = true;
820 } else if (isPrintable(linestr[i])) {
821 newline_inserted = false;
824 insertStringAsLines(dit, linestr, font);
828 // insert a character, moves all the following breaks in the
829 // same Paragraph one to the right and make a rebreak
830 void Text::insertChar(Cursor & cur, char_type c)
832 LASSERT(this == cur.text(), /**/);
834 cur.recordUndo(INSERT_UNDO);
836 TextMetrics const & tm = cur.bv().textMetrics(this);
837 Buffer const & buffer = *cur.buffer();
838 Paragraph & par = cur.paragraph();
839 // try to remove this
840 pit_type const pit = cur.pit();
842 bool const freeSpacing = par.layout().free_spacing ||
845 if (lyxrc.auto_number) {
846 static docstring const number_operators = from_ascii("+-/*");
847 static docstring const number_unary_operators = from_ascii("+-");
848 static docstring const number_seperators = from_ascii(".,:");
850 if (cur.current_font.fontInfo().number() == FONT_ON) {
851 if (!isDigit(c) && !contains(number_operators, c) &&
852 !(contains(number_seperators, c) &&
854 cur.pos() != cur.lastpos() &&
855 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
856 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
858 number(cur); // Set current_font.number to OFF
859 } else if (isDigit(c) &&
860 cur.real_current_font.isVisibleRightToLeft()) {
861 number(cur); // Set current_font.number to ON
863 if (cur.pos() != 0) {
864 char_type const c = par.getChar(cur.pos() - 1);
865 if (contains(number_unary_operators, c) &&
867 || par.isSeparator(cur.pos() - 2)
868 || par.isNewline(cur.pos() - 2))
870 setCharFont(pit, cur.pos() - 1, cur.current_font,
872 } else if (contains(number_seperators, c)
874 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
875 setCharFont(pit, cur.pos() - 1, cur.current_font,
882 // In Bidi text, we want spaces to be treated in a special way: spaces
883 // which are between words in different languages should get the
884 // paragraph's language; otherwise, spaces should keep the language
885 // they were originally typed in. This is only in effect while typing;
886 // after the text is already typed in, the user can always go back and
887 // explicitly set the language of a space as desired. But 99.9% of the
888 // time, what we're doing here is what the user actually meant.
890 // The following cases are the ones in which the language of the space
891 // should be changed to match that of the containing paragraph. In the
892 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
893 // represents a space, pipe (|) represents the cursor position (so the
894 // character before it is the one just typed in). The different cases
895 // are depicted logically (not visually), from left to right:
900 // Theoretically, there are other situations that we should, perhaps, deal
901 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
902 // point (to understand why, just try to create this situation...).
904 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
905 // get font in front and behind the space in question. But do NOT
906 // use getFont(cur.pos()) because the character c is not inserted yet
907 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
908 Font const & post_space_font = cur.real_current_font;
909 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
910 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
912 if (pre_space_rtl != post_space_rtl) {
913 // Set the space's language to match the language of the
914 // adjacent character whose direction is the paragraph's
915 // direction; don't touch other properties of the font
916 Language const * lang =
917 (pre_space_rtl == par.isRTL(buffer.params())) ?
918 pre_space_font.language() : post_space_font.language();
920 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
921 space_font.setLanguage(lang);
922 par.setFont(cur.pos() - 1, space_font);
926 // Next check, if there will be two blanks together or a blank at
927 // the beginning of a paragraph.
928 // I decided to handle blanks like normal characters, the main
929 // difference are the special checks when calculating the row.fill
930 // (blank does not count at the end of a row) and the check here
932 // When the free-spacing option is set for the current layout,
933 // disable the double-space checking
934 if (!freeSpacing && isLineSeparatorChar(c)) {
935 if (cur.pos() == 0) {
936 static bool sent_space_message = false;
937 if (!sent_space_message) {
938 cur.message(_("You cannot insert a space at the "
939 "beginning of a paragraph. Please read the Tutorial."));
940 sent_space_message = true;
944 LASSERT(cur.pos() > 0, /**/);
945 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
946 && !par.isDeleted(cur.pos() - 1)) {
947 static bool sent_space_message = false;
948 if (!sent_space_message) {
949 cur.message(_("You cannot type two spaces this way. "
950 "Please read the Tutorial."));
951 sent_space_message = true;
957 par.insertChar(cur.pos(), c, cur.current_font,
958 cur.buffer()->params().trackChanges);
959 cur.checkBufferStructure();
961 // cur.screenUpdateFlags(Update::Force);
962 bool boundary = cur.boundary()
963 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
964 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
969 void Text::charInserted(Cursor & cur)
971 Paragraph & par = cur.paragraph();
973 // Here we call finishUndo for every 20 characters inserted.
974 // This is from my experience how emacs does it. (Lgb)
975 if (undo_counter_ < 20) {
982 // register word if a non-letter was entered
984 && !par.isWordSeparator(cur.pos() - 2)
985 && par.isWordSeparator(cur.pos() - 1)) {
986 // get the word in front of cursor
987 LASSERT(this == cur.text(), /**/);
988 cur.paragraph().updateWords();
993 // the cursor set functions have a special mechanism. When they
994 // realize, that you left an empty paragraph, they will delete it.
996 bool Text::cursorForwardOneWord(Cursor & cur)
998 LASSERT(this == cur.text(), /**/);
1000 pos_type const lastpos = cur.lastpos();
1001 pit_type pit = cur.pit();
1002 pos_type pos = cur.pos();
1003 Paragraph const & par = cur.paragraph();
1005 // Paragraph boundary is a word boundary
1006 if (pos == lastpos) {
1007 if (pit != cur.lastpit())
1008 return setCursor(cur, pit + 1, 0);
1013 if (lyxrc.mac_like_word_movement) {
1014 // Skip through trailing punctuation and spaces.
1015 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1018 // Skip over either a non-char inset or a full word
1019 if (pos != lastpos && par.isWordSeparator(pos))
1021 else while (pos != lastpos && !par.isWordSeparator(pos))
1024 LASSERT(pos < lastpos, /**/); // see above
1025 if (!par.isWordSeparator(pos))
1026 while (pos != lastpos && !par.isWordSeparator(pos))
1028 else if (par.isChar(pos))
1029 while (pos != lastpos && par.isChar(pos))
1031 else if (!par.isSpace(pos)) // non-char inset
1034 // Skip over white space
1035 while (pos != lastpos && par.isSpace(pos))
1039 return setCursor(cur, pit, pos);
1043 bool Text::cursorBackwardOneWord(Cursor & cur)
1045 LASSERT(this == cur.text(), /**/);
1047 pit_type pit = cur.pit();
1048 pos_type pos = cur.pos();
1049 Paragraph & par = cur.paragraph();
1051 // Paragraph boundary is a word boundary
1052 if (pos == 0 && pit != 0)
1053 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1055 if (lyxrc.mac_like_word_movement) {
1056 // Skip through punctuation and spaces.
1057 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1060 // Skip over either a non-char inset or a full word
1061 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1063 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1066 // Skip over white space
1067 while (pos != 0 && par.isSpace(pos - 1))
1070 if (pos != 0 && !par.isWordSeparator(pos - 1))
1071 while (pos != 0 && !par.isWordSeparator(pos - 1))
1073 else if (pos != 0 && par.isChar(pos - 1))
1074 while (pos != 0 && par.isChar(pos - 1))
1076 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1080 return setCursor(cur, pit, pos);
1084 bool Text::cursorVisLeftOneWord(Cursor & cur)
1086 LASSERT(this == cur.text(), /**/);
1088 pos_type left_pos, right_pos;
1089 bool left_is_letter, right_is_letter;
1091 Cursor temp_cur = cur;
1093 // always try to move at least once...
1094 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1096 // collect some information about current cursor position
1097 temp_cur.getSurroundingPos(left_pos, right_pos);
1099 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1101 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1103 // if we're not at a letter/non-letter boundary, continue moving
1104 if (left_is_letter == right_is_letter)
1107 // we should stop when we have an LTR word on our right or an RTL word
1109 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1110 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1111 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1112 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1116 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1117 true, temp_cur.boundary());
1121 bool Text::cursorVisRightOneWord(Cursor & cur)
1123 LASSERT(this == cur.text(), /**/);
1125 pos_type left_pos, right_pos;
1126 bool left_is_letter, right_is_letter;
1128 Cursor temp_cur = cur;
1130 // always try to move at least once...
1131 while (temp_cur.posVisRight(true /* skip_inset */)) {
1133 // collect some information about current cursor position
1134 temp_cur.getSurroundingPos(left_pos, right_pos);
1136 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1138 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1140 // if we're not at a letter/non-letter boundary, continue moving
1141 if (left_is_letter == right_is_letter)
1144 // we should stop when we have an LTR word on our right or an RTL word
1146 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1147 temp_cur.buffer()->params(),
1148 left_pos).isRightToLeft())
1149 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1150 temp_cur.buffer()->params(),
1151 right_pos).isRightToLeft()))
1155 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1156 true, temp_cur.boundary());
1160 void Text::selectWord(Cursor & cur, word_location loc)
1162 LASSERT(this == cur.text(), /**/);
1163 CursorSlice from = cur.top();
1164 CursorSlice to = cur.top();
1165 getWord(from, to, loc);
1166 if (cur.top() != from)
1167 setCursor(cur, from.pit(), from.pos());
1170 if (!cur.selection())
1172 setCursor(cur, to.pit(), to.pos());
1174 cur.setWordSelection(true);
1178 void Text::selectAll(Cursor & cur)
1180 LASSERT(this == cur.text(), /**/);
1181 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1183 // If the cursor is at the beginning, make sure the cursor ends there
1184 if (cur.pit() == 0 && cur.pos() == 0) {
1185 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1187 setCursor(cur, 0, 0);
1189 setCursor(cur, 0, 0);
1191 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1197 // Select the word currently under the cursor when no
1198 // selection is currently set
1199 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1201 LASSERT(this == cur.text(), /**/);
1202 if (cur.selection())
1204 selectWord(cur, loc);
1205 return cur.selection();
1209 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1211 LASSERT(this == cur.text(), /**/);
1213 if (!cur.selection()) {
1214 bool const changed = cur.paragraph().isChanged(cur.pos());
1215 if (!(changed && findNextChange(&cur.bv())))
1219 cur.recordUndoSelection();
1221 pit_type begPit = cur.selectionBegin().pit();
1222 pit_type endPit = cur.selectionEnd().pit();
1224 pos_type begPos = cur.selectionBegin().pos();
1225 pos_type endPos = cur.selectionEnd().pos();
1227 // keep selection info, because endPos becomes invalid after the first loop
1228 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1230 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1232 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1233 pos_type parSize = pars_[pit].size();
1235 // ignore empty paragraphs; otherwise, an assertion will fail for
1236 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1240 // do not consider first paragraph if the cursor starts at pos size()
1241 if (pit == begPit && begPos == parSize)
1244 // do not consider last paragraph if the cursor ends at pos 0
1245 if (pit == endPit && endPos == 0)
1246 break; // last iteration anyway
1248 pos_type left = (pit == begPit ? begPos : 0);
1249 pos_type right = (pit == endPit ? endPos : parSize);
1252 pars_[pit].acceptChanges(left, right);
1254 pars_[pit].rejectChanges(left, right);
1258 // next, accept/reject imaginary end-of-par characters
1260 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1261 pos_type pos = pars_[pit].size();
1263 // skip if the selection ends before the end-of-par
1264 if (pit == endPit && endsBeforeEndOfPar)
1265 break; // last iteration anyway
1267 // skip if this is not the last paragraph of the document
1268 // note: the user should be able to accept/reject the par break of the last par!
1269 if (pit == endPit && pit + 1 != int(pars_.size()))
1270 break; // last iteration anway
1273 if (pars_[pit].isInserted(pos)) {
1274 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1275 } else if (pars_[pit].isDeleted(pos)) {
1276 if (pit + 1 == int(pars_.size())) {
1277 // we cannot remove a par break at the end of the last paragraph;
1278 // instead, we mark it unchanged
1279 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1281 mergeParagraph(cur.buffer()->params(), pars_, pit);
1287 if (pars_[pit].isDeleted(pos)) {
1288 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1289 } else if (pars_[pit].isInserted(pos)) {
1290 if (pit + 1 == int(pars_.size())) {
1291 // we mark the par break at the end of the last paragraph unchanged
1292 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1294 mergeParagraph(cur.buffer()->params(), pars_, pit);
1302 // finally, invoke the DEPM
1304 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1309 cur.clearSelection();
1310 setCursorIntern(cur, begPit, begPos);
1311 cur.screenUpdateFlags(Update::Force);
1312 cur.forceBufferUpdate();
1316 void Text::acceptChanges()
1318 BufferParams const & bparams = owner_->buffer().params();
1319 lyx::acceptChanges(pars_, bparams);
1320 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1324 void Text::rejectChanges()
1326 BufferParams const & bparams = owner_->buffer().params();
1327 pit_type pars_size = static_cast<pit_type>(pars_.size());
1329 // first, reject changes within each individual paragraph
1330 // (do not consider end-of-par)
1331 for (pit_type pit = 0; pit < pars_size; ++pit) {
1332 if (!pars_[pit].empty()) // prevent assertion failure
1333 pars_[pit].rejectChanges(0, pars_[pit].size());
1336 // next, reject imaginary end-of-par characters
1337 for (pit_type pit = 0; pit < pars_size; ++pit) {
1338 pos_type pos = pars_[pit].size();
1340 if (pars_[pit].isDeleted(pos)) {
1341 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1342 } else if (pars_[pit].isInserted(pos)) {
1343 if (pit == pars_size - 1) {
1344 // we mark the par break at the end of the last
1345 // paragraph unchanged
1346 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1348 mergeParagraph(bparams, pars_, pit);
1355 // finally, invoke the DEPM
1356 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1360 void Text::deleteWordForward(Cursor & cur)
1362 LASSERT(this == cur.text(), /**/);
1363 if (cur.lastpos() == 0)
1367 cur.setSelection(true);
1368 cursorForwardOneWord(cur);
1370 cutSelection(cur, true, false);
1371 cur.checkBufferStructure();
1376 void Text::deleteWordBackward(Cursor & cur)
1378 LASSERT(this == cur.text(), /**/);
1379 if (cur.lastpos() == 0)
1380 cursorBackward(cur);
1383 cur.setSelection(true);
1384 cursorBackwardOneWord(cur);
1386 cutSelection(cur, true, false);
1387 cur.checkBufferStructure();
1392 // Kill to end of line.
1393 void Text::changeCase(Cursor & cur, TextCase action)
1395 LASSERT(this == cur.text(), /**/);
1399 bool gotsel = false;
1400 if (cur.selection()) {
1401 from = cur.selBegin();
1406 getWord(from, to, PARTIAL_WORD);
1407 cursorForwardOneWord(cur);
1410 cur.recordUndoSelection();
1412 pit_type begPit = from.pit();
1413 pit_type endPit = to.pit();
1415 pos_type begPos = from.pos();
1416 pos_type endPos = to.pos();
1418 pos_type right = 0; // needed after the for loop
1420 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1421 Paragraph & par = pars_[pit];
1422 pos_type const pos = (pit == begPit ? begPos : 0);
1423 right = (pit == endPit ? endPos : par.size());
1424 par.changeCase(cur.buffer()->params(), pos, right, action);
1427 // the selection may have changed due to logically-only deleted chars
1429 setCursor(cur, begPit, begPos);
1431 setCursor(cur, endPit, right);
1434 setCursor(cur, endPit, right);
1436 cur.checkBufferStructure();
1440 bool Text::handleBibitems(Cursor & cur)
1442 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1448 BufferParams const & bufparams = cur.buffer()->params();
1449 Paragraph const & par = cur.paragraph();
1450 Cursor prevcur = cur;
1451 if (cur.pit() > 0) {
1453 prevcur.pos() = prevcur.lastpos();
1455 Paragraph const & prevpar = prevcur.paragraph();
1457 // if a bibitem is deleted, merge with previous paragraph
1458 // if this is a bibliography item as well
1459 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1460 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1461 mergeParagraph(bufparams, cur.text()->paragraphs(),
1463 cur.forceBufferUpdate();
1464 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1465 cur.screenUpdateFlags(Update::Force);
1469 // otherwise reset to default
1470 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1475 bool Text::erase(Cursor & cur)
1477 LASSERT(this == cur.text(), return false);
1478 bool needsUpdate = false;
1479 Paragraph & par = cur.paragraph();
1481 if (cur.pos() != cur.lastpos()) {
1482 // this is the code for a normal delete, not pasting
1484 cur.recordUndo(DELETE_UNDO);
1485 bool const was_inset = cur.paragraph().isInset(cur.pos());
1486 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1487 // the character has been logically deleted only => skip it
1488 cur.top().forwardPos();
1491 cur.forceBufferUpdate();
1493 cur.checkBufferStructure();
1496 if (cur.pit() == cur.lastpit())
1497 return dissolveInset(cur);
1499 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1500 par.setChange(cur.pos(), Change(Change::DELETED));
1504 setCursorIntern(cur, cur.pit() + 1, 0);
1505 needsUpdate = backspacePos0(cur);
1509 needsUpdate |= handleBibitems(cur);
1512 // Make sure the cursor is correct. Is this really needed?
1513 // No, not really... at least not here!
1514 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1515 cur.checkBufferStructure();
1522 bool Text::backspacePos0(Cursor & cur)
1524 LASSERT(this == cur.text(), /**/);
1528 bool needsUpdate = false;
1530 BufferParams const & bufparams = cur.buffer()->params();
1531 DocumentClass const & tclass = bufparams.documentClass();
1532 ParagraphList & plist = cur.text()->paragraphs();
1533 Paragraph const & par = cur.paragraph();
1534 Cursor prevcur = cur;
1536 prevcur.pos() = prevcur.lastpos();
1537 Paragraph const & prevpar = prevcur.paragraph();
1539 // is it an empty paragraph?
1540 if (cur.lastpos() == 0
1541 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1542 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1543 plist.erase(boost::next(plist.begin(), cur.pit()));
1546 // is previous par empty?
1547 else if (prevcur.lastpos() == 0
1548 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1549 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1550 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1553 // Pasting is not allowed, if the paragraphs have different
1554 // layouts. I think it is a real bug of all other
1555 // word processors to allow it. It confuses the user.
1556 // Correction: Pasting is always allowed with standard-layout
1557 // or the empty layout.
1558 else if (par.layout() == prevpar.layout()
1559 || tclass.isDefaultLayout(par.layout())
1560 || tclass.isPlainLayout(par.layout())) {
1561 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1562 mergeParagraph(bufparams, plist, prevcur.pit());
1567 cur.forceBufferUpdate();
1568 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1575 bool Text::backspace(Cursor & cur)
1577 LASSERT(this == cur.text(), /**/);
1578 bool needsUpdate = false;
1579 if (cur.pos() == 0) {
1581 return dissolveInset(cur);
1583 Paragraph & prev_par = pars_[cur.pit() - 1];
1585 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1586 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1587 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1590 // The cursor is at the beginning of a paragraph, so
1591 // the backspace will collapse two paragraphs into one.
1592 needsUpdate = backspacePos0(cur);
1595 // this is the code for a normal backspace, not pasting
1597 cur.recordUndo(DELETE_UNDO);
1598 // We used to do cursorBackwardIntern() here, but it is
1599 // not a good idea since it triggers the auto-delete
1600 // mechanism. So we do a cursorBackwardIntern()-lite,
1601 // without the dreaded mechanism. (JMarc)
1602 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1603 false, cur.boundary());
1604 bool const was_inset = cur.paragraph().isInset(cur.pos());
1605 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1607 cur.forceBufferUpdate();
1609 cur.checkBufferStructure();
1612 if (cur.pos() == cur.lastpos())
1613 cur.setCurrentFont();
1615 needsUpdate |= handleBibitems(cur);
1617 // A singlePar update is not enough in this case.
1618 // cur.screenUpdateFlags(Update::Force);
1619 setCursor(cur.top(), cur.pit(), cur.pos());
1625 bool Text::dissolveInset(Cursor & cur)
1627 LASSERT(this == cur.text(), return false);
1629 if (isMainText() || cur.inset().nargs() != 1)
1632 cur.recordUndoInset();
1634 cur.selHandle(false);
1636 pos_type spos = cur.pos();
1637 pit_type spit = cur.pit();
1638 ParagraphList plist;
1639 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1640 plist = paragraphs();
1642 // store cursor offset
1646 Buffer & b = *cur.buffer();
1647 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1648 if (!plist.empty()) {
1649 // ERT paragraphs have the Language latex_language.
1650 // This is invalid outside of ERT, so we need to
1651 // change it to the buffer language.
1652 ParagraphList::iterator it = plist.begin();
1653 ParagraphList::iterator it_end = plist.end();
1654 for (; it != it_end; it++)
1655 it->changeLanguage(b.params(), latex_language, b.language());
1657 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1658 b.errorList("Paste"));
1660 cur.pit() = min(cur.lastpit(), spit);
1661 cur.pos() = min(cur.lastpos(), spos);
1663 cur.forceBufferUpdate();
1665 // Ensure the current language is set correctly (bug 6292)
1666 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1667 cur.clearSelection();
1673 void Text::getWord(CursorSlice & from, CursorSlice & to,
1674 word_location const loc) const
1677 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1681 void Text::write(ostream & os) const
1683 Buffer const & buf = owner_->buffer();
1684 ParagraphList::const_iterator pit = paragraphs().begin();
1685 ParagraphList::const_iterator end = paragraphs().end();
1687 for (; pit != end; ++pit)
1688 pit->write(os, buf.params(), dth);
1690 // Close begin_deeper
1691 for(; dth > 0; --dth)
1692 os << "\n\\end_deeper";
1696 bool Text::read(Lexer & lex,
1697 ErrorList & errorList, InsetText * insetPtr)
1699 Buffer const & buf = owner_->buffer();
1700 depth_type depth = 0;
1703 while (lex.isOK()) {
1705 string const token = lex.getString();
1710 if (token == "\\end_inset")
1713 if (token == "\\end_body")
1716 if (token == "\\begin_body")
1719 if (token == "\\end_document") {
1724 if (token == "\\begin_layout") {
1725 lex.pushToken(token);
1728 par.setInsetOwner(insetPtr);
1729 par.params().depth(depth);
1730 par.setFont(0, Font(inherit_font, buf.params().language));
1731 pars_.push_back(par);
1732 readParagraph(pars_.back(), lex, errorList);
1734 // register the words in the global word list
1735 pars_.back().updateWords();
1736 } else if (token == "\\begin_deeper") {
1738 } else if (token == "\\end_deeper") {
1740 lex.printError("\\end_deeper: " "depth is already null");
1744 LYXERR0("Handling unknown body token: `" << token << '\'');
1748 // avoid a crash on weird documents (bug 4859)
1749 if (pars_.empty()) {
1751 par.setInsetOwner(insetPtr);
1752 par.params().depth(depth);
1753 par.setFont(0, Font(inherit_font,
1754 buf.params().language));
1755 par.setPlainOrDefaultLayout(buf.params().documentClass());
1756 pars_.push_back(par);
1762 // Returns the current font and depth as a message.
1763 docstring Text::currentState(Cursor const & cur) const
1765 LASSERT(this == cur.text(), /**/);
1766 Buffer & buf = *cur.buffer();
1767 Paragraph const & par = cur.paragraph();
1768 odocstringstream os;
1770 if (buf.params().trackChanges)
1771 os << _("[Change Tracking] ");
1773 Change change = par.lookupChange(cur.pos());
1775 if (change.changed()) {
1776 Author const & a = buf.params().authors().get(change.author);
1777 os << _("Change: ") << a.name();
1778 if (!a.email().empty())
1779 os << " (" << a.email() << ")";
1780 // FIXME ctime is english, we should translate that
1781 os << _(" at ") << ctime(&change.changetime);
1785 // I think we should only show changes from the default
1787 // No, from the document font (MV)
1788 Font font = cur.real_current_font;
1789 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1791 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1793 // The paragraph depth
1794 int depth = cur.paragraph().getDepth();
1796 os << bformat(_(", Depth: %1$d"), depth);
1798 // The paragraph spacing, but only if different from
1800 Spacing const & spacing = par.params().spacing();
1801 if (!spacing.isDefault()) {
1802 os << _(", Spacing: ");
1803 switch (spacing.getSpace()) {
1804 case Spacing::Single:
1807 case Spacing::Onehalf:
1810 case Spacing::Double:
1813 case Spacing::Other:
1814 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1816 case Spacing::Default:
1817 // should never happen, do nothing
1822 #ifdef DEVEL_VERSION
1823 os << _(", Inset: ") << &cur.inset();
1824 os << _(", Paragraph: ") << cur.pit();
1825 os << _(", Id: ") << par.id();
1826 os << _(", Position: ") << cur.pos();
1827 // FIXME: Why is the check for par.size() needed?
1828 // We are called with cur.pos() == par.size() quite often.
1829 if (!par.empty() && cur.pos() < par.size()) {
1830 // Force output of code point, not character
1831 size_t const c = par.getChar(cur.pos());
1832 os << _(", Char: 0x") << hex << c;
1834 os << _(", Boundary: ") << cur.boundary();
1835 // Row & row = cur.textRow();
1836 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1842 docstring Text::getPossibleLabel(Cursor const & cur) const
1844 pit_type pit = cur.pit();
1846 Layout const * layout = &(pars_[pit].layout());
1849 docstring par_text = pars_[pit].asString();
1851 // The return string of math matrices might contain linebreaks
1852 par_text = subst(par_text, '\n', '-');
1853 int const numwords = 3;
1854 for (int i = 0; i < numwords; ++i) {
1855 if (par_text.empty())
1858 par_text = split(par_text, head, ' ');
1859 // Is it legal to use spaces in labels ?
1865 // Make sure it isn't too long
1866 unsigned int const max_label_length = 32;
1867 if (text.size() > max_label_length)
1868 text.resize(max_label_length);
1870 // Will contain the label prefix.
1873 // For section, subsection, etc...
1874 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1875 Layout const * layout2 = &(pars_[pit - 1].layout());
1876 if (layout2->latextype != LATEX_PARAGRAPH) {
1881 if (layout->latextype != LATEX_PARAGRAPH)
1882 name = layout->refprefix;
1884 // For captions, we just take the caption type
1885 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1886 if (caption_inset) {
1887 string const & ftype = static_cast<InsetCaption *>(caption_inset)->type();
1888 FloatList const & fl = cur.buffer()->params().documentClass().floats();
1889 if (fl.typeExist(ftype)) {
1890 Floating const & flt = fl.getType(ftype);
1891 name = from_utf8(flt.refPrefix());
1894 name = from_utf8(ftype.substr(0,3));
1897 // If none of the above worked, see if the inset knows.
1899 InsetLayout const & il = cur.inset().getLayout();
1900 name = il.refprefix();
1905 // We should allow customization of the separator or else change it
1906 text = name + ':' + text;
1912 docstring Text::asString(int options) const
1914 return asString(0, pars_.size(), options);
1918 docstring Text::asString(pit_type beg, pit_type end, int options) const
1920 size_t i = size_t(beg);
1921 docstring str = pars_[i].asString(options);
1922 for (++i; i != size_t(end); ++i) {
1924 str += pars_[i].asString(options);
1931 void Text::charsTranspose(Cursor & cur)
1933 LASSERT(this == cur.text(), /**/);
1935 pos_type pos = cur.pos();
1937 // If cursor is at beginning or end of paragraph, do nothing.
1938 if (pos == cur.lastpos() || pos == 0)
1941 Paragraph & par = cur.paragraph();
1943 // Get the positions of the characters to be transposed.
1944 pos_type pos1 = pos - 1;
1945 pos_type pos2 = pos;
1947 // In change tracking mode, ignore deleted characters.
1948 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1950 if (pos2 == cur.lastpos())
1953 while (pos1 >= 0 && par.isDeleted(pos1))
1958 // Don't do anything if one of the "characters" is not regular text.
1959 if (par.isInset(pos1) || par.isInset(pos2))
1962 // Store the characters to be transposed (including font information).
1963 char_type const char1 = par.getChar(pos1);
1965 par.getFontSettings(cur.buffer()->params(), pos1);
1967 char_type const char2 = par.getChar(pos2);
1969 par.getFontSettings(cur.buffer()->params(), pos2);
1971 // And finally, we are ready to perform the transposition.
1972 // Track the changes if Change Tracking is enabled.
1973 bool const trackChanges = cur.buffer()->params().trackChanges;
1977 par.eraseChar(pos2, trackChanges);
1978 par.eraseChar(pos1, trackChanges);
1979 par.insertChar(pos1, char2, font2, trackChanges);
1980 par.insertChar(pos2, char1, font1, trackChanges);
1982 cur.checkBufferStructure();
1984 // After the transposition, move cursor to after the transposition.
1985 setCursor(cur, cur.pit(), pos2);
1990 DocIterator Text::macrocontextPosition() const
1992 return macrocontext_position_;
1996 void Text::setMacrocontextPosition(DocIterator const & pos)
1998 macrocontext_position_ = pos;
2002 docstring Text::previousWord(CursorSlice const & sl) const
2004 CursorSlice from = sl;
2005 CursorSlice to = sl;
2006 getWord(from, to, PREVIOUS_WORD);
2007 if (sl == from || to == from)
2010 Paragraph const & par = sl.paragraph();
2011 return par.asString(from.pos(), to.pos());
2015 bool Text::completionSupported(Cursor const & cur) const
2017 Paragraph const & par = cur.paragraph();
2018 return cur.pos() > 0
2019 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2020 && !par.isWordSeparator(cur.pos() - 1);
2024 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2026 WordList const * list = theWordList(*cur.getFont().language());
2027 return new TextCompletionList(cur, list);
2031 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2033 LASSERT(cur.bv().cursor() == cur, /**/);
2035 cur.bv().cursor() = cur;
2036 if (!(cur.result().update() & Update::Force))
2037 cur.screenUpdateFlags(cur.result().update() | Update::SinglePar);
2042 docstring Text::completionPrefix(Cursor const & cur) const
2044 return previousWord(cur.top());