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/convert.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
71 #include <boost/next_prior.hpp>
76 using namespace lyx::support;
80 using cap::cutSelection;
81 using cap::pasteParagraphList;
85 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
86 string const & token, Font & font, Change & change, ErrorList & errorList)
88 BufferParams const & bp = buf.params();
90 if (token[0] != '\\') {
91 docstring dstr = lex.getDocString();
92 par.appendString(dstr, font, change);
94 } else if (token == "\\begin_layout") {
96 docstring layoutname = lex.getDocString();
98 font = Font(inherit_font, bp.language);
99 change = Change(Change::UNCHANGED);
101 DocumentClass const & tclass = bp.documentClass();
103 if (layoutname.empty())
104 layoutname = tclass.defaultLayoutName();
106 if (par.forcePlainLayout()) {
107 // in this case only the empty layout is allowed
108 layoutname = tclass.plainLayoutName();
109 } else if (par.usePlainLayout()) {
110 // in this case, default layout maps to empty layout
111 if (layoutname == tclass.defaultLayoutName())
112 layoutname = tclass.plainLayoutName();
114 // otherwise, the empty layout maps to the default
115 if (layoutname == tclass.plainLayoutName())
116 layoutname = tclass.defaultLayoutName();
119 // When we apply an unknown layout to a document, we add this layout to the textclass
120 // of this document. For example, when you apply class article to a beamer document,
121 // all unknown layouts such as frame will be added to document class article so that
122 // these layouts can keep their original names.
123 tclass.addLayoutIfNeeded(layoutname);
125 par.setLayout(bp.documentClass()[layoutname]);
127 // Test whether the layout is obsolete.
128 Layout const & layout = par.layout();
129 if (!layout.obsoleted_by().empty())
130 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
132 par.params().read(lex);
134 } else if (token == "\\end_layout") {
135 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
136 << "Missing \\begin_layout ?");
137 } else if (token == "\\end_inset") {
138 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
139 << "Missing \\begin_inset ?");
140 } else if (token == "\\begin_inset") {
141 Inset * inset = readInset(lex, buf);
143 par.insertInset(par.size(), inset, font, change);
146 docstring line = lex.getDocString();
147 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
148 par.id(), 0, par.size()));
150 } else if (token == "\\family") {
152 setLyXFamily(lex.getString(), font.fontInfo());
153 } else if (token == "\\series") {
155 setLyXSeries(lex.getString(), font.fontInfo());
156 } else if (token == "\\shape") {
158 setLyXShape(lex.getString(), font.fontInfo());
159 } else if (token == "\\size") {
161 setLyXSize(lex.getString(), font.fontInfo());
162 } else if (token == "\\lang") {
164 string const tok = lex.getString();
165 Language const * lang = languages.getLanguage(tok);
167 font.setLanguage(lang);
169 font.setLanguage(bp.language);
170 lex.printError("Unknown language `$$Token'");
172 } else if (token == "\\numeric") {
174 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
175 } else if (token == "\\emph") {
177 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
178 } else if (token == "\\bar") {
180 string const tok = lex.getString();
183 font.fontInfo().setUnderbar(FONT_ON);
184 else if (tok == "no")
185 font.fontInfo().setUnderbar(FONT_OFF);
186 else if (tok == "default")
187 font.fontInfo().setUnderbar(FONT_INHERIT);
189 lex.printError("Unknown bar font flag "
191 } else if (token == "\\strikeout") {
193 font.fontInfo().setStrikeout(font.setLyXMisc(lex.getString()));
194 } else if (token == "\\uuline") {
196 font.fontInfo().setUuline(font.setLyXMisc(lex.getString()));
197 } else if (token == "\\uwave") {
199 font.fontInfo().setUwave(font.setLyXMisc(lex.getString()));
200 } else if (token == "\\noun") {
202 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
203 } else if (token == "\\color") {
205 setLyXColor(lex.getString(), font.fontInfo());
206 } else if (token == "\\SpecialChar") {
207 auto_ptr<Inset> inset;
208 inset.reset(new InsetSpecialChar);
210 par.insertInset(par.size(), inset.release(),
212 } else if (token == "\\backslash") {
213 par.appendChar('\\', font, change);
214 } else if (token == "\\LyXTable") {
215 auto_ptr<Inset> inset(new InsetTabular(const_cast<Buffer &>(buf)));
217 par.insertInset(par.size(), inset.release(), font, change);
218 } else if (token == "\\lyxline") {
219 par.insertInset(par.size(), new InsetLine, font, change);
220 } else if (token == "\\change_unchanged") {
221 change = Change(Change::UNCHANGED);
222 } else if (token == "\\change_inserted") {
224 istringstream is(lex.getString());
228 if (aid >= bp.author_map.size()) {
229 errorList.push_back(ErrorItem(_("Change tracking error"),
230 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
231 par.id(), 0, par.size()));
232 change = Change(Change::UNCHANGED);
234 change = Change(Change::INSERTED, bp.author_map[aid], ct);
235 } else if (token == "\\change_deleted") {
237 istringstream is(lex.getString());
241 if (aid >= bp.author_map.size()) {
242 errorList.push_back(ErrorItem(_("Change tracking error"),
243 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
244 par.id(), 0, par.size()));
245 change = Change(Change::UNCHANGED);
247 change = Change(Change::DELETED, bp.author_map[aid], ct);
250 errorList.push_back(ErrorItem(_("Unknown token"),
251 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
253 par.id(), 0, par.size()));
258 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
259 ErrorList & errorList)
262 string token = lex.getString();
264 Change change(Change::UNCHANGED);
267 readParToken(buf, par, lex, token, font, change, errorList);
270 token = lex.getString();
275 if (token == "\\end_layout") {
276 //Ok, paragraph finished
280 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
281 if (token == "\\begin_layout" || token == "\\end_document"
282 || token == "\\end_inset" || token == "\\begin_deeper"
283 || token == "\\end_deeper") {
284 lex.pushToken(token);
285 lyxerr << "Paragraph ended in line "
286 << lex.lineNumber() << "\n"
287 << "Missing \\end_layout.\n";
291 // Final change goes to paragraph break:
292 par.setChange(par.size(), change);
294 // Initialize begin_of_body_ on load; redoParagraph maintains
295 par.setBeginOfBody();
301 class TextCompletionList : public CompletionList
305 TextCompletionList(Cursor const & cur)
306 : buffer_(cur.buffer()), pos_(0)
309 virtual ~TextCompletionList() {}
312 virtual bool sorted() const { return true; }
314 virtual size_t size() const
316 return theWordList().size();
319 virtual docstring const & data(size_t idx) const
321 return theWordList().word(idx);
326 Buffer const * buffer_;
332 bool Text::empty() const
334 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
335 // FIXME: Should we consider the labeled type as empty too?
336 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
340 double Text::spacing(Buffer const & buffer, Paragraph const & par) const
342 if (par.params().spacing().isDefault())
343 return buffer.params().spacing().getValue();
344 return par.params().spacing().getValue();
348 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
350 LASSERT(this == cur.text(), /**/);
352 Paragraph & cpar = cur.paragraph();
353 pit_type cpit = cur.pit();
355 DocumentClass const & tclass = cur.buffer()->params().documentClass();
356 Layout const & layout = cpar.layout();
358 // this is only allowed, if the current paragraph is not empty
359 // or caption and if it has not the keepempty flag active
360 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
361 layout.labeltype != LABEL_SENSITIVE)
364 // a layout change may affect also the following paragraph
365 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
367 // Always break behind a space
368 // It is better to erase the space (Dekel)
369 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
370 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
372 // What should the layout for the new paragraph be?
373 bool keep_layout = inverse_logic ?
374 !layout.isEnvironment()
375 : layout.isEnvironment();
377 // We need to remember this before we break the paragraph, because
378 // that invalidates the layout variable
379 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
381 // we need to set this before we insert the paragraph.
382 bool const isempty = cpar.allowEmpty() && cpar.empty();
384 lyx::breakParagraph(cur.buffer()->params(), paragraphs(), cpit,
385 cur.pos(), keep_layout);
387 // After this, neither paragraph contains any rows!
390 pit_type next_par = cpit + 1;
392 // well this is the caption hack since one caption is really enough
395 // set to standard-layout
396 //FIXME Check if this should be plainLayout() in some cases
397 pars_[cpit].applyLayout(tclass.defaultLayout());
399 // set to standard-layout
400 //FIXME Check if this should be plainLayout() in some cases
401 pars_[next_par].applyLayout(tclass.defaultLayout());
404 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
405 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
406 break; // the character couldn't be deleted physically due to change tracking
409 cur.buffer()->updateLabels();
411 // A singlePar update is not enough in this case.
412 cur.updateFlags(Update::Force);
414 // This check is necessary. Otherwise the new empty paragraph will
415 // be deleted automatically. And it is more friendly for the user!
416 if (cur.pos() != 0 || isempty)
417 setCursor(cur, cur.pit() + 1, 0);
419 setCursor(cur, cur.pit(), 0);
423 // insert a character, moves all the following breaks in the
424 // same Paragraph one to the right and make a rebreak
425 void Text::insertChar(Cursor & cur, char_type c)
427 LASSERT(this == cur.text(), /**/);
429 cur.recordUndo(INSERT_UNDO);
431 TextMetrics const & tm = cur.bv().textMetrics(this);
432 Buffer const & buffer = *cur.buffer();
433 Paragraph & par = cur.paragraph();
434 // try to remove this
435 pit_type const pit = cur.pit();
437 bool const freeSpacing = par.layout().free_spacing ||
440 if (lyxrc.auto_number) {
441 static docstring const number_operators = from_ascii("+-/*");
442 static docstring const number_unary_operators = from_ascii("+-");
443 static docstring const number_seperators = from_ascii(".,:");
445 if (cur.current_font.fontInfo().number() == FONT_ON) {
446 if (!isDigit(c) && !contains(number_operators, c) &&
447 !(contains(number_seperators, c) &&
449 cur.pos() != cur.lastpos() &&
450 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
451 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
453 number(cur); // Set current_font.number to OFF
454 } else if (isDigit(c) &&
455 cur.real_current_font.isVisibleRightToLeft()) {
456 number(cur); // Set current_font.number to ON
458 if (cur.pos() != 0) {
459 char_type const c = par.getChar(cur.pos() - 1);
460 if (contains(number_unary_operators, c) &&
462 || par.isSeparator(cur.pos() - 2)
463 || par.isNewline(cur.pos() - 2))
465 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
467 } else if (contains(number_seperators, c)
469 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
470 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
477 // In Bidi text, we want spaces to be treated in a special way: spaces
478 // which are between words in different languages should get the
479 // paragraph's language; otherwise, spaces should keep the language
480 // they were originally typed in. This is only in effect while typing;
481 // after the text is already typed in, the user can always go back and
482 // explicitly set the language of a space as desired. But 99.9% of the
483 // time, what we're doing here is what the user actually meant.
485 // The following cases are the ones in which the language of the space
486 // should be changed to match that of the containing paragraph. In the
487 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
488 // represents a space, pipe (|) represents the cursor position (so the
489 // character before it is the one just typed in). The different cases
490 // are depicted logically (not visually), from left to right:
495 // Theoretically, there are other situations that we should, perhaps, deal
496 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
497 // point (to understand why, just try to create this situation...).
499 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
500 // get font in front and behind the space in question. But do NOT
501 // use getFont(cur.pos()) because the character c is not inserted yet
502 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
503 Font const & post_space_font = cur.real_current_font;
504 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
505 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
507 if (pre_space_rtl != post_space_rtl) {
508 // Set the space's language to match the language of the
509 // adjacent character whose direction is the paragraph's
510 // direction; don't touch other properties of the font
511 Language const * lang =
512 (pre_space_rtl == par.isRTL(buffer.params())) ?
513 pre_space_font.language() : post_space_font.language();
515 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
516 space_font.setLanguage(lang);
517 par.setFont(cur.pos() - 1, space_font);
521 // Next check, if there will be two blanks together or a blank at
522 // the beginning of a paragraph.
523 // I decided to handle blanks like normal characters, the main
524 // difference are the special checks when calculating the row.fill
525 // (blank does not count at the end of a row) and the check here
527 // When the free-spacing option is set for the current layout,
528 // disable the double-space checking
529 if (!freeSpacing && isLineSeparatorChar(c)) {
530 if (cur.pos() == 0) {
531 static bool sent_space_message = false;
532 if (!sent_space_message) {
533 cur.message(_("You cannot insert a space at the "
534 "beginning of a paragraph. Please read the Tutorial."));
535 sent_space_message = true;
539 LASSERT(cur.pos() > 0, /**/);
540 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
541 && !par.isDeleted(cur.pos() - 1)) {
542 static bool sent_space_message = false;
543 if (!sent_space_message) {
544 cur.message(_("You cannot type two spaces this way. "
545 "Please read the Tutorial."));
546 sent_space_message = true;
552 par.insertChar(cur.pos(), c, cur.current_font,
553 cur.buffer()->params().trackChanges);
554 cur.checkBufferStructure();
556 // cur.updateFlags(Update::Force);
557 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
562 void Text::charInserted(Cursor & cur)
564 Paragraph & par = cur.paragraph();
566 // Here we call finishUndo for every 20 characters inserted.
567 // This is from my experience how emacs does it. (Lgb)
568 static unsigned int counter;
576 // register word if a non-letter was entered
578 && par.isLetter(cur.pos() - 2)
579 && !par.isLetter(cur.pos() - 1)) {
580 // get the word in front of cursor
581 LASSERT(this == cur.text(), /**/);
582 cur.paragraph().updateWords();
587 // the cursor set functions have a special mechanism. When they
588 // realize, that you left an empty paragraph, they will delete it.
590 bool Text::cursorForwardOneWord(Cursor & cur)
592 LASSERT(this == cur.text(), /**/);
594 pos_type const lastpos = cur.lastpos();
595 pit_type pit = cur.pit();
596 pos_type pos = cur.pos();
597 Paragraph const & par = cur.paragraph();
599 // Paragraph boundary is a word boundary
600 if (pos == lastpos) {
601 if (pit != cur.lastpit())
602 return setCursor(cur, pit + 1, 0);
607 if (lyxrc.mac_like_word_movement) {
608 // Skip through trailing punctuation and spaces.
609 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
612 // Skip over either a non-char inset or a full word
613 if (pos != lastpos && !par.isLetter(pos))
615 else while (pos != lastpos && par.isLetter(pos))
618 LASSERT(pos < lastpos, /**/); // see above
619 if (par.isLetter(pos))
620 while (pos != lastpos && par.isLetter(pos))
622 else if (par.isChar(pos))
623 while (pos != lastpos && par.isChar(pos))
625 else if (!par.isSpace(pos)) // non-char inset
628 // Skip over white space
629 while (pos != lastpos && par.isSpace(pos))
633 return setCursor(cur, pit, pos);
637 bool Text::cursorBackwardOneWord(Cursor & cur)
639 LASSERT(this == cur.text(), /**/);
641 pit_type pit = cur.pit();
642 pos_type pos = cur.pos();
643 Paragraph & par = cur.paragraph();
645 // Paragraph boundary is a word boundary
646 if (pos == 0 && pit != 0)
647 return setCursor(cur, pit - 1, getPar(pit - 1).size());
649 if (lyxrc.mac_like_word_movement) {
650 // Skip through punctuation and spaces.
651 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
654 // Skip over either a non-char inset or a full word
655 if (pos != 0 && !par.isLetter(pos - 1) && !par.isChar(pos - 1))
657 else while (pos != 0 && par.isLetter(pos - 1))
660 // Skip over white space
661 while (pos != 0 && par.isSpace(pos - 1))
664 if (pos != 0 && par.isLetter(pos - 1))
665 while (pos != 0 && par.isLetter(pos - 1))
667 else if (pos != 0 && par.isChar(pos - 1))
668 while (pos != 0 && par.isChar(pos - 1))
670 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
674 return setCursor(cur, pit, pos);
678 bool Text::cursorVisLeftOneWord(Cursor & cur)
680 LASSERT(this == cur.text(), /**/);
682 pos_type left_pos, right_pos;
683 bool left_is_letter, right_is_letter;
685 Cursor temp_cur = cur;
687 // always try to move at least once...
688 while (temp_cur.posVisLeft(true /* skip_inset */)) {
690 // collect some information about current cursor position
691 temp_cur.getSurroundingPos(left_pos, right_pos);
693 (left_pos > -1 ? temp_cur.paragraph().isLetter(left_pos) : false);
695 (right_pos > -1 ? temp_cur.paragraph().isLetter(right_pos) : false);
697 // if we're not at a letter/non-letter boundary, continue moving
698 if (left_is_letter == right_is_letter)
701 // we should stop when we have an LTR word on our right or an RTL word
703 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
704 temp_cur.buffer()->params(), left_pos).isRightToLeft())
705 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
706 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
710 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
711 true, temp_cur.boundary());
715 bool Text::cursorVisRightOneWord(Cursor & cur)
717 LASSERT(this == cur.text(), /**/);
719 pos_type left_pos, right_pos;
720 bool left_is_letter, right_is_letter;
722 Cursor temp_cur = cur;
724 // always try to move at least once...
725 while (temp_cur.posVisRight(true /* skip_inset */)) {
727 // collect some information about current cursor position
728 temp_cur.getSurroundingPos(left_pos, right_pos);
730 (left_pos > -1 ? temp_cur.paragraph().isLetter(left_pos) : false);
732 (right_pos > -1 ? temp_cur.paragraph().isLetter(right_pos) : false);
734 // if we're not at a letter/non-letter boundary, continue moving
735 if (left_is_letter == right_is_letter)
738 // we should stop when we have an LTR word on our right or an RTL word
740 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
741 temp_cur.buffer()->params(),
742 left_pos).isRightToLeft())
743 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
744 temp_cur.buffer()->params(),
745 right_pos).isRightToLeft()))
749 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
750 true, temp_cur.boundary());
754 void Text::selectWord(Cursor & cur, word_location loc)
756 LASSERT(this == cur.text(), /**/);
757 CursorSlice from = cur.top();
758 CursorSlice to = cur.top();
759 getWord(from, to, loc);
760 if (cur.top() != from)
761 setCursor(cur, from.pit(), from.pos());
765 setCursor(cur, to.pit(), to.pos());
770 void Text::selectAll(Cursor & cur)
772 LASSERT(this == cur.text(), /**/);
773 if (cur.lastpos() == 0 && cur.lastpit() == 0)
775 // If the cursor is at the beginning, make sure the cursor ends there
776 if (cur.pit() == 0 && cur.pos() == 0) {
777 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
779 setCursor(cur, 0, 0);
781 setCursor(cur, 0, 0);
783 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
789 // Select the word currently under the cursor when no
790 // selection is currently set
791 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
793 LASSERT(this == cur.text(), /**/);
796 selectWord(cur, loc);
797 return cur.selection();
801 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
803 LASSERT(this == cur.text(), /**/);
805 if (!cur.selection()) {
806 Change const & change = cur.paragraph().lookupChange(cur.pos());
807 if (!(change.changed() && findNextChange(&cur.bv())))
811 cur.recordUndoSelection();
813 pit_type begPit = cur.selectionBegin().pit();
814 pit_type endPit = cur.selectionEnd().pit();
816 pos_type begPos = cur.selectionBegin().pos();
817 pos_type endPos = cur.selectionEnd().pos();
819 // keep selection info, because endPos becomes invalid after the first loop
820 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
822 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
824 for (pit_type pit = begPit; pit <= endPit; ++pit) {
825 pos_type parSize = pars_[pit].size();
827 // ignore empty paragraphs; otherwise, an assertion will fail for
828 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
832 // do not consider first paragraph if the cursor starts at pos size()
833 if (pit == begPit && begPos == parSize)
836 // do not consider last paragraph if the cursor ends at pos 0
837 if (pit == endPit && endPos == 0)
838 break; // last iteration anyway
840 pos_type left = (pit == begPit ? begPos : 0);
841 pos_type right = (pit == endPit ? endPos : parSize);
844 pars_[pit].acceptChanges(cur.buffer()->params(), left, right);
846 pars_[pit].rejectChanges(cur.buffer()->params(), left, right);
850 // next, accept/reject imaginary end-of-par characters
852 for (pit_type pit = begPit; pit <= endPit; ++pit) {
853 pos_type pos = pars_[pit].size();
855 // skip if the selection ends before the end-of-par
856 if (pit == endPit && endsBeforeEndOfPar)
857 break; // last iteration anyway
859 // skip if this is not the last paragraph of the document
860 // note: the user should be able to accept/reject the par break of the last par!
861 if (pit == endPit && pit + 1 != int(pars_.size()))
862 break; // last iteration anway
865 if (pars_[pit].isInserted(pos)) {
866 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
867 } else if (pars_[pit].isDeleted(pos)) {
868 if (pit + 1 == int(pars_.size())) {
869 // we cannot remove a par break at the end of the last paragraph;
870 // instead, we mark it unchanged
871 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
873 mergeParagraph(cur.buffer()->params(), pars_, pit);
879 if (pars_[pit].isDeleted(pos)) {
880 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
881 } else if (pars_[pit].isInserted(pos)) {
882 if (pit + 1 == int(pars_.size())) {
883 // we mark the par break at the end of the last paragraph unchanged
884 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
886 mergeParagraph(cur.buffer()->params(), pars_, pit);
894 // finally, invoke the DEPM
896 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
901 cur.clearSelection();
902 setCursorIntern(cur, begPit, begPos);
903 cur.updateFlags(Update::Force);
904 cur.buffer()->updateLabels();
908 void Text::acceptChanges(BufferParams const & bparams)
910 lyx::acceptChanges(pars_, bparams);
911 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
915 void Text::rejectChanges(BufferParams const & bparams)
917 pit_type pars_size = static_cast<pit_type>(pars_.size());
919 // first, reject changes within each individual paragraph
920 // (do not consider end-of-par)
921 for (pit_type pit = 0; pit < pars_size; ++pit) {
922 if (!pars_[pit].empty()) // prevent assertion failure
923 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
926 // next, reject imaginary end-of-par characters
927 for (pit_type pit = 0; pit < pars_size; ++pit) {
928 pos_type pos = pars_[pit].size();
930 if (pars_[pit].isDeleted(pos)) {
931 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
932 } else if (pars_[pit].isInserted(pos)) {
933 if (pit == pars_size - 1) {
934 // we mark the par break at the end of the last
935 // paragraph unchanged
936 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
938 mergeParagraph(bparams, pars_, pit);
945 // finally, invoke the DEPM
946 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
950 void Text::deleteWordForward(Cursor & cur)
952 LASSERT(this == cur.text(), /**/);
953 if (cur.lastpos() == 0)
957 cur.setSelection(true);
958 cursorForwardOneWord(cur);
960 cutSelection(cur, true, false);
961 cur.checkBufferStructure();
966 void Text::deleteWordBackward(Cursor & cur)
968 LASSERT(this == cur.text(), /**/);
969 if (cur.lastpos() == 0)
973 cur.setSelection(true);
974 cursorBackwardOneWord(cur);
976 cutSelection(cur, true, false);
977 cur.checkBufferStructure();
982 // Kill to end of line.
983 void Text::changeCase(Cursor & cur, TextCase action)
985 LASSERT(this == cur.text(), /**/);
990 if (cur.selection()) {
991 from = cur.selBegin();
996 getWord(from, to, PARTIAL_WORD);
997 cursorForwardOneWord(cur);
1000 cur.recordUndoSelection();
1002 pit_type begPit = from.pit();
1003 pit_type endPit = to.pit();
1005 pos_type begPos = from.pos();
1006 pos_type endPos = to.pos();
1008 pos_type right = 0; // needed after the for loop
1010 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1011 Paragraph & par = pars_[pit];
1012 pos_type const pos = (pit == begPit ? begPos : 0);
1013 right = (pit == endPit ? endPos : par.size());
1014 par.changeCase(cur.buffer()->params(), pos, right, action);
1017 // the selection may have changed due to logically-only deleted chars
1019 setCursor(cur, begPit, begPos);
1021 setCursor(cur, endPit, right);
1024 setCursor(cur, endPit, right);
1026 cur.checkBufferStructure();
1030 bool Text::handleBibitems(Cursor & cur)
1032 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1038 BufferParams const & bufparams = cur.buffer()->params();
1039 Paragraph const & par = cur.paragraph();
1040 Cursor prevcur = cur;
1041 if (cur.pit() > 0) {
1043 prevcur.pos() = prevcur.lastpos();
1045 Paragraph const & prevpar = prevcur.paragraph();
1047 // if a bibitem is deleted, merge with previous paragraph
1048 // if this is a bibliography item as well
1049 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1050 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1051 mergeParagraph(bufparams, cur.text()->paragraphs(),
1053 cur.buffer()->updateLabels();
1054 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1055 cur.updateFlags(Update::Force);
1059 // otherwise reset to default
1060 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1065 bool Text::erase(Cursor & cur)
1067 LASSERT(this == cur.text(), return false);
1068 bool needsUpdate = false;
1069 Paragraph & par = cur.paragraph();
1071 if (cur.pos() != cur.lastpos()) {
1072 // this is the code for a normal delete, not pasting
1074 cur.recordUndo(DELETE_UNDO);
1075 bool const was_inset = cur.paragraph().isInset(cur.pos());
1076 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1077 // the character has been logically deleted only => skip it
1078 cur.top().forwardPos();
1081 cur.buffer()->updateLabels();
1083 cur.checkBufferStructure();
1086 if (cur.pit() == cur.lastpit())
1087 return dissolveInset(cur);
1089 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1090 par.setChange(cur.pos(), Change(Change::DELETED));
1094 setCursorIntern(cur, cur.pit() + 1, 0);
1095 needsUpdate = backspacePos0(cur);
1099 needsUpdate |= handleBibitems(cur);
1102 // Make sure the cursor is correct. Is this really needed?
1103 // No, not really... at least not here!
1104 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1105 cur.checkBufferStructure();
1112 bool Text::backspacePos0(Cursor & cur)
1114 LASSERT(this == cur.text(), /**/);
1118 bool needsUpdate = false;
1120 BufferParams const & bufparams = cur.buffer()->params();
1121 DocumentClass const & tclass = bufparams.documentClass();
1122 ParagraphList & plist = cur.text()->paragraphs();
1123 Paragraph const & par = cur.paragraph();
1124 Cursor prevcur = cur;
1126 prevcur.pos() = prevcur.lastpos();
1127 Paragraph const & prevpar = prevcur.paragraph();
1129 // is it an empty paragraph?
1130 if (cur.lastpos() == 0
1131 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1132 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1133 plist.erase(boost::next(plist.begin(), cur.pit()));
1136 // is previous par empty?
1137 else if (prevcur.lastpos() == 0
1138 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1139 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1140 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1143 // Pasting is not allowed, if the paragraphs have different
1144 // layouts. I think it is a real bug of all other
1145 // word processors to allow it. It confuses the user.
1146 // Correction: Pasting is always allowed with standard-layout
1147 // or the empty layout.
1148 else if (par.layout() == prevpar.layout()
1149 || tclass.isDefaultLayout(par.layout())
1150 || tclass.isPlainLayout(par.layout())) {
1151 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1152 mergeParagraph(bufparams, plist, prevcur.pit());
1157 cur.buffer()->updateLabels();
1158 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1165 bool Text::backspace(Cursor & cur)
1167 LASSERT(this == cur.text(), /**/);
1168 bool needsUpdate = false;
1169 if (cur.pos() == 0) {
1171 return dissolveInset(cur);
1173 Paragraph & prev_par = pars_[cur.pit() - 1];
1175 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1176 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1177 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1180 // The cursor is at the beginning of a paragraph, so
1181 // the backspace will collapse two paragraphs into one.
1182 needsUpdate = backspacePos0(cur);
1185 // this is the code for a normal backspace, not pasting
1187 cur.recordUndo(DELETE_UNDO);
1188 // We used to do cursorBackwardIntern() here, but it is
1189 // not a good idea since it triggers the auto-delete
1190 // mechanism. So we do a cursorBackwardIntern()-lite,
1191 // without the dreaded mechanism. (JMarc)
1192 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1193 false, cur.boundary());
1194 bool const was_inset = cur.paragraph().isInset(cur.pos());
1195 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1197 cur.buffer()->updateLabels();
1199 cur.checkBufferStructure();
1202 if (cur.pos() == cur.lastpos())
1203 cur.setCurrentFont();
1205 needsUpdate |= handleBibitems(cur);
1207 // A singlePar update is not enough in this case.
1208 // cur.updateFlags(Update::Force);
1209 setCursor(cur.top(), cur.pit(), cur.pos());
1215 bool Text::dissolveInset(Cursor & cur)
1217 LASSERT(this == cur.text(), return false);
1219 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1222 cur.recordUndoInset();
1224 cur.selHandle(false);
1226 pos_type spos = cur.pos();
1227 pit_type spit = cur.pit();
1228 ParagraphList plist;
1229 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1230 plist = paragraphs();
1232 // store cursor offset
1236 Buffer & b = *cur.buffer();
1237 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1238 if (!plist.empty()) {
1239 // ERT paragraphs have the Language latex_language.
1240 // This is invalid outside of ERT, so we need to
1241 // change it to the buffer language.
1242 ParagraphList::iterator it = plist.begin();
1243 ParagraphList::iterator it_end = plist.end();
1244 for (; it != it_end; it++)
1245 it->changeLanguage(b.params(), latex_language, b.language());
1247 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1248 b.errorList("Paste"));
1250 cur.pit() = min(cur.lastpit(), spit);
1251 cur.pos() = min(cur.lastpos(), spos);
1253 cur.clearSelection();
1259 void Text::getWord(CursorSlice & from, CursorSlice & to,
1260 word_location const loc) const
1263 pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1267 void Text::write(Buffer const & buf, ostream & os) const
1269 ParagraphList::const_iterator pit = paragraphs().begin();
1270 ParagraphList::const_iterator end = paragraphs().end();
1272 for (; pit != end; ++pit)
1273 pit->write(os, buf.params(), dth);
1275 // Close begin_deeper
1276 for(; dth > 0; --dth)
1277 os << "\n\\end_deeper";
1281 bool Text::read(Buffer const & buf, Lexer & lex,
1282 ErrorList & errorList, InsetText * insetPtr)
1284 depth_type depth = 0;
1287 while (lex.isOK()) {
1289 string const token = lex.getString();
1294 if (token == "\\end_inset")
1297 if (token == "\\end_body")
1300 if (token == "\\begin_body")
1303 if (token == "\\end_document") {
1308 if (token == "\\begin_layout") {
1309 lex.pushToken(token);
1312 par.setInsetOwner(insetPtr);
1313 par.params().depth(depth);
1314 par.setFont(0, Font(inherit_font, buf.params().language));
1315 pars_.push_back(par);
1317 // FIXME: goddamn InsetTabular makes us pass a Buffer
1319 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1321 // register the words in the global word list
1322 CursorSlice sl = CursorSlice(*insetPtr);
1323 sl.pit() = pars_.size() - 1;
1324 pars_.back().updateWords();
1325 } else if (token == "\\begin_deeper") {
1327 } else if (token == "\\end_deeper") {
1329 lex.printError("\\end_deeper: " "depth is already null");
1333 LYXERR0("Handling unknown body token: `" << token << '\'');
1337 // avoid a crash on weird documents (bug 4859)
1338 if (pars_.empty()) {
1340 par.setInsetOwner(insetPtr);
1341 par.params().depth(depth);
1342 par.setFont(0, Font(inherit_font,
1343 buf.params().language));
1344 par.setPlainOrDefaultLayout(buf.params().documentClass());
1345 pars_.push_back(par);
1351 // Returns the current font and depth as a message.
1352 docstring Text::currentState(Cursor const & cur) const
1354 LASSERT(this == cur.text(), /**/);
1355 Buffer & buf = *cur.buffer();
1356 Paragraph const & par = cur.paragraph();
1357 odocstringstream os;
1359 if (buf.params().trackChanges)
1360 os << _("[Change Tracking] ");
1362 Change change = par.lookupChange(cur.pos());
1364 if (change.type != Change::UNCHANGED) {
1365 Author const & a = buf.params().authors().get(change.author);
1366 os << _("Change: ") << a.name();
1367 if (!a.email().empty())
1368 os << " (" << a.email() << ")";
1369 // FIXME ctime is english, we should translate that
1370 os << _(" at ") << ctime(&change.changetime);
1374 // I think we should only show changes from the default
1376 // No, from the document font (MV)
1377 Font font = cur.real_current_font;
1378 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1380 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1382 // The paragraph depth
1383 int depth = cur.paragraph().getDepth();
1385 os << bformat(_(", Depth: %1$d"), depth);
1387 // The paragraph spacing, but only if different from
1389 Spacing const & spacing = par.params().spacing();
1390 if (!spacing.isDefault()) {
1391 os << _(", Spacing: ");
1392 switch (spacing.getSpace()) {
1393 case Spacing::Single:
1396 case Spacing::Onehalf:
1399 case Spacing::Double:
1402 case Spacing::Other:
1403 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1405 case Spacing::Default:
1406 // should never happen, do nothing
1411 #ifdef DEVEL_VERSION
1412 os << _(", Inset: ") << &cur.inset();
1413 os << _(", Paragraph: ") << cur.pit();
1414 os << _(", Id: ") << par.id();
1415 os << _(", Position: ") << cur.pos();
1416 // FIXME: Why is the check for par.size() needed?
1417 // We are called with cur.pos() == par.size() quite often.
1418 if (!par.empty() && cur.pos() < par.size()) {
1419 // Force output of code point, not character
1420 size_t const c = par.getChar(cur.pos());
1421 os << _(", Char: 0x") << hex << c;
1423 os << _(", Boundary: ") << cur.boundary();
1424 // Row & row = cur.textRow();
1425 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1431 docstring Text::getPossibleLabel(Cursor const & cur) const
1433 pit_type pit = cur.pit();
1435 Layout const * layout = &(pars_[pit].layout());
1438 docstring par_text = pars_[pit].asString();
1440 // the return string of math matrices might contain linebreaks
1441 par_text = subst(par_text, '\n', '-');
1442 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1443 if (par_text.empty())
1446 par_text = split(par_text, head, ' ');
1447 // Is it legal to use spaces in labels ?
1453 // No need for a prefix if the user said so.
1454 if (lyxrc.label_init_length <= 0)
1457 // Will contain the label type.
1460 // For section, subsection, etc...
1461 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1462 Layout const * layout2 = &(pars_[pit - 1].layout());
1463 if (layout2->latextype != LATEX_PARAGRAPH) {
1468 if (layout->latextype != LATEX_PARAGRAPH)
1469 name = from_ascii(layout->latexname());
1471 // for captions, we just take the caption type
1472 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1474 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1476 // If none of the above worked, we'll see if we're inside various
1477 // types of insets and take our abbreviation from them.
1479 InsetCode const codes[] = {
1484 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1485 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1487 name = float_inset->name();
1493 // Create a correct prefix for prettyref
1494 if (name == "theorem")
1495 name = from_ascii("thm");
1496 else if (name == "Foot")
1497 name = from_ascii("fn");
1498 else if (name == "listing")
1499 name = from_ascii("lst");
1502 text = name.substr(0, 3) + ':' + text;
1508 docstring Text::asString(int options) const
1510 return asString(0, pars_.size(), options);
1514 docstring Text::asString(pit_type beg, pit_type end, int options) const
1516 size_t i = size_t(beg);
1517 docstring str = pars_[i].asString(options);
1518 for (++i; i != size_t(end); ++i) {
1520 str += pars_[i].asString(options);
1527 void Text::charsTranspose(Cursor & cur)
1529 LASSERT(this == cur.text(), /**/);
1531 pos_type pos = cur.pos();
1533 // If cursor is at beginning or end of paragraph, do nothing.
1534 if (pos == cur.lastpos() || pos == 0)
1537 Paragraph & par = cur.paragraph();
1539 // Get the positions of the characters to be transposed.
1540 pos_type pos1 = pos - 1;
1541 pos_type pos2 = pos;
1543 // In change tracking mode, ignore deleted characters.
1544 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1546 if (pos2 == cur.lastpos())
1549 while (pos1 >= 0 && par.isDeleted(pos1))
1554 // Don't do anything if one of the "characters" is not regular text.
1555 if (par.isInset(pos1) || par.isInset(pos2))
1558 // Store the characters to be transposed (including font information).
1559 char_type const char1 = par.getChar(pos1);
1561 par.getFontSettings(cur.buffer()->params(), pos1);
1563 char_type const char2 = par.getChar(pos2);
1565 par.getFontSettings(cur.buffer()->params(), pos2);
1567 // And finally, we are ready to perform the transposition.
1568 // Track the changes if Change Tracking is enabled.
1569 bool const trackChanges = cur.buffer()->params().trackChanges;
1573 par.eraseChar(pos2, trackChanges);
1574 par.eraseChar(pos1, trackChanges);
1575 par.insertChar(pos1, char2, font2, trackChanges);
1576 par.insertChar(pos2, char1, font1, trackChanges);
1578 cur.checkBufferStructure();
1580 // After the transposition, move cursor to after the transposition.
1581 setCursor(cur, cur.pit(), pos2);
1586 DocIterator Text::macrocontextPosition() const
1588 return macrocontext_position_;
1592 void Text::setMacrocontextPosition(DocIterator const & pos)
1594 macrocontext_position_ = pos;
1598 docstring Text::previousWord(CursorSlice const & sl) const
1600 CursorSlice from = sl;
1601 CursorSlice to = sl;
1602 getWord(from, to, PREVIOUS_WORD);
1603 if (sl == from || to == from)
1606 Paragraph const & par = sl.paragraph();
1607 return par.asString(from.pos(), to.pos());
1611 bool Text::completionSupported(Cursor const & cur) const
1613 Paragraph const & par = cur.paragraph();
1614 return cur.pos() > 0
1615 && (cur.pos() >= par.size() || !par.isLetter(cur.pos()))
1616 && par.isLetter(cur.pos() - 1);
1620 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1622 return new TextCompletionList(cur);
1626 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1628 LASSERT(cur.bv().cursor() == cur, /**/);
1630 cur.bv().cursor() = cur;
1631 if (!(cur.disp_.update() & Update::Force))
1632 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
1637 docstring Text::completionPrefix(Cursor const & cur) const
1639 return previousWord(cur.top());