3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Dov Feldstern
9 * \author Jean-Marc Lasgouttes
11 * \author André Pönitz
12 * \author Stefan Schimanski
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "CompletionList.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
37 #include "InsetList.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TextMetrics.h"
50 #include "WordLangTuple.h"
53 #include "insets/InsetText.h"
54 #include "insets/InsetBibitem.h"
55 #include "insets/InsetCaption.h"
56 #include "insets/InsetLine.h"
57 #include "insets/InsetNewline.h"
58 #include "insets/InsetNewpage.h"
59 #include "insets/InsetOptArg.h"
60 #include "insets/InsetSpace.h"
61 #include "insets/InsetSpecialChar.h"
62 #include "insets/InsetTabular.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
71 #include <boost/next_prior.hpp>
76 using namespace lyx::support;
80 using cap::cutSelection;
81 using cap::pasteParagraphList;
83 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
84 Paragraph & toPar, pos_type toPos, BufferParams const & params)
86 // Note: moveItem() does not honour change tracking!
87 // Therefore, it should only be used for breaking and merging paragraphs
89 // We need a copy here because the character at fromPos is going to be erased.
90 Font const tmpFont = fromPar.getFontSettings(params, fromPos);
91 Change const tmpChange = fromPar.lookupChange(fromPos);
93 if (Inset * tmpInset = fromPar.getInset(fromPos)) {
94 fromPar.releaseInset(fromPos);
95 // The inset is not in fromPar any more.
96 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
103 char_type const tmpChar = fromPar.getChar(fromPos);
104 fromPar.eraseChar(fromPos, false);
105 toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
110 void breakParagraphConservative(BufferParams const & bparams,
111 ParagraphList & pars, pit_type par_offset, pos_type pos)
113 // create a new paragraph
114 Paragraph & tmp = *pars.insert(boost::next(pars.begin(), par_offset + 1),
116 Paragraph & par = pars[par_offset];
118 tmp.setInsetOwner(&par.inInset());
119 tmp.makeSameLayout(par);
121 LASSERT(pos <= par.size(), /**/);
123 if (pos < par.size()) {
124 // move everything behind the break position to the new paragraph
125 pos_type pos_end = par.size() - 1;
127 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
128 if (moveItem(par, pos, tmp, j, bparams)) {
132 // Move over the end-of-par change information
133 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
134 par.setChange(par.size(), Change(bparams.trackChanges ?
135 Change::INSERTED : Change::UNCHANGED));
140 void mergeParagraph(BufferParams const & bparams,
141 ParagraphList & pars, pit_type par_offset)
143 Paragraph & next = pars[par_offset + 1];
144 Paragraph & par = pars[par_offset];
146 pos_type pos_end = next.size() - 1;
147 pos_type pos_insert = par.size();
149 // the imaginary end-of-paragraph character (at par.size()) has to be
150 // marked as unmodified. Otherwise, its change is adopted by the first
151 // character of the next paragraph.
152 if (par.isChanged(par.size())) {
153 LYXERR(Debug::CHANGES,
154 "merging par with inserted/deleted end-of-par character");
155 par.setChange(par.size(), Change(Change::UNCHANGED));
158 Change change = next.lookupChange(next.size());
160 // move the content of the second paragraph to the end of the first one
161 for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
162 if (moveItem(next, 0, par, j, bparams)) {
167 // move the change of the end-of-paragraph character
168 par.setChange(par.size(), change);
170 pars.erase(boost::next(pars.begin(), par_offset + 1));
174 pit_type depthHook(pit_type pit, ParagraphList const & pars, depth_type depth)
176 pit_type newpit = pit;
181 while (newpit != 0 && pars[newpit].getDepth() > depth)
184 if (pars[newpit].getDepth() > depth)
191 pit_type outerHook(pit_type par_offset, ParagraphList const & pars)
193 Paragraph const & par = pars[par_offset];
195 if (par.getDepth() == 0)
197 return depthHook(par_offset, pars, depth_type(par.getDepth() - 1));
201 bool isFirstInSequence(pit_type par_offset, ParagraphList const & pars)
203 Paragraph const & par = pars[par_offset];
205 pit_type dhook_offset = depthHook(par_offset, pars, par.getDepth());
207 if (dhook_offset == par_offset)
210 Paragraph const & dhook = pars[dhook_offset];
212 return dhook.layout() != par.layout()
213 || dhook.getDepth() != par.getDepth();
217 int getEndLabel(pit_type p, ParagraphList const & pars)
220 depth_type par_depth = pars[p].getDepth();
221 while (pit != pit_type(pars.size())) {
222 Layout const & layout = pars[pit].layout();
223 int const endlabeltype = layout.endlabeltype;
225 if (endlabeltype != END_LABEL_NO_LABEL) {
226 if (p + 1 == pit_type(pars.size()))
229 depth_type const next_depth =
230 pars[p + 1].getDepth();
231 if (par_depth > next_depth ||
232 (par_depth == next_depth && layout != pars[p + 1].layout()))
238 pit = outerHook(pit, pars);
239 if (pit != pit_type(pars.size()))
240 par_depth = pars[pit].getDepth();
242 return END_LABEL_NO_LABEL;
246 Font const outerFont(pit_type par_offset, ParagraphList const & pars)
248 depth_type par_depth = pars[par_offset].getDepth();
249 FontInfo tmpfont = inherit_font;
251 // Resolve against environment font information
252 while (par_offset != pit_type(pars.size())
254 && !tmpfont.resolved()) {
255 par_offset = outerHook(par_offset, pars);
256 if (par_offset != pit_type(pars.size())) {
257 tmpfont.realize(pars[par_offset].layout().font);
258 par_depth = pars[par_offset].getDepth();
262 return Font(tmpfont);
266 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
268 pit_type pars_size = static_cast<pit_type>(pars.size());
270 // first, accept changes within each individual paragraph
271 // (do not consider end-of-par)
272 for (pit_type pit = 0; pit < pars_size; ++pit) {
273 if (!pars[pit].empty()) // prevent assertion failure
274 pars[pit].acceptChanges(0, pars[pit].size());
277 // next, accept imaginary end-of-par characters
278 for (pit_type pit = 0; pit < pars_size; ++pit) {
279 pos_type pos = pars[pit].size();
281 if (pars[pit].isInserted(pos)) {
282 pars[pit].setChange(pos, Change(Change::UNCHANGED));
283 } else if (pars[pit].isDeleted(pos)) {
284 if (pit == pars_size - 1) {
285 // we cannot remove a par break at the end of the last
286 // paragraph; instead, we mark it unchanged
287 pars[pit].setChange(pos, Change(Change::UNCHANGED));
289 mergeParagraph(bparams, pars, pit);
297 InsetText const & Text::inset() const
303 void Text::readParToken(Paragraph & par, Lexer & lex,
304 string const & token, Font & font, Change & change, ErrorList & errorList)
306 Buffer const & buf = owner_->buffer();
307 BufferParams const & bp = buf.params();
309 if (token[0] != '\\') {
310 docstring dstr = lex.getDocString();
311 par.appendString(dstr, font, change);
313 } else if (token == "\\begin_layout") {
315 docstring layoutname = lex.getDocString();
317 font = Font(inherit_font, bp.language);
318 change = Change(Change::UNCHANGED);
320 DocumentClass const & tclass = bp.documentClass();
322 if (layoutname.empty())
323 layoutname = tclass.defaultLayoutName();
325 if (owner_->forcePlainLayout()) {
326 // in this case only the empty layout is allowed
327 layoutname = tclass.plainLayoutName();
328 } else if (par.usePlainLayout()) {
329 // in this case, default layout maps to empty layout
330 if (layoutname == tclass.defaultLayoutName())
331 layoutname = tclass.plainLayoutName();
333 // otherwise, the empty layout maps to the default
334 if (layoutname == tclass.plainLayoutName())
335 layoutname = tclass.defaultLayoutName();
338 // When we apply an unknown layout to a document, we add this layout to the textclass
339 // of this document. For example, when you apply class article to a beamer document,
340 // all unknown layouts such as frame will be added to document class article so that
341 // these layouts can keep their original names.
342 tclass.addLayoutIfNeeded(layoutname);
344 par.setLayout(bp.documentClass()[layoutname]);
346 // Test whether the layout is obsolete.
347 Layout const & layout = par.layout();
348 if (!layout.obsoleted_by().empty())
349 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
351 par.params().read(lex);
353 } else if (token == "\\end_layout") {
354 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
355 << "Missing \\begin_layout ?");
356 } else if (token == "\\end_inset") {
357 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
358 << "Missing \\begin_inset ?");
359 } else if (token == "\\begin_inset") {
360 Inset * inset = readInset(lex, buf);
362 par.insertInset(par.size(), inset, font, change);
365 docstring line = lex.getDocString();
366 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
367 par.id(), 0, par.size()));
369 } else if (token == "\\family") {
371 setLyXFamily(lex.getString(), font.fontInfo());
372 } else if (token == "\\series") {
374 setLyXSeries(lex.getString(), font.fontInfo());
375 } else if (token == "\\shape") {
377 setLyXShape(lex.getString(), font.fontInfo());
378 } else if (token == "\\size") {
380 setLyXSize(lex.getString(), font.fontInfo());
381 } else if (token == "\\lang") {
383 string const tok = lex.getString();
384 Language const * lang = languages.getLanguage(tok);
386 font.setLanguage(lang);
388 font.setLanguage(bp.language);
389 lex.printError("Unknown language `$$Token'");
391 } else if (token == "\\numeric") {
393 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
394 } else if (token == "\\emph") {
396 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
397 } else if (token == "\\bar") {
399 string const tok = lex.getString();
402 font.fontInfo().setUnderbar(FONT_ON);
403 else if (tok == "no")
404 font.fontInfo().setUnderbar(FONT_OFF);
405 else if (tok == "default")
406 font.fontInfo().setUnderbar(FONT_INHERIT);
408 lex.printError("Unknown bar font flag "
410 } else if (token == "\\strikeout") {
412 font.fontInfo().setStrikeout(font.setLyXMisc(lex.getString()));
413 } else if (token == "\\uuline") {
415 font.fontInfo().setUuline(font.setLyXMisc(lex.getString()));
416 } else if (token == "\\uwave") {
418 font.fontInfo().setUwave(font.setLyXMisc(lex.getString()));
419 } else if (token == "\\noun") {
421 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
422 } else if (token == "\\color") {
424 setLyXColor(lex.getString(), font.fontInfo());
425 } else if (token == "\\SpecialChar") {
426 auto_ptr<Inset> inset;
427 inset.reset(new InsetSpecialChar);
429 par.insertInset(par.size(), inset.release(),
431 } else if (token == "\\backslash") {
432 par.appendChar('\\', font, change);
433 } else if (token == "\\LyXTable") {
434 auto_ptr<Inset> inset(new InsetTabular(const_cast<Buffer &>(buf)));
436 par.insertInset(par.size(), inset.release(), font, change);
437 } else if (token == "\\lyxline") {
438 par.insertInset(par.size(), new InsetLine, font, change);
439 } else if (token == "\\change_unchanged") {
440 change = Change(Change::UNCHANGED);
441 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
443 istringstream is(lex.getString());
447 map<unsigned int, int> const & am = bp.author_map;
448 if (am.find(aid) == am.end()) {
449 errorList.push_back(ErrorItem(_("Change tracking error"),
450 bformat(_("Unknown author index for change: %1$d\n"), aid),
451 par.id(), 0, par.size()));
452 change = Change(Change::UNCHANGED);
454 if (token == "\\change_inserted")
455 change = Change(Change::INSERTED, am.find(aid)->second, ct);
457 change = Change(Change::DELETED, am.find(aid)->second, ct);
461 errorList.push_back(ErrorItem(_("Unknown token"),
462 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
464 par.id(), 0, par.size()));
469 void Text::readParagraph(Paragraph & par, Lexer & lex,
470 ErrorList & errorList)
473 string token = lex.getString();
475 Change change(Change::UNCHANGED);
478 readParToken(par, lex, token, font, change, errorList);
481 token = lex.getString();
486 if (token == "\\end_layout") {
487 //Ok, paragraph finished
491 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
492 if (token == "\\begin_layout" || token == "\\end_document"
493 || token == "\\end_inset" || token == "\\begin_deeper"
494 || token == "\\end_deeper") {
495 lex.pushToken(token);
496 lyxerr << "Paragraph ended in line "
497 << lex.lineNumber() << "\n"
498 << "Missing \\end_layout.\n";
502 // Final change goes to paragraph break:
503 par.setChange(par.size(), change);
505 // Initialize begin_of_body_ on load; redoParagraph maintains
506 par.setBeginOfBody();
510 class TextCompletionList : public CompletionList
514 TextCompletionList(Cursor const & cur)
515 : buffer_(cur.buffer()), pos_(0)
518 virtual ~TextCompletionList() {}
521 virtual bool sorted() const { return true; }
523 virtual size_t size() const
525 return theWordList().size();
528 virtual docstring const & data(size_t idx) const
530 return theWordList().word(idx);
535 Buffer const * buffer_;
541 bool Text::empty() const
543 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
544 // FIXME: Should we consider the labeled type as empty too?
545 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
549 double Text::spacing(Paragraph const & par) const
551 if (par.params().spacing().isDefault())
552 return owner_->buffer().params().spacing().getValue();
553 return par.params().spacing().getValue();
558 * This breaks a paragraph at the specified position.
559 * The new paragraph will:
560 * - Decrease depth by one (or change layout to default layout) when
561 * keep_layout == false
562 * - keep current depth and layout when keep_layout == true
564 static void breakParagraph(BufferParams const & bparams,
565 ParagraphList & pars, pit_type par_offset, pos_type pos,
568 // create a new paragraph, and insert into the list
569 ParagraphList::iterator tmp =
570 pars.insert(boost::next(pars.begin(), par_offset + 1),
573 Paragraph & par = pars[par_offset];
575 // remember to set the inset_owner
576 tmp->setInsetOwner(&par.inInset());
577 // without doing that we get a crash when typing <Return> at the
578 // end of a paragraph
579 tmp->setPlainOrDefaultLayout(bparams.documentClass());
581 // layout stays the same with latex-environments
583 tmp->setLayout(par.layout());
584 tmp->setLabelWidthString(par.params().labelWidthString());
585 tmp->params().depth(par.params().depth());
586 } else if (par.params().depth() > 0) {
587 Paragraph const & hook = pars[outerHook(par_offset, pars)];
588 tmp->setLayout(hook.layout());
589 // not sure the line below is useful
590 tmp->setLabelWidthString(par.params().labelWidthString());
591 tmp->params().depth(hook.params().depth());
594 bool const isempty = (par.allowEmpty() && par.empty());
596 if (!isempty && (par.size() > pos || par.empty())) {
597 tmp->setLayout(par.layout());
598 tmp->params().align(par.params().align());
599 tmp->setLabelWidthString(par.params().labelWidthString());
601 tmp->params().depth(par.params().depth());
602 tmp->params().noindent(par.params().noindent());
604 // move everything behind the break position
605 // to the new paragraph
607 /* Note: if !keepempty, empty() == true, then we reach
608 * here with size() == 0. So pos_end becomes - 1. This
609 * doesn't cause problems because both loops below
610 * enforce pos <= pos_end and 0 <= pos
612 pos_type pos_end = par.size() - 1;
614 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
615 if (moveItem(par, pos, *tmp, j, bparams)) {
621 // Move over the end-of-par change information
622 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
623 par.setChange(par.size(), Change(bparams.trackChanges ?
624 Change::INSERTED : Change::UNCHANGED));
627 // Make sure that we keep the language when
628 // breaking paragraph.
630 Font changed = tmp->getFirstFontSettings(bparams);
631 Font const & old = par.getFontSettings(bparams, par.size());
632 changed.setLanguage(old.language());
633 tmp->setFont(0, changed);
640 bool const soa = par.params().startOfAppendix();
641 par.params().clear();
642 // do not lose start of appendix marker (bug 4212)
643 par.params().startOfAppendix(soa);
644 par.setPlainOrDefaultLayout(bparams.documentClass());
647 // layout stays the same with latex-environments
649 par.setLayout(tmp->layout());
650 par.setLabelWidthString(tmp->params().labelWidthString());
651 par.params().depth(tmp->params().depth());
656 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
658 LASSERT(this == cur.text(), /**/);
660 Paragraph & cpar = cur.paragraph();
661 pit_type cpit = cur.pit();
663 DocumentClass const & tclass = cur.buffer()->params().documentClass();
664 Layout const & layout = cpar.layout();
666 // this is only allowed, if the current paragraph is not empty
667 // or caption and if it has not the keepempty flag active
668 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
669 layout.labeltype != LABEL_SENSITIVE)
672 // a layout change may affect also the following paragraph
673 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
675 // Always break behind a space
676 // It is better to erase the space (Dekel)
677 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
678 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
680 // What should the layout for the new paragraph be?
681 bool keep_layout = inverse_logic ?
682 !layout.isEnvironment()
683 : layout.isEnvironment();
685 // We need to remember this before we break the paragraph, because
686 // that invalidates the layout variable
687 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
689 // we need to set this before we insert the paragraph.
690 bool const isempty = cpar.allowEmpty() && cpar.empty();
692 lyx::breakParagraph(cur.buffer()->params(), paragraphs(), cpit,
693 cur.pos(), keep_layout);
695 // After this, neither paragraph contains any rows!
698 pit_type next_par = cpit + 1;
700 // well this is the caption hack since one caption is really enough
703 // set to standard-layout
704 //FIXME Check if this should be plainLayout() in some cases
705 pars_[cpit].applyLayout(tclass.defaultLayout());
707 // set to standard-layout
708 //FIXME Check if this should be plainLayout() in some cases
709 pars_[next_par].applyLayout(tclass.defaultLayout());
712 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
713 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
714 break; // the character couldn't be deleted physically due to change tracking
717 cur.buffer()->updateLabels();
719 // A singlePar update is not enough in this case.
720 cur.updateFlags(Update::Force);
722 // This check is necessary. Otherwise the new empty paragraph will
723 // be deleted automatically. And it is more friendly for the user!
724 if (cur.pos() != 0 || isempty)
725 setCursor(cur, cur.pit() + 1, 0);
727 setCursor(cur, cur.pit(), 0);
731 // needed to insert the selection
732 void Text::insertStringAsLines(DocIterator const & dit, docstring const & str,
735 BufferParams const & bparams = owner_->buffer().params();
736 pit_type pit = dit.pit();
737 pos_type pos = dit.pos();
739 // insert the string, don't insert doublespace
740 bool space_inserted = true;
741 for (docstring::const_iterator cit = str.begin();
742 cit != str.end(); ++cit) {
743 Paragraph & par = pars_[pit];
745 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
746 lyx::breakParagraph(bparams, pars_, pit, pos,
747 par.layout().isEnvironment());
750 space_inserted = true;
754 // do not insert consecutive spaces if !free_spacing
755 } else if ((*cit == ' ' || *cit == '\t') &&
756 space_inserted && !par.isFreeSpacing()) {
758 } else if (*cit == '\t') {
759 if (!par.isFreeSpacing()) {
760 // tabs are like spaces here
761 par.insertChar(pos, ' ', font, bparams.trackChanges);
763 space_inserted = true;
765 par.insertChar(pos, *cit, font, bparams.trackChanges);
767 space_inserted = true;
769 } else if (!isPrintable(*cit)) {
770 // Ignore unprintables
773 // just insert the character
774 par.insertChar(pos, *cit, font, bparams.trackChanges);
776 space_inserted = (*cit == ' ');
782 // turn double CR to single CR, others are converted into one
783 // blank. Then insertStringAsLines is called
784 void Text::insertStringAsParagraphs(DocIterator const & dit, docstring const & str,
787 docstring linestr = str;
788 bool newline_inserted = false;
790 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
791 if (linestr[i] == '\n') {
792 if (newline_inserted) {
793 // we know that \r will be ignored by
794 // insertStringAsLines. Of course, it is a dirty
795 // trick, but it works...
796 linestr[i - 1] = '\r';
800 newline_inserted = true;
802 } else if (isPrintable(linestr[i])) {
803 newline_inserted = false;
806 insertStringAsLines(dit, linestr, font);
810 // insert a character, moves all the following breaks in the
811 // same Paragraph one to the right and make a rebreak
812 void Text::insertChar(Cursor & cur, char_type c)
814 LASSERT(this == cur.text(), /**/);
816 cur.recordUndo(INSERT_UNDO);
818 TextMetrics const & tm = cur.bv().textMetrics(this);
819 Buffer const & buffer = *cur.buffer();
820 Paragraph & par = cur.paragraph();
821 // try to remove this
822 pit_type const pit = cur.pit();
824 bool const freeSpacing = par.layout().free_spacing ||
827 if (lyxrc.auto_number) {
828 static docstring const number_operators = from_ascii("+-/*");
829 static docstring const number_unary_operators = from_ascii("+-");
830 static docstring const number_seperators = from_ascii(".,:");
832 if (cur.current_font.fontInfo().number() == FONT_ON) {
833 if (!isDigit(c) && !contains(number_operators, c) &&
834 !(contains(number_seperators, c) &&
836 cur.pos() != cur.lastpos() &&
837 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
838 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
840 number(cur); // Set current_font.number to OFF
841 } else if (isDigit(c) &&
842 cur.real_current_font.isVisibleRightToLeft()) {
843 number(cur); // Set current_font.number to ON
845 if (cur.pos() != 0) {
846 char_type const c = par.getChar(cur.pos() - 1);
847 if (contains(number_unary_operators, c) &&
849 || par.isSeparator(cur.pos() - 2)
850 || par.isNewline(cur.pos() - 2))
852 setCharFont(pit, cur.pos() - 1, cur.current_font,
854 } else if (contains(number_seperators, c)
856 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
857 setCharFont(pit, cur.pos() - 1, cur.current_font,
864 // In Bidi text, we want spaces to be treated in a special way: spaces
865 // which are between words in different languages should get the
866 // paragraph's language; otherwise, spaces should keep the language
867 // they were originally typed in. This is only in effect while typing;
868 // after the text is already typed in, the user can always go back and
869 // explicitly set the language of a space as desired. But 99.9% of the
870 // time, what we're doing here is what the user actually meant.
872 // The following cases are the ones in which the language of the space
873 // should be changed to match that of the containing paragraph. In the
874 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
875 // represents a space, pipe (|) represents the cursor position (so the
876 // character before it is the one just typed in). The different cases
877 // are depicted logically (not visually), from left to right:
882 // Theoretically, there are other situations that we should, perhaps, deal
883 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
884 // point (to understand why, just try to create this situation...).
886 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
887 // get font in front and behind the space in question. But do NOT
888 // use getFont(cur.pos()) because the character c is not inserted yet
889 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
890 Font const & post_space_font = cur.real_current_font;
891 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
892 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
894 if (pre_space_rtl != post_space_rtl) {
895 // Set the space's language to match the language of the
896 // adjacent character whose direction is the paragraph's
897 // direction; don't touch other properties of the font
898 Language const * lang =
899 (pre_space_rtl == par.isRTL(buffer.params())) ?
900 pre_space_font.language() : post_space_font.language();
902 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
903 space_font.setLanguage(lang);
904 par.setFont(cur.pos() - 1, space_font);
908 // Next check, if there will be two blanks together or a blank at
909 // the beginning of a paragraph.
910 // I decided to handle blanks like normal characters, the main
911 // difference are the special checks when calculating the row.fill
912 // (blank does not count at the end of a row) and the check here
914 // When the free-spacing option is set for the current layout,
915 // disable the double-space checking
916 if (!freeSpacing && isLineSeparatorChar(c)) {
917 if (cur.pos() == 0) {
918 static bool sent_space_message = false;
919 if (!sent_space_message) {
920 cur.message(_("You cannot insert a space at the "
921 "beginning of a paragraph. Please read the Tutorial."));
922 sent_space_message = true;
926 LASSERT(cur.pos() > 0, /**/);
927 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
928 && !par.isDeleted(cur.pos() - 1)) {
929 static bool sent_space_message = false;
930 if (!sent_space_message) {
931 cur.message(_("You cannot type two spaces this way. "
932 "Please read the Tutorial."));
933 sent_space_message = true;
939 par.insertChar(cur.pos(), c, cur.current_font,
940 cur.buffer()->params().trackChanges);
941 cur.checkBufferStructure();
943 // cur.updateFlags(Update::Force);
944 bool boundary = tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
945 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
950 void Text::charInserted(Cursor & cur)
952 Paragraph & par = cur.paragraph();
954 // Here we call finishUndo for every 20 characters inserted.
955 // This is from my experience how emacs does it. (Lgb)
956 static unsigned int counter;
964 // register word if a non-letter was entered
966 && !par.isWordSeparator(cur.pos() - 2)
967 && par.isWordSeparator(cur.pos() - 1)) {
968 // get the word in front of cursor
969 LASSERT(this == cur.text(), /**/);
970 cur.paragraph().updateWords();
975 // the cursor set functions have a special mechanism. When they
976 // realize, that you left an empty paragraph, they will delete it.
978 bool Text::cursorForwardOneWord(Cursor & cur)
980 LASSERT(this == cur.text(), /**/);
982 pos_type const lastpos = cur.lastpos();
983 pit_type pit = cur.pit();
984 pos_type pos = cur.pos();
985 Paragraph const & par = cur.paragraph();
987 // Paragraph boundary is a word boundary
988 if (pos == lastpos) {
989 if (pit != cur.lastpit())
990 return setCursor(cur, pit + 1, 0);
995 if (lyxrc.mac_like_word_movement) {
996 // Skip through trailing punctuation and spaces.
997 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1000 // Skip over either a non-char inset or a full word
1001 if (pos != lastpos && par.isWordSeparator(pos))
1003 else while (pos != lastpos && !par.isWordSeparator(pos))
1006 LASSERT(pos < lastpos, /**/); // see above
1007 if (!par.isWordSeparator(pos))
1008 while (pos != lastpos && !par.isWordSeparator(pos))
1010 else if (par.isChar(pos))
1011 while (pos != lastpos && par.isChar(pos))
1013 else if (!par.isSpace(pos)) // non-char inset
1016 // Skip over white space
1017 while (pos != lastpos && par.isSpace(pos))
1021 return setCursor(cur, pit, pos);
1025 bool Text::cursorBackwardOneWord(Cursor & cur)
1027 LASSERT(this == cur.text(), /**/);
1029 pit_type pit = cur.pit();
1030 pos_type pos = cur.pos();
1031 Paragraph & par = cur.paragraph();
1033 // Paragraph boundary is a word boundary
1034 if (pos == 0 && pit != 0)
1035 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1037 if (lyxrc.mac_like_word_movement) {
1038 // Skip through punctuation and spaces.
1039 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1042 // Skip over either a non-char inset or a full word
1043 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1045 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1048 // Skip over white space
1049 while (pos != 0 && par.isSpace(pos - 1))
1052 if (pos != 0 && !par.isWordSeparator(pos - 1))
1053 while (pos != 0 && !par.isWordSeparator(pos - 1))
1055 else if (pos != 0 && par.isChar(pos - 1))
1056 while (pos != 0 && par.isChar(pos - 1))
1058 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1062 return setCursor(cur, pit, pos);
1066 bool Text::cursorVisLeftOneWord(Cursor & cur)
1068 LASSERT(this == cur.text(), /**/);
1070 pos_type left_pos, right_pos;
1071 bool left_is_letter, right_is_letter;
1073 Cursor temp_cur = cur;
1075 // always try to move at least once...
1076 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1078 // collect some information about current cursor position
1079 temp_cur.getSurroundingPos(left_pos, right_pos);
1081 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1083 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1085 // if we're not at a letter/non-letter boundary, continue moving
1086 if (left_is_letter == right_is_letter)
1089 // we should stop when we have an LTR word on our right or an RTL word
1091 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1092 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1093 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1094 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1098 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1099 true, temp_cur.boundary());
1103 bool Text::cursorVisRightOneWord(Cursor & cur)
1105 LASSERT(this == cur.text(), /**/);
1107 pos_type left_pos, right_pos;
1108 bool left_is_letter, right_is_letter;
1110 Cursor temp_cur = cur;
1112 // always try to move at least once...
1113 while (temp_cur.posVisRight(true /* skip_inset */)) {
1115 // collect some information about current cursor position
1116 temp_cur.getSurroundingPos(left_pos, right_pos);
1118 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1120 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1122 // if we're not at a letter/non-letter boundary, continue moving
1123 if (left_is_letter == right_is_letter)
1126 // we should stop when we have an LTR word on our right or an RTL word
1128 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1129 temp_cur.buffer()->params(),
1130 left_pos).isRightToLeft())
1131 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1132 temp_cur.buffer()->params(),
1133 right_pos).isRightToLeft()))
1137 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1138 true, temp_cur.boundary());
1142 void Text::selectWord(Cursor & cur, word_location loc)
1144 LASSERT(this == cur.text(), /**/);
1145 CursorSlice from = cur.top();
1146 CursorSlice to = cur.top();
1147 getWord(from, to, loc);
1148 if (cur.top() != from)
1149 setCursor(cur, from.pit(), from.pos());
1153 setCursor(cur, to.pit(), to.pos());
1158 void Text::selectAll(Cursor & cur)
1160 LASSERT(this == cur.text(), /**/);
1161 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1163 // If the cursor is at the beginning, make sure the cursor ends there
1164 if (cur.pit() == 0 && cur.pos() == 0) {
1165 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1167 setCursor(cur, 0, 0);
1169 setCursor(cur, 0, 0);
1171 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1177 // Select the word currently under the cursor when no
1178 // selection is currently set
1179 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1181 LASSERT(this == cur.text(), /**/);
1182 if (cur.selection())
1184 selectWord(cur, loc);
1185 return cur.selection();
1189 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1191 LASSERT(this == cur.text(), /**/);
1193 if (!cur.selection()) {
1194 bool const changed = cur.paragraph().isChanged(cur.pos());
1195 if (!(changed && findNextChange(&cur.bv())))
1199 cur.recordUndoSelection();
1201 pit_type begPit = cur.selectionBegin().pit();
1202 pit_type endPit = cur.selectionEnd().pit();
1204 pos_type begPos = cur.selectionBegin().pos();
1205 pos_type endPos = cur.selectionEnd().pos();
1207 // keep selection info, because endPos becomes invalid after the first loop
1208 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1210 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1212 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1213 pos_type parSize = pars_[pit].size();
1215 // ignore empty paragraphs; otherwise, an assertion will fail for
1216 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1220 // do not consider first paragraph if the cursor starts at pos size()
1221 if (pit == begPit && begPos == parSize)
1224 // do not consider last paragraph if the cursor ends at pos 0
1225 if (pit == endPit && endPos == 0)
1226 break; // last iteration anyway
1228 pos_type left = (pit == begPit ? begPos : 0);
1229 pos_type right = (pit == endPit ? endPos : parSize);
1232 pars_[pit].acceptChanges(left, right);
1234 pars_[pit].rejectChanges(left, right);
1238 // next, accept/reject imaginary end-of-par characters
1240 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1241 pos_type pos = pars_[pit].size();
1243 // skip if the selection ends before the end-of-par
1244 if (pit == endPit && endsBeforeEndOfPar)
1245 break; // last iteration anyway
1247 // skip if this is not the last paragraph of the document
1248 // note: the user should be able to accept/reject the par break of the last par!
1249 if (pit == endPit && pit + 1 != int(pars_.size()))
1250 break; // last iteration anway
1253 if (pars_[pit].isInserted(pos)) {
1254 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1255 } else if (pars_[pit].isDeleted(pos)) {
1256 if (pit + 1 == int(pars_.size())) {
1257 // we cannot remove a par break at the end of the last paragraph;
1258 // instead, we mark it unchanged
1259 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1261 mergeParagraph(cur.buffer()->params(), pars_, pit);
1267 if (pars_[pit].isDeleted(pos)) {
1268 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1269 } else if (pars_[pit].isInserted(pos)) {
1270 if (pit + 1 == int(pars_.size())) {
1271 // we mark the par break at the end of the last paragraph unchanged
1272 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1274 mergeParagraph(cur.buffer()->params(), pars_, pit);
1282 // finally, invoke the DEPM
1284 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1289 cur.clearSelection();
1290 setCursorIntern(cur, begPit, begPos);
1291 cur.updateFlags(Update::Force);
1292 cur.buffer()->updateLabels();
1296 void Text::acceptChanges()
1298 BufferParams const & bparams = owner_->buffer().params();
1299 lyx::acceptChanges(pars_, bparams);
1300 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1304 void Text::rejectChanges()
1306 BufferParams const & bparams = owner_->buffer().params();
1307 pit_type pars_size = static_cast<pit_type>(pars_.size());
1309 // first, reject changes within each individual paragraph
1310 // (do not consider end-of-par)
1311 for (pit_type pit = 0; pit < pars_size; ++pit) {
1312 if (!pars_[pit].empty()) // prevent assertion failure
1313 pars_[pit].rejectChanges(0, pars_[pit].size());
1316 // next, reject imaginary end-of-par characters
1317 for (pit_type pit = 0; pit < pars_size; ++pit) {
1318 pos_type pos = pars_[pit].size();
1320 if (pars_[pit].isDeleted(pos)) {
1321 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1322 } else if (pars_[pit].isInserted(pos)) {
1323 if (pit == pars_size - 1) {
1324 // we mark the par break at the end of the last
1325 // paragraph unchanged
1326 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1328 mergeParagraph(bparams, pars_, pit);
1335 // finally, invoke the DEPM
1336 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1340 void Text::deleteWordForward(Cursor & cur)
1342 LASSERT(this == cur.text(), /**/);
1343 if (cur.lastpos() == 0)
1347 cur.setSelection(true);
1348 cursorForwardOneWord(cur);
1350 cutSelection(cur, true, false);
1351 cur.checkBufferStructure();
1356 void Text::deleteWordBackward(Cursor & cur)
1358 LASSERT(this == cur.text(), /**/);
1359 if (cur.lastpos() == 0)
1360 cursorBackward(cur);
1363 cur.setSelection(true);
1364 cursorBackwardOneWord(cur);
1366 cutSelection(cur, true, false);
1367 cur.checkBufferStructure();
1372 // Kill to end of line.
1373 void Text::changeCase(Cursor & cur, TextCase action)
1375 LASSERT(this == cur.text(), /**/);
1379 bool gotsel = false;
1380 if (cur.selection()) {
1381 from = cur.selBegin();
1386 getWord(from, to, PARTIAL_WORD);
1387 cursorForwardOneWord(cur);
1390 cur.recordUndoSelection();
1392 pit_type begPit = from.pit();
1393 pit_type endPit = to.pit();
1395 pos_type begPos = from.pos();
1396 pos_type endPos = to.pos();
1398 pos_type right = 0; // needed after the for loop
1400 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1401 Paragraph & par = pars_[pit];
1402 pos_type const pos = (pit == begPit ? begPos : 0);
1403 right = (pit == endPit ? endPos : par.size());
1404 par.changeCase(cur.buffer()->params(), pos, right, action);
1407 // the selection may have changed due to logically-only deleted chars
1409 setCursor(cur, begPit, begPos);
1411 setCursor(cur, endPit, right);
1414 setCursor(cur, endPit, right);
1416 cur.checkBufferStructure();
1420 bool Text::handleBibitems(Cursor & cur)
1422 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1428 BufferParams const & bufparams = cur.buffer()->params();
1429 Paragraph const & par = cur.paragraph();
1430 Cursor prevcur = cur;
1431 if (cur.pit() > 0) {
1433 prevcur.pos() = prevcur.lastpos();
1435 Paragraph const & prevpar = prevcur.paragraph();
1437 // if a bibitem is deleted, merge with previous paragraph
1438 // if this is a bibliography item as well
1439 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1440 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1441 mergeParagraph(bufparams, cur.text()->paragraphs(),
1443 cur.buffer()->updateLabels();
1444 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1445 cur.updateFlags(Update::Force);
1449 // otherwise reset to default
1450 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1455 bool Text::erase(Cursor & cur)
1457 LASSERT(this == cur.text(), return false);
1458 bool needsUpdate = false;
1459 Paragraph & par = cur.paragraph();
1461 if (cur.pos() != cur.lastpos()) {
1462 // this is the code for a normal delete, not pasting
1464 cur.recordUndo(DELETE_UNDO);
1465 bool const was_inset = cur.paragraph().isInset(cur.pos());
1466 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1467 // the character has been logically deleted only => skip it
1468 cur.top().forwardPos();
1471 cur.buffer()->updateLabels();
1473 cur.checkBufferStructure();
1476 if (cur.pit() == cur.lastpit())
1477 return dissolveInset(cur);
1479 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1480 par.setChange(cur.pos(), Change(Change::DELETED));
1484 setCursorIntern(cur, cur.pit() + 1, 0);
1485 needsUpdate = backspacePos0(cur);
1489 needsUpdate |= handleBibitems(cur);
1492 // Make sure the cursor is correct. Is this really needed?
1493 // No, not really... at least not here!
1494 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1495 cur.checkBufferStructure();
1502 bool Text::backspacePos0(Cursor & cur)
1504 LASSERT(this == cur.text(), /**/);
1508 bool needsUpdate = false;
1510 BufferParams const & bufparams = cur.buffer()->params();
1511 DocumentClass const & tclass = bufparams.documentClass();
1512 ParagraphList & plist = cur.text()->paragraphs();
1513 Paragraph const & par = cur.paragraph();
1514 Cursor prevcur = cur;
1516 prevcur.pos() = prevcur.lastpos();
1517 Paragraph const & prevpar = prevcur.paragraph();
1519 // is it an empty paragraph?
1520 if (cur.lastpos() == 0
1521 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1522 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1523 plist.erase(boost::next(plist.begin(), cur.pit()));
1526 // is previous par empty?
1527 else if (prevcur.lastpos() == 0
1528 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1529 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1530 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1533 // Pasting is not allowed, if the paragraphs have different
1534 // layouts. I think it is a real bug of all other
1535 // word processors to allow it. It confuses the user.
1536 // Correction: Pasting is always allowed with standard-layout
1537 // or the empty layout.
1538 else if (par.layout() == prevpar.layout()
1539 || tclass.isDefaultLayout(par.layout())
1540 || tclass.isPlainLayout(par.layout())) {
1541 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1542 mergeParagraph(bufparams, plist, prevcur.pit());
1547 cur.buffer()->updateLabels();
1548 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1555 bool Text::backspace(Cursor & cur)
1557 LASSERT(this == cur.text(), /**/);
1558 bool needsUpdate = false;
1559 if (cur.pos() == 0) {
1561 return dissolveInset(cur);
1563 Paragraph & prev_par = pars_[cur.pit() - 1];
1565 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1566 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1567 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1570 // The cursor is at the beginning of a paragraph, so
1571 // the backspace will collapse two paragraphs into one.
1572 needsUpdate = backspacePos0(cur);
1575 // this is the code for a normal backspace, not pasting
1577 cur.recordUndo(DELETE_UNDO);
1578 // We used to do cursorBackwardIntern() here, but it is
1579 // not a good idea since it triggers the auto-delete
1580 // mechanism. So we do a cursorBackwardIntern()-lite,
1581 // without the dreaded mechanism. (JMarc)
1582 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1583 false, cur.boundary());
1584 bool const was_inset = cur.paragraph().isInset(cur.pos());
1585 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1587 cur.buffer()->updateLabels();
1589 cur.checkBufferStructure();
1592 if (cur.pos() == cur.lastpos())
1593 cur.setCurrentFont();
1595 needsUpdate |= handleBibitems(cur);
1597 // A singlePar update is not enough in this case.
1598 // cur.updateFlags(Update::Force);
1599 setCursor(cur.top(), cur.pit(), cur.pos());
1605 bool Text::dissolveInset(Cursor & cur)
1607 LASSERT(this == cur.text(), return false);
1609 if (isMainText() || cur.inset().nargs() != 1)
1612 cur.recordUndoInset();
1614 cur.selHandle(false);
1616 pos_type spos = cur.pos();
1617 pit_type spit = cur.pit();
1618 ParagraphList plist;
1619 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1620 plist = paragraphs();
1622 // store cursor offset
1626 Buffer & b = *cur.buffer();
1627 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1628 if (!plist.empty()) {
1629 // ERT paragraphs have the Language latex_language.
1630 // This is invalid outside of ERT, so we need to
1631 // change it to the buffer language.
1632 ParagraphList::iterator it = plist.begin();
1633 ParagraphList::iterator it_end = plist.end();
1634 for (; it != it_end; it++)
1635 it->changeLanguage(b.params(), latex_language, b.language());
1637 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1638 b.errorList("Paste"));
1640 cur.pit() = min(cur.lastpit(), spit);
1641 cur.pos() = min(cur.lastpos(), spos);
1643 // this is the least that needs to be done (bug 6003)
1644 // in the above case, pasteParagraphList handles this
1645 cur.buffer()->updateLabels();
1646 cur.clearSelection();
1652 void Text::getWord(CursorSlice & from, CursorSlice & to,
1653 word_location const loc) const
1656 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1660 void Text::write(ostream & os) const
1662 Buffer const & buf = owner_->buffer();
1663 ParagraphList::const_iterator pit = paragraphs().begin();
1664 ParagraphList::const_iterator end = paragraphs().end();
1666 for (; pit != end; ++pit)
1667 pit->write(os, buf.params(), dth);
1669 // Close begin_deeper
1670 for(; dth > 0; --dth)
1671 os << "\n\\end_deeper";
1675 bool Text::read(Lexer & lex,
1676 ErrorList & errorList, InsetText * insetPtr)
1678 Buffer const & buf = owner_->buffer();
1679 depth_type depth = 0;
1682 while (lex.isOK()) {
1684 string const token = lex.getString();
1689 if (token == "\\end_inset")
1692 if (token == "\\end_body")
1695 if (token == "\\begin_body")
1698 if (token == "\\end_document") {
1703 if (token == "\\begin_layout") {
1704 lex.pushToken(token);
1707 par.setInsetOwner(insetPtr);
1708 par.params().depth(depth);
1709 par.setFont(0, Font(inherit_font, buf.params().language));
1710 pars_.push_back(par);
1711 readParagraph(pars_.back(), lex, errorList);
1713 // register the words in the global word list
1714 CursorSlice sl = CursorSlice(*insetPtr);
1715 sl.pit() = pars_.size() - 1;
1716 pars_.back().updateWords();
1717 } else if (token == "\\begin_deeper") {
1719 } else if (token == "\\end_deeper") {
1721 lex.printError("\\end_deeper: " "depth is already null");
1725 LYXERR0("Handling unknown body token: `" << token << '\'');
1729 // avoid a crash on weird documents (bug 4859)
1730 if (pars_.empty()) {
1732 par.setInsetOwner(insetPtr);
1733 par.params().depth(depth);
1734 par.setFont(0, Font(inherit_font,
1735 buf.params().language));
1736 par.setPlainOrDefaultLayout(buf.params().documentClass());
1737 pars_.push_back(par);
1743 // Returns the current font and depth as a message.
1744 docstring Text::currentState(Cursor const & cur) const
1746 LASSERT(this == cur.text(), /**/);
1747 Buffer & buf = *cur.buffer();
1748 Paragraph const & par = cur.paragraph();
1749 odocstringstream os;
1751 if (buf.params().trackChanges)
1752 os << _("[Change Tracking] ");
1754 Change change = par.lookupChange(cur.pos());
1756 if (change.changed()) {
1757 Author const & a = buf.params().authors().get(change.author);
1758 os << _("Change: ") << a.name();
1759 if (!a.email().empty())
1760 os << " (" << a.email() << ")";
1761 // FIXME ctime is english, we should translate that
1762 os << _(" at ") << ctime(&change.changetime);
1766 // I think we should only show changes from the default
1768 // No, from the document font (MV)
1769 Font font = cur.real_current_font;
1770 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1772 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1774 // The paragraph depth
1775 int depth = cur.paragraph().getDepth();
1777 os << bformat(_(", Depth: %1$d"), depth);
1779 // The paragraph spacing, but only if different from
1781 Spacing const & spacing = par.params().spacing();
1782 if (!spacing.isDefault()) {
1783 os << _(", Spacing: ");
1784 switch (spacing.getSpace()) {
1785 case Spacing::Single:
1788 case Spacing::Onehalf:
1791 case Spacing::Double:
1794 case Spacing::Other:
1795 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1797 case Spacing::Default:
1798 // should never happen, do nothing
1803 #ifdef DEVEL_VERSION
1804 os << _(", Inset: ") << &cur.inset();
1805 os << _(", Paragraph: ") << cur.pit();
1806 os << _(", Id: ") << par.id();
1807 os << _(", Position: ") << cur.pos();
1808 // FIXME: Why is the check for par.size() needed?
1809 // We are called with cur.pos() == par.size() quite often.
1810 if (!par.empty() && cur.pos() < par.size()) {
1811 // Force output of code point, not character
1812 size_t const c = par.getChar(cur.pos());
1813 os << _(", Char: 0x") << hex << c;
1815 os << _(", Boundary: ") << cur.boundary();
1816 // Row & row = cur.textRow();
1817 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1823 docstring Text::getPossibleLabel(Cursor const & cur) const
1825 pit_type pit = cur.pit();
1827 Layout const * layout = &(pars_[pit].layout());
1830 docstring par_text = pars_[pit].asString();
1832 // the return string of math matrices might contain linebreaks
1833 par_text = subst(par_text, '\n', '-');
1834 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1835 if (par_text.empty())
1838 par_text = split(par_text, head, ' ');
1839 // Is it legal to use spaces in labels ?
1845 // No need for a prefix if the user said so.
1846 if (lyxrc.label_init_length <= 0)
1849 // Will contain the label type.
1852 // For section, subsection, etc...
1853 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1854 Layout const * layout2 = &(pars_[pit - 1].layout());
1855 if (layout2->latextype != LATEX_PARAGRAPH) {
1860 if (layout->latextype != LATEX_PARAGRAPH)
1861 name = from_ascii(layout->latexname());
1863 // for captions, we just take the caption type
1864 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1866 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1868 // If none of the above worked, we'll see if we're inside various
1869 // types of insets and take our abbreviation from them.
1871 InsetCode const codes[] = {
1876 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1877 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1879 name = float_inset->name();
1885 // Create a correct prefix for prettyref
1886 if (name == "theorem")
1887 name = from_ascii("thm");
1888 else if (name == "Foot")
1889 name = from_ascii("fn");
1890 else if (name == "listing")
1891 name = from_ascii("lst");
1894 text = name.substr(0, 3) + ':' + text;
1900 docstring Text::asString(int options) const
1902 return asString(0, pars_.size(), options);
1906 docstring Text::asString(pit_type beg, pit_type end, int options) const
1908 size_t i = size_t(beg);
1909 docstring str = pars_[i].asString(options);
1910 for (++i; i != size_t(end); ++i) {
1912 str += pars_[i].asString(options);
1919 void Text::charsTranspose(Cursor & cur)
1921 LASSERT(this == cur.text(), /**/);
1923 pos_type pos = cur.pos();
1925 // If cursor is at beginning or end of paragraph, do nothing.
1926 if (pos == cur.lastpos() || pos == 0)
1929 Paragraph & par = cur.paragraph();
1931 // Get the positions of the characters to be transposed.
1932 pos_type pos1 = pos - 1;
1933 pos_type pos2 = pos;
1935 // In change tracking mode, ignore deleted characters.
1936 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1938 if (pos2 == cur.lastpos())
1941 while (pos1 >= 0 && par.isDeleted(pos1))
1946 // Don't do anything if one of the "characters" is not regular text.
1947 if (par.isInset(pos1) || par.isInset(pos2))
1950 // Store the characters to be transposed (including font information).
1951 char_type const char1 = par.getChar(pos1);
1953 par.getFontSettings(cur.buffer()->params(), pos1);
1955 char_type const char2 = par.getChar(pos2);
1957 par.getFontSettings(cur.buffer()->params(), pos2);
1959 // And finally, we are ready to perform the transposition.
1960 // Track the changes if Change Tracking is enabled.
1961 bool const trackChanges = cur.buffer()->params().trackChanges;
1965 par.eraseChar(pos2, trackChanges);
1966 par.eraseChar(pos1, trackChanges);
1967 par.insertChar(pos1, char2, font2, trackChanges);
1968 par.insertChar(pos2, char1, font1, trackChanges);
1970 cur.checkBufferStructure();
1972 // After the transposition, move cursor to after the transposition.
1973 setCursor(cur, cur.pit(), pos2);
1978 DocIterator Text::macrocontextPosition() const
1980 return macrocontext_position_;
1984 void Text::setMacrocontextPosition(DocIterator const & pos)
1986 macrocontext_position_ = pos;
1990 docstring Text::previousWord(CursorSlice const & sl) const
1992 CursorSlice from = sl;
1993 CursorSlice to = sl;
1994 getWord(from, to, PREVIOUS_WORD);
1995 if (sl == from || to == from)
1998 Paragraph const & par = sl.paragraph();
1999 return par.asString(from.pos(), to.pos());
2003 bool Text::completionSupported(Cursor const & cur) const
2005 Paragraph const & par = cur.paragraph();
2006 return cur.pos() > 0
2007 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2008 && !par.isWordSeparator(cur.pos() - 1);
2012 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2014 return new TextCompletionList(cur);
2018 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2020 LASSERT(cur.bv().cursor() == cur, /**/);
2022 cur.bv().cursor() = cur;
2023 if (!(cur.disp_.update() & Update::Force))
2024 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2029 docstring Text::completionPrefix(Cursor const & cur) const
2031 return previousWord(cur.top());