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.isNewline(cur.pos() - 2))
926 setCharFont(pit, cur.pos() - 1, cur.current_font,
928 } else if (contains(number_seperators, c)
930 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
931 setCharFont(pit, cur.pos() - 1, cur.current_font,
938 // In Bidi text, we want spaces to be treated in a special way: spaces
939 // which are between words in different languages should get the
940 // paragraph's language; otherwise, spaces should keep the language
941 // they were originally typed in. This is only in effect while typing;
942 // after the text is already typed in, the user can always go back and
943 // explicitly set the language of a space as desired. But 99.9% of the
944 // time, what we're doing here is what the user actually meant.
946 // The following cases are the ones in which the language of the space
947 // should be changed to match that of the containing paragraph. In the
948 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
949 // represents a space, pipe (|) represents the cursor position (so the
950 // character before it is the one just typed in). The different cases
951 // are depicted logically (not visually), from left to right:
956 // Theoretically, there are other situations that we should, perhaps, deal
957 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
958 // point (to understand why, just try to create this situation...).
960 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
961 // get font in front and behind the space in question. But do NOT
962 // use getFont(cur.pos()) because the character c is not inserted yet
963 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
964 Font const & post_space_font = cur.real_current_font;
965 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
966 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
968 if (pre_space_rtl != post_space_rtl) {
969 // Set the space's language to match the language of the
970 // adjacent character whose direction is the paragraph's
971 // direction; don't touch other properties of the font
972 Language const * lang =
973 (pre_space_rtl == par.isRTL(buffer.params())) ?
974 pre_space_font.language() : post_space_font.language();
976 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
977 space_font.setLanguage(lang);
978 par.setFont(cur.pos() - 1, space_font);
982 // Next check, if there will be two blanks together or a blank at
983 // the beginning of a paragraph.
984 // I decided to handle blanks like normal characters, the main
985 // difference are the special checks when calculating the row.fill
986 // (blank does not count at the end of a row) and the check here
988 // When the free-spacing option is set for the current layout,
989 // disable the double-space checking
990 if (!freeSpacing && isLineSeparatorChar(c)) {
991 if (cur.pos() == 0) {
993 "You cannot insert a space at the "
994 "beginning of a paragraph. Please read the Tutorial."));
997 // LASSERT: Is it safe to continue here?
998 LASSERT(cur.pos() > 0, /**/);
999 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
1000 && !par.isDeleted(cur.pos() - 1)) {
1002 "You cannot type two spaces this way. "
1003 "Please read the Tutorial."));
1008 // Prevent to insert uncodable characters in verbatim and ERT
1009 // (workaround for bug 9012)
1010 if (cur.paragraph().isPassThru() && cur.current_font.language()) {
1011 Encoding const * e = cur.current_font.language()->encoding();
1012 if (!e->encodable(c)) {
1013 cur.message(_("Character is uncodable in verbatim paragraphs."));
1018 par.insertChar(cur.pos(), c, cur.current_font,
1019 cur.buffer()->params().track_changes);
1020 cur.checkBufferStructure();
1022 // cur.screenUpdateFlags(Update::Force);
1023 bool boundary = cur.boundary()
1024 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
1025 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
1030 void Text::charInserted(Cursor & cur)
1032 Paragraph & par = cur.paragraph();
1034 // Here we call finishUndo for every 20 characters inserted.
1035 // This is from my experience how emacs does it. (Lgb)
1036 if (undo_counter_ < 20) {
1043 // register word if a non-letter was entered
1045 && !par.isWordSeparator(cur.pos() - 2)
1046 && par.isWordSeparator(cur.pos() - 1)) {
1047 // get the word in front of cursor
1048 LBUFERR(this == cur.text());
1049 cur.paragraph().updateWords();
1054 // the cursor set functions have a special mechanism. When they
1055 // realize, that you left an empty paragraph, they will delete it.
1057 bool Text::cursorForwardOneWord(Cursor & cur)
1059 LBUFERR(this == cur.text());
1061 pos_type const lastpos = cur.lastpos();
1062 pit_type pit = cur.pit();
1063 pos_type pos = cur.pos();
1064 Paragraph const & par = cur.paragraph();
1066 // Paragraph boundary is a word boundary
1067 if (pos == lastpos) {
1068 if (pit != cur.lastpit())
1069 return setCursor(cur, pit + 1, 0);
1074 if (lyxrc.mac_like_cursor_movement) {
1075 // Skip through trailing punctuation and spaces.
1076 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1079 // Skip over either a non-char inset or a full word
1080 if (pos != lastpos && par.isWordSeparator(pos))
1082 else while (pos != lastpos && !par.isWordSeparator(pos))
1085 LASSERT(pos < lastpos, return false); // see above
1086 if (!par.isWordSeparator(pos))
1087 while (pos != lastpos && !par.isWordSeparator(pos))
1089 else if (par.isChar(pos))
1090 while (pos != lastpos && par.isChar(pos))
1092 else if (!par.isSpace(pos)) // non-char inset
1095 // Skip over white space
1096 while (pos != lastpos && par.isSpace(pos))
1100 return setCursor(cur, pit, pos);
1104 bool Text::cursorBackwardOneWord(Cursor & cur)
1106 LBUFERR(this == cur.text());
1108 pit_type pit = cur.pit();
1109 pos_type pos = cur.pos();
1110 Paragraph & par = cur.paragraph();
1112 // Paragraph boundary is a word boundary
1113 if (pos == 0 && pit != 0)
1114 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1116 if (lyxrc.mac_like_cursor_movement) {
1117 // Skip through punctuation and spaces.
1118 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1121 // Skip over either a non-char inset or a full word
1122 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1124 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1127 // Skip over white space
1128 while (pos != 0 && par.isSpace(pos - 1))
1131 if (pos != 0 && !par.isWordSeparator(pos - 1))
1132 while (pos != 0 && !par.isWordSeparator(pos - 1))
1134 else if (pos != 0 && par.isChar(pos - 1))
1135 while (pos != 0 && par.isChar(pos - 1))
1137 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1141 return setCursor(cur, pit, pos);
1145 bool Text::cursorVisLeftOneWord(Cursor & cur)
1147 LBUFERR(this == cur.text());
1149 pos_type left_pos, right_pos;
1150 bool left_is_letter, right_is_letter;
1152 Cursor temp_cur = cur;
1154 // always try to move at least once...
1155 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1157 // collect some information about current cursor position
1158 temp_cur.getSurroundingPos(left_pos, right_pos);
1160 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1162 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1164 // if we're not at a letter/non-letter boundary, continue moving
1165 if (left_is_letter == right_is_letter)
1168 // we should stop when we have an LTR word on our right or an RTL word
1170 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1171 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1172 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1173 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1177 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1178 true, temp_cur.boundary());
1182 bool Text::cursorVisRightOneWord(Cursor & cur)
1184 LBUFERR(this == cur.text());
1186 pos_type left_pos, right_pos;
1187 bool left_is_letter, right_is_letter;
1189 Cursor temp_cur = cur;
1191 // always try to move at least once...
1192 while (temp_cur.posVisRight(true /* skip_inset */)) {
1194 // collect some information about current cursor position
1195 temp_cur.getSurroundingPos(left_pos, right_pos);
1197 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1199 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1201 // if we're not at a letter/non-letter boundary, continue moving
1202 if (left_is_letter == right_is_letter)
1205 // we should stop when we have an LTR word on our right or an RTL word
1207 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1208 temp_cur.buffer()->params(),
1209 left_pos).isRightToLeft())
1210 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1211 temp_cur.buffer()->params(),
1212 right_pos).isRightToLeft()))
1216 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1217 true, temp_cur.boundary());
1221 void Text::selectWord(Cursor & cur, word_location loc)
1223 LBUFERR(this == cur.text());
1224 CursorSlice from = cur.top();
1225 CursorSlice to = cur.top();
1226 getWord(from, to, loc);
1227 if (cur.top() != from)
1228 setCursor(cur, from.pit(), from.pos());
1231 if (!cur.selection())
1233 setCursor(cur, to.pit(), to.pos());
1235 cur.setWordSelection(true);
1239 void Text::selectAll(Cursor & cur)
1241 LBUFERR(this == cur.text());
1242 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1244 // If the cursor is at the beginning, make sure the cursor ends there
1245 if (cur.pit() == 0 && cur.pos() == 0) {
1246 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1248 setCursor(cur, 0, 0);
1250 setCursor(cur, 0, 0);
1252 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1258 // Select the word currently under the cursor when no
1259 // selection is currently set
1260 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1262 LBUFERR(this == cur.text());
1263 if (cur.selection())
1265 selectWord(cur, loc);
1266 return cur.selection();
1270 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1272 LBUFERR(this == cur.text());
1274 if (!cur.selection()) {
1275 bool const changed = cur.paragraph().isChanged(cur.pos());
1276 if (!(changed && findNextChange(&cur.bv())))
1280 cur.recordUndoSelection();
1282 pit_type begPit = cur.selectionBegin().pit();
1283 pit_type endPit = cur.selectionEnd().pit();
1285 pos_type begPos = cur.selectionBegin().pos();
1286 pos_type endPos = cur.selectionEnd().pos();
1288 // keep selection info, because endPos becomes invalid after the first loop
1289 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1291 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1293 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1294 pos_type parSize = pars_[pit].size();
1296 // ignore empty paragraphs; otherwise, an assertion will fail for
1297 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1301 // do not consider first paragraph if the cursor starts at pos size()
1302 if (pit == begPit && begPos == parSize)
1305 // do not consider last paragraph if the cursor ends at pos 0
1306 if (pit == endPit && endPos == 0)
1307 break; // last iteration anyway
1309 pos_type left = (pit == begPit ? begPos : 0);
1310 pos_type right = (pit == endPit ? endPos : parSize);
1313 // there is no change here
1317 pars_[pit].acceptChanges(left, right);
1319 pars_[pit].rejectChanges(left, right);
1323 // next, accept/reject imaginary end-of-par characters
1325 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1326 pos_type pos = pars_[pit].size();
1328 // skip if the selection ends before the end-of-par
1329 if (pit == endPit && endsBeforeEndOfPar)
1330 break; // last iteration anyway
1332 // skip if this is not the last paragraph of the document
1333 // note: the user should be able to accept/reject the par break of the last par!
1334 if (pit == endPit && pit + 1 != int(pars_.size()))
1335 break; // last iteration anway
1338 if (pars_[pit].isInserted(pos)) {
1339 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1340 } else if (pars_[pit].isDeleted(pos)) {
1341 if (pit + 1 == int(pars_.size())) {
1342 // we cannot remove a par break at the end of the last paragraph;
1343 // instead, we mark it unchanged
1344 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1346 mergeParagraph(cur.buffer()->params(), pars_, pit);
1352 if (pars_[pit].isDeleted(pos)) {
1353 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1354 } else if (pars_[pit].isInserted(pos)) {
1355 if (pit + 1 == int(pars_.size())) {
1356 // we mark the par break at the end of the last paragraph unchanged
1357 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1359 mergeParagraph(cur.buffer()->params(), pars_, pit);
1367 // finally, invoke the DEPM
1369 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().track_changes);
1374 cur.clearSelection();
1375 setCursorIntern(cur, begPit, begPos);
1376 cur.screenUpdateFlags(Update::Force);
1377 cur.forceBufferUpdate();
1381 void Text::acceptChanges()
1383 BufferParams const & bparams = owner_->buffer().params();
1384 lyx::acceptChanges(pars_, bparams);
1385 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.track_changes);
1389 void Text::rejectChanges()
1391 BufferParams const & bparams = owner_->buffer().params();
1392 pit_type pars_size = static_cast<pit_type>(pars_.size());
1394 // first, reject changes within each individual paragraph
1395 // (do not consider end-of-par)
1396 for (pit_type pit = 0; pit < pars_size; ++pit) {
1397 if (!pars_[pit].empty()) // prevent assertion failure
1398 pars_[pit].rejectChanges(0, pars_[pit].size());
1401 // next, reject imaginary end-of-par characters
1402 for (pit_type pit = 0; pit < pars_size; ++pit) {
1403 pos_type pos = pars_[pit].size();
1405 if (pars_[pit].isDeleted(pos)) {
1406 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1407 } else if (pars_[pit].isInserted(pos)) {
1408 if (pit == pars_size - 1) {
1409 // we mark the par break at the end of the last
1410 // paragraph unchanged
1411 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1413 mergeParagraph(bparams, pars_, pit);
1420 // finally, invoke the DEPM
1421 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.track_changes);
1425 void Text::deleteWordForward(Cursor & cur)
1427 LBUFERR(this == cur.text());
1428 if (cur.lastpos() == 0)
1432 cur.setSelection(true);
1433 cursorForwardOneWord(cur);
1435 cutSelection(cur, true, false);
1436 cur.checkBufferStructure();
1441 void Text::deleteWordBackward(Cursor & cur)
1443 LBUFERR(this == cur.text());
1444 if (cur.lastpos() == 0)
1445 cursorBackward(cur);
1448 cur.setSelection(true);
1449 cursorBackwardOneWord(cur);
1451 cutSelection(cur, true, false);
1452 cur.checkBufferStructure();
1457 // Kill to end of line.
1458 void Text::changeCase(Cursor & cur, TextCase action)
1460 LBUFERR(this == cur.text());
1464 bool gotsel = false;
1465 if (cur.selection()) {
1466 from = cur.selBegin();
1471 getWord(from, to, PARTIAL_WORD);
1472 cursorForwardOneWord(cur);
1475 cur.recordUndoSelection();
1477 pit_type begPit = from.pit();
1478 pit_type endPit = to.pit();
1480 pos_type begPos = from.pos();
1481 pos_type endPos = to.pos();
1483 pos_type right = 0; // needed after the for loop
1485 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1486 Paragraph & par = pars_[pit];
1487 pos_type const pos = (pit == begPit ? begPos : 0);
1488 right = (pit == endPit ? endPos : par.size());
1489 par.changeCase(cur.buffer()->params(), pos, right, action);
1492 // the selection may have changed due to logically-only deleted chars
1494 setCursor(cur, begPit, begPos);
1496 setCursor(cur, endPit, right);
1499 setCursor(cur, endPit, right);
1501 cur.checkBufferStructure();
1505 bool Text::handleBibitems(Cursor & cur)
1507 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1513 BufferParams const & bufparams = cur.buffer()->params();
1514 Paragraph const & par = cur.paragraph();
1515 Cursor prevcur = cur;
1516 if (cur.pit() > 0) {
1518 prevcur.pos() = prevcur.lastpos();
1520 Paragraph const & prevpar = prevcur.paragraph();
1522 // if a bibitem is deleted, merge with previous paragraph
1523 // if this is a bibliography item as well
1524 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1525 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1526 mergeParagraph(bufparams, cur.text()->paragraphs(),
1528 cur.forceBufferUpdate();
1529 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1530 cur.screenUpdateFlags(Update::Force);
1534 // otherwise reset to default
1535 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1540 bool Text::erase(Cursor & cur)
1542 LASSERT(this == cur.text(), return false);
1543 bool needsUpdate = false;
1544 Paragraph & par = cur.paragraph();
1546 if (cur.pos() != cur.lastpos()) {
1547 // this is the code for a normal delete, not pasting
1549 cur.recordUndo(DELETE_UNDO);
1550 bool const was_inset = cur.paragraph().isInset(cur.pos());
1551 if(!par.eraseChar(cur.pos(), cur.buffer()->params().track_changes))
1552 // the character has been logically deleted only => skip it
1553 cur.top().forwardPos();
1556 cur.forceBufferUpdate();
1558 cur.checkBufferStructure();
1561 if (cur.pit() == cur.lastpit())
1562 return dissolveInset(cur);
1564 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1565 par.setChange(cur.pos(), Change(Change::DELETED));
1569 setCursorIntern(cur, cur.pit() + 1, 0);
1570 needsUpdate = backspacePos0(cur);
1574 needsUpdate |= handleBibitems(cur);
1577 // Make sure the cursor is correct. Is this really needed?
1578 // No, not really... at least not here!
1579 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1580 cur.checkBufferStructure();
1587 bool Text::backspacePos0(Cursor & cur)
1589 LBUFERR(this == cur.text());
1593 bool needsUpdate = false;
1595 BufferParams const & bufparams = cur.buffer()->params();
1596 DocumentClass const & tclass = bufparams.documentClass();
1597 ParagraphList & plist = cur.text()->paragraphs();
1598 Paragraph const & par = cur.paragraph();
1599 Cursor prevcur = cur;
1601 prevcur.pos() = prevcur.lastpos();
1602 Paragraph const & prevpar = prevcur.paragraph();
1604 // is it an empty paragraph?
1605 if (cur.lastpos() == 0
1606 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1607 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1608 plist.erase(boost::next(plist.begin(), cur.pit()));
1611 // is previous par empty?
1612 else if (prevcur.lastpos() == 0
1613 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1614 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1615 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1618 // Pasting is not allowed, if the paragraphs have different
1619 // layouts. I think it is a real bug of all other
1620 // word processors to allow it. It confuses the user.
1621 // Correction: Pasting is always allowed with standard-layout
1622 // or the empty layout.
1623 else if (par.layout() == prevpar.layout()
1624 || tclass.isDefaultLayout(par.layout())
1625 || tclass.isPlainLayout(par.layout())) {
1626 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1627 mergeParagraph(bufparams, plist, prevcur.pit());
1632 cur.forceBufferUpdate();
1633 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1640 bool Text::backspace(Cursor & cur)
1642 LBUFERR(this == cur.text());
1643 bool needsUpdate = false;
1644 if (cur.pos() == 0) {
1646 return dissolveInset(cur);
1648 Cursor prev_cur = cur;
1651 if (!prev_cur.paragraph().isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1652 cur.recordUndo(ATOMIC_UNDO, prev_cur.pit(), prev_cur.pit());
1653 prev_cur.paragraph().setChange(prev_cur.lastpos(), Change(Change::DELETED));
1654 setCursorIntern(cur, prev_cur.pit(), prev_cur.lastpos());
1657 // The cursor is at the beginning of a paragraph, so
1658 // the backspace will collapse two paragraphs into one.
1659 needsUpdate = backspacePos0(cur);
1662 // this is the code for a normal backspace, not pasting
1664 cur.recordUndo(DELETE_UNDO);
1665 // We used to do cursorBackwardIntern() here, but it is
1666 // not a good idea since it triggers the auto-delete
1667 // mechanism. So we do a cursorBackwardIntern()-lite,
1668 // without the dreaded mechanism. (JMarc)
1669 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1670 false, cur.boundary());
1671 bool const was_inset = cur.paragraph().isInset(cur.pos());
1672 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().track_changes);
1674 cur.forceBufferUpdate();
1676 cur.checkBufferStructure();
1679 if (cur.pos() == cur.lastpos())
1680 cur.setCurrentFont();
1682 needsUpdate |= handleBibitems(cur);
1684 // A singlePar update is not enough in this case.
1685 // cur.screenUpdateFlags(Update::Force);
1686 setCursor(cur.top(), cur.pit(), cur.pos());
1692 bool Text::dissolveInset(Cursor & cur)
1694 LASSERT(this == cur.text(), return false);
1696 if (isMainText() || cur.inset().nargs() != 1)
1699 cur.recordUndoInset();
1701 cur.selHandle(false);
1703 pos_type spos = cur.pos();
1704 pit_type spit = cur.pit();
1705 ParagraphList plist;
1706 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1707 plist = paragraphs();
1709 // store cursor offset
1713 Buffer & b = *cur.buffer();
1714 cur.paragraph().eraseChar(cur.pos(), b.params().track_changes);
1716 if (!plist.empty()) {
1718 // we clear the cache so that we won't get conflicts with labels
1719 // that get pasted into the buffer. we should update this before
1720 // its being empty matters. if not (i.e., if we encounter bugs),
1721 // then this should instead be:
1722 // cur.buffer().updateBuffer();
1723 // but we'll try the cheaper solution here.
1724 cur.buffer()->clearReferenceCache();
1726 // ERT paragraphs have the Language latex_language.
1727 // This is invalid outside of ERT, so we need to
1728 // change it to the buffer language.
1729 ParagraphList::iterator it = plist.begin();
1730 ParagraphList::iterator it_end = plist.end();
1731 for (; it != it_end; ++it)
1732 it->changeLanguage(b.params(), latex_language, b.language());
1734 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1735 b.errorList("Paste"));
1737 cur.pit() = min(cur.lastpit(), spit);
1738 cur.pos() = min(cur.lastpos(), spos);
1741 cur.forceBufferUpdate();
1743 // Ensure the current language is set correctly (bug 6292)
1744 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1745 cur.clearSelection();
1751 void Text::getWord(CursorSlice & from, CursorSlice & to,
1752 word_location const loc) const
1755 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1759 void Text::write(ostream & os) const
1761 Buffer const & buf = owner_->buffer();
1762 ParagraphList::const_iterator pit = paragraphs().begin();
1763 ParagraphList::const_iterator end = paragraphs().end();
1765 for (; pit != end; ++pit)
1766 pit->write(os, buf.params(), dth);
1768 // Close begin_deeper
1769 for(; dth > 0; --dth)
1770 os << "\n\\end_deeper";
1774 bool Text::read(Lexer & lex,
1775 ErrorList & errorList, InsetText * insetPtr)
1777 Buffer const & buf = owner_->buffer();
1778 depth_type depth = 0;
1781 while (lex.isOK()) {
1783 string const token = lex.getString();
1788 if (token == "\\end_inset")
1791 if (token == "\\end_body")
1794 if (token == "\\begin_body")
1797 if (token == "\\end_document") {
1802 if (token == "\\begin_layout") {
1803 lex.pushToken(token);
1806 par.setInsetOwner(insetPtr);
1807 par.params().depth(depth);
1808 par.setFont(0, Font(inherit_font, buf.params().language));
1809 pars_.push_back(par);
1810 readParagraph(pars_.back(), lex, errorList);
1812 // register the words in the global word list
1813 pars_.back().updateWords();
1814 } else if (token == "\\begin_deeper") {
1816 } else if (token == "\\end_deeper") {
1818 lex.printError("\\end_deeper: " "depth is already null");
1822 LYXERR0("Handling unknown body token: `" << token << '\'');
1826 // avoid a crash on weird documents (bug 4859)
1827 if (pars_.empty()) {
1829 par.setInsetOwner(insetPtr);
1830 par.params().depth(depth);
1831 par.setFont(0, Font(inherit_font,
1832 buf.params().language));
1833 par.setPlainOrDefaultLayout(buf.params().documentClass());
1834 pars_.push_back(par);
1841 // Returns the current font and depth as a message.
1842 docstring Text::currentState(Cursor const & cur) const
1844 LBUFERR(this == cur.text());
1845 Buffer & buf = *cur.buffer();
1846 Paragraph const & par = cur.paragraph();
1847 odocstringstream os;
1849 if (buf.params().track_changes)
1850 os << _("[Change Tracking] ");
1852 Change change = par.lookupChange(cur.pos());
1854 if (change.changed()) {
1855 Author const & a = buf.params().authors().get(change.author);
1856 os << _("Change: ") << a.name();
1857 if (!a.email().empty())
1858 os << " (" << a.email() << ")";
1859 // FIXME ctime is english, we should translate that
1860 os << _(" at ") << ctime(&change.changetime);
1864 // I think we should only show changes from the default
1866 // No, from the document font (MV)
1867 Font font = cur.real_current_font;
1868 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1870 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1872 // The paragraph depth
1873 int depth = cur.paragraph().getDepth();
1875 os << bformat(_(", Depth: %1$d"), depth);
1877 // The paragraph spacing, but only if different from
1879 Spacing const & spacing = par.params().spacing();
1880 if (!spacing.isDefault()) {
1881 os << _(", Spacing: ");
1882 switch (spacing.getSpace()) {
1883 case Spacing::Single:
1886 case Spacing::Onehalf:
1889 case Spacing::Double:
1892 case Spacing::Other:
1893 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1895 case Spacing::Default:
1896 // should never happen, do nothing
1901 #ifdef DEVEL_VERSION
1902 os << _(", Inset: ") << &cur.inset();
1903 os << _(", Paragraph: ") << cur.pit();
1904 os << _(", Id: ") << par.id();
1905 os << _(", Position: ") << cur.pos();
1906 // FIXME: Why is the check for par.size() needed?
1907 // We are called with cur.pos() == par.size() quite often.
1908 if (!par.empty() && cur.pos() < par.size()) {
1909 // Force output of code point, not character
1910 size_t const c = par.getChar(cur.pos());
1911 os << _(", Char: 0x") << hex << c;
1913 os << _(", Boundary: ") << cur.boundary();
1914 // Row & row = cur.textRow();
1915 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1921 docstring Text::getPossibleLabel(Cursor const & cur) const
1923 pit_type pit = cur.pit();
1925 Layout const * layout = &(pars_[pit].layout());
1928 docstring par_text = pars_[pit].asString();
1930 // The return string of math matrices might contain linebreaks
1931 par_text = subst(par_text, '\n', '-');
1932 int const numwords = 3;
1933 for (int i = 0; i < numwords; ++i) {
1934 if (par_text.empty())
1937 par_text = split(par_text, head, ' ');
1938 // Is it legal to use spaces in labels ?
1944 // Make sure it isn't too long
1945 unsigned int const max_label_length = 32;
1946 if (text.size() > max_label_length)
1947 text.resize(max_label_length);
1949 // Will contain the label prefix.
1952 // For section, subsection, etc...
1953 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1954 Layout const * layout2 = &(pars_[pit - 1].layout());
1955 if (layout2->latextype != LATEX_PARAGRAPH) {
1960 if (layout->latextype != LATEX_PARAGRAPH)
1961 name = layout->refprefix;
1963 // For captions, we just take the caption type
1964 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1965 if (caption_inset) {
1966 string const & ftype = static_cast<InsetCaption *>(caption_inset)->floattype();
1967 FloatList const & fl = cur.buffer()->params().documentClass().floats();
1968 if (fl.typeExist(ftype)) {
1969 Floating const & flt = fl.getType(ftype);
1970 name = from_utf8(flt.refPrefix());
1973 name = from_utf8(ftype.substr(0,3));
1976 // If none of the above worked, see if the inset knows.
1978 InsetLayout const & il = cur.inset().getLayout();
1979 name = il.refprefix();
1983 text = name + ':' + text;
1985 // We need a unique label
1986 docstring label = text;
1988 while (cur.buffer()->insetLabel(label)) {
1989 label = text + '-' + convert<docstring>(i);
1997 docstring Text::asString(int options) const
1999 return asString(0, pars_.size(), options);
2003 docstring Text::asString(pit_type beg, pit_type end, int options) const
2005 size_t i = size_t(beg);
2006 docstring str = pars_[i].asString(options);
2007 for (++i; i != size_t(end); ++i) {
2009 str += pars_[i].asString(options);
2015 void Text::forOutliner(docstring & os, size_t maxlen, bool shorten) const
2018 maxlen = std::numeric_limits<std::size_t>::max();
2020 LASSERT(maxlen >= 8, maxlen = TOC_ENTRY_LENGTH);
2021 for (size_t i = 0; i != pars_.size() && os.length() < maxlen; ++i)
2022 pars_[i].forOutliner(os, maxlen);
2023 if (shorten && os.length() >= maxlen)
2024 os = os.substr(0, maxlen - 3) + from_ascii("...");
2028 void Text::charsTranspose(Cursor & cur)
2030 LBUFERR(this == cur.text());
2032 pos_type pos = cur.pos();
2034 // If cursor is at beginning or end of paragraph, do nothing.
2035 if (pos == cur.lastpos() || pos == 0)
2038 Paragraph & par = cur.paragraph();
2040 // Get the positions of the characters to be transposed.
2041 pos_type pos1 = pos - 1;
2042 pos_type pos2 = pos;
2044 // In change tracking mode, ignore deleted characters.
2045 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2047 if (pos2 == cur.lastpos())
2050 while (pos1 >= 0 && par.isDeleted(pos1))
2055 // Don't do anything if one of the "characters" is not regular text.
2056 if (par.isInset(pos1) || par.isInset(pos2))
2059 // Store the characters to be transposed (including font information).
2060 char_type const char1 = par.getChar(pos1);
2062 par.getFontSettings(cur.buffer()->params(), pos1);
2064 char_type const char2 = par.getChar(pos2);
2066 par.getFontSettings(cur.buffer()->params(), pos2);
2068 // And finally, we are ready to perform the transposition.
2069 // Track the changes if Change Tracking is enabled.
2070 bool const trackChanges = cur.buffer()->params().track_changes;
2074 par.eraseChar(pos2, trackChanges);
2075 par.eraseChar(pos1, trackChanges);
2076 par.insertChar(pos1, char2, font2, trackChanges);
2077 par.insertChar(pos2, char1, font1, trackChanges);
2079 cur.checkBufferStructure();
2081 // After the transposition, move cursor to after the transposition.
2082 setCursor(cur, cur.pit(), pos2);
2087 DocIterator Text::macrocontextPosition() const
2089 return macrocontext_position_;
2093 void Text::setMacrocontextPosition(DocIterator const & pos)
2095 macrocontext_position_ = pos;
2099 docstring Text::previousWord(CursorSlice const & sl) const
2101 CursorSlice from = sl;
2102 CursorSlice to = sl;
2103 getWord(from, to, PREVIOUS_WORD);
2104 if (sl == from || to == from)
2107 Paragraph const & par = sl.paragraph();
2108 return par.asString(from.pos(), to.pos());
2112 bool Text::completionSupported(Cursor const & cur) const
2114 Paragraph const & par = cur.paragraph();
2115 return cur.pos() > 0
2116 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2117 && !par.isWordSeparator(cur.pos() - 1);
2121 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2123 WordList const * list = theWordList(cur.getFont().language()->lang());
2124 return new TextCompletionList(cur, list);
2128 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2130 LBUFERR(cur.bv().cursor() == cur);
2132 cur.bv().cursor() = cur;
2133 if (!(cur.result().screenUpdate() & Update::Force))
2134 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2139 docstring Text::completionPrefix(Cursor const & cur) const
2141 return previousWord(cur.top());