3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Dov Feldstern
9 * \author Jean-Marc Lasgouttes
11 * \author André Pönitz
12 * \author Stefan Schimanski
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "CompletionList.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
37 #include "InsetList.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TextMetrics.h"
49 #include "WordLangTuple.h"
52 #include "insets/InsetText.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetCaption.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetNewpage.h"
57 #include "insets/InsetArgument.h"
58 #include "insets/InsetIPAMacro.h"
59 #include "insets/InsetSpace.h"
60 #include "insets/InsetSpecialChar.h"
61 #include "insets/InsetTabular.h"
63 #include "support/convert.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>
77 // TODO: replace if in Text::readParToken() with compile time switch
80 #include "support/metahash.h"
82 typedef boost::mpl::string<'\\end','_lay','out'> end_layout;
83 typedef boost::mpl::string<'\\end','in','set'> end_inset;
87 std::string token = "\\end_layout";
89 switch (boost::hash_value(token)) {
90 case lyx::support::hash_string<end_layout>::value:
92 case lyx::support::hash_string<end_inset>::value:
102 using namespace lyx::support;
106 using cap::cutSelection;
107 using cap::pasteParagraphList;
109 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
110 Paragraph & toPar, pos_type toPos, BufferParams const & params)
112 // Note: moveItem() does not honour change tracking!
113 // Therefore, it should only be used for breaking and merging paragraphs
115 // We need a copy here because the character at fromPos is going to be erased.
116 Font const tmpFont = fromPar.getFontSettings(params, fromPos);
117 Change const tmpChange = fromPar.lookupChange(fromPos);
119 if (Inset * tmpInset = fromPar.getInset(fromPos)) {
120 fromPar.releaseInset(fromPos);
121 // The inset is not in fromPar any more.
122 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
129 char_type const tmpChar = fromPar.getChar(fromPos);
130 fromPar.eraseChar(fromPos, false);
131 toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
136 void breakParagraphConservative(BufferParams const & bparams,
137 ParagraphList & pars, pit_type par_offset, pos_type pos)
139 // create a new paragraph
140 Paragraph & tmp = *pars.insert(boost::next(pars.begin(), par_offset + 1),
142 Paragraph & par = pars[par_offset];
144 tmp.setInsetOwner(&par.inInset());
145 tmp.makeSameLayout(par);
147 LASSERT(pos <= par.size(), return);
149 if (pos < par.size()) {
150 // move everything behind the break position to the new paragraph
151 pos_type pos_end = par.size() - 1;
153 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
154 if (moveItem(par, pos, tmp, j, bparams)) {
158 // Move over the end-of-par change information
159 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
160 par.setChange(par.size(), Change(bparams.track_changes ?
161 Change::INSERTED : Change::UNCHANGED));
166 void mergeParagraph(BufferParams const & bparams,
167 ParagraphList & pars, pit_type par_offset)
169 Paragraph & next = pars[par_offset + 1];
170 Paragraph & par = pars[par_offset];
172 pos_type pos_end = next.size() - 1;
173 pos_type pos_insert = par.size();
175 // the imaginary end-of-paragraph character (at par.size()) has to be
176 // marked as unmodified. Otherwise, its change is adopted by the first
177 // character of the next paragraph.
178 if (par.isChanged(par.size())) {
179 LYXERR(Debug::CHANGES,
180 "merging par with inserted/deleted end-of-par character");
181 par.setChange(par.size(), Change(Change::UNCHANGED));
184 Change change = next.lookupChange(next.size());
186 // move the content of the second paragraph to the end of the first one
187 for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
188 if (moveItem(next, 0, par, j, bparams)) {
193 // move the change of the end-of-paragraph character
194 par.setChange(par.size(), change);
196 pars.erase(boost::next(pars.begin(), par_offset + 1));
200 Text::Text(InsetText * owner, bool use_default_layout)
201 : owner_(owner), autoBreakRows_(false), undo_counter_(0)
203 pars_.push_back(Paragraph());
204 Paragraph & par = pars_.back();
205 par.setInsetOwner(owner);
206 DocumentClass const & dc = owner->buffer().params().documentClass();
207 if (use_default_layout)
208 par.setDefaultLayout(dc);
210 par.setPlainLayout(dc);
214 Text::Text(InsetText * owner, Text const & text)
215 : owner_(owner), autoBreakRows_(text.autoBreakRows_), undo_counter_(0)
218 ParagraphList::iterator const end = pars_.end();
219 ParagraphList::iterator it = pars_.begin();
220 for (; it != end; ++it)
221 it->setInsetOwner(owner);
225 pit_type Text::depthHook(pit_type pit, depth_type depth) const
227 pit_type newpit = pit;
232 while (newpit != 0 && pars_[newpit].getDepth() > depth)
235 if (pars_[newpit].getDepth() > depth)
242 pit_type Text::outerHook(pit_type par_offset) const
244 Paragraph const & par = pars_[par_offset];
246 if (par.getDepth() == 0)
248 return depthHook(par_offset, depth_type(par.getDepth() - 1));
252 bool Text::isFirstInSequence(pit_type par_offset) const
254 Paragraph const & par = pars_[par_offset];
256 pit_type dhook_offset = depthHook(par_offset, par.getDepth());
258 if (dhook_offset == par_offset)
261 Paragraph const & dhook = pars_[dhook_offset];
263 return dhook.layout() != par.layout()
264 || dhook.getDepth() != par.getDepth();
268 int Text::getTocLevel(pit_type par_offset) const
270 Paragraph const & par = pars_[par_offset];
272 if (par.layout().isEnvironment() && !isFirstInSequence(par_offset))
273 return Layout::NOT_IN_TOC;
275 return par.layout().toclevel;
279 Font const Text::outerFont(pit_type par_offset) const
281 depth_type par_depth = pars_[par_offset].getDepth();
282 FontInfo tmpfont = inherit_font;
283 depth_type prev_par_depth = 0;
284 // Resolve against environment font information
285 while (par_offset != pit_type(pars_.size())
286 && par_depth != prev_par_depth
288 && !tmpfont.resolved()) {
289 prev_par_depth = par_depth;
290 par_offset = outerHook(par_offset);
291 if (par_offset != pit_type(pars_.size())) {
292 tmpfont.realize(pars_[par_offset].layout().font);
293 par_depth = pars_[par_offset].getDepth();
297 return Font(tmpfont);
301 static void acceptOrRejectChanges(ParagraphList & pars,
302 BufferParams const & bparams, Text::ChangeOp op)
304 pit_type pars_size = static_cast<pit_type>(pars.size());
306 // first, accept or reject changes within each individual
307 // paragraph (do not consider end-of-par)
308 for (pit_type pit = 0; pit < pars_size; ++pit) {
309 // prevent assertion failure
310 if (!pars[pit].empty()) {
311 if (op == Text::ACCEPT)
312 pars[pit].acceptChanges(0, pars[pit].size());
314 pars[pit].rejectChanges(0, pars[pit].size());
318 // next, accept or reject imaginary end-of-par characters
319 for (pit_type pit = 0; pit < pars_size; ++pit) {
320 pos_type pos = pars[pit].size();
321 if (pars[pit].isChanged(pos)) {
322 // keep the end-of-par char if it is inserted and accepted
323 // or when it is deleted and rejected.
324 if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
325 pars[pit].setChange(pos, Change(Change::UNCHANGED));
327 if (pit == pars_size - 1) {
328 // we cannot remove a par break at the end of the last
329 // paragraph; instead, we mark it unchanged
330 pars[pit].setChange(pos, Change(Change::UNCHANGED));
332 mergeParagraph(bparams, pars, pit);
342 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
344 acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
348 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
350 acceptOrRejectChanges(pars, bparams, Text::REJECT);
354 InsetText const & Text::inset() const
361 void Text::readParToken(Paragraph & par, Lexer & lex,
362 string const & token, Font & font, Change & change, ErrorList & errorList)
364 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
365 BufferParams const & bp = buf->params();
367 if (token[0] != '\\') {
368 docstring dstr = lex.getDocString();
369 par.appendString(dstr, font, change);
371 } else if (token == "\\begin_layout") {
373 docstring layoutname = lex.getDocString();
375 font = Font(inherit_font, bp.language);
376 change = Change(Change::UNCHANGED);
378 DocumentClass const & tclass = bp.documentClass();
380 if (layoutname.empty())
381 layoutname = tclass.defaultLayoutName();
383 if (owner_->forcePlainLayout()) {
384 // in this case only the empty layout is allowed
385 layoutname = tclass.plainLayoutName();
386 } else if (par.usePlainLayout()) {
387 // in this case, default layout maps to empty layout
388 if (layoutname == tclass.defaultLayoutName())
389 layoutname = tclass.plainLayoutName();
391 // otherwise, the empty layout maps to the default
392 if (layoutname == tclass.plainLayoutName())
393 layoutname = tclass.defaultLayoutName();
396 // When we apply an unknown layout to a document, we add this layout to the textclass
397 // of this document. For example, when you apply class article to a beamer document,
398 // all unknown layouts such as frame will be added to document class article so that
399 // these layouts can keep their original names.
400 bool const added_one = tclass.addLayoutIfNeeded(layoutname);
403 docstring const s = bformat(_("Layout `%1$s' was not found."), layoutname);
405 ErrorItem(_("Layout Not Found"), s, par.id(), 0, par.size()));
408 par.setLayout(bp.documentClass()[layoutname]);
410 // Test whether the layout is obsolete.
411 Layout const & layout = par.layout();
412 if (!layout.obsoleted_by().empty())
413 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
415 par.params().read(lex);
417 } else if (token == "\\end_layout") {
418 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
419 << "Missing \\begin_layout ?");
420 } else if (token == "\\end_inset") {
421 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
422 << "Missing \\begin_inset ?");
423 } else if (token == "\\begin_inset") {
424 Inset * inset = readInset(lex, buf);
426 par.insertInset(par.size(), inset, font, change);
429 docstring line = lex.getDocString();
430 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
431 par.id(), 0, par.size()));
433 } else if (token == "\\family") {
435 setLyXFamily(lex.getString(), font.fontInfo());
436 } else if (token == "\\series") {
438 setLyXSeries(lex.getString(), font.fontInfo());
439 } else if (token == "\\shape") {
441 setLyXShape(lex.getString(), font.fontInfo());
442 } else if (token == "\\size") {
444 setLyXSize(lex.getString(), font.fontInfo());
445 } else if (token == "\\lang") {
447 string const tok = lex.getString();
448 Language const * lang = languages.getLanguage(tok);
450 font.setLanguage(lang);
452 font.setLanguage(bp.language);
453 lex.printError("Unknown language `$$Token'");
455 } else if (token == "\\numeric") {
457 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
458 } else if (token == "\\emph") {
460 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
461 } else if (token == "\\bar") {
463 string const tok = lex.getString();
466 font.fontInfo().setUnderbar(FONT_ON);
467 else if (tok == "no")
468 font.fontInfo().setUnderbar(FONT_OFF);
469 else if (tok == "default")
470 font.fontInfo().setUnderbar(FONT_INHERIT);
472 lex.printError("Unknown bar font flag "
474 } else if (token == "\\strikeout") {
476 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
477 } else if (token == "\\uuline") {
479 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
480 } else if (token == "\\uwave") {
482 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
483 } else if (token == "\\noun") {
485 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
486 } else if (token == "\\color") {
488 setLyXColor(lex.getString(), font.fontInfo());
489 } else if (token == "\\SpecialChar") {
490 auto_ptr<Inset> inset;
491 inset.reset(new InsetSpecialChar);
493 inset->setBuffer(*buf);
494 par.insertInset(par.size(), inset.release(), font, change);
495 } else if (token == "\\IPAChar") {
496 auto_ptr<Inset> inset;
497 inset.reset(new InsetIPAChar);
499 inset->setBuffer(*buf);
500 par.insertInset(par.size(), inset.release(), font, change);
501 } else if (token == "\\backslash") {
502 par.appendChar('\\', font, change);
503 } else if (token == "\\LyXTable") {
504 auto_ptr<Inset> inset(new InsetTabular(buf));
506 par.insertInset(par.size(), inset.release(), font, change);
507 } else if (token == "\\change_unchanged") {
508 change = Change(Change::UNCHANGED);
509 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
511 istringstream is(lex.getString());
515 BufferParams::AuthorMap const & am = bp.author_map;
516 if (am.find(aid) == am.end()) {
517 errorList.push_back(ErrorItem(_("Change tracking error"),
518 bformat(_("Unknown author index for change: %1$d\n"), aid),
519 par.id(), 0, par.size()));
520 change = Change(Change::UNCHANGED);
522 if (token == "\\change_inserted")
523 change = Change(Change::INSERTED, am.find(aid)->second, ct);
525 change = Change(Change::DELETED, am.find(aid)->second, ct);
529 errorList.push_back(ErrorItem(_("Unknown token"),
530 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
532 par.id(), 0, par.size()));
537 void Text::readParagraph(Paragraph & par, Lexer & lex,
538 ErrorList & errorList)
541 string token = lex.getString();
543 Change change(Change::UNCHANGED);
546 readParToken(par, lex, token, font, change, errorList);
549 token = lex.getString();
554 if (token == "\\end_layout") {
555 //Ok, paragraph finished
559 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
560 if (token == "\\begin_layout" || token == "\\end_document"
561 || token == "\\end_inset" || token == "\\begin_deeper"
562 || token == "\\end_deeper") {
563 lex.pushToken(token);
564 lyxerr << "Paragraph ended in line "
565 << lex.lineNumber() << "\n"
566 << "Missing \\end_layout.\n";
570 // Final change goes to paragraph break:
571 par.setChange(par.size(), change);
573 // Initialize begin_of_body_ on load; redoParagraph maintains
574 par.setBeginOfBody();
576 // mark paragraph for spell checking on load
577 // par.requestSpellCheck();
581 class TextCompletionList : public CompletionList
585 TextCompletionList(Cursor const & cur, WordList const * list)
586 : buffer_(cur.buffer()), list_(list)
589 virtual ~TextCompletionList() {}
592 virtual bool sorted() const { return true; }
594 virtual size_t size() const
596 return list_->size();
599 virtual docstring const & data(size_t idx) const
601 return list_->word(idx);
606 Buffer const * buffer_;
608 WordList const * list_;
612 bool Text::empty() const
614 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
615 // FIXME: Should we consider the labeled type as empty too?
616 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
620 double Text::spacing(Paragraph const & par) const
622 if (par.params().spacing().isDefault())
623 return owner_->buffer().params().spacing().getValue();
624 return par.params().spacing().getValue();
629 * This breaks a paragraph at the specified position.
630 * The new paragraph will:
631 * - Decrease depth by one (or change layout to default layout) when
632 * keep_layout == false
633 * - keep current depth and layout when keep_layout == true
635 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
638 BufferParams const & bparams = text.inset().buffer().params();
639 ParagraphList & pars = text.paragraphs();
640 // create a new paragraph, and insert into the list
641 ParagraphList::iterator tmp =
642 pars.insert(boost::next(pars.begin(), par_offset + 1),
645 Paragraph & par = pars[par_offset];
647 // remember to set the inset_owner
648 tmp->setInsetOwner(&par.inInset());
649 // without doing that we get a crash when typing <Return> at the
650 // end of a paragraph
651 tmp->setPlainOrDefaultLayout(bparams.documentClass());
654 tmp->setLayout(par.layout());
655 tmp->setLabelWidthString(par.params().labelWidthString());
656 tmp->params().depth(par.params().depth());
657 } else if (par.params().depth() > 0) {
658 Paragraph const & hook = pars[text.outerHook(par_offset)];
659 tmp->setLayout(hook.layout());
660 // not sure the line below is useful
661 tmp->setLabelWidthString(par.params().labelWidthString());
662 tmp->params().depth(hook.params().depth());
665 bool const isempty = (par.allowEmpty() && par.empty());
667 if (!isempty && (par.size() > pos || par.empty())) {
668 tmp->setLayout(par.layout());
669 tmp->params().align(par.params().align());
670 tmp->setLabelWidthString(par.params().labelWidthString());
672 tmp->params().depth(par.params().depth());
673 tmp->params().noindent(par.params().noindent());
675 // move everything behind the break position
676 // to the new paragraph
678 /* Note: if !keepempty, empty() == true, then we reach
679 * here with size() == 0. So pos_end becomes - 1. This
680 * doesn't cause problems because both loops below
681 * enforce pos <= pos_end and 0 <= pos
683 pos_type pos_end = par.size() - 1;
685 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
686 if (moveItem(par, pos, *tmp, j, bparams)) {
692 // Move over the end-of-par change information
693 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
694 par.setChange(par.size(), Change(bparams.track_changes ?
695 Change::INSERTED : Change::UNCHANGED));
698 // Make sure that we keep the language when
699 // breaking paragraph.
701 Font changed = tmp->getFirstFontSettings(bparams);
702 Font const & old = par.getFontSettings(bparams, par.size());
703 changed.setLanguage(old.language());
704 tmp->setFont(0, changed);
711 bool const soa = par.params().startOfAppendix();
712 par.params().clear();
713 // do not lose start of appendix marker (bug 4212)
714 par.params().startOfAppendix(soa);
715 par.setPlainOrDefaultLayout(bparams.documentClass());
719 par.setLayout(tmp->layout());
720 par.setLabelWidthString(tmp->params().labelWidthString());
721 par.params().depth(tmp->params().depth());
726 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
728 LBUFERR(this == cur.text());
730 Paragraph & cpar = cur.paragraph();
731 pit_type cpit = cur.pit();
733 DocumentClass const & tclass = cur.buffer()->params().documentClass();
734 Layout const & layout = cpar.layout();
736 if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
737 if (changeDepthAllowed(cur, DEC_DEPTH))
738 changeDepth(cur, DEC_DEPTH);
740 docstring const & lay = cur.paragraph().usePlainLayout()
741 ? tclass.plainLayoutName() : tclass.defaultLayoutName();
749 // Always break behind a space
750 // It is better to erase the space (Dekel)
751 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
752 cpar.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
754 // What should the layout for the new paragraph be?
755 bool keep_layout = layout.isEnvironment()
756 || (layout.isParagraph() && layout.parbreak_is_newline);
758 keep_layout = !keep_layout;
760 // We need to remember this before we break the paragraph, because
761 // that invalidates the layout variable
762 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
764 // we need to set this before we insert the paragraph.
765 bool const isempty = cpar.allowEmpty() && cpar.empty();
767 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
769 // After this, neither paragraph contains any rows!
772 pit_type next_par = cpit + 1;
774 // well this is the caption hack since one caption is really enough
777 // set to standard-layout
778 //FIXME Check if this should be plainLayout() in some cases
779 pars_[cpit].applyLayout(tclass.defaultLayout());
781 // set to standard-layout
782 //FIXME Check if this should be plainLayout() in some cases
783 pars_[next_par].applyLayout(tclass.defaultLayout());
786 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
787 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().track_changes))
788 break; // the character couldn't be deleted physically due to change tracking
791 // A singlePar update is not enough in this case.
792 cur.screenUpdateFlags(Update::Force);
793 cur.forceBufferUpdate();
795 // This check is necessary. Otherwise the new empty paragraph will
796 // be deleted automatically. And it is more friendly for the user!
797 if (cur.pos() != 0 || isempty)
798 setCursor(cur, cur.pit() + 1, 0);
800 setCursor(cur, cur.pit(), 0);
804 // needed to insert the selection
805 void Text::insertStringAsLines(Cursor & cur, docstring const & str,
808 BufferParams const & bparams = owner_->buffer().params();
809 pit_type pit = cur.pit();
810 pos_type pos = cur.pos();
812 // insert the string, don't insert doublespace
813 bool space_inserted = true;
814 for (docstring::const_iterator cit = str.begin();
815 cit != str.end(); ++cit) {
816 Paragraph & par = pars_[pit];
818 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
819 lyx::breakParagraph(*this, pit, pos,
820 par.layout().isEnvironment());
823 space_inserted = true;
827 // do not insert consecutive spaces if !free_spacing
828 } else if ((*cit == ' ' || *cit == '\t') &&
829 space_inserted && !par.isFreeSpacing()) {
831 } else if (*cit == '\t') {
832 if (!par.isFreeSpacing()) {
833 // tabs are like spaces here
834 par.insertChar(pos, ' ', font, bparams.track_changes);
836 space_inserted = true;
838 par.insertChar(pos, *cit, font, bparams.track_changes);
840 space_inserted = true;
842 } else if (!isPrintable(*cit)) {
843 // Ignore unprintables
846 // just insert the character
847 par.insertChar(pos, *cit, font, bparams.track_changes);
849 space_inserted = (*cit == ' ');
852 setCursor(cur, pit, pos);
856 // turn double CR to single CR, others are converted into one
857 // blank. Then insertStringAsLines is called
858 void Text::insertStringAsParagraphs(Cursor & cur, docstring const & str,
861 docstring linestr = str;
862 bool newline_inserted = false;
864 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
865 if (linestr[i] == '\n') {
866 if (newline_inserted) {
867 // we know that \r will be ignored by
868 // insertStringAsLines. Of course, it is a dirty
869 // trick, but it works...
870 linestr[i - 1] = '\r';
874 newline_inserted = true;
876 } else if (isPrintable(linestr[i])) {
877 newline_inserted = false;
880 insertStringAsLines(cur, linestr, font);
884 // insert a character, moves all the following breaks in the
885 // same Paragraph one to the right and make a rebreak
886 void Text::insertChar(Cursor & cur, char_type c)
888 LBUFERR(this == cur.text());
890 cur.recordUndo(INSERT_UNDO);
892 TextMetrics const & tm = cur.bv().textMetrics(this);
893 Buffer const & buffer = *cur.buffer();
894 Paragraph & par = cur.paragraph();
895 // try to remove this
896 pit_type const pit = cur.pit();
898 bool const freeSpacing = par.layout().free_spacing ||
901 if (lyxrc.auto_number) {
902 static docstring const number_operators = from_ascii("+-/*");
903 static docstring const number_unary_operators = from_ascii("+-");
904 static docstring const number_seperators = from_ascii(".,:");
906 if (cur.current_font.fontInfo().number() == FONT_ON) {
907 if (!isDigitASCII(c) && !contains(number_operators, c) &&
908 !(contains(number_seperators, c) &&
910 cur.pos() != cur.lastpos() &&
911 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
912 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
914 number(cur); // Set current_font.number to OFF
915 } else if (isDigitASCII(c) &&
916 cur.real_current_font.isVisibleRightToLeft()) {
917 number(cur); // Set current_font.number to ON
919 if (cur.pos() != 0) {
920 char_type const c = par.getChar(cur.pos() - 1);
921 if (contains(number_unary_operators, c) &&
923 || par.isSeparator(cur.pos() - 2)
924 || par.isEnvSeparator(cur.pos() - 2)
925 || par.isNewline(cur.pos() - 2))
927 setCharFont(pit, cur.pos() - 1, cur.current_font,
929 } else if (contains(number_seperators, c)
931 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
932 setCharFont(pit, cur.pos() - 1, cur.current_font,
939 // In Bidi text, we want spaces to be treated in a special way: spaces
940 // which are between words in different languages should get the
941 // paragraph's language; otherwise, spaces should keep the language
942 // they were originally typed in. This is only in effect while typing;
943 // after the text is already typed in, the user can always go back and
944 // explicitly set the language of a space as desired. But 99.9% of the
945 // time, what we're doing here is what the user actually meant.
947 // The following cases are the ones in which the language of the space
948 // should be changed to match that of the containing paragraph. In the
949 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
950 // represents a space, pipe (|) represents the cursor position (so the
951 // character before it is the one just typed in). The different cases
952 // are depicted logically (not visually), from left to right:
957 // Theoretically, there are other situations that we should, perhaps, deal
958 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
959 // point (to understand why, just try to create this situation...).
961 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
962 // get font in front and behind the space in question. But do NOT
963 // use getFont(cur.pos()) because the character c is not inserted yet
964 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
965 Font const & post_space_font = cur.real_current_font;
966 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
967 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
969 if (pre_space_rtl != post_space_rtl) {
970 // Set the space's language to match the language of the
971 // adjacent character whose direction is the paragraph's
972 // direction; don't touch other properties of the font
973 Language const * lang =
974 (pre_space_rtl == par.isRTL(buffer.params())) ?
975 pre_space_font.language() : post_space_font.language();
977 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
978 space_font.setLanguage(lang);
979 par.setFont(cur.pos() - 1, space_font);
983 // Next check, if there will be two blanks together or a blank at
984 // the beginning of a paragraph.
985 // I decided to handle blanks like normal characters, the main
986 // difference are the special checks when calculating the row.fill
987 // (blank does not count at the end of a row) and the check here
989 // When the free-spacing option is set for the current layout,
990 // disable the double-space checking
991 if (!freeSpacing && isLineSeparatorChar(c)) {
992 if (cur.pos() == 0) {
994 "You cannot insert a space at the "
995 "beginning of a paragraph. Please read the Tutorial."));
998 // LASSERT: Is it safe to continue here?
999 LASSERT(cur.pos() > 0, /**/);
1000 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
1001 && !par.isDeleted(cur.pos() - 1)) {
1003 "You cannot type two spaces this way. "
1004 "Please read the Tutorial."));
1009 // Prevent to insert uncodable characters in verbatim and ERT
1010 // (workaround for bug 9012)
1011 // Don't do it for listings inset, since InsetListings::latex() tries
1012 // to switch to a usable encoding which works in many cases (bug 9102).
1013 if (cur.paragraph().isPassThru() && owner_->lyxCode() != LISTINGS_CODE &&
1014 cur.current_font.language()) {
1015 Encoding const * e = cur.current_font.language()->encoding();
1016 if (!e->encodable(c)) {
1017 cur.message(_("Character is uncodable in verbatim paragraphs."));
1022 par.insertChar(cur.pos(), c, cur.current_font,
1023 cur.buffer()->params().track_changes);
1024 cur.checkBufferStructure();
1026 // cur.screenUpdateFlags(Update::Force);
1027 bool boundary = cur.boundary()
1028 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
1029 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
1034 void Text::charInserted(Cursor & cur)
1036 Paragraph & par = cur.paragraph();
1038 // Here we call finishUndo for every 20 characters inserted.
1039 // This is from my experience how emacs does it. (Lgb)
1040 if (undo_counter_ < 20) {
1047 // register word if a non-letter was entered
1049 && !par.isWordSeparator(cur.pos() - 2)
1050 && par.isWordSeparator(cur.pos() - 1)) {
1051 // get the word in front of cursor
1052 LBUFERR(this == cur.text());
1053 cur.paragraph().updateWords();
1058 // the cursor set functions have a special mechanism. When they
1059 // realize, that you left an empty paragraph, they will delete it.
1061 bool Text::cursorForwardOneWord(Cursor & cur)
1063 LBUFERR(this == cur.text());
1065 pos_type const lastpos = cur.lastpos();
1066 pit_type pit = cur.pit();
1067 pos_type pos = cur.pos();
1068 Paragraph const & par = cur.paragraph();
1070 // Paragraph boundary is a word boundary
1071 if (pos == lastpos) {
1072 if (pit != cur.lastpit())
1073 return setCursor(cur, pit + 1, 0);
1078 if (lyxrc.mac_like_cursor_movement) {
1079 // Skip through trailing punctuation and spaces.
1080 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1083 // Skip over either a non-char inset or a full word
1084 if (pos != lastpos && par.isWordSeparator(pos))
1086 else while (pos != lastpos && !par.isWordSeparator(pos))
1089 LASSERT(pos < lastpos, return false); // see above
1090 if (!par.isWordSeparator(pos))
1091 while (pos != lastpos && !par.isWordSeparator(pos))
1093 else if (par.isChar(pos))
1094 while (pos != lastpos && par.isChar(pos))
1096 else if (!par.isSpace(pos)) // non-char inset
1099 // Skip over white space
1100 while (pos != lastpos && par.isSpace(pos))
1104 return setCursor(cur, pit, pos);
1108 bool Text::cursorBackwardOneWord(Cursor & cur)
1110 LBUFERR(this == cur.text());
1112 pit_type pit = cur.pit();
1113 pos_type pos = cur.pos();
1114 Paragraph & par = cur.paragraph();
1116 // Paragraph boundary is a word boundary
1117 if (pos == 0 && pit != 0)
1118 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1120 if (lyxrc.mac_like_cursor_movement) {
1121 // Skip through punctuation and spaces.
1122 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1125 // Skip over either a non-char inset or a full word
1126 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1128 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1131 // Skip over white space
1132 while (pos != 0 && par.isSpace(pos - 1))
1135 if (pos != 0 && !par.isWordSeparator(pos - 1))
1136 while (pos != 0 && !par.isWordSeparator(pos - 1))
1138 else if (pos != 0 && par.isChar(pos - 1))
1139 while (pos != 0 && par.isChar(pos - 1))
1141 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1145 return setCursor(cur, pit, pos);
1149 bool Text::cursorVisLeftOneWord(Cursor & cur)
1151 LBUFERR(this == cur.text());
1153 pos_type left_pos, right_pos;
1154 bool left_is_letter, right_is_letter;
1156 Cursor temp_cur = cur;
1158 // always try to move at least once...
1159 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1161 // collect some information about current cursor position
1162 temp_cur.getSurroundingPos(left_pos, right_pos);
1164 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1166 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1168 // if we're not at a letter/non-letter boundary, continue moving
1169 if (left_is_letter == right_is_letter)
1172 // we should stop when we have an LTR word on our right or an RTL word
1174 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1175 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1176 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1177 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1181 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1182 true, temp_cur.boundary());
1186 bool Text::cursorVisRightOneWord(Cursor & cur)
1188 LBUFERR(this == cur.text());
1190 pos_type left_pos, right_pos;
1191 bool left_is_letter, right_is_letter;
1193 Cursor temp_cur = cur;
1195 // always try to move at least once...
1196 while (temp_cur.posVisRight(true /* skip_inset */)) {
1198 // collect some information about current cursor position
1199 temp_cur.getSurroundingPos(left_pos, right_pos);
1201 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1203 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1205 // if we're not at a letter/non-letter boundary, continue moving
1206 if (left_is_letter == right_is_letter)
1209 // we should stop when we have an LTR word on our right or an RTL word
1211 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1212 temp_cur.buffer()->params(),
1213 left_pos).isRightToLeft())
1214 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1215 temp_cur.buffer()->params(),
1216 right_pos).isRightToLeft()))
1220 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1221 true, temp_cur.boundary());
1225 void Text::selectWord(Cursor & cur, word_location loc)
1227 LBUFERR(this == cur.text());
1228 CursorSlice from = cur.top();
1229 CursorSlice to = cur.top();
1230 getWord(from, to, loc);
1231 if (cur.top() != from)
1232 setCursor(cur, from.pit(), from.pos());
1235 if (!cur.selection())
1237 setCursor(cur, to.pit(), to.pos());
1239 cur.setWordSelection(true);
1243 void Text::selectAll(Cursor & cur)
1245 LBUFERR(this == cur.text());
1246 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1248 // If the cursor is at the beginning, make sure the cursor ends there
1249 if (cur.pit() == 0 && cur.pos() == 0) {
1250 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1252 setCursor(cur, 0, 0);
1254 setCursor(cur, 0, 0);
1256 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1262 // Select the word currently under the cursor when no
1263 // selection is currently set
1264 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1266 LBUFERR(this == cur.text());
1267 if (cur.selection())
1269 selectWord(cur, loc);
1270 return cur.selection();
1274 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1276 LBUFERR(this == cur.text());
1278 if (!cur.selection()) {
1279 if (!selectChange(cur))
1283 cur.recordUndoSelection();
1285 pit_type begPit = cur.selectionBegin().pit();
1286 pit_type endPit = cur.selectionEnd().pit();
1288 pos_type begPos = cur.selectionBegin().pos();
1289 pos_type endPos = cur.selectionEnd().pos();
1291 // keep selection info, because endPos becomes invalid after the first loop
1292 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1294 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1295 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1296 pos_type parSize = pars_[pit].size();
1298 // ignore empty paragraphs; otherwise, an assertion will fail for
1299 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1303 // do not consider first paragraph if the cursor starts at pos size()
1304 if (pit == begPit && begPos == parSize)
1307 // do not consider last paragraph if the cursor ends at pos 0
1308 if (pit == endPit && endPos == 0)
1309 break; // last iteration anyway
1311 pos_type left = (pit == begPit ? begPos : 0);
1312 pos_type right = (pit == endPit ? endPos : parSize);
1315 // there is no change here
1319 pars_[pit].acceptChanges(left, right);
1321 pars_[pit].rejectChanges(left, right);
1325 // next, accept/reject imaginary end-of-par characters
1327 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1328 pos_type pos = pars_[pit].size();
1330 // skip if the selection ends before the end-of-par
1331 if (pit == endPit && endsBeforeEndOfPar)
1332 break; // last iteration anyway
1334 // skip if this is not the last paragraph of the document
1335 // note: the user should be able to accept/reject the par break of the last par!
1336 if (pit == endPit && pit + 1 != int(pars_.size()))
1337 break; // last iteration anway
1340 if (pars_[pit].isInserted(pos)) {
1341 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1342 } else if (pars_[pit].isDeleted(pos)) {
1343 if (pit + 1 == int(pars_.size())) {
1344 // we cannot remove a par break at the end of the last paragraph;
1345 // instead, we mark it unchanged
1346 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1348 mergeParagraph(cur.buffer()->params(), pars_, pit);
1354 if (pars_[pit].isDeleted(pos)) {
1355 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1356 } else if (pars_[pit].isInserted(pos)) {
1357 if (pit + 1 == int(pars_.size())) {
1358 // we mark the par break at the end of the last paragraph unchanged
1359 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1361 mergeParagraph(cur.buffer()->params(), pars_, pit);
1369 // finally, invoke the DEPM
1370 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().track_changes);
1373 cur.clearSelection();
1374 setCursorIntern(cur, begPit, begPos);
1375 cur.screenUpdateFlags(Update::Force);
1376 cur.forceBufferUpdate();
1380 void Text::acceptChanges()
1382 BufferParams const & bparams = owner_->buffer().params();
1383 lyx::acceptChanges(pars_, bparams);
1384 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.track_changes);
1388 void Text::rejectChanges()
1390 BufferParams const & bparams = owner_->buffer().params();
1391 pit_type pars_size = static_cast<pit_type>(pars_.size());
1393 // first, reject changes within each individual paragraph
1394 // (do not consider end-of-par)
1395 for (pit_type pit = 0; pit < pars_size; ++pit) {
1396 if (!pars_[pit].empty()) // prevent assertion failure
1397 pars_[pit].rejectChanges(0, pars_[pit].size());
1400 // next, reject imaginary end-of-par characters
1401 for (pit_type pit = 0; pit < pars_size; ++pit) {
1402 pos_type pos = pars_[pit].size();
1404 if (pars_[pit].isDeleted(pos)) {
1405 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1406 } else if (pars_[pit].isInserted(pos)) {
1407 if (pit == pars_size - 1) {
1408 // we mark the par break at the end of the last
1409 // paragraph unchanged
1410 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1412 mergeParagraph(bparams, pars_, pit);
1419 // finally, invoke the DEPM
1420 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.track_changes);
1424 void Text::deleteWordForward(Cursor & cur)
1426 LBUFERR(this == cur.text());
1427 if (cur.lastpos() == 0)
1431 cur.setSelection(true);
1432 cursorForwardOneWord(cur);
1434 cutSelection(cur, true, false);
1435 cur.checkBufferStructure();
1440 void Text::deleteWordBackward(Cursor & cur)
1442 LBUFERR(this == cur.text());
1443 if (cur.lastpos() == 0)
1444 cursorBackward(cur);
1447 cur.setSelection(true);
1448 cursorBackwardOneWord(cur);
1450 cutSelection(cur, true, false);
1451 cur.checkBufferStructure();
1456 // Kill to end of line.
1457 void Text::changeCase(Cursor & cur, TextCase action)
1459 LBUFERR(this == cur.text());
1463 bool gotsel = false;
1464 if (cur.selection()) {
1465 from = cur.selBegin();
1470 getWord(from, to, PARTIAL_WORD);
1471 cursorForwardOneWord(cur);
1474 cur.recordUndoSelection();
1476 pit_type begPit = from.pit();
1477 pit_type endPit = to.pit();
1479 pos_type begPos = from.pos();
1480 pos_type endPos = to.pos();
1482 pos_type right = 0; // needed after the for loop
1484 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1485 Paragraph & par = pars_[pit];
1486 pos_type const pos = (pit == begPit ? begPos : 0);
1487 right = (pit == endPit ? endPos : par.size());
1488 par.changeCase(cur.buffer()->params(), pos, right, action);
1491 // the selection may have changed due to logically-only deleted chars
1493 setCursor(cur, begPit, begPos);
1495 setCursor(cur, endPit, right);
1498 setCursor(cur, endPit, right);
1500 cur.checkBufferStructure();
1504 bool Text::handleBibitems(Cursor & cur)
1506 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1512 BufferParams const & bufparams = cur.buffer()->params();
1513 Paragraph const & par = cur.paragraph();
1514 Cursor prevcur = cur;
1515 if (cur.pit() > 0) {
1517 prevcur.pos() = prevcur.lastpos();
1519 Paragraph const & prevpar = prevcur.paragraph();
1521 // if a bibitem is deleted, merge with previous paragraph
1522 // if this is a bibliography item as well
1523 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1524 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1525 mergeParagraph(bufparams, cur.text()->paragraphs(),
1527 cur.forceBufferUpdate();
1528 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1529 cur.screenUpdateFlags(Update::Force);
1533 // otherwise reset to default
1534 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1539 bool Text::erase(Cursor & cur)
1541 LASSERT(this == cur.text(), return false);
1542 bool needsUpdate = false;
1543 Paragraph & par = cur.paragraph();
1545 if (cur.pos() != cur.lastpos()) {
1546 // this is the code for a normal delete, not pasting
1548 cur.recordUndo(DELETE_UNDO);
1549 bool const was_inset = cur.paragraph().isInset(cur.pos());
1550 if(!par.eraseChar(cur.pos(), cur.buffer()->params().track_changes))
1551 // the character has been logically deleted only => skip it
1552 cur.top().forwardPos();
1555 cur.forceBufferUpdate();
1557 cur.checkBufferStructure();
1560 if (cur.pit() == cur.lastpit())
1561 return dissolveInset(cur);
1563 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1564 par.setChange(cur.pos(), Change(Change::DELETED));
1568 setCursorIntern(cur, cur.pit() + 1, 0);
1569 needsUpdate = backspacePos0(cur);
1573 needsUpdate |= handleBibitems(cur);
1576 // Make sure the cursor is correct. Is this really needed?
1577 // No, not really... at least not here!
1578 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1579 cur.checkBufferStructure();
1586 bool Text::backspacePos0(Cursor & cur)
1588 LBUFERR(this == cur.text());
1592 bool needsUpdate = false;
1594 BufferParams const & bufparams = cur.buffer()->params();
1595 DocumentClass const & tclass = bufparams.documentClass();
1596 ParagraphList & plist = cur.text()->paragraphs();
1597 Paragraph const & par = cur.paragraph();
1598 Cursor prevcur = cur;
1600 prevcur.pos() = prevcur.lastpos();
1601 Paragraph const & prevpar = prevcur.paragraph();
1603 // is it an empty paragraph?
1604 if (cur.lastpos() == 0
1605 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1606 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1607 plist.erase(boost::next(plist.begin(), cur.pit()));
1610 // is previous par empty?
1611 else if (prevcur.lastpos() == 0
1612 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1613 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1614 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1617 // Pasting is not allowed, if the paragraphs have different
1618 // layouts. I think it is a real bug of all other
1619 // word processors to allow it. It confuses the user.
1620 // Correction: Pasting is always allowed with standard-layout
1621 // or the empty layout.
1622 else if (par.layout() == prevpar.layout()
1623 || tclass.isDefaultLayout(par.layout())
1624 || tclass.isPlainLayout(par.layout())) {
1625 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1626 mergeParagraph(bufparams, plist, prevcur.pit());
1631 cur.forceBufferUpdate();
1632 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1639 bool Text::backspace(Cursor & cur)
1641 LBUFERR(this == cur.text());
1642 bool needsUpdate = false;
1643 if (cur.pos() == 0) {
1645 return dissolveInset(cur);
1647 Cursor prev_cur = cur;
1650 if (!prev_cur.paragraph().isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1651 cur.recordUndo(ATOMIC_UNDO, prev_cur.pit(), prev_cur.pit());
1652 prev_cur.paragraph().setChange(prev_cur.lastpos(), Change(Change::DELETED));
1653 setCursorIntern(cur, prev_cur.pit(), prev_cur.lastpos());
1656 // The cursor is at the beginning of a paragraph, so
1657 // the backspace will collapse two paragraphs into one.
1658 needsUpdate = backspacePos0(cur);
1661 // this is the code for a normal backspace, not pasting
1663 cur.recordUndo(DELETE_UNDO);
1664 // We used to do cursorBackwardIntern() here, but it is
1665 // not a good idea since it triggers the auto-delete
1666 // mechanism. So we do a cursorBackwardIntern()-lite,
1667 // without the dreaded mechanism. (JMarc)
1668 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1669 false, cur.boundary());
1670 bool const was_inset = cur.paragraph().isInset(cur.pos());
1671 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().track_changes);
1673 cur.forceBufferUpdate();
1675 cur.checkBufferStructure();
1678 if (cur.pos() == cur.lastpos())
1679 cur.setCurrentFont();
1681 needsUpdate |= handleBibitems(cur);
1683 // A singlePar update is not enough in this case.
1684 // cur.screenUpdateFlags(Update::Force);
1685 setCursor(cur.top(), cur.pit(), cur.pos());
1691 bool Text::dissolveInset(Cursor & cur)
1693 LASSERT(this == cur.text(), return false);
1695 if (isMainText() || cur.inset().nargs() != 1)
1698 cur.recordUndoInset();
1700 cur.selHandle(false);
1702 pos_type spos = cur.pos();
1703 pit_type spit = cur.pit();
1704 ParagraphList plist;
1705 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1706 plist = paragraphs();
1708 // store cursor offset
1712 Buffer & b = *cur.buffer();
1713 cur.paragraph().eraseChar(cur.pos(), b.params().track_changes);
1715 if (!plist.empty()) {
1717 // we clear the cache so that we won't get conflicts with labels
1718 // that get pasted into the buffer. we should update this before
1719 // its being empty matters. if not (i.e., if we encounter bugs),
1720 // then this should instead be:
1721 // cur.buffer().updateBuffer();
1722 // but we'll try the cheaper solution here.
1723 cur.buffer()->clearReferenceCache();
1725 // ERT paragraphs have the Language latex_language.
1726 // This is invalid outside of ERT, so we need to
1727 // change it to the buffer language.
1728 ParagraphList::iterator it = plist.begin();
1729 ParagraphList::iterator it_end = plist.end();
1730 for (; it != it_end; ++it)
1731 it->changeLanguage(b.params(), latex_language, b.language());
1733 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1734 b.errorList("Paste"));
1736 cur.pit() = min(cur.lastpit(), spit);
1737 cur.pos() = min(cur.lastpos(), spos);
1740 cur.forceBufferUpdate();
1742 // Ensure the current language is set correctly (bug 6292)
1743 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1744 cur.clearSelection();
1750 void Text::getWord(CursorSlice & from, CursorSlice & to,
1751 word_location const loc) const
1754 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1758 void Text::write(ostream & os) const
1760 Buffer const & buf = owner_->buffer();
1761 ParagraphList::const_iterator pit = paragraphs().begin();
1762 ParagraphList::const_iterator end = paragraphs().end();
1764 for (; pit != end; ++pit)
1765 pit->write(os, buf.params(), dth);
1767 // Close begin_deeper
1768 for(; dth > 0; --dth)
1769 os << "\n\\end_deeper";
1773 bool Text::read(Lexer & lex,
1774 ErrorList & errorList, InsetText * insetPtr)
1776 Buffer const & buf = owner_->buffer();
1777 depth_type depth = 0;
1780 while (lex.isOK()) {
1782 string const token = lex.getString();
1787 if (token == "\\end_inset")
1790 if (token == "\\end_body")
1793 if (token == "\\begin_body")
1796 if (token == "\\end_document") {
1801 if (token == "\\begin_layout") {
1802 lex.pushToken(token);
1805 par.setInsetOwner(insetPtr);
1806 par.params().depth(depth);
1807 par.setFont(0, Font(inherit_font, buf.params().language));
1808 pars_.push_back(par);
1809 readParagraph(pars_.back(), lex, errorList);
1811 // register the words in the global word list
1812 pars_.back().updateWords();
1813 } else if (token == "\\begin_deeper") {
1815 } else if (token == "\\end_deeper") {
1817 lex.printError("\\end_deeper: " "depth is already null");
1821 LYXERR0("Handling unknown body token: `" << token << '\'');
1825 // avoid a crash on weird documents (bug 4859)
1826 if (pars_.empty()) {
1828 par.setInsetOwner(insetPtr);
1829 par.params().depth(depth);
1830 par.setFont(0, Font(inherit_font,
1831 buf.params().language));
1832 par.setPlainOrDefaultLayout(buf.params().documentClass());
1833 pars_.push_back(par);
1840 // Returns the current font and depth as a message.
1841 docstring Text::currentState(Cursor const & cur) const
1843 LBUFERR(this == cur.text());
1844 Buffer & buf = *cur.buffer();
1845 Paragraph const & par = cur.paragraph();
1846 odocstringstream os;
1848 if (buf.params().track_changes)
1849 os << _("[Change Tracking] ");
1851 Change change = par.lookupChange(cur.pos());
1853 if (change.changed()) {
1854 Author const & a = buf.params().authors().get(change.author);
1855 os << _("Change: ") << a.name();
1856 if (!a.email().empty())
1857 os << " (" << a.email() << ")";
1858 // FIXME ctime is english, we should translate that
1859 os << _(" at ") << ctime(&change.changetime);
1863 // I think we should only show changes from the default
1865 // No, from the document font (MV)
1866 Font font = cur.real_current_font;
1867 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1869 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1871 // The paragraph depth
1872 int depth = cur.paragraph().getDepth();
1874 os << bformat(_(", Depth: %1$d"), depth);
1876 // The paragraph spacing, but only if different from
1878 Spacing const & spacing = par.params().spacing();
1879 if (!spacing.isDefault()) {
1880 os << _(", Spacing: ");
1881 switch (spacing.getSpace()) {
1882 case Spacing::Single:
1885 case Spacing::Onehalf:
1888 case Spacing::Double:
1891 case Spacing::Other:
1892 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1894 case Spacing::Default:
1895 // should never happen, do nothing
1900 #ifdef DEVEL_VERSION
1901 os << _(", Inset: ") << &cur.inset();
1902 os << _(", Paragraph: ") << cur.pit();
1903 os << _(", Id: ") << par.id();
1904 os << _(", Position: ") << cur.pos();
1905 // FIXME: Why is the check for par.size() needed?
1906 // We are called with cur.pos() == par.size() quite often.
1907 if (!par.empty() && cur.pos() < par.size()) {
1908 // Force output of code point, not character
1909 size_t const c = par.getChar(cur.pos());
1910 os << _(", Char: 0x") << hex << c;
1912 os << _(", Boundary: ") << cur.boundary();
1913 // Row & row = cur.textRow();
1914 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1920 docstring Text::getPossibleLabel(Cursor const & cur) const
1922 pit_type pit = cur.pit();
1924 Layout const * layout = &(pars_[pit].layout());
1927 docstring par_text = pars_[pit].asString();
1929 // The return string of math matrices might contain linebreaks
1930 par_text = subst(par_text, '\n', '-');
1931 int const numwords = 3;
1932 for (int i = 0; i < numwords; ++i) {
1933 if (par_text.empty())
1936 par_text = split(par_text, head, ' ');
1937 // Is it legal to use spaces in labels ?
1943 // Make sure it isn't too long
1944 unsigned int const max_label_length = 32;
1945 if (text.size() > max_label_length)
1946 text.resize(max_label_length);
1948 // Will contain the label prefix.
1951 // For section, subsection, etc...
1952 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1953 Layout const * layout2 = &(pars_[pit - 1].layout());
1954 if (layout2->latextype != LATEX_PARAGRAPH) {
1959 if (layout->latextype != LATEX_PARAGRAPH)
1960 name = layout->refprefix;
1962 // For captions, we just take the caption type
1963 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1964 if (caption_inset) {
1965 string const & ftype = static_cast<InsetCaption *>(caption_inset)->floattype();
1966 FloatList const & fl = cur.buffer()->params().documentClass().floats();
1967 if (fl.typeExist(ftype)) {
1968 Floating const & flt = fl.getType(ftype);
1969 name = from_utf8(flt.refPrefix());
1972 name = from_utf8(ftype.substr(0,3));
1975 // If none of the above worked, see if the inset knows.
1977 InsetLayout const & il = cur.inset().getLayout();
1978 name = il.refprefix();
1982 text = name + ':' + text;
1984 // We need a unique label
1985 docstring label = text;
1987 while (cur.buffer()->insetLabel(label)) {
1988 label = text + '-' + convert<docstring>(i);
1996 docstring Text::asString(int options) const
1998 return asString(0, pars_.size(), options);
2002 docstring Text::asString(pit_type beg, pit_type end, int options) const
2004 size_t i = size_t(beg);
2005 docstring str = pars_[i].asString(options);
2006 for (++i; i != size_t(end); ++i) {
2008 str += pars_[i].asString(options);
2014 void Text::forOutliner(docstring & os, size_t maxlen, bool shorten) const
2017 maxlen = std::numeric_limits<std::size_t>::max();
2019 LASSERT(maxlen >= 8, maxlen = TOC_ENTRY_LENGTH);
2020 for (size_t i = 0; i != pars_.size() && os.length() < maxlen; ++i)
2021 pars_[i].forOutliner(os, maxlen);
2022 if (shorten && os.length() >= maxlen)
2023 os = os.substr(0, maxlen - 3) + from_ascii("...");
2027 void Text::charsTranspose(Cursor & cur)
2029 LBUFERR(this == cur.text());
2031 pos_type pos = cur.pos();
2033 // If cursor is at beginning or end of paragraph, do nothing.
2034 if (pos == cur.lastpos() || pos == 0)
2037 Paragraph & par = cur.paragraph();
2039 // Get the positions of the characters to be transposed.
2040 pos_type pos1 = pos - 1;
2041 pos_type pos2 = pos;
2043 // In change tracking mode, ignore deleted characters.
2044 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2046 if (pos2 == cur.lastpos())
2049 while (pos1 >= 0 && par.isDeleted(pos1))
2054 // Don't do anything if one of the "characters" is not regular text.
2055 if (par.isInset(pos1) || par.isInset(pos2))
2058 // Store the characters to be transposed (including font information).
2059 char_type const char1 = par.getChar(pos1);
2061 par.getFontSettings(cur.buffer()->params(), pos1);
2063 char_type const char2 = par.getChar(pos2);
2065 par.getFontSettings(cur.buffer()->params(), pos2);
2067 // And finally, we are ready to perform the transposition.
2068 // Track the changes if Change Tracking is enabled.
2069 bool const trackChanges = cur.buffer()->params().track_changes;
2073 par.eraseChar(pos2, trackChanges);
2074 par.eraseChar(pos1, trackChanges);
2075 par.insertChar(pos1, char2, font2, trackChanges);
2076 par.insertChar(pos2, char1, font1, trackChanges);
2078 cur.checkBufferStructure();
2080 // After the transposition, move cursor to after the transposition.
2081 setCursor(cur, cur.pit(), pos2);
2086 DocIterator Text::macrocontextPosition() const
2088 return macrocontext_position_;
2092 void Text::setMacrocontextPosition(DocIterator const & pos)
2094 macrocontext_position_ = pos;
2098 docstring Text::previousWord(CursorSlice const & sl) const
2100 CursorSlice from = sl;
2101 CursorSlice to = sl;
2102 getWord(from, to, PREVIOUS_WORD);
2103 if (sl == from || to == from)
2106 Paragraph const & par = sl.paragraph();
2107 return par.asString(from.pos(), to.pos());
2111 bool Text::completionSupported(Cursor const & cur) const
2113 Paragraph const & par = cur.paragraph();
2114 return cur.pos() > 0
2115 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2116 && !par.isWordSeparator(cur.pos() - 1);
2120 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2122 WordList const * list = theWordList(cur.getFont().language()->lang());
2123 return new TextCompletionList(cur, list);
2127 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2129 LBUFERR(cur.bv().cursor() == cur);
2131 cur.bv().cursor() = cur;
2132 if (!(cur.result().screenUpdate() & Update::Force))
2133 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2138 docstring Text::completionPrefix(Cursor const & cur) const
2140 return previousWord(cur.top());