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"
41 #include "Paragraph.h"
42 #include "paragraph_funcs.h"
43 #include "ParagraphParameters.h"
44 #include "ParIterator.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
48 #include "WordLangTuple.h"
51 #include "insets/InsetText.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetCaption.h"
54 #include "insets/InsetLine.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetNewpage.h"
57 #include "insets/InsetOptArg.h"
58 #include "insets/InsetSpace.h"
59 #include "insets/InsetSpecialChar.h"
60 #include "insets/InsetTabular.h"
62 #include "support/lassert.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.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.forceEmptyLayout()) {
106 // in this case only the empty layout is allowed
107 layoutname = tclass.emptyLayoutName();
108 } else if (par.useEmptyLayout()) {
109 // in this case, default layout maps to empty layout
110 if (layoutname == tclass.defaultLayoutName())
111 layoutname = tclass.emptyLayoutName();
113 // otherwise, the empty layout maps to the default
114 if (layoutname == tclass.emptyLayoutName())
115 layoutname = tclass.defaultLayoutName();
118 bool hasLayout = tclass.hasLayout(layoutname);
121 errorList.push_back(ErrorItem(_("Unknown layout"),
122 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
123 layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
124 layoutname = par.useEmptyLayout() ?
125 tclass.emptyLayoutName() :
126 tclass.defaultLayoutName();
129 par.setLayout(bp.documentClass()[layoutname]);
131 // Test whether the layout is obsolete.
132 Layout const & layout = par.layout();
133 if (!layout.obsoleted_by().empty())
134 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
136 par.params().read(lex);
138 } else if (token == "\\end_layout") {
139 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
140 << "Missing \\begin_layout ?");
141 } else if (token == "\\end_inset") {
142 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
143 << "Missing \\begin_inset ?");
144 } else if (token == "\\begin_inset") {
145 Inset * inset = readInset(lex, buf);
147 par.insertInset(par.size(), inset, font, change);
150 docstring line = lex.getDocString();
151 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
152 par.id(), 0, par.size()));
154 } else if (token == "\\family") {
156 setLyXFamily(lex.getString(), font.fontInfo());
157 } else if (token == "\\series") {
159 setLyXSeries(lex.getString(), font.fontInfo());
160 } else if (token == "\\shape") {
162 setLyXShape(lex.getString(), font.fontInfo());
163 } else if (token == "\\size") {
165 setLyXSize(lex.getString(), font.fontInfo());
166 } else if (token == "\\lang") {
168 string const tok = lex.getString();
169 Language const * lang = languages.getLanguage(tok);
171 font.setLanguage(lang);
173 font.setLanguage(bp.language);
174 lex.printError("Unknown language `$$Token'");
176 } else if (token == "\\numeric") {
178 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
179 } else if (token == "\\emph") {
181 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
182 } else if (token == "\\bar") {
184 string const tok = lex.getString();
187 font.fontInfo().setUnderbar(FONT_ON);
188 else if (tok == "no")
189 font.fontInfo().setUnderbar(FONT_OFF);
190 else if (tok == "default")
191 font.fontInfo().setUnderbar(FONT_INHERIT);
193 lex.printError("Unknown bar font flag "
195 } else if (token == "\\noun") {
197 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
198 } else if (token == "\\color") {
200 setLyXColor(lex.getString(), font.fontInfo());
201 } else if (token == "\\SpecialChar") {
202 auto_ptr<Inset> inset;
203 inset.reset(new InsetSpecialChar);
205 par.insertInset(par.size(), inset.release(),
207 } else if (token == "\\backslash") {
208 par.appendChar('\\', font, change);
209 } else if (token == "\\LyXTable") {
210 auto_ptr<Inset> inset(new InsetTabular(buf));
212 par.insertInset(par.size(), inset.release(), font, change);
213 } else if (token == "\\lyxline") {
214 par.insertInset(par.size(), new InsetLine, font, change);
215 } else if (token == "\\change_unchanged") {
216 change = Change(Change::UNCHANGED);
217 } else if (token == "\\change_inserted") {
219 istringstream is(lex.getString());
223 if (aid >= bp.author_map.size()) {
224 errorList.push_back(ErrorItem(_("Change tracking error"),
225 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
226 par.id(), 0, par.size()));
227 change = Change(Change::UNCHANGED);
229 change = Change(Change::INSERTED, bp.author_map[aid], ct);
230 } else if (token == "\\change_deleted") {
232 istringstream is(lex.getString());
236 if (aid >= bp.author_map.size()) {
237 errorList.push_back(ErrorItem(_("Change tracking error"),
238 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
239 par.id(), 0, par.size()));
240 change = Change(Change::UNCHANGED);
242 change = Change(Change::DELETED, bp.author_map[aid], ct);
245 errorList.push_back(ErrorItem(_("Unknown token"),
246 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
248 par.id(), 0, par.size()));
253 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
254 ErrorList & errorList)
257 string token = lex.getString();
259 Change change(Change::UNCHANGED);
262 readParToken(buf, par, lex, token, font, change, errorList);
265 token = lex.getString();
270 if (token == "\\end_layout") {
271 //Ok, paragraph finished
275 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
276 if (token == "\\begin_layout" || token == "\\end_document"
277 || token == "\\end_inset" || token == "\\begin_deeper"
278 || token == "\\end_deeper") {
279 lex.pushToken(token);
280 lyxerr << "Paragraph ended in line "
281 << lex.lineNumber() << "\n"
282 << "Missing \\end_layout.\n";
286 // Final change goes to paragraph break:
287 par.setChange(par.size(), change);
289 // Initialize begin_of_body_ on load; redoParagraph maintains
290 par.setBeginOfBody();
296 class TextCompletionList : public CompletionList
300 TextCompletionList(Cursor const & cur)
301 : buf_(cur.buffer()), pos_(0) {}
303 virtual ~TextCompletionList() {}
306 virtual bool sorted() const { return true; }
308 virtual size_t size() const
310 return theWordList().size();
313 virtual docstring const & data(size_t idx) const
315 return theWordList().word(idx);
326 bool Text::empty() const
328 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
329 // FIXME: Should we consider the labeled type as empty too?
330 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
334 double Text::spacing(Buffer const & buffer, Paragraph const & par) const
336 if (par.params().spacing().isDefault())
337 return buffer.params().spacing().getValue();
338 return par.params().spacing().getValue();
342 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
344 LASSERT(this == cur.text(), /**/);
346 Paragraph & cpar = cur.paragraph();
347 pit_type cpit = cur.pit();
349 DocumentClass const & tclass = cur.buffer().params().documentClass();
350 Layout const & layout = cpar.layout();
352 // this is only allowed, if the current paragraph is not empty
353 // or caption and if it has not the keepempty flag active
354 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
355 layout.labeltype != LABEL_SENSITIVE)
358 // a layout change may affect also the following paragraph
359 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
361 // Always break behind a space
362 // It is better to erase the space (Dekel)
363 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
364 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
366 // What should the layout for the new paragraph be?
367 bool keep_layout = inverse_logic ?
368 !layout.isEnvironment()
369 : layout.isEnvironment();
371 // We need to remember this before we break the paragraph, because
372 // that invalidates the layout variable
373 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
375 // we need to set this before we insert the paragraph.
376 bool const isempty = cpar.allowEmpty() && cpar.empty();
378 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
379 cur.pos(), keep_layout);
381 // After this, neither paragraph contains any rows!
384 pit_type next_par = cpit + 1;
386 // well this is the caption hack since one caption is really enough
389 // set to standard-layout
390 //FIXME Check if this should be emptyLayout() in some cases
391 pars_[cpit].applyLayout(tclass.defaultLayout());
393 // set to standard-layout
394 //FIXME Check if this should be emptyLayout() in some cases
395 pars_[next_par].applyLayout(tclass.defaultLayout());
398 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
399 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
400 break; // the character couldn't be deleted physically due to change tracking
403 updateLabels(cur.buffer());
405 // A singlePar update is not enough in this case.
406 cur.updateFlags(Update::Force);
408 // This check is necessary. Otherwise the new empty paragraph will
409 // be deleted automatically. And it is more friendly for the user!
410 if (cur.pos() != 0 || isempty)
411 setCursor(cur, cur.pit() + 1, 0);
413 setCursor(cur, cur.pit(), 0);
417 // insert a character, moves all the following breaks in the
418 // same Paragraph one to the right and make a rebreak
419 void Text::insertChar(Cursor & cur, char_type c)
421 LASSERT(this == cur.text(), /**/);
423 cur.recordUndo(INSERT_UNDO);
425 TextMetrics const & tm = cur.bv().textMetrics(this);
426 Buffer const & buffer = cur.buffer();
427 Paragraph & par = cur.paragraph();
428 // try to remove this
429 pit_type const pit = cur.pit();
431 bool const freeSpacing = par.layout().free_spacing ||
434 if (lyxrc.auto_number) {
435 static docstring const number_operators = from_ascii("+-/*");
436 static docstring const number_unary_operators = from_ascii("+-");
437 static docstring const number_seperators = from_ascii(".,:");
439 if (cur.current_font.fontInfo().number() == FONT_ON) {
440 if (!isDigit(c) && !contains(number_operators, c) &&
441 !(contains(number_seperators, c) &&
443 cur.pos() != cur.lastpos() &&
444 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
445 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
447 number(cur); // Set current_font.number to OFF
448 } else if (isDigit(c) &&
449 cur.real_current_font.isVisibleRightToLeft()) {
450 number(cur); // Set current_font.number to ON
452 if (cur.pos() != 0) {
453 char_type const c = par.getChar(cur.pos() - 1);
454 if (contains(number_unary_operators, c) &&
456 || par.isSeparator(cur.pos() - 2)
457 || par.isNewline(cur.pos() - 2))
459 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
461 } else if (contains(number_seperators, c)
463 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
464 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
471 // In Bidi text, we want spaces to be treated in a special way: spaces
472 // which are between words in different languages should get the
473 // paragraph's language; otherwise, spaces should keep the language
474 // they were originally typed in. This is only in effect while typing;
475 // after the text is already typed in, the user can always go back and
476 // explicitly set the language of a space as desired. But 99.9% of the
477 // time, what we're doing here is what the user actually meant.
479 // The following cases are the ones in which the language of the space
480 // should be changed to match that of the containing paragraph. In the
481 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
482 // represents a space, pipe (|) represents the cursor position (so the
483 // character before it is the one just typed in). The different cases
484 // are depicted logically (not visually), from left to right:
489 // Theoretically, there are other situations that we should, perhaps, deal
490 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
491 // point (to understand why, just try to create this situation...).
493 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
494 // get font in front and behind the space in question. But do NOT
495 // use getFont(cur.pos()) because the character c is not inserted yet
496 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
497 Font const & post_space_font = cur.real_current_font;
498 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
499 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
501 if (pre_space_rtl != post_space_rtl) {
502 // Set the space's language to match the language of the
503 // adjacent character whose direction is the paragraph's
504 // direction; don't touch other properties of the font
505 Language const * lang =
506 (pre_space_rtl == par.isRTL(buffer.params())) ?
507 pre_space_font.language() : post_space_font.language();
509 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
510 space_font.setLanguage(lang);
511 par.setFont(cur.pos() - 1, space_font);
515 // Next check, if there will be two blanks together or a blank at
516 // the beginning of a paragraph.
517 // I decided to handle blanks like normal characters, the main
518 // difference are the special checks when calculating the row.fill
519 // (blank does not count at the end of a row) and the check here
521 // When the free-spacing option is set for the current layout,
522 // disable the double-space checking
523 if (!freeSpacing && isLineSeparatorChar(c)) {
524 if (cur.pos() == 0) {
525 static bool sent_space_message = false;
526 if (!sent_space_message) {
527 cur.message(_("You cannot insert a space at the "
528 "beginning of a paragraph. Please read the Tutorial."));
529 sent_space_message = true;
533 LASSERT(cur.pos() > 0, /**/);
534 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
535 && !par.isDeleted(cur.pos() - 1)) {
536 static bool sent_space_message = false;
537 if (!sent_space_message) {
538 cur.message(_("You cannot type two spaces this way. "
539 "Please read the Tutorial."));
540 sent_space_message = true;
546 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
547 cur.checkBufferStructure();
549 // cur.updateFlags(Update::Force);
550 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
555 void Text::charInserted(Cursor & cur)
557 Paragraph & par = cur.paragraph();
559 // Here we call finishUndo for every 20 characters inserted.
560 // This is from my experience how emacs does it. (Lgb)
561 static unsigned int counter;
569 // register word if a non-letter was entered
571 && par.isLetter(cur.pos() - 2)
572 && !par.isLetter(cur.pos() - 1)) {
573 // get the word in front of cursor
574 LASSERT(this == cur.text(), /**/);
575 cur.paragraph().updateWords(cur.top());
580 // the cursor set functions have a special mechanism. When they
581 // realize, that you left an empty paragraph, they will delete it.
583 bool Text::cursorForwardOneWord(Cursor & cur)
585 LASSERT(this == cur.text(), /**/);
589 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
593 // Advance through word.
594 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
596 // Skip through trailing nonword stuff.
597 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
600 return setCursor(cur, old.pit(), old.pos());
604 bool Text::cursorBackwardOneWord(Cursor & cur)
606 LASSERT(this == cur.text(), /**/);
610 if (old.pos() == 0 && old.pit() != 0) {
612 old.pos() = old.lastpos();
614 // Skip through initial nonword stuff.
615 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
617 // Advance through word.
618 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
621 return setCursor(cur, old.pit(), old.pos());
625 bool Text::cursorVisLeftOneWord(Cursor & cur)
627 LASSERT(this == cur.text(), /**/);
629 pos_type left_pos, right_pos;
630 bool left_is_letter, right_is_letter;
632 Cursor temp_cur = cur;
634 // always try to move at least once...
635 while (temp_cur.posVisLeft(true /* skip_inset */)) {
637 // collect some information about current cursor position
638 temp_cur.getSurroundingPos(left_pos, right_pos);
640 (left_pos > -1 ? temp_cur.paragraph().isLetter(left_pos) : false);
642 (right_pos > -1 ? temp_cur.paragraph().isLetter(right_pos) : false);
644 // if we're not at a letter/non-letter boundary, continue moving
645 if (left_is_letter == right_is_letter)
648 // we should stop when we have an LTR word on our right or an RTL word
650 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
651 temp_cur.bv().buffer().params(),
652 left_pos).isRightToLeft())
653 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
654 temp_cur.bv().buffer().params(),
655 right_pos).isRightToLeft()))
659 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
660 true, temp_cur.boundary());
664 bool Text::cursorVisRightOneWord(Cursor & cur)
666 LASSERT(this == cur.text(), /**/);
668 pos_type left_pos, right_pos;
669 bool left_is_letter, right_is_letter;
671 Cursor temp_cur = cur;
673 // always try to move at least once...
674 while (temp_cur.posVisRight(true /* skip_inset */)) {
676 // collect some information about current cursor position
677 temp_cur.getSurroundingPos(left_pos, right_pos);
679 (left_pos > -1 ? temp_cur.paragraph().isLetter(left_pos) : false);
681 (right_pos > -1 ? temp_cur.paragraph().isLetter(right_pos) : false);
683 // if we're not at a letter/non-letter boundary, continue moving
684 if (left_is_letter == right_is_letter)
687 // we should stop when we have an LTR word on our right or an RTL word
689 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
690 temp_cur.bv().buffer().params(),
691 left_pos).isRightToLeft())
692 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
693 temp_cur.bv().buffer().params(),
694 right_pos).isRightToLeft()))
698 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
699 true, temp_cur.boundary());
703 void Text::selectWord(Cursor & cur, word_location loc)
705 LASSERT(this == cur.text(), /**/);
706 CursorSlice from = cur.top();
707 CursorSlice to = cur.top();
708 getWord(from, to, loc);
709 if (cur.top() != from)
710 setCursor(cur, from.pit(), from.pos());
714 setCursor(cur, to.pit(), to.pos());
719 // Select the word currently under the cursor when no
720 // selection is currently set
721 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
723 LASSERT(this == cur.text(), /**/);
726 selectWord(cur, loc);
727 return cur.selection();
731 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
733 LASSERT(this == cur.text(), /**/);
735 if (!cur.selection())
738 cur.recordUndoSelection();
740 pit_type begPit = cur.selectionBegin().pit();
741 pit_type endPit = cur.selectionEnd().pit();
743 pos_type begPos = cur.selectionBegin().pos();
744 pos_type endPos = cur.selectionEnd().pos();
746 // keep selection info, because endPos becomes invalid after the first loop
747 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
749 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
751 for (pit_type pit = begPit; pit <= endPit; ++pit) {
752 pos_type parSize = pars_[pit].size();
754 // ignore empty paragraphs; otherwise, an assertion will fail for
755 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
759 // do not consider first paragraph if the cursor starts at pos size()
760 if (pit == begPit && begPos == parSize)
763 // do not consider last paragraph if the cursor ends at pos 0
764 if (pit == endPit && endPos == 0)
765 break; // last iteration anyway
767 pos_type left = (pit == begPit ? begPos : 0);
768 pos_type right = (pit == endPit ? endPos : parSize);
771 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
773 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
777 // next, accept/reject imaginary end-of-par characters
779 for (pit_type pit = begPit; pit <= endPit; ++pit) {
780 pos_type pos = pars_[pit].size();
782 // skip if the selection ends before the end-of-par
783 if (pit == endPit && endsBeforeEndOfPar)
784 break; // last iteration anyway
786 // skip if this is not the last paragraph of the document
787 // note: the user should be able to accept/reject the par break of the last par!
788 if (pit == endPit && pit + 1 != int(pars_.size()))
789 break; // last iteration anway
792 if (pars_[pit].isInserted(pos)) {
793 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
794 } else if (pars_[pit].isDeleted(pos)) {
795 if (pit + 1 == int(pars_.size())) {
796 // we cannot remove a par break at the end of the last paragraph;
797 // instead, we mark it unchanged
798 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
800 mergeParagraph(cur.buffer().params(), pars_, pit);
806 if (pars_[pit].isDeleted(pos)) {
807 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
808 } else if (pars_[pit].isInserted(pos)) {
809 if (pit + 1 == int(pars_.size())) {
810 // we mark the par break at the end of the last paragraph unchanged
811 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
813 mergeParagraph(cur.buffer().params(), pars_, pit);
821 // finally, invoke the DEPM
823 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
828 cur.clearSelection();
829 setCursorIntern(cur, begPit, begPos);
830 cur.updateFlags(Update::Force);
831 updateLabels(cur.buffer());
835 void Text::acceptChanges(BufferParams const & bparams)
837 lyx::acceptChanges(pars_, bparams);
838 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
842 void Text::rejectChanges(BufferParams const & bparams)
844 pit_type pars_size = static_cast<pit_type>(pars_.size());
846 // first, reject changes within each individual paragraph
847 // (do not consider end-of-par)
848 for (pit_type pit = 0; pit < pars_size; ++pit) {
849 if (!pars_[pit].empty()) // prevent assertion failure
850 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
853 // next, reject imaginary end-of-par characters
854 for (pit_type pit = 0; pit < pars_size; ++pit) {
855 pos_type pos = pars_[pit].size();
857 if (pars_[pit].isDeleted(pos)) {
858 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
859 } else if (pars_[pit].isInserted(pos)) {
860 if (pit == pars_size - 1) {
861 // we mark the par break at the end of the last
862 // paragraph unchanged
863 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
865 mergeParagraph(bparams, pars_, pit);
872 // finally, invoke the DEPM
873 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
877 void Text::deleteWordForward(Cursor & cur)
879 LASSERT(this == cur.text(), /**/);
880 if (cur.lastpos() == 0)
884 cur.selection() = true;
885 cursorForwardOneWord(cur);
887 cutSelection(cur, true, false);
888 cur.checkBufferStructure();
893 void Text::deleteWordBackward(Cursor & cur)
895 LASSERT(this == cur.text(), /**/);
896 if (cur.lastpos() == 0)
900 cur.selection() = true;
901 cursorBackwardOneWord(cur);
903 cutSelection(cur, true, false);
904 cur.checkBufferStructure();
909 // Kill to end of line.
910 void Text::changeCase(Cursor & cur, TextCase action)
912 LASSERT(this == cur.text(), /**/);
917 if (cur.selection()) {
918 from = cur.selBegin();
923 getWord(from, to, PARTIAL_WORD);
924 cursorForwardOneWord(cur);
927 cur.recordUndoSelection();
929 pit_type begPit = from.pit();
930 pit_type endPit = to.pit();
932 pos_type begPos = from.pos();
933 pos_type endPos = to.pos();
935 pos_type right = 0; // needed after the for loop
937 for (pit_type pit = begPit; pit <= endPit; ++pit) {
938 Paragraph & par = pars_[pit];
939 pos_type const pos = (pit == begPit ? begPos : 0);
940 right = (pit == endPit ? endPos : par.size());
941 par.changeCase(cur.buffer().params(), pos, right, action);
944 // the selection may have changed due to logically-only deleted chars
946 setCursor(cur, begPit, begPos);
948 setCursor(cur, endPit, right);
951 setCursor(cur, endPit, right);
953 cur.checkBufferStructure();
957 bool Text::handleBibitems(Cursor & cur)
959 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
965 BufferParams const & bufparams = cur.buffer().params();
966 Paragraph const & par = cur.paragraph();
967 Cursor prevcur = cur;
970 prevcur.pos() = prevcur.lastpos();
972 Paragraph const & prevpar = prevcur.paragraph();
974 // if a bibitem is deleted, merge with previous paragraph
975 // if this is a bibliography item as well
976 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
977 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
978 mergeParagraph(bufparams, cur.text()->paragraphs(),
980 updateLabels(cur.buffer());
981 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
982 cur.updateFlags(Update::Force);
986 // otherwise reset to default
987 cur.paragraph().setEmptyOrDefaultLayout(bufparams.documentClass());
992 bool Text::erase(Cursor & cur)
994 LASSERT(this == cur.text(), /**/);
995 bool needsUpdate = false;
996 Paragraph & par = cur.paragraph();
998 if (cur.pos() != cur.lastpos()) {
999 // this is the code for a normal delete, not pasting
1001 cur.recordUndo(DELETE_UNDO);
1002 bool const was_inset = cur.paragraph().isInset(cur.pos());
1003 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges))
1004 // the character has been logically deleted only => skip it
1005 cur.top().forwardPos();
1008 updateLabels(cur.buffer());
1010 cur.checkBufferStructure();
1013 if (cur.pit() == cur.lastpit())
1014 return dissolveInset(cur);
1016 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1017 par.setChange(cur.pos(), Change(Change::DELETED));
1021 setCursorIntern(cur, cur.pit() + 1, 0);
1022 needsUpdate = backspacePos0(cur);
1026 needsUpdate |= handleBibitems(cur);
1029 // Make sure the cursor is correct. Is this really needed?
1030 // No, not really... at least not here!
1031 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1032 cur.checkBufferStructure();
1039 bool Text::backspacePos0(Cursor & cur)
1041 LASSERT(this == cur.text(), /**/);
1045 bool needsUpdate = false;
1047 BufferParams const & bufparams = cur.buffer().params();
1048 DocumentClass const & tclass = bufparams.documentClass();
1049 ParagraphList & plist = cur.text()->paragraphs();
1050 Paragraph const & par = cur.paragraph();
1051 Cursor prevcur = cur;
1053 prevcur.pos() = prevcur.lastpos();
1054 Paragraph const & prevpar = prevcur.paragraph();
1056 // is it an empty paragraph?
1057 if (cur.lastpos() == 0
1058 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1059 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1060 plist.erase(boost::next(plist.begin(), cur.pit()));
1063 // is previous par empty?
1064 else if (prevcur.lastpos() == 0
1065 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1066 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1067 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1070 // Pasting is not allowed, if the paragraphs have different
1071 // layouts. I think it is a real bug of all other
1072 // word processors to allow it. It confuses the user.
1073 // Correction: Pasting is always allowed with standard-layout
1074 // or the empty layout.
1075 else if (par.layout() == prevpar.layout()
1076 || tclass.isDefaultLayout(par.layout())
1077 || tclass.isEmptyLayout(par.layout())) {
1078 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1079 mergeParagraph(bufparams, plist, prevcur.pit());
1084 updateLabels(cur.buffer());
1085 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1092 bool Text::backspace(Cursor & cur)
1094 LASSERT(this == cur.text(), /**/);
1095 bool needsUpdate = false;
1096 if (cur.pos() == 0) {
1098 return dissolveInset(cur);
1100 Paragraph & prev_par = pars_[cur.pit() - 1];
1102 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1103 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1104 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1107 // The cursor is at the beginning of a paragraph, so
1108 // the backspace will collapse two paragraphs into one.
1109 needsUpdate = backspacePos0(cur);
1112 // this is the code for a normal backspace, not pasting
1114 cur.recordUndo(DELETE_UNDO);
1115 // We used to do cursorBackwardIntern() here, but it is
1116 // not a good idea since it triggers the auto-delete
1117 // mechanism. So we do a cursorBackwardIntern()-lite,
1118 // without the dreaded mechanism. (JMarc)
1119 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1120 false, cur.boundary());
1121 bool const was_inset = cur.paragraph().isInset(cur.pos());
1122 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1124 updateLabels(cur.buffer());
1126 cur.checkBufferStructure();
1129 if (cur.pos() == cur.lastpos())
1130 cur.setCurrentFont();
1132 needsUpdate |= handleBibitems(cur);
1134 // A singlePar update is not enough in this case.
1135 // cur.updateFlags(Update::Force);
1136 setCursor(cur.top(), cur.pit(), cur.pos());
1142 bool Text::dissolveInset(Cursor & cur) {
1143 LASSERT(this == cur.text(), /**/);
1145 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1148 cur.recordUndoInset();
1150 cur.selHandle(false);
1152 pos_type spos = cur.pos();
1153 pit_type spit = cur.pit();
1154 ParagraphList plist;
1155 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1156 plist = paragraphs();
1158 // store cursor offset
1162 Buffer & b = cur.buffer();
1163 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1164 if (!plist.empty()) {
1165 // ERT paragraphs have the Language latex_language.
1166 // This is invalid outside of ERT, so we need to
1167 // change it to the buffer language.
1168 ParagraphList::iterator it = plist.begin();
1169 ParagraphList::iterator it_end = plist.end();
1170 for (; it != it_end; it++)
1171 it->changeLanguage(b.params(), latex_language, b.language());
1173 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1174 b.errorList("Paste"));
1176 cur.pit() = min(cur.lastpit(), spit);
1177 cur.pos() = min(cur.lastpos(), spos);
1179 cur.clearSelection();
1185 void Text::getWord(CursorSlice & from, CursorSlice & to,
1186 word_location const loc) const
1188 Paragraph const & from_par = pars_[from.pit()];
1190 case WHOLE_WORD_STRICT:
1191 if (from.pos() == 0 || from.pos() == from_par.size()
1192 || !from_par.isLetter(from.pos())
1193 || !from_par.isLetter(from.pos() - 1)) {
1197 // no break here, we go to the next
1200 // If we are already at the beginning of a word, do nothing
1201 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1203 // no break here, we go to the next
1206 // always move the cursor to the beginning of previous word
1207 while (from.pos() && from_par.isLetter(from.pos() - 1))
1211 LYXERR0("Text::getWord: NEXT_WORD not implemented yet");
1214 // no need to move the 'from' cursor
1218 Paragraph const & to_par = pars_[to.pit()];
1219 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1224 void Text::write(Buffer const & buf, ostream & os) const
1226 ParagraphList::const_iterator pit = paragraphs().begin();
1227 ParagraphList::const_iterator end = paragraphs().end();
1229 for (; pit != end; ++pit)
1230 pit->write(os, buf.params(), dth);
1232 // Close begin_deeper
1233 for(; dth > 0; --dth)
1234 os << "\n\\end_deeper";
1238 bool Text::read(Buffer const & buf, Lexer & lex,
1239 ErrorList & errorList, InsetText * insetPtr)
1241 depth_type depth = 0;
1243 while (lex.isOK()) {
1245 string const token = lex.getString();
1250 if (token == "\\end_inset")
1253 if (token == "\\end_body")
1256 if (token == "\\begin_body")
1259 if (token == "\\end_document")
1262 if (token == "\\begin_layout") {
1263 lex.pushToken(token);
1266 par.params().depth(depth);
1267 par.setFont(0, Font(inherit_font, buf.params().language));
1268 par.setInsetOwner(insetPtr);
1269 pars_.push_back(par);
1271 // FIXME: goddamn InsetTabular makes us pass a Buffer
1273 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1275 // register the words in the global word list
1276 CursorSlice sl = CursorSlice(*insetPtr);
1277 sl.pit() = pars_.size() - 1;
1278 pars_.back().updateWords(sl);
1279 } else if (token == "\\begin_deeper") {
1281 } else if (token == "\\end_deeper") {
1283 lex.printError("\\end_deeper: " "depth is already null");
1287 LYXERR0("Handling unknown body token: `" << token << '\'');
1293 // Returns the current font and depth as a message.
1294 docstring Text::currentState(Cursor & cur)
1296 LASSERT(this == cur.text(), /**/);
1297 Buffer & buf = cur.buffer();
1298 Paragraph const & par = cur.paragraph();
1299 odocstringstream os;
1301 if (buf.params().trackChanges)
1302 os << _("[Change Tracking] ");
1304 Change change = par.lookupChange(cur.pos());
1306 if (change.type != Change::UNCHANGED) {
1307 Author const & a = buf.params().authors().get(change.author);
1308 os << _("Change: ") << a.name();
1309 if (!a.email().empty())
1310 os << " (" << a.email() << ")";
1311 // FIXME ctime is english, we should translate that
1312 os << _(" at ") << ctime(&change.changetime);
1316 // I think we should only show changes from the default
1318 // No, from the document font (MV)
1319 Font font = cur.real_current_font;
1320 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1322 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1324 // The paragraph depth
1325 int depth = cur.paragraph().getDepth();
1327 os << bformat(_(", Depth: %1$d"), depth);
1329 // The paragraph spacing, but only if different from
1331 Spacing const & spacing = par.params().spacing();
1332 if (!spacing.isDefault()) {
1333 os << _(", Spacing: ");
1334 switch (spacing.getSpace()) {
1335 case Spacing::Single:
1338 case Spacing::Onehalf:
1341 case Spacing::Double:
1344 case Spacing::Other:
1345 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1347 case Spacing::Default:
1348 // should never happen, do nothing
1353 #ifdef DEVEL_VERSION
1354 os << _(", Inset: ") << &cur.inset();
1355 os << _(", Paragraph: ") << cur.pit();
1356 os << _(", Id: ") << par.id();
1357 os << _(", Position: ") << cur.pos();
1358 // FIXME: Why is the check for par.size() needed?
1359 // We are called with cur.pos() == par.size() quite often.
1360 if (!par.empty() && cur.pos() < par.size()) {
1361 // Force output of code point, not character
1362 size_t const c = par.getChar(cur.pos());
1363 os << _(", Char: 0x") << hex << c;
1365 os << _(", Boundary: ") << cur.boundary();
1366 // Row & row = cur.textRow();
1367 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1373 docstring Text::getPossibleLabel(Cursor & cur) const
1375 pit_type pit = cur.pit();
1377 Layout const * layout = &(pars_[pit].layout());
1380 docstring par_text = pars_[pit].asString();
1382 // the return string of math matrices might contain linebreaks
1383 par_text = subst(par_text, '\n', '-');
1384 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1385 if (par_text.empty())
1388 par_text = split(par_text, head, ' ');
1389 // Is it legal to use spaces in labels ?
1395 // No need for a prefix if the user said so.
1396 if (lyxrc.label_init_length <= 0)
1399 // Will contain the label type.
1402 // For section, subsection, etc...
1403 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1404 Layout const * layout2 = &(pars_[pit - 1].layout());
1405 if (layout2->latextype != LATEX_PARAGRAPH) {
1410 if (layout->latextype != LATEX_PARAGRAPH)
1411 name = from_ascii(layout->latexname());
1413 // for captions, we just take the caption type
1414 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1416 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1418 // If none of the above worked, we'll see if we're inside various
1419 // types of insets and take our abbreviation from them.
1421 InsetCode const codes[] = {
1426 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1427 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1429 name = float_inset->name();
1435 // Create a correct prefix for prettyref
1436 if (name == "theorem")
1437 name = from_ascii("thm");
1438 else if (name == "Foot")
1439 name = from_ascii("fn");
1440 else if (name == "listing")
1441 name = from_ascii("lst");
1444 text = name.substr(0, 3) + ':' + text;
1450 void Text::charsTranspose(Cursor & cur)
1452 LASSERT(this == cur.text(), /**/);
1454 pos_type pos = cur.pos();
1456 // If cursor is at beginning or end of paragraph, do nothing.
1457 if (pos == cur.lastpos() || pos == 0)
1460 Paragraph & par = cur.paragraph();
1462 // Get the positions of the characters to be transposed.
1463 pos_type pos1 = pos - 1;
1464 pos_type pos2 = pos;
1466 // In change tracking mode, ignore deleted characters.
1467 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1469 if (pos2 == cur.lastpos())
1472 while (pos1 >= 0 && par.isDeleted(pos1))
1477 // Don't do anything if one of the "characters" is not regular text.
1478 if (par.isInset(pos1) || par.isInset(pos2))
1481 // Store the characters to be transposed (including font information).
1482 char_type char1 = par.getChar(pos1);
1484 par.getFontSettings(cur.buffer().params(), pos1);
1486 char_type char2 = par.getChar(pos2);
1488 par.getFontSettings(cur.buffer().params(), pos2);
1490 // And finally, we are ready to perform the transposition.
1491 // Track the changes if Change Tracking is enabled.
1492 bool const trackChanges = cur.buffer().params().trackChanges;
1496 par.eraseChar(pos2, trackChanges);
1497 par.eraseChar(pos1, trackChanges);
1498 par.insertChar(pos1, char2, font2, trackChanges);
1499 par.insertChar(pos2, char1, font1, trackChanges);
1501 cur.checkBufferStructure();
1503 // After the transposition, move cursor to after the transposition.
1504 setCursor(cur, cur.pit(), pos2);
1509 DocIterator Text::macrocontextPosition() const
1511 return macrocontext_position_;
1515 void Text::setMacrocontextPosition(DocIterator const & pos)
1517 macrocontext_position_ = pos;
1521 docstring Text::previousWord(CursorSlice const & sl) const
1523 CursorSlice from = sl;
1524 CursorSlice to = sl;
1525 getWord(from, to, PREVIOUS_WORD);
1526 if (sl == from || to == from)
1529 Paragraph const & par = sl.paragraph();
1530 return par.asString(from.pos(), to.pos());
1534 bool Text::completionSupported(Cursor const & cur) const
1536 Paragraph const & par = cur.paragraph();
1537 return cur.pos() > 0
1538 && (cur.pos() >= par.size() || !par.isLetter(cur.pos()))
1539 && par.isLetter(cur.pos() - 1);
1543 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1545 return new TextCompletionList(cur);
1549 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1551 LASSERT(cur.bv().cursor() == cur, /**/);
1553 cur.bv().cursor() = cur;
1554 if (!(cur.disp_.update() & Update::Force))
1555 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
1560 docstring Text::completionPrefix(Cursor const & cur) const
1562 return previousWord(cur.top());