3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Dov Feldstern
9 * \author Jean-Marc Lasgouttes
11 * \author André Pönitz
12 * \author Stefan Schimanski
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "CompletionList.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
37 #include "FontIterator.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/InsetHFill.h"
56 #include "insets/InsetLine.h"
57 #include "insets/InsetNewline.h"
58 #include "insets/InsetNewpage.h"
59 #include "insets/InsetOptArg.h"
60 #include "insets/InsetSpace.h"
61 #include "insets/InsetSpecialChar.h"
62 #include "insets/InsetTabular.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/docstream.h"
67 #include "support/gettext.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.forceEmptyLayout()) {
107 // in this case only the empty layout is allowed
108 layoutname = tclass.emptyLayoutName();
109 } else if (par.useEmptyLayout()) {
110 // in this case, default layout maps to empty layout
111 if (layoutname == tclass.defaultLayoutName())
112 layoutname = tclass.emptyLayoutName();
114 // otherwise, the empty layout maps to the default
115 if (layoutname == tclass.emptyLayoutName())
116 layoutname = tclass.defaultLayoutName();
119 bool hasLayout = tclass.hasLayout(layoutname);
122 errorList.push_back(ErrorItem(_("Unknown layout"),
123 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
124 layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
125 layoutname = par.useEmptyLayout() ?
126 tclass.emptyLayoutName() :
127 tclass.defaultLayoutName();
130 par.setLayout(bp.documentClass()[layoutname]);
132 // Test whether the layout is obsolete.
133 Layout const & layout = par.layout();
134 if (!layout.obsoleted_by().empty())
135 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
137 par.params().read(lex);
139 } else if (token == "\\end_layout") {
140 LYXERR0("Solitary \\end_layout in line " << lex.getLineNo() << "\n"
141 << "Missing \\begin_layout ?");
142 } else if (token == "\\end_inset") {
143 LYXERR0("Solitary \\end_inset in line " << lex.getLineNo() << "\n"
144 << "Missing \\begin_inset ?");
145 } else if (token == "\\begin_inset") {
146 Inset * inset = readInset(lex, buf);
148 par.insertInset(par.size(), inset, font, change);
151 docstring line = lex.getDocString();
152 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
153 par.id(), 0, par.size()));
155 } else if (token == "\\family") {
157 setLyXFamily(lex.getString(), font.fontInfo());
158 } else if (token == "\\series") {
160 setLyXSeries(lex.getString(), font.fontInfo());
161 } else if (token == "\\shape") {
163 setLyXShape(lex.getString(), font.fontInfo());
164 } else if (token == "\\size") {
166 setLyXSize(lex.getString(), font.fontInfo());
167 } else if (token == "\\lang") {
169 string const tok = lex.getString();
170 Language const * lang = languages.getLanguage(tok);
172 font.setLanguage(lang);
174 font.setLanguage(bp.language);
175 lex.printError("Unknown language `$$Token'");
177 } else if (token == "\\numeric") {
179 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
180 } else if (token == "\\emph") {
182 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
183 } else if (token == "\\bar") {
185 string const tok = lex.getString();
188 font.fontInfo().setUnderbar(FONT_ON);
189 else if (tok == "no")
190 font.fontInfo().setUnderbar(FONT_OFF);
191 else if (tok == "default")
192 font.fontInfo().setUnderbar(FONT_INHERIT);
194 lex.printError("Unknown bar font flag "
196 } else if (token == "\\noun") {
198 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
199 } else if (token == "\\color") {
201 setLyXColor(lex.getString(), font.fontInfo());
202 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
204 // Insets don't make sense in a free-spacing context! ---Kayvan
205 if (par.isFreeSpacing()) {
206 if (token == "\\InsetSpace")
207 par.appendChar(' ', font, change);
208 else if (lex.isOK()) {
210 string const next_token = lex.getString();
211 if (next_token == "\\-")
212 par.appendChar('-', font, change);
214 lex.printError("Token `$$Token' "
216 "paragraph layout!");
220 auto_ptr<Inset> inset;
221 if (token == "\\SpecialChar" )
222 inset.reset(new InsetSpecialChar);
224 inset.reset(new InsetSpace);
226 par.insertInset(par.size(), inset.release(),
229 } else if (token == "\\backslash") {
230 par.appendChar('\\', font, change);
231 } else if (token == "\\linebreak") {
232 auto_ptr<Inset> inset(new InsetLinebreak);
234 par.insertInset(par.size(), inset.release(), font, change);
235 } else if (token == "\\newline") {
236 auto_ptr<Inset> inset(new InsetNewline);
238 par.insertInset(par.size(), inset.release(), font, change);
239 } else if (token == "\\LyXTable") {
240 auto_ptr<Inset> inset(new InsetTabular(buf));
242 par.insertInset(par.size(), inset.release(), font, change);
243 } else if (token == "\\hfill") {
244 par.insertInset(par.size(), new InsetHFill, font, change);
245 } else if (token == "\\lyxline") {
246 par.insertInset(par.size(), new InsetLine, font, change);
247 } else if (token == "\\newpage") {
248 par.insertInset(par.size(), new InsetNewpage, font, change);
249 } else if (token == "\\pagebreak") {
250 par.insertInset(par.size(), new InsetPagebreak, font, change);
251 } else if (token == "\\clearpage") {
252 par.insertInset(par.size(), new InsetClearPage, font, change);
253 } else if (token == "\\cleardoublepage") {
254 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
255 } else if (token == "\\change_unchanged") {
256 change = Change(Change::UNCHANGED);
257 } else if (token == "\\change_inserted") {
259 istringstream is(lex.getString());
263 if (aid >= bp.author_map.size()) {
264 errorList.push_back(ErrorItem(_("Change tracking error"),
265 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
266 par.id(), 0, par.size()));
267 change = Change(Change::UNCHANGED);
269 change = Change(Change::INSERTED, bp.author_map[aid], ct);
270 } else if (token == "\\change_deleted") {
272 istringstream is(lex.getString());
276 if (aid >= bp.author_map.size()) {
277 errorList.push_back(ErrorItem(_("Change tracking error"),
278 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
279 par.id(), 0, par.size()));
280 change = Change(Change::UNCHANGED);
282 change = Change(Change::DELETED, bp.author_map[aid], ct);
285 errorList.push_back(ErrorItem(_("Unknown token"),
286 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
288 par.id(), 0, par.size()));
293 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
294 ErrorList & errorList)
297 string token = lex.getString();
299 Change change(Change::UNCHANGED);
302 readParToken(buf, par, lex, token, font, change, errorList);
305 token = lex.getString();
310 if (token == "\\end_layout") {
311 //Ok, paragraph finished
315 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
316 if (token == "\\begin_layout" || token == "\\end_document"
317 || token == "\\end_inset" || token == "\\begin_deeper"
318 || token == "\\end_deeper") {
319 lex.pushToken(token);
320 lyxerr << "Paragraph ended in line "
321 << lex.getLineNo() << "\n"
322 << "Missing \\end_layout.\n";
326 // Final change goes to paragraph break:
327 par.setChange(par.size(), change);
329 // Initialize begin_of_body_ on load; redoParagraph maintains
330 par.setBeginOfBody();
336 class TextCompletionList : public CompletionList
340 TextCompletionList(Cursor const & cur)
341 : buf_(cur.buffer()), pos_(0) {}
343 virtual ~TextCompletionList() {}
346 virtual bool sorted() const { return true; }
348 virtual size_t size() const
350 return theWordList().size();
353 virtual docstring const & data(size_t idx) const
355 return theWordList().word(idx);
366 bool Text::empty() const
368 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
369 // FIXME: Should we consider the labeled type as empty too?
370 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
374 double Text::spacing(Buffer const & buffer, Paragraph const & par) const
376 if (par.params().spacing().isDefault())
377 return buffer.params().spacing().getValue();
378 return par.params().spacing().getValue();
382 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
384 BOOST_ASSERT(this == cur.text());
386 Paragraph & cpar = cur.paragraph();
387 pit_type cpit = cur.pit();
389 DocumentClass const & tclass = cur.buffer().params().documentClass();
390 Layout const & layout = cpar.layout();
392 // this is only allowed, if the current paragraph is not empty
393 // or caption and if it has not the keepempty flag active
394 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
395 layout.labeltype != LABEL_SENSITIVE)
398 // a layout change may affect also the following paragraph
399 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
401 // Always break behind a space
402 // It is better to erase the space (Dekel)
403 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
404 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
406 // What should the layout for the new paragraph be?
407 bool keep_layout = inverse_logic ?
408 !layout.isEnvironment()
409 : layout.isEnvironment();
411 // We need to remember this before we break the paragraph, because
412 // that invalidates the layout variable
413 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
415 // we need to set this before we insert the paragraph.
416 bool const isempty = cpar.allowEmpty() && cpar.empty();
418 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
419 cur.pos(), keep_layout);
421 // After this, neither paragraph contains any rows!
424 pit_type next_par = cpit + 1;
426 // well this is the caption hack since one caption is really enough
429 // set to standard-layout
430 //FIXME Check if this should be emptyLayout() in some cases
431 pars_[cpit].applyLayout(tclass.defaultLayout());
433 // set to standard-layout
434 //FIXME Check if this should be emptyLayout() in some cases
435 pars_[next_par].applyLayout(tclass.defaultLayout());
438 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
439 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
440 break; // the character couldn't be deleted physically due to change tracking
443 updateLabels(cur.buffer());
445 // A singlePar update is not enough in this case.
446 cur.updateFlags(Update::Force);
448 // This check is necessary. Otherwise the new empty paragraph will
449 // be deleted automatically. And it is more friendly for the user!
450 if (cur.pos() != 0 || isempty)
451 setCursor(cur, cur.pit() + 1, 0);
453 setCursor(cur, cur.pit(), 0);
457 // insert a character, moves all the following breaks in the
458 // same Paragraph one to the right and make a rebreak
459 void Text::insertChar(Cursor & cur, char_type c)
461 BOOST_ASSERT(this == cur.text());
463 cur.recordUndo(INSERT_UNDO);
465 TextMetrics const & tm = cur.bv().textMetrics(this);
466 Buffer const & buffer = cur.buffer();
467 Paragraph & par = cur.paragraph();
468 // try to remove this
469 pit_type const pit = cur.pit();
471 bool const freeSpacing = par.layout().free_spacing ||
474 if (lyxrc.auto_number) {
475 static docstring const number_operators = from_ascii("+-/*");
476 static docstring const number_unary_operators = from_ascii("+-");
477 static docstring const number_seperators = from_ascii(".,:");
479 if (cur.current_font.fontInfo().number() == FONT_ON) {
480 if (!isDigit(c) && !contains(number_operators, c) &&
481 !(contains(number_seperators, c) &&
483 cur.pos() != cur.lastpos() &&
484 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
485 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
487 number(cur); // Set current_font.number to OFF
488 } else if (isDigit(c) &&
489 cur.real_current_font.isVisibleRightToLeft()) {
490 number(cur); // Set current_font.number to ON
492 if (cur.pos() != 0) {
493 char_type const c = par.getChar(cur.pos() - 1);
494 if (contains(number_unary_operators, c) &&
496 || par.isSeparator(cur.pos() - 2)
497 || par.isNewline(cur.pos() - 2))
499 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
501 } else if (contains(number_seperators, c)
503 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
504 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
511 // In Bidi text, we want spaces to be treated in a special way: spaces
512 // which are between words in different languages should get the
513 // paragraph's language; otherwise, spaces should keep the language
514 // they were originally typed in. This is only in effect while typing;
515 // after the text is already typed in, the user can always go back and
516 // explicitly set the language of a space as desired. But 99.9% of the
517 // time, what we're doing here is what the user actually meant.
519 // The following cases are the ones in which the language of the space
520 // should be changed to match that of the containing paragraph. In the
521 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
522 // represents a space, pipe (|) represents the cursor position (so the
523 // character before it is the one just typed in). The different cases
524 // are depicted logically (not visually), from left to right:
529 // Theoretically, there are other situations that we should, perhaps, deal
530 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
531 // point (to understand why, just try to create this situation...).
533 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
534 // get font in front and behind the space in question. But do NOT
535 // use getFont(cur.pos()) because the character c is not inserted yet
536 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
537 Font const & post_space_font = cur.real_current_font;
538 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
539 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
541 if (pre_space_rtl != post_space_rtl) {
542 // Set the space's language to match the language of the
543 // adjacent character whose direction is the paragraph's
544 // direction; don't touch other properties of the font
545 Language const * lang =
546 (pre_space_rtl == par.isRTL(buffer.params())) ?
547 pre_space_font.language() : post_space_font.language();
549 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
550 space_font.setLanguage(lang);
551 par.setFont(cur.pos() - 1, space_font);
555 // Next check, if there will be two blanks together or a blank at
556 // the beginning of a paragraph.
557 // I decided to handle blanks like normal characters, the main
558 // difference are the special checks when calculating the row.fill
559 // (blank does not count at the end of a row) and the check here
561 // When the free-spacing option is set for the current layout,
562 // disable the double-space checking
563 if (!freeSpacing && isLineSeparatorChar(c)) {
564 if (cur.pos() == 0) {
565 static bool sent_space_message = false;
566 if (!sent_space_message) {
567 cur.message(_("You cannot insert a space at the "
568 "beginning of a paragraph. Please read the Tutorial."));
569 sent_space_message = true;
573 BOOST_ASSERT(cur.pos() > 0);
574 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
575 && !par.isDeleted(cur.pos() - 1)) {
576 static bool sent_space_message = false;
577 if (!sent_space_message) {
578 cur.message(_("You cannot type two spaces this way. "
579 "Please read the Tutorial."));
580 sent_space_message = true;
586 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
587 cur.checkBufferStructure();
589 // cur.updateFlags(Update::Force);
590 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
595 void Text::charInserted(Cursor & cur)
597 Paragraph & par = cur.paragraph();
599 // Here we call finishUndo for every 20 characters inserted.
600 // This is from my experience how emacs does it. (Lgb)
601 static unsigned int counter;
609 // register word if a non-letter was entered
611 && par.isLetter(cur.pos() - 2)
612 && !par.isLetter(cur.pos() - 1)) {
613 // get the word in front of cursor
614 BOOST_ASSERT(this == cur.text());
615 cur.paragraph().updateWords(cur.top());
620 // the cursor set functions have a special mechanism. When they
621 // realize, that you left an empty paragraph, they will delete it.
623 bool Text::cursorForwardOneWord(Cursor & cur)
625 BOOST_ASSERT(this == cur.text());
629 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
633 // Advance through word.
634 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
636 // Skip through trailing nonword stuff.
637 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
640 return setCursor(cur, old.pit(), old.pos());
644 bool Text::cursorBackwardOneWord(Cursor & cur)
646 BOOST_ASSERT(this == cur.text());
650 if (old.pos() == 0 && old.pit() != 0) {
652 old.pos() = old.lastpos();
654 // Skip through initial nonword stuff.
655 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
657 // Advance through word.
658 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
661 return setCursor(cur, old.pit(), old.pos());
665 void Text::selectWord(Cursor & cur, word_location loc)
667 BOOST_ASSERT(this == cur.text());
668 CursorSlice from = cur.top();
669 CursorSlice to = cur.top();
670 getWord(from, to, loc);
671 if (cur.top() != from)
672 setCursor(cur, from.pit(), from.pos());
676 setCursor(cur, to.pit(), to.pos());
681 // Select the word currently under the cursor when no
682 // selection is currently set
683 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
685 BOOST_ASSERT(this == cur.text());
688 selectWord(cur, loc);
689 return cur.selection();
693 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
695 BOOST_ASSERT(this == cur.text());
697 if (!cur.selection())
700 cur.recordUndoSelection();
702 pit_type begPit = cur.selectionBegin().pit();
703 pit_type endPit = cur.selectionEnd().pit();
705 pos_type begPos = cur.selectionBegin().pos();
706 pos_type endPos = cur.selectionEnd().pos();
708 // keep selection info, because endPos becomes invalid after the first loop
709 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
711 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
713 for (pit_type pit = begPit; pit <= endPit; ++pit) {
714 pos_type parSize = pars_[pit].size();
716 // ignore empty paragraphs; otherwise, an assertion will fail for
717 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
721 // do not consider first paragraph if the cursor starts at pos size()
722 if (pit == begPit && begPos == parSize)
725 // do not consider last paragraph if the cursor ends at pos 0
726 if (pit == endPit && endPos == 0)
727 break; // last iteration anyway
729 pos_type left = (pit == begPit ? begPos : 0);
730 pos_type right = (pit == endPit ? endPos : parSize);
733 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
735 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
739 // next, accept/reject imaginary end-of-par characters
741 for (pit_type pit = begPit; pit <= endPit; ++pit) {
742 pos_type pos = pars_[pit].size();
744 // skip if the selection ends before the end-of-par
745 if (pit == endPit && endsBeforeEndOfPar)
746 break; // last iteration anyway
748 // skip if this is not the last paragraph of the document
749 // note: the user should be able to accept/reject the par break of the last par!
750 if (pit == endPit && pit + 1 != int(pars_.size()))
751 break; // last iteration anway
754 if (pars_[pit].isInserted(pos)) {
755 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
756 } else if (pars_[pit].isDeleted(pos)) {
757 if (pit + 1 == int(pars_.size())) {
758 // we cannot remove a par break at the end of the last paragraph;
759 // instead, we mark it unchanged
760 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
762 mergeParagraph(cur.buffer().params(), pars_, pit);
768 if (pars_[pit].isDeleted(pos)) {
769 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
770 } else if (pars_[pit].isInserted(pos)) {
771 if (pit + 1 == int(pars_.size())) {
772 // we mark the par break at the end of the last paragraph unchanged
773 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
775 mergeParagraph(cur.buffer().params(), pars_, pit);
783 // finally, invoke the DEPM
785 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
790 cur.clearSelection();
791 setCursorIntern(cur, begPit, begPos);
792 cur.updateFlags(Update::Force);
793 updateLabels(cur.buffer());
797 void Text::acceptChanges(BufferParams const & bparams)
799 lyx::acceptChanges(pars_, bparams);
800 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
804 void Text::rejectChanges(BufferParams const & bparams)
806 pit_type pars_size = static_cast<pit_type>(pars_.size());
808 // first, reject changes within each individual paragraph
809 // (do not consider end-of-par)
810 for (pit_type pit = 0; pit < pars_size; ++pit) {
811 if (!pars_[pit].empty()) // prevent assertion failure
812 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
815 // next, reject imaginary end-of-par characters
816 for (pit_type pit = 0; pit < pars_size; ++pit) {
817 pos_type pos = pars_[pit].size();
819 if (pars_[pit].isDeleted(pos)) {
820 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
821 } else if (pars_[pit].isInserted(pos)) {
822 if (pit == pars_size - 1) {
823 // we mark the par break at the end of the last
824 // paragraph unchanged
825 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
827 mergeParagraph(bparams, pars_, pit);
834 // finally, invoke the DEPM
835 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
839 void Text::deleteWordForward(Cursor & cur)
841 BOOST_ASSERT(this == cur.text());
842 if (cur.lastpos() == 0)
846 cur.selection() = true;
847 cursorForwardOneWord(cur);
849 cutSelection(cur, true, false);
850 cur.checkBufferStructure();
855 void Text::deleteWordBackward(Cursor & cur)
857 BOOST_ASSERT(this == cur.text());
858 if (cur.lastpos() == 0)
862 cur.selection() = true;
863 cursorBackwardOneWord(cur);
865 cutSelection(cur, true, false);
866 cur.checkBufferStructure();
871 // Kill to end of line.
872 void Text::changeCase(Cursor & cur, TextCase action)
874 BOOST_ASSERT(this == cur.text());
879 if (cur.selection()) {
880 from = cur.selBegin();
885 getWord(from, to, PARTIAL_WORD);
886 cursorForwardOneWord(cur);
889 cur.recordUndoSelection();
891 pit_type begPit = from.pit();
892 pit_type endPit = to.pit();
894 pos_type begPos = from.pos();
895 pos_type endPos = to.pos();
897 pos_type right = 0; // needed after the for loop
899 for (pit_type pit = begPit; pit <= endPit; ++pit) {
900 Paragraph & par = pars_[pit];
901 pos_type const pos = (pit == begPit ? begPos : 0);
902 right = (pit == endPit ? endPos : par.size());
903 par.changeCase(cur.buffer().params(), pos, right, action);
906 // the selection may have changed due to logically-only deleted chars
908 setCursor(cur, begPit, begPos);
910 setCursor(cur, endPit, right);
913 setCursor(cur, endPit, right);
915 cur.checkBufferStructure();
919 bool Text::handleBibitems(Cursor & cur)
921 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
927 BufferParams const & bufparams = cur.buffer().params();
928 Paragraph const & par = cur.paragraph();
929 Cursor prevcur = cur;
932 prevcur.pos() = prevcur.lastpos();
934 Paragraph const & prevpar = prevcur.paragraph();
936 // if a bibitem is deleted, merge with previous paragraph
937 // if this is a bibliography item as well
938 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
939 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
940 mergeParagraph(bufparams, cur.text()->paragraphs(),
942 updateLabels(cur.buffer());
943 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
944 cur.updateFlags(Update::Force);
948 // otherwise reset to default
949 cur.paragraph().setEmptyOrDefaultLayout(bufparams.documentClass());
954 bool Text::erase(Cursor & cur)
956 BOOST_ASSERT(this == cur.text());
957 bool needsUpdate = false;
958 Paragraph & par = cur.paragraph();
960 if (cur.pos() != cur.lastpos()) {
961 // this is the code for a normal delete, not pasting
963 cur.recordUndo(DELETE_UNDO);
964 bool const was_inset = cur.paragraph().isInset(cur.pos());
965 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges))
966 // the character has been logically deleted only => skip it
967 cur.top().forwardPos();
970 updateLabels(cur.buffer());
972 cur.checkBufferStructure();
975 if (cur.pit() == cur.lastpit())
976 return dissolveInset(cur);
978 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
979 par.setChange(cur.pos(), Change(Change::DELETED));
983 setCursorIntern(cur, cur.pit() + 1, 0);
984 needsUpdate = backspacePos0(cur);
988 needsUpdate |= handleBibitems(cur);
991 // Make sure the cursor is correct. Is this really needed?
992 // No, not really... at least not here!
993 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
994 cur.checkBufferStructure();
1001 bool Text::backspacePos0(Cursor & cur)
1003 BOOST_ASSERT(this == cur.text());
1007 bool needsUpdate = false;
1009 BufferParams const & bufparams = cur.buffer().params();
1010 DocumentClass const & tclass = bufparams.documentClass();
1011 ParagraphList & plist = cur.text()->paragraphs();
1012 Paragraph const & par = cur.paragraph();
1013 Cursor prevcur = cur;
1015 prevcur.pos() = prevcur.lastpos();
1016 Paragraph const & prevpar = prevcur.paragraph();
1018 // is it an empty paragraph?
1019 if (cur.lastpos() == 0
1020 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1021 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1022 plist.erase(boost::next(plist.begin(), cur.pit()));
1025 // is previous par empty?
1026 else if (prevcur.lastpos() == 0
1027 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1028 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1029 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1032 // Pasting is not allowed, if the paragraphs have different
1033 // layouts. I think it is a real bug of all other
1034 // word processors to allow it. It confuses the user.
1035 // Correction: Pasting is always allowed with standard-layout
1036 // or the empty layout.
1037 else if (par.layout() == prevpar.layout()
1038 || tclass.isDefaultLayout(par.layout())
1039 || tclass.isEmptyLayout(par.layout())) {
1040 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1041 mergeParagraph(bufparams, plist, prevcur.pit());
1046 updateLabels(cur.buffer());
1047 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1054 bool Text::backspace(Cursor & cur)
1056 BOOST_ASSERT(this == cur.text());
1057 bool needsUpdate = false;
1058 if (cur.pos() == 0) {
1060 return dissolveInset(cur);
1062 Paragraph & prev_par = pars_[cur.pit() - 1];
1064 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1065 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1066 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1069 // The cursor is at the beginning of a paragraph, so
1070 // the backspace will collapse two paragraphs into one.
1071 needsUpdate = backspacePos0(cur);
1074 // this is the code for a normal backspace, not pasting
1076 cur.recordUndo(DELETE_UNDO);
1077 // We used to do cursorBackwardIntern() here, but it is
1078 // not a good idea since it triggers the auto-delete
1079 // mechanism. So we do a cursorBackwardIntern()-lite,
1080 // without the dreaded mechanism. (JMarc)
1081 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1082 false, cur.boundary());
1083 bool const was_inset = cur.paragraph().isInset(cur.pos());
1084 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1086 updateLabels(cur.buffer());
1088 cur.checkBufferStructure();
1091 if (cur.pos() == cur.lastpos())
1092 cur.setCurrentFont();
1094 needsUpdate |= handleBibitems(cur);
1096 // A singlePar update is not enough in this case.
1097 // cur.updateFlags(Update::Force);
1098 setCursor(cur.top(), cur.pit(), cur.pos());
1104 bool Text::dissolveInset(Cursor & cur) {
1105 BOOST_ASSERT(this == cur.text());
1107 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1110 cur.recordUndoInset();
1112 cur.selHandle(false);
1114 pos_type spos = cur.pos();
1115 pit_type spit = cur.pit();
1116 ParagraphList plist;
1117 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1118 plist = paragraphs();
1120 // store cursor offset
1124 Buffer & b = cur.buffer();
1125 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1126 if (!plist.empty()) {
1127 // ERT paragraphs have the Language latex_language.
1128 // This is invalid outside of ERT, so we need to
1129 // change it to the buffer language.
1130 ParagraphList::iterator it = plist.begin();
1131 ParagraphList::iterator it_end = plist.end();
1132 for (; it != it_end; it++)
1133 it->changeLanguage(b.params(), latex_language, b.language());
1135 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1136 b.errorList("Paste"));
1138 cur.pit() = min(cur.lastpit(), spit);
1139 cur.pos() = min(cur.lastpos(), spos);
1141 cur.clearSelection();
1147 void Text::getWord(CursorSlice & from, CursorSlice & to,
1148 word_location const loc) const
1150 Paragraph const & from_par = pars_[from.pit()];
1152 case WHOLE_WORD_STRICT:
1153 if (from.pos() == 0 || from.pos() == from_par.size()
1154 || !from_par.isLetter(from.pos())
1155 || !from_par.isLetter(from.pos() - 1)) {
1159 // no break here, we go to the next
1162 // If we are already at the beginning of a word, do nothing
1163 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1165 // no break here, we go to the next
1168 // always move the cursor to the beginning of previous word
1169 while (from.pos() && from_par.isLetter(from.pos() - 1))
1173 LYXERR0("Text::getWord: NEXT_WORD not implemented yet");
1176 // no need to move the 'from' cursor
1180 Paragraph const & to_par = pars_[to.pit()];
1181 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1186 void Text::write(Buffer const & buf, ostream & os) const
1188 ParagraphList::const_iterator pit = paragraphs().begin();
1189 ParagraphList::const_iterator end = paragraphs().end();
1191 for (; pit != end; ++pit)
1192 pit->write(os, buf.params(), dth);
1194 // Close begin_deeper
1195 for(; dth > 0; --dth)
1196 os << "\n\\end_deeper";
1200 bool Text::read(Buffer const & buf, Lexer & lex,
1201 ErrorList & errorList, InsetText * insetPtr)
1203 depth_type depth = 0;
1205 while (lex.isOK()) {
1207 string const token = lex.getString();
1212 if (token == "\\end_inset")
1215 if (token == "\\end_body")
1218 if (token == "\\begin_body")
1221 if (token == "\\end_document")
1224 if (token == "\\begin_layout") {
1225 lex.pushToken(token);
1228 par.params().depth(depth);
1229 par.setFont(0, Font(inherit_font, buf.params().language));
1230 par.setInsetOwner(insetPtr);
1231 pars_.push_back(par);
1233 // FIXME: goddamn InsetTabular makes us pass a Buffer
1235 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1237 // register the words in the global word list
1238 CursorSlice sl = CursorSlice(*insetPtr);
1239 sl.pit() = pars_.size() - 1;
1240 pars_.back().updateWords(sl);
1241 } else if (token == "\\begin_deeper") {
1243 } else if (token == "\\end_deeper") {
1245 lex.printError("\\end_deeper: " "depth is already null");
1249 LYXERR0("Handling unknown body token: `" << token << '\'');
1255 // Returns the current font and depth as a message.
1256 docstring Text::currentState(Cursor & cur)
1258 BOOST_ASSERT(this == cur.text());
1259 Buffer & buf = cur.buffer();
1260 Paragraph const & par = cur.paragraph();
1261 odocstringstream os;
1263 if (buf.params().trackChanges)
1264 os << _("[Change Tracking] ");
1266 Change change = par.lookupChange(cur.pos());
1268 if (change.type != Change::UNCHANGED) {
1269 Author const & a = buf.params().authors().get(change.author);
1270 os << _("Change: ") << a.name();
1271 if (!a.email().empty())
1272 os << " (" << a.email() << ")";
1273 // FIXME ctime is english, we should translate that
1274 os << _(" at ") << ctime(&change.changetime);
1278 // I think we should only show changes from the default
1280 // No, from the document font (MV)
1281 Font font = cur.real_current_font;
1282 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1284 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1286 // The paragraph depth
1287 int depth = cur.paragraph().getDepth();
1289 os << bformat(_(", Depth: %1$d"), depth);
1291 // The paragraph spacing, but only if different from
1293 Spacing const & spacing = par.params().spacing();
1294 if (!spacing.isDefault()) {
1295 os << _(", Spacing: ");
1296 switch (spacing.getSpace()) {
1297 case Spacing::Single:
1300 case Spacing::Onehalf:
1303 case Spacing::Double:
1306 case Spacing::Other:
1307 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1309 case Spacing::Default:
1310 // should never happen, do nothing
1315 #ifdef DEVEL_VERSION
1316 os << _(", Inset: ") << &cur.inset();
1317 os << _(", Paragraph: ") << cur.pit();
1318 os << _(", Id: ") << par.id();
1319 os << _(", Position: ") << cur.pos();
1320 // FIXME: Why is the check for par.size() needed?
1321 // We are called with cur.pos() == par.size() quite often.
1322 if (!par.empty() && cur.pos() < par.size()) {
1323 // Force output of code point, not character
1324 size_t const c = par.getChar(cur.pos());
1325 os << _(", Char: 0x") << hex << c;
1327 os << _(", Boundary: ") << cur.boundary();
1328 // Row & row = cur.textRow();
1329 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1335 docstring Text::getPossibleLabel(Cursor & cur) const
1337 pit_type pit = cur.pit();
1339 Layout const * layout = &(pars_[pit].layout());
1342 docstring par_text = pars_[pit].asString(false);
1344 // the return string of math matrices might contain linebreaks
1345 par_text = subst(par_text, '\n', '-');
1346 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1347 if (par_text.empty())
1350 par_text = split(par_text, head, ' ');
1351 // Is it legal to use spaces in labels ?
1357 // No need for a prefix if the user said so.
1358 if (lyxrc.label_init_length <= 0)
1361 // Will contain the label type.
1364 // For section, subsection, etc...
1365 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1366 Layout const * layout2 = &(pars_[pit - 1].layout());
1367 if (layout2->latextype != LATEX_PARAGRAPH) {
1372 if (layout->latextype != LATEX_PARAGRAPH)
1373 name = from_ascii(layout->latexname());
1375 // for captions, we just take the caption type
1376 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1378 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1380 // If none of the above worked, we'll see if we're inside various
1381 // types of insets and take our abbreviation from them.
1383 InsetCode const codes[] = {
1388 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1389 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1391 name = float_inset->name();
1397 // Create a correct prefix for prettyref
1398 if (name == "theorem")
1399 name = from_ascii("thm");
1400 else if (name == "Foot")
1401 name = from_ascii("fn");
1402 else if (name == "listing")
1403 name = from_ascii("lst");
1406 text = name.substr(0, 3) + ':' + text;
1412 void Text::charsTranspose(Cursor & cur)
1414 BOOST_ASSERT(this == cur.text());
1416 pos_type pos = cur.pos();
1418 // If cursor is at beginning or end of paragraph, do nothing.
1419 if (pos == cur.lastpos() || pos == 0)
1422 Paragraph & par = cur.paragraph();
1424 // Get the positions of the characters to be transposed.
1425 pos_type pos1 = pos - 1;
1426 pos_type pos2 = pos;
1428 // In change tracking mode, ignore deleted characters.
1429 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1431 if (pos2 == cur.lastpos())
1434 while (pos1 >= 0 && par.isDeleted(pos1))
1439 // Don't do anything if one of the "characters" is not regular text.
1440 if (par.isInset(pos1) || par.isInset(pos2))
1443 // Store the characters to be transposed (including font information).
1444 char_type char1 = par.getChar(pos1);
1446 par.getFontSettings(cur.buffer().params(), pos1);
1448 char_type char2 = par.getChar(pos2);
1450 par.getFontSettings(cur.buffer().params(), pos2);
1452 // And finally, we are ready to perform the transposition.
1453 // Track the changes if Change Tracking is enabled.
1454 bool const trackChanges = cur.buffer().params().trackChanges;
1458 par.eraseChar(pos2, trackChanges);
1459 par.eraseChar(pos1, trackChanges);
1460 par.insertChar(pos1, char2, font2, trackChanges);
1461 par.insertChar(pos2, char1, font1, trackChanges);
1463 cur.checkBufferStructure();
1465 // After the transposition, move cursor to after the transposition.
1466 setCursor(cur, cur.pit(), pos2);
1471 DocIterator Text::macrocontextPosition() const
1473 return macrocontext_position_;
1477 void Text::setMacrocontextPosition(DocIterator const & pos)
1479 macrocontext_position_ = pos;
1483 docstring Text::previousWord(CursorSlice const & sl) const
1485 CursorSlice from = sl;
1486 CursorSlice to = sl;
1487 getWord(from, to, PREVIOUS_WORD);
1488 if (sl == from || to == from)
1491 Paragraph const & par = sl.paragraph();
1492 return par.asString(from.pos(), to.pos(), false);
1496 bool Text::completionSupported(Cursor const & cur) const
1498 Paragraph const & par = cur.paragraph();
1499 return cur.pos() > 0
1500 && (cur.pos() >= par.size() || !par.isLetter(cur.pos()))
1501 && par.isLetter(cur.pos() - 1);
1505 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1507 return new TextCompletionList(cur);
1511 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1513 BOOST_ASSERT(cur.bv().cursor() == cur);
1515 cur.bv().cursor() = cur;
1516 if (!(cur.disp_.update() & Update::Force))
1517 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
1522 docstring Text::completionPrefix(Cursor const & cur) const
1524 return previousWord(cur.top());