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 Text::depthHook(pit_type pit, depth_type depth) const
176 pit_type newpit = pit;
181 while (newpit != 0 && pars_[newpit].getDepth() > depth)
184 if (pars_[newpit].getDepth() > depth)
191 pit_type Text::outerHook(pit_type par_offset) const
193 Paragraph const & par = pars_[par_offset];
195 if (par.getDepth() == 0)
197 return depthHook(par_offset, depth_type(par.getDepth() - 1));
201 bool Text::isFirstInSequence(pit_type par_offset) const
203 Paragraph const & par = pars_[par_offset];
205 pit_type dhook_offset = depthHook(par_offset, 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 Font const Text::outerFont(pit_type par_offset) const
219 depth_type par_depth = pars_[par_offset].getDepth();
220 FontInfo tmpfont = inherit_font;
222 // Resolve against environment font information
223 while (par_offset != pit_type(pars_.size())
225 && !tmpfont.resolved()) {
226 par_offset = outerHook(par_offset);
227 if (par_offset != pit_type(pars_.size())) {
228 tmpfont.realize(pars_[par_offset].layout().font);
229 par_depth = pars_[par_offset].getDepth();
233 return Font(tmpfont);
237 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
239 pit_type pars_size = static_cast<pit_type>(pars.size());
241 // first, accept changes within each individual paragraph
242 // (do not consider end-of-par)
243 for (pit_type pit = 0; pit < pars_size; ++pit) {
244 if (!pars[pit].empty()) // prevent assertion failure
245 pars[pit].acceptChanges(0, pars[pit].size());
248 // next, accept imaginary end-of-par characters
249 for (pit_type pit = 0; pit < pars_size; ++pit) {
250 pos_type pos = pars[pit].size();
252 if (pars[pit].isInserted(pos)) {
253 pars[pit].setChange(pos, Change(Change::UNCHANGED));
254 } else if (pars[pit].isDeleted(pos)) {
255 if (pit == pars_size - 1) {
256 // we cannot remove a par break at the end of the last
257 // paragraph; instead, we mark it unchanged
258 pars[pit].setChange(pos, Change(Change::UNCHANGED));
260 mergeParagraph(bparams, pars, pit);
268 InsetText const & Text::inset() const
274 void Text::readParToken(Paragraph & par, Lexer & lex,
275 string const & token, Font & font, Change & change, ErrorList & errorList)
277 Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
278 BufferParams const & bp = buf->params();
280 if (token[0] != '\\') {
281 docstring dstr = lex.getDocString();
282 par.appendString(dstr, font, change);
284 } else if (token == "\\begin_layout") {
286 docstring layoutname = lex.getDocString();
288 font = Font(inherit_font, bp.language);
289 change = Change(Change::UNCHANGED);
291 DocumentClass const & tclass = bp.documentClass();
293 if (layoutname.empty())
294 layoutname = tclass.defaultLayoutName();
296 if (owner_->forcePlainLayout()) {
297 // in this case only the empty layout is allowed
298 layoutname = tclass.plainLayoutName();
299 } else if (par.usePlainLayout()) {
300 // in this case, default layout maps to empty layout
301 if (layoutname == tclass.defaultLayoutName())
302 layoutname = tclass.plainLayoutName();
304 // otherwise, the empty layout maps to the default
305 if (layoutname == tclass.plainLayoutName())
306 layoutname = tclass.defaultLayoutName();
309 // When we apply an unknown layout to a document, we add this layout to the textclass
310 // of this document. For example, when you apply class article to a beamer document,
311 // all unknown layouts such as frame will be added to document class article so that
312 // these layouts can keep their original names.
313 tclass.addLayoutIfNeeded(layoutname);
315 par.setLayout(bp.documentClass()[layoutname]);
317 // Test whether the layout is obsolete.
318 Layout const & layout = par.layout();
319 if (!layout.obsoleted_by().empty())
320 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
322 par.params().read(lex);
324 } else if (token == "\\end_layout") {
325 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
326 << "Missing \\begin_layout ?");
327 } else if (token == "\\end_inset") {
328 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
329 << "Missing \\begin_inset ?");
330 } else if (token == "\\begin_inset") {
331 Inset * inset = readInset(lex, buf);
333 par.insertInset(par.size(), inset, font, change);
336 docstring line = lex.getDocString();
337 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
338 par.id(), 0, par.size()));
340 } else if (token == "\\family") {
342 setLyXFamily(lex.getString(), font.fontInfo());
343 } else if (token == "\\series") {
345 setLyXSeries(lex.getString(), font.fontInfo());
346 } else if (token == "\\shape") {
348 setLyXShape(lex.getString(), font.fontInfo());
349 } else if (token == "\\size") {
351 setLyXSize(lex.getString(), font.fontInfo());
352 } else if (token == "\\lang") {
354 string const tok = lex.getString();
355 Language const * lang = languages.getLanguage(tok);
357 font.setLanguage(lang);
359 font.setLanguage(bp.language);
360 lex.printError("Unknown language `$$Token'");
362 } else if (token == "\\numeric") {
364 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
365 } else if (token == "\\emph") {
367 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
368 } else if (token == "\\bar") {
370 string const tok = lex.getString();
373 font.fontInfo().setUnderbar(FONT_ON);
374 else if (tok == "no")
375 font.fontInfo().setUnderbar(FONT_OFF);
376 else if (tok == "default")
377 font.fontInfo().setUnderbar(FONT_INHERIT);
379 lex.printError("Unknown bar font flag "
381 } else if (token == "\\strikeout") {
383 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
384 } else if (token == "\\uuline") {
386 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
387 } else if (token == "\\uwave") {
389 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
390 } else if (token == "\\noun") {
392 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
393 } else if (token == "\\color") {
395 setLyXColor(lex.getString(), font.fontInfo());
396 } else if (token == "\\SpecialChar") {
397 auto_ptr<Inset> inset;
398 inset.reset(new InsetSpecialChar);
400 inset->setBuffer(*buf);
401 par.insertInset(par.size(), inset.release(), font, change);
402 } else if (token == "\\backslash") {
403 par.appendChar('\\', font, change);
404 } else if (token == "\\LyXTable") {
405 auto_ptr<Inset> inset(new InsetTabular(buf));
407 par.insertInset(par.size(), inset.release(), font, change);
408 } else if (token == "\\lyxline") {
409 auto_ptr<Inset> inset;
410 inset.reset(new InsetLine);
411 inset->setBuffer(*buf);
412 par.insertInset(par.size(), inset.release(), font, change);
413 } else if (token == "\\change_unchanged") {
414 change = Change(Change::UNCHANGED);
415 } else if (token == "\\change_inserted" || token == "\\change_deleted") {
417 istringstream is(lex.getString());
421 map<unsigned int, int> const & am = bp.author_map;
422 if (am.find(aid) == am.end()) {
423 errorList.push_back(ErrorItem(_("Change tracking error"),
424 bformat(_("Unknown author index for change: %1$d\n"), aid),
425 par.id(), 0, par.size()));
426 change = Change(Change::UNCHANGED);
428 if (token == "\\change_inserted")
429 change = Change(Change::INSERTED, am.find(aid)->second, ct);
431 change = Change(Change::DELETED, am.find(aid)->second, ct);
435 errorList.push_back(ErrorItem(_("Unknown token"),
436 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
438 par.id(), 0, par.size()));
443 void Text::readParagraph(Paragraph & par, Lexer & lex,
444 ErrorList & errorList)
447 string token = lex.getString();
449 Change change(Change::UNCHANGED);
452 readParToken(par, lex, token, font, change, errorList);
455 token = lex.getString();
460 if (token == "\\end_layout") {
461 //Ok, paragraph finished
465 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
466 if (token == "\\begin_layout" || token == "\\end_document"
467 || token == "\\end_inset" || token == "\\begin_deeper"
468 || token == "\\end_deeper") {
469 lex.pushToken(token);
470 lyxerr << "Paragraph ended in line "
471 << lex.lineNumber() << "\n"
472 << "Missing \\end_layout.\n";
476 // Final change goes to paragraph break:
477 par.setChange(par.size(), change);
479 // Initialize begin_of_body_ on load; redoParagraph maintains
480 par.setBeginOfBody();
484 class TextCompletionList : public CompletionList
488 TextCompletionList(Cursor const & cur, WordList const * list)
489 : buffer_(cur.buffer()), pos_(0), list_(list)
492 virtual ~TextCompletionList() {}
495 virtual bool sorted() const { return true; }
497 virtual size_t size() const
499 return list_->size();
502 virtual docstring const & data(size_t idx) const
504 return list_->word(idx);
509 Buffer const * buffer_;
513 WordList const * list_;
517 bool Text::empty() const
519 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
520 // FIXME: Should we consider the labeled type as empty too?
521 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
525 double Text::spacing(Paragraph const & par) const
527 if (par.params().spacing().isDefault())
528 return owner_->buffer().params().spacing().getValue();
529 return par.params().spacing().getValue();
534 * This breaks a paragraph at the specified position.
535 * The new paragraph will:
536 * - Decrease depth by one (or change layout to default layout) when
537 * keep_layout == false
538 * - keep current depth and layout when keep_layout == true
540 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
543 BufferParams const & bparams = text.inset().buffer().params();
544 ParagraphList & pars = text.paragraphs();
545 // create a new paragraph, and insert into the list
546 ParagraphList::iterator tmp =
547 pars.insert(boost::next(pars.begin(), par_offset + 1),
550 Paragraph & par = pars[par_offset];
552 // remember to set the inset_owner
553 tmp->setInsetOwner(&par.inInset());
554 // without doing that we get a crash when typing <Return> at the
555 // end of a paragraph
556 tmp->setPlainOrDefaultLayout(bparams.documentClass());
558 // layout stays the same with latex-environments
560 tmp->setLayout(par.layout());
561 tmp->setLabelWidthString(par.params().labelWidthString());
562 tmp->params().depth(par.params().depth());
563 } else if (par.params().depth() > 0) {
564 Paragraph const & hook = pars[text.outerHook(par_offset)];
565 tmp->setLayout(hook.layout());
566 // not sure the line below is useful
567 tmp->setLabelWidthString(par.params().labelWidthString());
568 tmp->params().depth(hook.params().depth());
571 bool const isempty = (par.allowEmpty() && par.empty());
573 if (!isempty && (par.size() > pos || par.empty())) {
574 tmp->setLayout(par.layout());
575 tmp->params().align(par.params().align());
576 tmp->setLabelWidthString(par.params().labelWidthString());
578 tmp->params().depth(par.params().depth());
579 tmp->params().noindent(par.params().noindent());
581 // move everything behind the break position
582 // to the new paragraph
584 /* Note: if !keepempty, empty() == true, then we reach
585 * here with size() == 0. So pos_end becomes - 1. This
586 * doesn't cause problems because both loops below
587 * enforce pos <= pos_end and 0 <= pos
589 pos_type pos_end = par.size() - 1;
591 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
592 if (moveItem(par, pos, *tmp, j, bparams)) {
598 // Move over the end-of-par change information
599 tmp->setChange(tmp->size(), par.lookupChange(par.size()));
600 par.setChange(par.size(), Change(bparams.trackChanges ?
601 Change::INSERTED : Change::UNCHANGED));
604 // Make sure that we keep the language when
605 // breaking paragraph.
607 Font changed = tmp->getFirstFontSettings(bparams);
608 Font const & old = par.getFontSettings(bparams, par.size());
609 changed.setLanguage(old.language());
610 tmp->setFont(0, changed);
617 bool const soa = par.params().startOfAppendix();
618 par.params().clear();
619 // do not lose start of appendix marker (bug 4212)
620 par.params().startOfAppendix(soa);
621 par.setPlainOrDefaultLayout(bparams.documentClass());
624 // layout stays the same with latex-environments
626 par.setLayout(tmp->layout());
627 par.setLabelWidthString(tmp->params().labelWidthString());
628 par.params().depth(tmp->params().depth());
633 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
635 LASSERT(this == cur.text(), /**/);
637 Paragraph & cpar = cur.paragraph();
638 pit_type cpit = cur.pit();
640 DocumentClass const & tclass = cur.buffer()->params().documentClass();
641 Layout const & layout = cpar.layout();
643 // this is only allowed, if the current paragraph is not empty
644 // or caption and if it has not the keepempty flag active
645 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
646 layout.labeltype != LABEL_SENSITIVE)
649 // a layout change may affect also the following paragraph
650 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
652 // Always break behind a space
653 // It is better to erase the space (Dekel)
654 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
655 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
657 // What should the layout for the new paragraph be?
658 bool keep_layout = inverse_logic ?
659 !layout.isEnvironment()
660 : layout.isEnvironment();
662 // We need to remember this before we break the paragraph, because
663 // that invalidates the layout variable
664 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
666 // we need to set this before we insert the paragraph.
667 bool const isempty = cpar.allowEmpty() && cpar.empty();
669 lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
671 // After this, neither paragraph contains any rows!
674 pit_type next_par = cpit + 1;
676 // well this is the caption hack since one caption is really enough
679 // set to standard-layout
680 //FIXME Check if this should be plainLayout() in some cases
681 pars_[cpit].applyLayout(tclass.defaultLayout());
683 // set to standard-layout
684 //FIXME Check if this should be plainLayout() in some cases
685 pars_[next_par].applyLayout(tclass.defaultLayout());
688 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
689 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
690 break; // the character couldn't be deleted physically due to change tracking
693 cur.buffer()->updateLabels();
695 // A singlePar update is not enough in this case.
696 cur.updateFlags(Update::Force);
698 // This check is necessary. Otherwise the new empty paragraph will
699 // be deleted automatically. And it is more friendly for the user!
700 if (cur.pos() != 0 || isempty)
701 setCursor(cur, cur.pit() + 1, 0);
703 setCursor(cur, cur.pit(), 0);
707 // needed to insert the selection
708 void Text::insertStringAsLines(DocIterator const & dit, docstring const & str,
711 BufferParams const & bparams = owner_->buffer().params();
712 pit_type pit = dit.pit();
713 pos_type pos = dit.pos();
715 // insert the string, don't insert doublespace
716 bool space_inserted = true;
717 for (docstring::const_iterator cit = str.begin();
718 cit != str.end(); ++cit) {
719 Paragraph & par = pars_[pit];
721 if (autoBreakRows_ && (!par.empty() || par.allowEmpty())) {
722 lyx::breakParagraph(*this, pit, pos,
723 par.layout().isEnvironment());
726 space_inserted = true;
730 // do not insert consecutive spaces if !free_spacing
731 } else if ((*cit == ' ' || *cit == '\t') &&
732 space_inserted && !par.isFreeSpacing()) {
734 } else if (*cit == '\t') {
735 if (!par.isFreeSpacing()) {
736 // tabs are like spaces here
737 par.insertChar(pos, ' ', font, bparams.trackChanges);
739 space_inserted = true;
741 par.insertChar(pos, *cit, font, bparams.trackChanges);
743 space_inserted = true;
745 } else if (!isPrintable(*cit)) {
746 // Ignore unprintables
749 // just insert the character
750 par.insertChar(pos, *cit, font, bparams.trackChanges);
752 space_inserted = (*cit == ' ');
758 // turn double CR to single CR, others are converted into one
759 // blank. Then insertStringAsLines is called
760 void Text::insertStringAsParagraphs(DocIterator const & dit, docstring const & str,
763 docstring linestr = str;
764 bool newline_inserted = false;
766 for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
767 if (linestr[i] == '\n') {
768 if (newline_inserted) {
769 // we know that \r will be ignored by
770 // insertStringAsLines. Of course, it is a dirty
771 // trick, but it works...
772 linestr[i - 1] = '\r';
776 newline_inserted = true;
778 } else if (isPrintable(linestr[i])) {
779 newline_inserted = false;
782 insertStringAsLines(dit, linestr, font);
786 // insert a character, moves all the following breaks in the
787 // same Paragraph one to the right and make a rebreak
788 void Text::insertChar(Cursor & cur, char_type c)
790 LASSERT(this == cur.text(), /**/);
792 cur.recordUndo(INSERT_UNDO);
794 TextMetrics const & tm = cur.bv().textMetrics(this);
795 Buffer const & buffer = *cur.buffer();
796 Paragraph & par = cur.paragraph();
797 // try to remove this
798 pit_type const pit = cur.pit();
800 bool const freeSpacing = par.layout().free_spacing ||
803 if (lyxrc.auto_number) {
804 static docstring const number_operators = from_ascii("+-/*");
805 static docstring const number_unary_operators = from_ascii("+-");
806 static docstring const number_seperators = from_ascii(".,:");
808 if (cur.current_font.fontInfo().number() == FONT_ON) {
809 if (!isDigit(c) && !contains(number_operators, c) &&
810 !(contains(number_seperators, c) &&
812 cur.pos() != cur.lastpos() &&
813 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
814 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
816 number(cur); // Set current_font.number to OFF
817 } else if (isDigit(c) &&
818 cur.real_current_font.isVisibleRightToLeft()) {
819 number(cur); // Set current_font.number to ON
821 if (cur.pos() != 0) {
822 char_type const c = par.getChar(cur.pos() - 1);
823 if (contains(number_unary_operators, c) &&
825 || par.isSeparator(cur.pos() - 2)
826 || par.isNewline(cur.pos() - 2))
828 setCharFont(pit, cur.pos() - 1, cur.current_font,
830 } else if (contains(number_seperators, c)
832 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
833 setCharFont(pit, cur.pos() - 1, cur.current_font,
840 // In Bidi text, we want spaces to be treated in a special way: spaces
841 // which are between words in different languages should get the
842 // paragraph's language; otherwise, spaces should keep the language
843 // they were originally typed in. This is only in effect while typing;
844 // after the text is already typed in, the user can always go back and
845 // explicitly set the language of a space as desired. But 99.9% of the
846 // time, what we're doing here is what the user actually meant.
848 // The following cases are the ones in which the language of the space
849 // should be changed to match that of the containing paragraph. In the
850 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
851 // represents a space, pipe (|) represents the cursor position (so the
852 // character before it is the one just typed in). The different cases
853 // are depicted logically (not visually), from left to right:
858 // Theoretically, there are other situations that we should, perhaps, deal
859 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
860 // point (to understand why, just try to create this situation...).
862 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
863 // get font in front and behind the space in question. But do NOT
864 // use getFont(cur.pos()) because the character c is not inserted yet
865 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
866 Font const & post_space_font = cur.real_current_font;
867 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
868 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
870 if (pre_space_rtl != post_space_rtl) {
871 // Set the space's language to match the language of the
872 // adjacent character whose direction is the paragraph's
873 // direction; don't touch other properties of the font
874 Language const * lang =
875 (pre_space_rtl == par.isRTL(buffer.params())) ?
876 pre_space_font.language() : post_space_font.language();
878 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
879 space_font.setLanguage(lang);
880 par.setFont(cur.pos() - 1, space_font);
884 // Next check, if there will be two blanks together or a blank at
885 // the beginning of a paragraph.
886 // I decided to handle blanks like normal characters, the main
887 // difference are the special checks when calculating the row.fill
888 // (blank does not count at the end of a row) and the check here
890 // When the free-spacing option is set for the current layout,
891 // disable the double-space checking
892 if (!freeSpacing && isLineSeparatorChar(c)) {
893 if (cur.pos() == 0) {
894 static bool sent_space_message = false;
895 if (!sent_space_message) {
896 cur.message(_("You cannot insert a space at the "
897 "beginning of a paragraph. Please read the Tutorial."));
898 sent_space_message = true;
902 LASSERT(cur.pos() > 0, /**/);
903 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
904 && !par.isDeleted(cur.pos() - 1)) {
905 static bool sent_space_message = false;
906 if (!sent_space_message) {
907 cur.message(_("You cannot type two spaces this way. "
908 "Please read the Tutorial."));
909 sent_space_message = true;
915 par.insertChar(cur.pos(), c, cur.current_font,
916 cur.buffer()->params().trackChanges);
917 cur.checkBufferStructure();
919 // cur.updateFlags(Update::Force);
920 bool boundary = cur.boundary()
921 || tm.isRTLBoundary(cur.pit(), cur.pos() + 1);
922 setCursor(cur, cur.pit(), cur.pos() + 1, false, boundary);
927 void Text::charInserted(Cursor & cur)
929 Paragraph & par = cur.paragraph();
931 // Here we call finishUndo for every 20 characters inserted.
932 // This is from my experience how emacs does it. (Lgb)
933 if (undo_counter_ < 20) {
940 // register word if a non-letter was entered
942 && !par.isWordSeparator(cur.pos() - 2)
943 && par.isWordSeparator(cur.pos() - 1)) {
944 // get the word in front of cursor
945 LASSERT(this == cur.text(), /**/);
946 cur.paragraph().updateWords();
951 // the cursor set functions have a special mechanism. When they
952 // realize, that you left an empty paragraph, they will delete it.
954 bool Text::cursorForwardOneWord(Cursor & cur)
956 LASSERT(this == cur.text(), /**/);
958 pos_type const lastpos = cur.lastpos();
959 pit_type pit = cur.pit();
960 pos_type pos = cur.pos();
961 Paragraph const & par = cur.paragraph();
963 // Paragraph boundary is a word boundary
964 if (pos == lastpos) {
965 if (pit != cur.lastpit())
966 return setCursor(cur, pit + 1, 0);
971 if (lyxrc.mac_like_word_movement) {
972 // Skip through trailing punctuation and spaces.
973 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
976 // Skip over either a non-char inset or a full word
977 if (pos != lastpos && par.isWordSeparator(pos))
979 else while (pos != lastpos && !par.isWordSeparator(pos))
982 LASSERT(pos < lastpos, /**/); // see above
983 if (!par.isWordSeparator(pos))
984 while (pos != lastpos && !par.isWordSeparator(pos))
986 else if (par.isChar(pos))
987 while (pos != lastpos && par.isChar(pos))
989 else if (!par.isSpace(pos)) // non-char inset
992 // Skip over white space
993 while (pos != lastpos && par.isSpace(pos))
997 return setCursor(cur, pit, pos);
1001 bool Text::cursorBackwardOneWord(Cursor & cur)
1003 LASSERT(this == cur.text(), /**/);
1005 pit_type pit = cur.pit();
1006 pos_type pos = cur.pos();
1007 Paragraph & par = cur.paragraph();
1009 // Paragraph boundary is a word boundary
1010 if (pos == 0 && pit != 0)
1011 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1013 if (lyxrc.mac_like_word_movement) {
1014 // Skip through punctuation and spaces.
1015 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1018 // Skip over either a non-char inset or a full word
1019 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1021 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1024 // Skip over white space
1025 while (pos != 0 && par.isSpace(pos - 1))
1028 if (pos != 0 && !par.isWordSeparator(pos - 1))
1029 while (pos != 0 && !par.isWordSeparator(pos - 1))
1031 else if (pos != 0 && par.isChar(pos - 1))
1032 while (pos != 0 && par.isChar(pos - 1))
1034 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1038 return setCursor(cur, pit, pos);
1042 bool Text::cursorVisLeftOneWord(Cursor & cur)
1044 LASSERT(this == cur.text(), /**/);
1046 pos_type left_pos, right_pos;
1047 bool left_is_letter, right_is_letter;
1049 Cursor temp_cur = cur;
1051 // always try to move at least once...
1052 while (temp_cur.posVisLeft(true /* skip_inset */)) {
1054 // collect some information about current cursor position
1055 temp_cur.getSurroundingPos(left_pos, right_pos);
1057 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1059 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1061 // if we're not at a letter/non-letter boundary, continue moving
1062 if (left_is_letter == right_is_letter)
1065 // we should stop when we have an LTR word on our right or an RTL word
1067 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1068 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1069 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1070 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1074 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1075 true, temp_cur.boundary());
1079 bool Text::cursorVisRightOneWord(Cursor & cur)
1081 LASSERT(this == cur.text(), /**/);
1083 pos_type left_pos, right_pos;
1084 bool left_is_letter, right_is_letter;
1086 Cursor temp_cur = cur;
1088 // always try to move at least once...
1089 while (temp_cur.posVisRight(true /* skip_inset */)) {
1091 // collect some information about current cursor position
1092 temp_cur.getSurroundingPos(left_pos, right_pos);
1094 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1096 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1098 // if we're not at a letter/non-letter boundary, continue moving
1099 if (left_is_letter == right_is_letter)
1102 // we should stop when we have an LTR word on our right or an RTL word
1104 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1105 temp_cur.buffer()->params(),
1106 left_pos).isRightToLeft())
1107 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1108 temp_cur.buffer()->params(),
1109 right_pos).isRightToLeft()))
1113 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1114 true, temp_cur.boundary());
1118 void Text::selectWord(Cursor & cur, word_location loc)
1120 LASSERT(this == cur.text(), /**/);
1121 CursorSlice from = cur.top();
1122 CursorSlice to = cur.top();
1123 getWord(from, to, loc);
1124 if (cur.top() != from)
1125 setCursor(cur, from.pit(), from.pos());
1128 if (!cur.selection())
1130 setCursor(cur, to.pit(), to.pos());
1132 cur.setWordSelection(true);
1136 void Text::selectAll(Cursor & cur)
1138 LASSERT(this == cur.text(), /**/);
1139 if (cur.lastpos() == 0 && cur.lastpit() == 0)
1141 // If the cursor is at the beginning, make sure the cursor ends there
1142 if (cur.pit() == 0 && cur.pos() == 0) {
1143 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1145 setCursor(cur, 0, 0);
1147 setCursor(cur, 0, 0);
1149 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1155 // Select the word currently under the cursor when no
1156 // selection is currently set
1157 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1159 LASSERT(this == cur.text(), /**/);
1160 if (cur.selection())
1162 selectWord(cur, loc);
1163 return cur.selection();
1167 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1169 LASSERT(this == cur.text(), /**/);
1171 if (!cur.selection()) {
1172 bool const changed = cur.paragraph().isChanged(cur.pos());
1173 if (!(changed && findNextChange(&cur.bv())))
1177 cur.recordUndoSelection();
1179 pit_type begPit = cur.selectionBegin().pit();
1180 pit_type endPit = cur.selectionEnd().pit();
1182 pos_type begPos = cur.selectionBegin().pos();
1183 pos_type endPos = cur.selectionEnd().pos();
1185 // keep selection info, because endPos becomes invalid after the first loop
1186 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1188 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1190 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1191 pos_type parSize = pars_[pit].size();
1193 // ignore empty paragraphs; otherwise, an assertion will fail for
1194 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1198 // do not consider first paragraph if the cursor starts at pos size()
1199 if (pit == begPit && begPos == parSize)
1202 // do not consider last paragraph if the cursor ends at pos 0
1203 if (pit == endPit && endPos == 0)
1204 break; // last iteration anyway
1206 pos_type left = (pit == begPit ? begPos : 0);
1207 pos_type right = (pit == endPit ? endPos : parSize);
1210 pars_[pit].acceptChanges(left, right);
1212 pars_[pit].rejectChanges(left, right);
1216 // next, accept/reject imaginary end-of-par characters
1218 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1219 pos_type pos = pars_[pit].size();
1221 // skip if the selection ends before the end-of-par
1222 if (pit == endPit && endsBeforeEndOfPar)
1223 break; // last iteration anyway
1225 // skip if this is not the last paragraph of the document
1226 // note: the user should be able to accept/reject the par break of the last par!
1227 if (pit == endPit && pit + 1 != int(pars_.size()))
1228 break; // last iteration anway
1231 if (pars_[pit].isInserted(pos)) {
1232 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1233 } else if (pars_[pit].isDeleted(pos)) {
1234 if (pit + 1 == int(pars_.size())) {
1235 // we cannot remove a par break at the end of the last paragraph;
1236 // instead, we mark it unchanged
1237 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1239 mergeParagraph(cur.buffer()->params(), pars_, pit);
1245 if (pars_[pit].isDeleted(pos)) {
1246 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1247 } else if (pars_[pit].isInserted(pos)) {
1248 if (pit + 1 == int(pars_.size())) {
1249 // we mark the par break at the end of the last paragraph unchanged
1250 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1252 mergeParagraph(cur.buffer()->params(), pars_, pit);
1260 // finally, invoke the DEPM
1262 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
1267 cur.clearSelection();
1268 setCursorIntern(cur, begPit, begPos);
1269 cur.updateFlags(Update::Force);
1270 cur.buffer()->updateLabels();
1274 void Text::acceptChanges()
1276 BufferParams const & bparams = owner_->buffer().params();
1277 lyx::acceptChanges(pars_, bparams);
1278 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
1282 void Text::rejectChanges()
1284 BufferParams const & bparams = owner_->buffer().params();
1285 pit_type pars_size = static_cast<pit_type>(pars_.size());
1287 // first, reject changes within each individual paragraph
1288 // (do not consider end-of-par)
1289 for (pit_type pit = 0; pit < pars_size; ++pit) {
1290 if (!pars_[pit].empty()) // prevent assertion failure
1291 pars_[pit].rejectChanges(0, pars_[pit].size());
1294 // next, reject imaginary end-of-par characters
1295 for (pit_type pit = 0; pit < pars_size; ++pit) {
1296 pos_type pos = pars_[pit].size();
1298 if (pars_[pit].isDeleted(pos)) {
1299 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1300 } else if (pars_[pit].isInserted(pos)) {
1301 if (pit == pars_size - 1) {
1302 // we mark the par break at the end of the last
1303 // paragraph unchanged
1304 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1306 mergeParagraph(bparams, pars_, pit);
1313 // finally, invoke the DEPM
1314 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1318 void Text::deleteWordForward(Cursor & cur)
1320 LASSERT(this == cur.text(), /**/);
1321 if (cur.lastpos() == 0)
1325 cur.setSelection(true);
1326 cursorForwardOneWord(cur);
1328 cutSelection(cur, true, false);
1329 cur.checkBufferStructure();
1334 void Text::deleteWordBackward(Cursor & cur)
1336 LASSERT(this == cur.text(), /**/);
1337 if (cur.lastpos() == 0)
1338 cursorBackward(cur);
1341 cur.setSelection(true);
1342 cursorBackwardOneWord(cur);
1344 cutSelection(cur, true, false);
1345 cur.checkBufferStructure();
1350 // Kill to end of line.
1351 void Text::changeCase(Cursor & cur, TextCase action)
1353 LASSERT(this == cur.text(), /**/);
1357 bool gotsel = false;
1358 if (cur.selection()) {
1359 from = cur.selBegin();
1364 getWord(from, to, PARTIAL_WORD);
1365 cursorForwardOneWord(cur);
1368 cur.recordUndoSelection();
1370 pit_type begPit = from.pit();
1371 pit_type endPit = to.pit();
1373 pos_type begPos = from.pos();
1374 pos_type endPos = to.pos();
1376 pos_type right = 0; // needed after the for loop
1378 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1379 Paragraph & par = pars_[pit];
1380 pos_type const pos = (pit == begPit ? begPos : 0);
1381 right = (pit == endPit ? endPos : par.size());
1382 par.changeCase(cur.buffer()->params(), pos, right, action);
1385 // the selection may have changed due to logically-only deleted chars
1387 setCursor(cur, begPit, begPos);
1389 setCursor(cur, endPit, right);
1392 setCursor(cur, endPit, right);
1394 cur.checkBufferStructure();
1398 bool Text::handleBibitems(Cursor & cur)
1400 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1406 BufferParams const & bufparams = cur.buffer()->params();
1407 Paragraph const & par = cur.paragraph();
1408 Cursor prevcur = cur;
1409 if (cur.pit() > 0) {
1411 prevcur.pos() = prevcur.lastpos();
1413 Paragraph const & prevpar = prevcur.paragraph();
1415 // if a bibitem is deleted, merge with previous paragraph
1416 // if this is a bibliography item as well
1417 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1418 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1419 mergeParagraph(bufparams, cur.text()->paragraphs(),
1421 cur.buffer()->updateLabels();
1422 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1423 cur.updateFlags(Update::Force);
1427 // otherwise reset to default
1428 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1433 bool Text::erase(Cursor & cur)
1435 LASSERT(this == cur.text(), return false);
1436 bool needsUpdate = false;
1437 Paragraph & par = cur.paragraph();
1439 if (cur.pos() != cur.lastpos()) {
1440 // this is the code for a normal delete, not pasting
1442 cur.recordUndo(DELETE_UNDO);
1443 bool const was_inset = cur.paragraph().isInset(cur.pos());
1444 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1445 // the character has been logically deleted only => skip it
1446 cur.top().forwardPos();
1449 cur.buffer()->updateLabels();
1451 cur.checkBufferStructure();
1454 if (cur.pit() == cur.lastpit())
1455 return dissolveInset(cur);
1457 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1458 par.setChange(cur.pos(), Change(Change::DELETED));
1462 setCursorIntern(cur, cur.pit() + 1, 0);
1463 needsUpdate = backspacePos0(cur);
1467 needsUpdate |= handleBibitems(cur);
1470 // Make sure the cursor is correct. Is this really needed?
1471 // No, not really... at least not here!
1472 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1473 cur.checkBufferStructure();
1480 bool Text::backspacePos0(Cursor & cur)
1482 LASSERT(this == cur.text(), /**/);
1486 bool needsUpdate = false;
1488 BufferParams const & bufparams = cur.buffer()->params();
1489 DocumentClass const & tclass = bufparams.documentClass();
1490 ParagraphList & plist = cur.text()->paragraphs();
1491 Paragraph const & par = cur.paragraph();
1492 Cursor prevcur = cur;
1494 prevcur.pos() = prevcur.lastpos();
1495 Paragraph const & prevpar = prevcur.paragraph();
1497 // is it an empty paragraph?
1498 if (cur.lastpos() == 0
1499 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1500 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1501 plist.erase(boost::next(plist.begin(), cur.pit()));
1504 // is previous par empty?
1505 else if (prevcur.lastpos() == 0
1506 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1507 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1508 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1511 // Pasting is not allowed, if the paragraphs have different
1512 // layouts. I think it is a real bug of all other
1513 // word processors to allow it. It confuses the user.
1514 // Correction: Pasting is always allowed with standard-layout
1515 // or the empty layout.
1516 else if (par.layout() == prevpar.layout()
1517 || tclass.isDefaultLayout(par.layout())
1518 || tclass.isPlainLayout(par.layout())) {
1519 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1520 mergeParagraph(bufparams, plist, prevcur.pit());
1525 cur.buffer()->updateLabels();
1526 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1533 bool Text::backspace(Cursor & cur)
1535 LASSERT(this == cur.text(), /**/);
1536 bool needsUpdate = false;
1537 if (cur.pos() == 0) {
1539 return dissolveInset(cur);
1541 Paragraph & prev_par = pars_[cur.pit() - 1];
1543 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1544 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1545 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1548 // The cursor is at the beginning of a paragraph, so
1549 // the backspace will collapse two paragraphs into one.
1550 needsUpdate = backspacePos0(cur);
1553 // this is the code for a normal backspace, not pasting
1555 cur.recordUndo(DELETE_UNDO);
1556 // We used to do cursorBackwardIntern() here, but it is
1557 // not a good idea since it triggers the auto-delete
1558 // mechanism. So we do a cursorBackwardIntern()-lite,
1559 // without the dreaded mechanism. (JMarc)
1560 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1561 false, cur.boundary());
1562 bool const was_inset = cur.paragraph().isInset(cur.pos());
1563 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1565 cur.buffer()->updateLabels();
1567 cur.checkBufferStructure();
1570 if (cur.pos() == cur.lastpos())
1571 cur.setCurrentFont();
1573 needsUpdate |= handleBibitems(cur);
1575 // A singlePar update is not enough in this case.
1576 // cur.updateFlags(Update::Force);
1577 setCursor(cur.top(), cur.pit(), cur.pos());
1583 bool Text::dissolveInset(Cursor & cur)
1585 LASSERT(this == cur.text(), return false);
1587 if (isMainText() || cur.inset().nargs() != 1)
1590 cur.recordUndoInset();
1592 cur.selHandle(false);
1594 pos_type spos = cur.pos();
1595 pit_type spit = cur.pit();
1596 ParagraphList plist;
1597 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1598 plist = paragraphs();
1600 // store cursor offset
1604 Buffer & b = *cur.buffer();
1605 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1606 if (!plist.empty()) {
1607 // ERT paragraphs have the Language latex_language.
1608 // This is invalid outside of ERT, so we need to
1609 // change it to the buffer language.
1610 ParagraphList::iterator it = plist.begin();
1611 ParagraphList::iterator it_end = plist.end();
1612 for (; it != it_end; it++)
1613 it->changeLanguage(b.params(), latex_language, b.language());
1615 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1616 b.errorList("Paste"));
1618 cur.pit() = min(cur.lastpit(), spit);
1619 cur.pos() = min(cur.lastpos(), spos);
1621 // this is the least that needs to be done (bug 6003)
1622 // in the above case, pasteParagraphList handles this
1623 cur.buffer()->updateLabels();
1625 // Ensure the current language is set correctly (bug 6292)
1626 cur.text()->setCursor(cur, cur.pit(), cur.pos());
1627 cur.clearSelection();
1633 void Text::getWord(CursorSlice & from, CursorSlice & to,
1634 word_location const loc) const
1637 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1641 void Text::write(ostream & os) const
1643 Buffer const & buf = owner_->buffer();
1644 ParagraphList::const_iterator pit = paragraphs().begin();
1645 ParagraphList::const_iterator end = paragraphs().end();
1647 for (; pit != end; ++pit)
1648 pit->write(os, buf.params(), dth);
1650 // Close begin_deeper
1651 for(; dth > 0; --dth)
1652 os << "\n\\end_deeper";
1656 bool Text::read(Lexer & lex,
1657 ErrorList & errorList, InsetText * insetPtr)
1659 Buffer const & buf = owner_->buffer();
1660 depth_type depth = 0;
1663 while (lex.isOK()) {
1665 string const token = lex.getString();
1670 if (token == "\\end_inset")
1673 if (token == "\\end_body")
1676 if (token == "\\begin_body")
1679 if (token == "\\end_document") {
1684 if (token == "\\begin_layout") {
1685 lex.pushToken(token);
1688 par.setInsetOwner(insetPtr);
1689 par.params().depth(depth);
1690 par.setFont(0, Font(inherit_font, buf.params().language));
1691 pars_.push_back(par);
1692 readParagraph(pars_.back(), lex, errorList);
1694 // register the words in the global word list
1695 pars_.back().updateWords();
1696 } else if (token == "\\begin_deeper") {
1698 } else if (token == "\\end_deeper") {
1700 lex.printError("\\end_deeper: " "depth is already null");
1704 LYXERR0("Handling unknown body token: `" << token << '\'');
1708 // avoid a crash on weird documents (bug 4859)
1709 if (pars_.empty()) {
1711 par.setInsetOwner(insetPtr);
1712 par.params().depth(depth);
1713 par.setFont(0, Font(inherit_font,
1714 buf.params().language));
1715 par.setPlainOrDefaultLayout(buf.params().documentClass());
1716 pars_.push_back(par);
1722 // Returns the current font and depth as a message.
1723 docstring Text::currentState(Cursor const & cur) const
1725 LASSERT(this == cur.text(), /**/);
1726 Buffer & buf = *cur.buffer();
1727 Paragraph const & par = cur.paragraph();
1728 odocstringstream os;
1730 if (buf.params().trackChanges)
1731 os << _("[Change Tracking] ");
1733 Change change = par.lookupChange(cur.pos());
1735 if (change.changed()) {
1736 Author const & a = buf.params().authors().get(change.author);
1737 os << _("Change: ") << a.name();
1738 if (!a.email().empty())
1739 os << " (" << a.email() << ")";
1740 // FIXME ctime is english, we should translate that
1741 os << _(" at ") << ctime(&change.changetime);
1745 // I think we should only show changes from the default
1747 // No, from the document font (MV)
1748 Font font = cur.real_current_font;
1749 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1751 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1753 // The paragraph depth
1754 int depth = cur.paragraph().getDepth();
1756 os << bformat(_(", Depth: %1$d"), depth);
1758 // The paragraph spacing, but only if different from
1760 Spacing const & spacing = par.params().spacing();
1761 if (!spacing.isDefault()) {
1762 os << _(", Spacing: ");
1763 switch (spacing.getSpace()) {
1764 case Spacing::Single:
1767 case Spacing::Onehalf:
1770 case Spacing::Double:
1773 case Spacing::Other:
1774 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1776 case Spacing::Default:
1777 // should never happen, do nothing
1782 #ifdef DEVEL_VERSION
1783 os << _(", Inset: ") << &cur.inset();
1784 os << _(", Paragraph: ") << cur.pit();
1785 os << _(", Id: ") << par.id();
1786 os << _(", Position: ") << cur.pos();
1787 // FIXME: Why is the check for par.size() needed?
1788 // We are called with cur.pos() == par.size() quite often.
1789 if (!par.empty() && cur.pos() < par.size()) {
1790 // Force output of code point, not character
1791 size_t const c = par.getChar(cur.pos());
1792 os << _(", Char: 0x") << hex << c;
1794 os << _(", Boundary: ") << cur.boundary();
1795 // Row & row = cur.textRow();
1796 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1802 docstring Text::getPossibleLabel(Cursor const & cur) const
1804 pit_type pit = cur.pit();
1806 Layout const * layout = &(pars_[pit].layout());
1809 docstring par_text = pars_[pit].asString();
1811 // the return string of math matrices might contain linebreaks
1812 par_text = subst(par_text, '\n', '-');
1813 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1814 if (par_text.empty())
1817 par_text = split(par_text, head, ' ');
1818 // Is it legal to use spaces in labels ?
1824 // No need for a prefix if the user said so.
1825 if (lyxrc.label_init_length <= 0)
1828 // Will contain the label type.
1831 // For section, subsection, etc...
1832 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1833 Layout const * layout2 = &(pars_[pit - 1].layout());
1834 if (layout2->latextype != LATEX_PARAGRAPH) {
1839 if (layout->latextype != LATEX_PARAGRAPH)
1840 name = from_ascii(layout->latexname());
1842 // for captions, we just take the caption type
1843 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1845 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1847 // If none of the above worked, we'll see if we're inside various
1848 // types of insets and take our abbreviation from them.
1850 InsetCode const codes[] = {
1855 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1856 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1858 name = float_inset->name();
1864 // Create a correct prefix for prettyref
1865 if (name == "theorem")
1866 name = from_ascii("thm");
1867 else if (name == "Foot")
1868 name = from_ascii("fn");
1869 else if (name == "listing")
1870 name = from_ascii("lst");
1873 text = name.substr(0, 3) + ':' + text;
1879 docstring Text::asString(int options) const
1881 return asString(0, pars_.size(), options);
1885 docstring Text::asString(pit_type beg, pit_type end, int options) const
1887 size_t i = size_t(beg);
1888 docstring str = pars_[i].asString(options);
1889 for (++i; i != size_t(end); ++i) {
1891 str += pars_[i].asString(options);
1898 void Text::charsTranspose(Cursor & cur)
1900 LASSERT(this == cur.text(), /**/);
1902 pos_type pos = cur.pos();
1904 // If cursor is at beginning or end of paragraph, do nothing.
1905 if (pos == cur.lastpos() || pos == 0)
1908 Paragraph & par = cur.paragraph();
1910 // Get the positions of the characters to be transposed.
1911 pos_type pos1 = pos - 1;
1912 pos_type pos2 = pos;
1914 // In change tracking mode, ignore deleted characters.
1915 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1917 if (pos2 == cur.lastpos())
1920 while (pos1 >= 0 && par.isDeleted(pos1))
1925 // Don't do anything if one of the "characters" is not regular text.
1926 if (par.isInset(pos1) || par.isInset(pos2))
1929 // Store the characters to be transposed (including font information).
1930 char_type const char1 = par.getChar(pos1);
1932 par.getFontSettings(cur.buffer()->params(), pos1);
1934 char_type const char2 = par.getChar(pos2);
1936 par.getFontSettings(cur.buffer()->params(), pos2);
1938 // And finally, we are ready to perform the transposition.
1939 // Track the changes if Change Tracking is enabled.
1940 bool const trackChanges = cur.buffer()->params().trackChanges;
1944 par.eraseChar(pos2, trackChanges);
1945 par.eraseChar(pos1, trackChanges);
1946 par.insertChar(pos1, char2, font2, trackChanges);
1947 par.insertChar(pos2, char1, font1, trackChanges);
1949 cur.checkBufferStructure();
1951 // After the transposition, move cursor to after the transposition.
1952 setCursor(cur, cur.pit(), pos2);
1957 DocIterator Text::macrocontextPosition() const
1959 return macrocontext_position_;
1963 void Text::setMacrocontextPosition(DocIterator const & pos)
1965 macrocontext_position_ = pos;
1969 docstring Text::previousWord(CursorSlice const & sl) const
1971 CursorSlice from = sl;
1972 CursorSlice to = sl;
1973 getWord(from, to, PREVIOUS_WORD);
1974 if (sl == from || to == from)
1977 Paragraph const & par = sl.paragraph();
1978 return par.asString(from.pos(), to.pos());
1982 bool Text::completionSupported(Cursor const & cur) const
1984 Paragraph const & par = cur.paragraph();
1985 return cur.pos() > 0
1986 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
1987 && !par.isWordSeparator(cur.pos() - 1);
1991 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1993 WordList const * list = theWordList(*cur.getFont().language());
1994 return new TextCompletionList(cur, list);
1998 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2000 LASSERT(cur.bv().cursor() == cur, /**/);
2002 cur.bv().cursor() = cur;
2003 if (!(cur.disp_.update() & Update::Force))
2004 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2009 docstring Text::completionPrefix(Cursor const & cur) const
2011 return previousWord(cur.top());