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"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
49 #include "WordLangTuple.h"
52 #include "insets/InsetText.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetCaption.h"
55 #include "insets/InsetLine.h"
56 #include "insets/InsetNewline.h"
57 #include "insets/InsetNewpage.h"
58 #include "insets/InsetOptArg.h"
59 #include "insets/InsetSpace.h"
60 #include "insets/InsetSpecialChar.h"
61 #include "insets/InsetTabular.h"
63 #include "support/debug.h"
64 #include "support/docstream.h"
65 #include "support/gettext.h"
66 #include "support/lassert.h"
67 #include "support/lstrings.h"
68 #include "support/textutils.h"
70 #include <boost/next_prior.hpp>
75 using namespace lyx::support;
79 using cap::cutSelection;
80 using cap::pasteParagraphList;
84 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
85 string const & token, Font & font, Change & change, ErrorList & errorList)
87 BufferParams const & bp = buf.params();
89 if (token[0] != '\\') {
90 docstring dstr = lex.getDocString();
91 par.appendString(dstr, font, change);
93 } else if (token == "\\begin_layout") {
95 docstring layoutname = lex.getDocString();
97 font = Font(inherit_font, bp.language);
98 change = Change(Change::UNCHANGED);
100 DocumentClass const & tclass = bp.documentClass();
102 if (layoutname.empty())
103 layoutname = tclass.defaultLayoutName();
105 if (par.forcePlainLayout()) {
106 // in this case only the empty layout is allowed
107 layoutname = tclass.plainLayoutName();
108 } else if (par.usePlainLayout()) {
109 // in this case, default layout maps to empty layout
110 if (layoutname == tclass.defaultLayoutName())
111 layoutname = tclass.plainLayoutName();
113 // otherwise, the empty layout maps to the default
114 if (layoutname == tclass.plainLayoutName())
115 layoutname = tclass.defaultLayoutName();
118 // When we apply an unknown layout to a document, we add this layout to the textclass
119 // of this document. For example, when you apply class article to a beamer document,
120 // all unknown layouts such as frame will be added to document class article so that
121 // these layouts can keep their original names.
122 tclass.addLayoutIfNeeded(layoutname);
124 par.setLayout(bp.documentClass()[layoutname]);
126 // Test whether the layout is obsolete.
127 Layout const & layout = par.layout();
128 if (!layout.obsoleted_by().empty())
129 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
131 par.params().read(lex);
133 } else if (token == "\\end_layout") {
134 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
135 << "Missing \\begin_layout ?");
136 } else if (token == "\\end_inset") {
137 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
138 << "Missing \\begin_inset ?");
139 } else if (token == "\\begin_inset") {
140 Inset * inset = readInset(lex, buf);
142 par.insertInset(par.size(), inset, font, change);
145 docstring line = lex.getDocString();
146 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
147 par.id(), 0, par.size()));
149 } else if (token == "\\family") {
151 setLyXFamily(lex.getString(), font.fontInfo());
152 } else if (token == "\\series") {
154 setLyXSeries(lex.getString(), font.fontInfo());
155 } else if (token == "\\shape") {
157 setLyXShape(lex.getString(), font.fontInfo());
158 } else if (token == "\\size") {
160 setLyXSize(lex.getString(), font.fontInfo());
161 } else if (token == "\\lang") {
163 string const tok = lex.getString();
164 Language const * lang = languages.getLanguage(tok);
166 font.setLanguage(lang);
168 font.setLanguage(bp.language);
169 lex.printError("Unknown language `$$Token'");
171 } else if (token == "\\numeric") {
173 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
174 } else if (token == "\\emph") {
176 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
177 } else if (token == "\\bar") {
179 string const tok = lex.getString();
182 font.fontInfo().setUnderbar(FONT_ON);
183 else if (tok == "no")
184 font.fontInfo().setUnderbar(FONT_OFF);
185 else if (tok == "default")
186 font.fontInfo().setUnderbar(FONT_INHERIT);
188 lex.printError("Unknown bar font flag "
190 } else if (token == "\\strikeout") {
192 font.fontInfo().setStrikeout(font.setLyXMisc(lex.getString()));
193 } else if (token == "\\uuline") {
195 font.fontInfo().setUuline(font.setLyXMisc(lex.getString()));
196 } else if (token == "\\uwave") {
198 font.fontInfo().setUwave(font.setLyXMisc(lex.getString()));
199 } else if (token == "\\noun") {
201 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
202 } else if (token == "\\color") {
204 setLyXColor(lex.getString(), font.fontInfo());
205 } else if (token == "\\SpecialChar") {
206 auto_ptr<Inset> inset;
207 inset.reset(new InsetSpecialChar);
209 par.insertInset(par.size(), inset.release(),
211 } else if (token == "\\backslash") {
212 par.appendChar('\\', font, change);
213 } else if (token == "\\LyXTable") {
214 auto_ptr<Inset> inset(new InsetTabular(const_cast<Buffer &>(buf)));
216 par.insertInset(par.size(), inset.release(), font, change);
217 } else if (token == "\\lyxline") {
218 par.insertInset(par.size(), new InsetLine, font, change);
219 } else if (token == "\\change_unchanged") {
220 change = Change(Change::UNCHANGED);
221 } else if (token == "\\change_inserted") {
223 istringstream is(lex.getString());
227 if (aid >= bp.author_map.size()) {
228 errorList.push_back(ErrorItem(_("Change tracking error"),
229 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
230 par.id(), 0, par.size()));
231 change = Change(Change::UNCHANGED);
233 change = Change(Change::INSERTED, bp.author_map[aid], ct);
234 } else if (token == "\\change_deleted") {
236 istringstream is(lex.getString());
240 if (aid >= bp.author_map.size()) {
241 errorList.push_back(ErrorItem(_("Change tracking error"),
242 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
243 par.id(), 0, par.size()));
244 change = Change(Change::UNCHANGED);
246 change = Change(Change::DELETED, bp.author_map[aid], ct);
249 errorList.push_back(ErrorItem(_("Unknown token"),
250 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
252 par.id(), 0, par.size()));
257 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
258 ErrorList & errorList)
261 string token = lex.getString();
263 Change change(Change::UNCHANGED);
266 readParToken(buf, par, lex, token, font, change, errorList);
269 token = lex.getString();
274 if (token == "\\end_layout") {
275 //Ok, paragraph finished
279 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
280 if (token == "\\begin_layout" || token == "\\end_document"
281 || token == "\\end_inset" || token == "\\begin_deeper"
282 || token == "\\end_deeper") {
283 lex.pushToken(token);
284 lyxerr << "Paragraph ended in line "
285 << lex.lineNumber() << "\n"
286 << "Missing \\end_layout.\n";
290 // Final change goes to paragraph break:
291 par.setChange(par.size(), change);
293 // Initialize begin_of_body_ on load; redoParagraph maintains
294 par.setBeginOfBody();
300 class TextCompletionList : public CompletionList
304 TextCompletionList(Cursor const & cur)
305 : buffer_(cur.buffer()), pos_(0)
308 virtual ~TextCompletionList() {}
311 virtual bool sorted() const { return true; }
313 virtual size_t size() const
315 return theWordList().size();
318 virtual docstring const & data(size_t idx) const
320 return theWordList().word(idx);
325 Buffer const * buffer_;
331 bool Text::empty() const
333 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
334 // FIXME: Should we consider the labeled type as empty too?
335 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
339 double Text::spacing(Buffer const & buffer, Paragraph const & par) const
341 if (par.params().spacing().isDefault())
342 return buffer.params().spacing().getValue();
343 return par.params().spacing().getValue();
347 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
349 LASSERT(this == cur.text(), /**/);
351 Paragraph & cpar = cur.paragraph();
352 pit_type cpit = cur.pit();
354 DocumentClass const & tclass = cur.buffer()->params().documentClass();
355 Layout const & layout = cpar.layout();
357 // this is only allowed, if the current paragraph is not empty
358 // or caption and if it has not the keepempty flag active
359 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
360 layout.labeltype != LABEL_SENSITIVE)
363 // a layout change may affect also the following paragraph
364 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
366 // Always break behind a space
367 // It is better to erase the space (Dekel)
368 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
369 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
371 // What should the layout for the new paragraph be?
372 bool keep_layout = inverse_logic ?
373 !layout.isEnvironment()
374 : layout.isEnvironment();
376 // We need to remember this before we break the paragraph, because
377 // that invalidates the layout variable
378 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
380 // we need to set this before we insert the paragraph.
381 bool const isempty = cpar.allowEmpty() && cpar.empty();
383 lyx::breakParagraph(cur.buffer()->params(), paragraphs(), cpit,
384 cur.pos(), keep_layout);
386 // After this, neither paragraph contains any rows!
389 pit_type next_par = cpit + 1;
391 // well this is the caption hack since one caption is really enough
394 // set to standard-layout
395 //FIXME Check if this should be plainLayout() in some cases
396 pars_[cpit].applyLayout(tclass.defaultLayout());
398 // set to standard-layout
399 //FIXME Check if this should be plainLayout() in some cases
400 pars_[next_par].applyLayout(tclass.defaultLayout());
403 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
404 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
405 break; // the character couldn't be deleted physically due to change tracking
408 cur.buffer()->updateLabels();
410 // A singlePar update is not enough in this case.
411 cur.updateFlags(Update::Force);
413 // This check is necessary. Otherwise the new empty paragraph will
414 // be deleted automatically. And it is more friendly for the user!
415 if (cur.pos() != 0 || isempty)
416 setCursor(cur, cur.pit() + 1, 0);
418 setCursor(cur, cur.pit(), 0);
422 // insert a character, moves all the following breaks in the
423 // same Paragraph one to the right and make a rebreak
424 void Text::insertChar(Cursor & cur, char_type c)
426 LASSERT(this == cur.text(), /**/);
428 cur.recordUndo(INSERT_UNDO);
430 TextMetrics const & tm = cur.bv().textMetrics(this);
431 Buffer const & buffer = *cur.buffer();
432 Paragraph & par = cur.paragraph();
433 // try to remove this
434 pit_type const pit = cur.pit();
436 bool const freeSpacing = par.layout().free_spacing ||
439 if (lyxrc.auto_number) {
440 static docstring const number_operators = from_ascii("+-/*");
441 static docstring const number_unary_operators = from_ascii("+-");
442 static docstring const number_seperators = from_ascii(".,:");
444 if (cur.current_font.fontInfo().number() == FONT_ON) {
445 if (!isDigit(c) && !contains(number_operators, c) &&
446 !(contains(number_seperators, c) &&
448 cur.pos() != cur.lastpos() &&
449 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
450 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
452 number(cur); // Set current_font.number to OFF
453 } else if (isDigit(c) &&
454 cur.real_current_font.isVisibleRightToLeft()) {
455 number(cur); // Set current_font.number to ON
457 if (cur.pos() != 0) {
458 char_type const c = par.getChar(cur.pos() - 1);
459 if (contains(number_unary_operators, c) &&
461 || par.isSeparator(cur.pos() - 2)
462 || par.isNewline(cur.pos() - 2))
464 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
466 } else if (contains(number_seperators, c)
468 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
469 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
476 // In Bidi text, we want spaces to be treated in a special way: spaces
477 // which are between words in different languages should get the
478 // paragraph's language; otherwise, spaces should keep the language
479 // they were originally typed in. This is only in effect while typing;
480 // after the text is already typed in, the user can always go back and
481 // explicitly set the language of a space as desired. But 99.9% of the
482 // time, what we're doing here is what the user actually meant.
484 // The following cases are the ones in which the language of the space
485 // should be changed to match that of the containing paragraph. In the
486 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
487 // represents a space, pipe (|) represents the cursor position (so the
488 // character before it is the one just typed in). The different cases
489 // are depicted logically (not visually), from left to right:
494 // Theoretically, there are other situations that we should, perhaps, deal
495 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
496 // point (to understand why, just try to create this situation...).
498 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
499 // get font in front and behind the space in question. But do NOT
500 // use getFont(cur.pos()) because the character c is not inserted yet
501 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
502 Font const & post_space_font = cur.real_current_font;
503 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
504 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
506 if (pre_space_rtl != post_space_rtl) {
507 // Set the space's language to match the language of the
508 // adjacent character whose direction is the paragraph's
509 // direction; don't touch other properties of the font
510 Language const * lang =
511 (pre_space_rtl == par.isRTL(buffer.params())) ?
512 pre_space_font.language() : post_space_font.language();
514 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
515 space_font.setLanguage(lang);
516 par.setFont(cur.pos() - 1, space_font);
520 // Next check, if there will be two blanks together or a blank at
521 // the beginning of a paragraph.
522 // I decided to handle blanks like normal characters, the main
523 // difference are the special checks when calculating the row.fill
524 // (blank does not count at the end of a row) and the check here
526 // When the free-spacing option is set for the current layout,
527 // disable the double-space checking
528 if (!freeSpacing && isLineSeparatorChar(c)) {
529 if (cur.pos() == 0) {
530 static bool sent_space_message = false;
531 if (!sent_space_message) {
532 cur.message(_("You cannot insert a space at the "
533 "beginning of a paragraph. Please read the Tutorial."));
534 sent_space_message = true;
538 LASSERT(cur.pos() > 0, /**/);
539 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
540 && !par.isDeleted(cur.pos() - 1)) {
541 static bool sent_space_message = false;
542 if (!sent_space_message) {
543 cur.message(_("You cannot type two spaces this way. "
544 "Please read the Tutorial."));
545 sent_space_message = true;
551 par.insertChar(cur.pos(), c, cur.current_font,
552 cur.buffer()->params().trackChanges);
553 cur.checkBufferStructure();
555 // cur.updateFlags(Update::Force);
556 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
561 void Text::charInserted(Cursor & cur)
563 Paragraph & par = cur.paragraph();
565 // Here we call finishUndo for every 20 characters inserted.
566 // This is from my experience how emacs does it. (Lgb)
567 static unsigned int counter;
575 // register word if a non-letter was entered
577 && !par.isWordSeparator(cur.pos() - 2)
578 && par.isWordSeparator(cur.pos() - 1)) {
579 // get the word in front of cursor
580 LASSERT(this == cur.text(), /**/);
581 cur.paragraph().updateWords();
586 // the cursor set functions have a special mechanism. When they
587 // realize, that you left an empty paragraph, they will delete it.
589 bool Text::cursorForwardOneWord(Cursor & cur)
591 LASSERT(this == cur.text(), /**/);
593 pos_type const lastpos = cur.lastpos();
594 pit_type pit = cur.pit();
595 pos_type pos = cur.pos();
596 Paragraph const & par = cur.paragraph();
598 // Paragraph boundary is a word boundary
599 if (pos == lastpos) {
600 if (pit != cur.lastpit())
601 return setCursor(cur, pit + 1, 0);
606 if (lyxrc.mac_like_word_movement) {
607 // Skip through trailing punctuation and spaces.
608 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
611 // Skip over either a non-char inset or a full word
612 if (pos != lastpos && par.isWordSeparator(pos))
614 else while (pos != lastpos && !par.isWordSeparator(pos))
617 LASSERT(pos < lastpos, /**/); // see above
618 if (!par.isWordSeparator(pos))
619 while (pos != lastpos && !par.isWordSeparator(pos))
621 else if (par.isChar(pos))
622 while (pos != lastpos && par.isChar(pos))
624 else if (!par.isSpace(pos)) // non-char inset
627 // Skip over white space
628 while (pos != lastpos && par.isSpace(pos))
632 return setCursor(cur, pit, pos);
636 bool Text::cursorBackwardOneWord(Cursor & cur)
638 LASSERT(this == cur.text(), /**/);
640 pit_type pit = cur.pit();
641 pos_type pos = cur.pos();
642 Paragraph & par = cur.paragraph();
644 // Paragraph boundary is a word boundary
645 if (pos == 0 && pit != 0)
646 return setCursor(cur, pit - 1, getPar(pit - 1).size());
648 if (lyxrc.mac_like_word_movement) {
649 // Skip through punctuation and spaces.
650 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
653 // Skip over either a non-char inset or a full word
654 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
656 else while (pos != 0 && !par.isWordSeparator(pos - 1))
659 // Skip over white space
660 while (pos != 0 && par.isSpace(pos - 1))
663 if (pos != 0 && !par.isWordSeparator(pos - 1))
664 while (pos != 0 && !par.isWordSeparator(pos - 1))
666 else if (pos != 0 && par.isChar(pos - 1))
667 while (pos != 0 && par.isChar(pos - 1))
669 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
673 return setCursor(cur, pit, pos);
677 bool Text::cursorVisLeftOneWord(Cursor & cur)
679 LASSERT(this == cur.text(), /**/);
681 pos_type left_pos, right_pos;
682 bool left_is_letter, right_is_letter;
684 Cursor temp_cur = cur;
686 // always try to move at least once...
687 while (temp_cur.posVisLeft(true /* skip_inset */)) {
689 // collect some information about current cursor position
690 temp_cur.getSurroundingPos(left_pos, right_pos);
692 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
694 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
696 // if we're not at a letter/non-letter boundary, continue moving
697 if (left_is_letter == right_is_letter)
700 // we should stop when we have an LTR word on our right or an RTL word
702 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
703 temp_cur.buffer()->params(), left_pos).isRightToLeft())
704 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
705 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
709 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
710 true, temp_cur.boundary());
714 bool Text::cursorVisRightOneWord(Cursor & cur)
716 LASSERT(this == cur.text(), /**/);
718 pos_type left_pos, right_pos;
719 bool left_is_letter, right_is_letter;
721 Cursor temp_cur = cur;
723 // always try to move at least once...
724 while (temp_cur.posVisRight(true /* skip_inset */)) {
726 // collect some information about current cursor position
727 temp_cur.getSurroundingPos(left_pos, right_pos);
729 (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
731 (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
733 // if we're not at a letter/non-letter boundary, continue moving
734 if (left_is_letter == right_is_letter)
737 // we should stop when we have an LTR word on our right or an RTL word
739 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
740 temp_cur.buffer()->params(),
741 left_pos).isRightToLeft())
742 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
743 temp_cur.buffer()->params(),
744 right_pos).isRightToLeft()))
748 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
749 true, temp_cur.boundary());
753 void Text::selectWord(Cursor & cur, word_location loc)
755 LASSERT(this == cur.text(), /**/);
756 CursorSlice from = cur.top();
757 CursorSlice to = cur.top();
758 getWord(from, to, loc);
759 if (cur.top() != from)
760 setCursor(cur, from.pit(), from.pos());
764 setCursor(cur, to.pit(), to.pos());
769 void Text::selectAll(Cursor & cur)
771 LASSERT(this == cur.text(), /**/);
772 if (cur.lastpos() == 0 && cur.lastpit() == 0)
774 // If the cursor is at the beginning, make sure the cursor ends there
775 if (cur.pit() == 0 && cur.pos() == 0) {
776 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
778 setCursor(cur, 0, 0);
780 setCursor(cur, 0, 0);
782 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
788 // Select the word currently under the cursor when no
789 // selection is currently set
790 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
792 LASSERT(this == cur.text(), /**/);
795 selectWord(cur, loc);
796 return cur.selection();
800 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
802 LASSERT(this == cur.text(), /**/);
804 if (!cur.selection()) {
805 Change const & change = cur.paragraph().lookupChange(cur.pos());
806 if (!(change.changed() && findNextChange(&cur.bv())))
810 cur.recordUndoSelection();
812 pit_type begPit = cur.selectionBegin().pit();
813 pit_type endPit = cur.selectionEnd().pit();
815 pos_type begPos = cur.selectionBegin().pos();
816 pos_type endPos = cur.selectionEnd().pos();
818 // keep selection info, because endPos becomes invalid after the first loop
819 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
821 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
823 for (pit_type pit = begPit; pit <= endPit; ++pit) {
824 pos_type parSize = pars_[pit].size();
826 // ignore empty paragraphs; otherwise, an assertion will fail for
827 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
831 // do not consider first paragraph if the cursor starts at pos size()
832 if (pit == begPit && begPos == parSize)
835 // do not consider last paragraph if the cursor ends at pos 0
836 if (pit == endPit && endPos == 0)
837 break; // last iteration anyway
839 pos_type left = (pit == begPit ? begPos : 0);
840 pos_type right = (pit == endPit ? endPos : parSize);
843 pars_[pit].acceptChanges(cur.buffer()->params(), left, right);
845 pars_[pit].rejectChanges(cur.buffer()->params(), left, right);
849 // next, accept/reject imaginary end-of-par characters
851 for (pit_type pit = begPit; pit <= endPit; ++pit) {
852 pos_type pos = pars_[pit].size();
854 // skip if the selection ends before the end-of-par
855 if (pit == endPit && endsBeforeEndOfPar)
856 break; // last iteration anyway
858 // skip if this is not the last paragraph of the document
859 // note: the user should be able to accept/reject the par break of the last par!
860 if (pit == endPit && pit + 1 != int(pars_.size()))
861 break; // last iteration anway
864 if (pars_[pit].isInserted(pos)) {
865 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
866 } else if (pars_[pit].isDeleted(pos)) {
867 if (pit + 1 == int(pars_.size())) {
868 // we cannot remove a par break at the end of the last paragraph;
869 // instead, we mark it unchanged
870 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
872 mergeParagraph(cur.buffer()->params(), pars_, pit);
878 if (pars_[pit].isDeleted(pos)) {
879 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
880 } else if (pars_[pit].isInserted(pos)) {
881 if (pit + 1 == int(pars_.size())) {
882 // we mark the par break at the end of the last paragraph unchanged
883 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
885 mergeParagraph(cur.buffer()->params(), pars_, pit);
893 // finally, invoke the DEPM
895 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
900 cur.clearSelection();
901 setCursorIntern(cur, begPit, begPos);
902 cur.updateFlags(Update::Force);
903 cur.buffer()->updateLabels();
907 void Text::acceptChanges(BufferParams const & bparams)
909 lyx::acceptChanges(pars_, bparams);
910 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
914 void Text::rejectChanges(BufferParams const & bparams)
916 pit_type pars_size = static_cast<pit_type>(pars_.size());
918 // first, reject changes within each individual paragraph
919 // (do not consider end-of-par)
920 for (pit_type pit = 0; pit < pars_size; ++pit) {
921 if (!pars_[pit].empty()) // prevent assertion failure
922 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
925 // next, reject imaginary end-of-par characters
926 for (pit_type pit = 0; pit < pars_size; ++pit) {
927 pos_type pos = pars_[pit].size();
929 if (pars_[pit].isDeleted(pos)) {
930 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
931 } else if (pars_[pit].isInserted(pos)) {
932 if (pit == pars_size - 1) {
933 // we mark the par break at the end of the last
934 // paragraph unchanged
935 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
937 mergeParagraph(bparams, pars_, pit);
944 // finally, invoke the DEPM
945 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
949 void Text::deleteWordForward(Cursor & cur)
951 LASSERT(this == cur.text(), /**/);
952 if (cur.lastpos() == 0)
956 cur.setSelection(true);
957 cursorForwardOneWord(cur);
959 cutSelection(cur, true, false);
960 cur.checkBufferStructure();
965 void Text::deleteWordBackward(Cursor & cur)
967 LASSERT(this == cur.text(), /**/);
968 if (cur.lastpos() == 0)
972 cur.setSelection(true);
973 cursorBackwardOneWord(cur);
975 cutSelection(cur, true, false);
976 cur.checkBufferStructure();
981 // Kill to end of line.
982 void Text::changeCase(Cursor & cur, TextCase action)
984 LASSERT(this == cur.text(), /**/);
989 if (cur.selection()) {
990 from = cur.selBegin();
995 getWord(from, to, PARTIAL_WORD);
996 cursorForwardOneWord(cur);
999 cur.recordUndoSelection();
1001 pit_type begPit = from.pit();
1002 pit_type endPit = to.pit();
1004 pos_type begPos = from.pos();
1005 pos_type endPos = to.pos();
1007 pos_type right = 0; // needed after the for loop
1009 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1010 Paragraph & par = pars_[pit];
1011 pos_type const pos = (pit == begPit ? begPos : 0);
1012 right = (pit == endPit ? endPos : par.size());
1013 par.changeCase(cur.buffer()->params(), pos, right, action);
1016 // the selection may have changed due to logically-only deleted chars
1018 setCursor(cur, begPit, begPos);
1020 setCursor(cur, endPit, right);
1023 setCursor(cur, endPit, right);
1025 cur.checkBufferStructure();
1029 bool Text::handleBibitems(Cursor & cur)
1031 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1037 BufferParams const & bufparams = cur.buffer()->params();
1038 Paragraph const & par = cur.paragraph();
1039 Cursor prevcur = cur;
1040 if (cur.pit() > 0) {
1042 prevcur.pos() = prevcur.lastpos();
1044 Paragraph const & prevpar = prevcur.paragraph();
1046 // if a bibitem is deleted, merge with previous paragraph
1047 // if this is a bibliography item as well
1048 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1049 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1050 mergeParagraph(bufparams, cur.text()->paragraphs(),
1052 cur.buffer()->updateLabels();
1053 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1054 cur.updateFlags(Update::Force);
1058 // otherwise reset to default
1059 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1064 bool Text::erase(Cursor & cur)
1066 LASSERT(this == cur.text(), return false);
1067 bool needsUpdate = false;
1068 Paragraph & par = cur.paragraph();
1070 if (cur.pos() != cur.lastpos()) {
1071 // this is the code for a normal delete, not pasting
1073 cur.recordUndo(DELETE_UNDO);
1074 bool const was_inset = cur.paragraph().isInset(cur.pos());
1075 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1076 // the character has been logically deleted only => skip it
1077 cur.top().forwardPos();
1080 cur.buffer()->updateLabels();
1082 cur.checkBufferStructure();
1085 if (cur.pit() == cur.lastpit())
1086 return dissolveInset(cur);
1088 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1089 par.setChange(cur.pos(), Change(Change::DELETED));
1093 setCursorIntern(cur, cur.pit() + 1, 0);
1094 needsUpdate = backspacePos0(cur);
1098 needsUpdate |= handleBibitems(cur);
1101 // Make sure the cursor is correct. Is this really needed?
1102 // No, not really... at least not here!
1103 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1104 cur.checkBufferStructure();
1111 bool Text::backspacePos0(Cursor & cur)
1113 LASSERT(this == cur.text(), /**/);
1117 bool needsUpdate = false;
1119 BufferParams const & bufparams = cur.buffer()->params();
1120 DocumentClass const & tclass = bufparams.documentClass();
1121 ParagraphList & plist = cur.text()->paragraphs();
1122 Paragraph const & par = cur.paragraph();
1123 Cursor prevcur = cur;
1125 prevcur.pos() = prevcur.lastpos();
1126 Paragraph const & prevpar = prevcur.paragraph();
1128 // is it an empty paragraph?
1129 if (cur.lastpos() == 0
1130 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1131 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1132 plist.erase(boost::next(plist.begin(), cur.pit()));
1135 // is previous par empty?
1136 else if (prevcur.lastpos() == 0
1137 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1138 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1139 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1142 // Pasting is not allowed, if the paragraphs have different
1143 // layouts. I think it is a real bug of all other
1144 // word processors to allow it. It confuses the user.
1145 // Correction: Pasting is always allowed with standard-layout
1146 // or the empty layout.
1147 else if (par.layout() == prevpar.layout()
1148 || tclass.isDefaultLayout(par.layout())
1149 || tclass.isPlainLayout(par.layout())) {
1150 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1151 mergeParagraph(bufparams, plist, prevcur.pit());
1156 cur.buffer()->updateLabels();
1157 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1164 bool Text::backspace(Cursor & cur)
1166 LASSERT(this == cur.text(), /**/);
1167 bool needsUpdate = false;
1168 if (cur.pos() == 0) {
1170 return dissolveInset(cur);
1172 Paragraph & prev_par = pars_[cur.pit() - 1];
1174 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1175 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1176 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1179 // The cursor is at the beginning of a paragraph, so
1180 // the backspace will collapse two paragraphs into one.
1181 needsUpdate = backspacePos0(cur);
1184 // this is the code for a normal backspace, not pasting
1186 cur.recordUndo(DELETE_UNDO);
1187 // We used to do cursorBackwardIntern() here, but it is
1188 // not a good idea since it triggers the auto-delete
1189 // mechanism. So we do a cursorBackwardIntern()-lite,
1190 // without the dreaded mechanism. (JMarc)
1191 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1192 false, cur.boundary());
1193 bool const was_inset = cur.paragraph().isInset(cur.pos());
1194 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1196 cur.buffer()->updateLabels();
1198 cur.checkBufferStructure();
1201 if (cur.pos() == cur.lastpos())
1202 cur.setCurrentFont();
1204 needsUpdate |= handleBibitems(cur);
1206 // A singlePar update is not enough in this case.
1207 // cur.updateFlags(Update::Force);
1208 setCursor(cur.top(), cur.pit(), cur.pos());
1214 bool Text::dissolveInset(Cursor & cur)
1216 LASSERT(this == cur.text(), return false);
1218 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1221 cur.recordUndoInset();
1223 cur.selHandle(false);
1225 pos_type spos = cur.pos();
1226 pit_type spit = cur.pit();
1227 ParagraphList plist;
1228 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1229 plist = paragraphs();
1231 // store cursor offset
1235 Buffer & b = *cur.buffer();
1236 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1237 if (!plist.empty()) {
1238 // ERT paragraphs have the Language latex_language.
1239 // This is invalid outside of ERT, so we need to
1240 // change it to the buffer language.
1241 ParagraphList::iterator it = plist.begin();
1242 ParagraphList::iterator it_end = plist.end();
1243 for (; it != it_end; it++)
1244 it->changeLanguage(b.params(), latex_language, b.language());
1246 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1247 b.errorList("Paste"));
1249 cur.pit() = min(cur.lastpit(), spit);
1250 cur.pos() = min(cur.lastpos(), spos);
1252 cur.clearSelection();
1258 void Text::getWord(CursorSlice & from, CursorSlice & to,
1259 word_location const loc) const
1262 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1266 void Text::write(Buffer const & buf, ostream & os) const
1268 ParagraphList::const_iterator pit = paragraphs().begin();
1269 ParagraphList::const_iterator end = paragraphs().end();
1271 for (; pit != end; ++pit)
1272 pit->write(os, buf.params(), dth);
1274 // Close begin_deeper
1275 for(; dth > 0; --dth)
1276 os << "\n\\end_deeper";
1280 bool Text::read(Buffer const & buf, Lexer & lex,
1281 ErrorList & errorList, InsetText * insetPtr)
1283 depth_type depth = 0;
1286 while (lex.isOK()) {
1288 string const token = lex.getString();
1293 if (token == "\\end_inset")
1296 if (token == "\\end_body")
1299 if (token == "\\begin_body")
1302 if (token == "\\end_document") {
1307 if (token == "\\begin_layout") {
1308 lex.pushToken(token);
1311 par.setInsetOwner(insetPtr);
1312 par.params().depth(depth);
1313 par.setFont(0, Font(inherit_font, buf.params().language));
1314 pars_.push_back(par);
1316 // FIXME: goddamn InsetTabular makes us pass a Buffer
1318 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1320 // register the words in the global word list
1321 CursorSlice sl = CursorSlice(*insetPtr);
1322 sl.pit() = pars_.size() - 1;
1323 pars_.back().updateWords();
1324 } else if (token == "\\begin_deeper") {
1326 } else if (token == "\\end_deeper") {
1328 lex.printError("\\end_deeper: " "depth is already null");
1332 LYXERR0("Handling unknown body token: `" << token << '\'');
1336 // avoid a crash on weird documents (bug 4859)
1337 if (pars_.empty()) {
1339 par.setInsetOwner(insetPtr);
1340 par.params().depth(depth);
1341 par.setFont(0, Font(inherit_font,
1342 buf.params().language));
1343 par.setPlainOrDefaultLayout(buf.params().documentClass());
1344 pars_.push_back(par);
1350 // Returns the current font and depth as a message.
1351 docstring Text::currentState(Cursor const & cur) const
1353 LASSERT(this == cur.text(), /**/);
1354 Buffer & buf = *cur.buffer();
1355 Paragraph const & par = cur.paragraph();
1356 odocstringstream os;
1358 if (buf.params().trackChanges)
1359 os << _("[Change Tracking] ");
1361 Change change = par.lookupChange(cur.pos());
1363 if (change.type != Change::UNCHANGED) {
1364 Author const & a = buf.params().authors().get(change.author);
1365 os << _("Change: ") << a.name();
1366 if (!a.email().empty())
1367 os << " (" << a.email() << ")";
1368 // FIXME ctime is english, we should translate that
1369 os << _(" at ") << ctime(&change.changetime);
1373 // I think we should only show changes from the default
1375 // No, from the document font (MV)
1376 Font font = cur.real_current_font;
1377 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1379 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1381 // The paragraph depth
1382 int depth = cur.paragraph().getDepth();
1384 os << bformat(_(", Depth: %1$d"), depth);
1386 // The paragraph spacing, but only if different from
1388 Spacing const & spacing = par.params().spacing();
1389 if (!spacing.isDefault()) {
1390 os << _(", Spacing: ");
1391 switch (spacing.getSpace()) {
1392 case Spacing::Single:
1395 case Spacing::Onehalf:
1398 case Spacing::Double:
1401 case Spacing::Other:
1402 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1404 case Spacing::Default:
1405 // should never happen, do nothing
1410 #ifdef DEVEL_VERSION
1411 os << _(", Inset: ") << &cur.inset();
1412 os << _(", Paragraph: ") << cur.pit();
1413 os << _(", Id: ") << par.id();
1414 os << _(", Position: ") << cur.pos();
1415 // FIXME: Why is the check for par.size() needed?
1416 // We are called with cur.pos() == par.size() quite often.
1417 if (!par.empty() && cur.pos() < par.size()) {
1418 // Force output of code point, not character
1419 size_t const c = par.getChar(cur.pos());
1420 os << _(", Char: 0x") << hex << c;
1422 os << _(", Boundary: ") << cur.boundary();
1423 // Row & row = cur.textRow();
1424 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1430 docstring Text::getPossibleLabel(Cursor const & cur) const
1432 pit_type pit = cur.pit();
1434 Layout const * layout = &(pars_[pit].layout());
1437 docstring par_text = pars_[pit].asString();
1439 // the return string of math matrices might contain linebreaks
1440 par_text = subst(par_text, '\n', '-');
1441 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1442 if (par_text.empty())
1445 par_text = split(par_text, head, ' ');
1446 // Is it legal to use spaces in labels ?
1452 // No need for a prefix if the user said so.
1453 if (lyxrc.label_init_length <= 0)
1456 // Will contain the label type.
1459 // For section, subsection, etc...
1460 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1461 Layout const * layout2 = &(pars_[pit - 1].layout());
1462 if (layout2->latextype != LATEX_PARAGRAPH) {
1467 if (layout->latextype != LATEX_PARAGRAPH)
1468 name = from_ascii(layout->latexname());
1470 // for captions, we just take the caption type
1471 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1473 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1475 // If none of the above worked, we'll see if we're inside various
1476 // types of insets and take our abbreviation from them.
1478 InsetCode const codes[] = {
1483 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1484 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1486 name = float_inset->name();
1492 // Create a correct prefix for prettyref
1493 if (name == "theorem")
1494 name = from_ascii("thm");
1495 else if (name == "Foot")
1496 name = from_ascii("fn");
1497 else if (name == "listing")
1498 name = from_ascii("lst");
1501 text = name.substr(0, 3) + ':' + text;
1507 docstring Text::asString(int options) const
1509 return asString(0, pars_.size(), options);
1513 docstring Text::asString(pit_type beg, pit_type end, int options) const
1515 size_t i = size_t(beg);
1516 docstring str = pars_[i].asString(options);
1517 for (++i; i != size_t(end); ++i) {
1519 str += pars_[i].asString(options);
1526 void Text::charsTranspose(Cursor & cur)
1528 LASSERT(this == cur.text(), /**/);
1530 pos_type pos = cur.pos();
1532 // If cursor is at beginning or end of paragraph, do nothing.
1533 if (pos == cur.lastpos() || pos == 0)
1536 Paragraph & par = cur.paragraph();
1538 // Get the positions of the characters to be transposed.
1539 pos_type pos1 = pos - 1;
1540 pos_type pos2 = pos;
1542 // In change tracking mode, ignore deleted characters.
1543 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1545 if (pos2 == cur.lastpos())
1548 while (pos1 >= 0 && par.isDeleted(pos1))
1553 // Don't do anything if one of the "characters" is not regular text.
1554 if (par.isInset(pos1) || par.isInset(pos2))
1557 // Store the characters to be transposed (including font information).
1558 char_type const char1 = par.getChar(pos1);
1560 par.getFontSettings(cur.buffer()->params(), pos1);
1562 char_type const char2 = par.getChar(pos2);
1564 par.getFontSettings(cur.buffer()->params(), pos2);
1566 // And finally, we are ready to perform the transposition.
1567 // Track the changes if Change Tracking is enabled.
1568 bool const trackChanges = cur.buffer()->params().trackChanges;
1572 par.eraseChar(pos2, trackChanges);
1573 par.eraseChar(pos1, trackChanges);
1574 par.insertChar(pos1, char2, font2, trackChanges);
1575 par.insertChar(pos2, char1, font1, trackChanges);
1577 cur.checkBufferStructure();
1579 // After the transposition, move cursor to after the transposition.
1580 setCursor(cur, cur.pit(), pos2);
1585 DocIterator Text::macrocontextPosition() const
1587 return macrocontext_position_;
1591 void Text::setMacrocontextPosition(DocIterator const & pos)
1593 macrocontext_position_ = pos;
1597 docstring Text::previousWord(CursorSlice const & sl) const
1599 CursorSlice from = sl;
1600 CursorSlice to = sl;
1601 getWord(from, to, PREVIOUS_WORD);
1602 if (sl == from || to == from)
1605 Paragraph const & par = sl.paragraph();
1606 return par.asString(from.pos(), to.pos());
1610 bool Text::completionSupported(Cursor const & cur) const
1612 Paragraph const & par = cur.paragraph();
1613 return cur.pos() > 0
1614 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
1615 && !par.isWordSeparator(cur.pos() - 1);
1619 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1621 return new TextCompletionList(cur);
1625 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1627 LASSERT(cur.bv().cursor() == cur, /**/);
1629 cur.bv().cursor() = cur;
1630 if (!(cur.disp_.update() & Update::Force))
1631 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
1636 docstring Text::completionPrefix(Cursor const & cur) const
1638 return previousWord(cur.top());