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/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/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.getLineNo() << "\n"
140 << "Missing \\begin_layout ?");
141 } else if (token == "\\end_inset") {
142 LYXERR0("Solitary \\end_inset in line " << lex.getLineNo() << "\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 == "\\linebreak") {
210 auto_ptr<Inset> inset(new InsetLinebreak);
212 par.insertInset(par.size(), inset.release(), font, change);
213 } else if (token == "\\newline") {
214 auto_ptr<Inset> inset(new InsetNewline);
216 par.insertInset(par.size(), inset.release(), font, change);
217 } else if (token == "\\LyXTable") {
218 auto_ptr<Inset> inset(new InsetTabular(buf));
220 par.insertInset(par.size(), inset.release(), font, change);
221 } else if (token == "\\lyxline") {
222 par.insertInset(par.size(), new InsetLine, font, change);
223 } else if (token == "\\newpage") {
224 par.insertInset(par.size(), new InsetNewpage, font, change);
225 } else if (token == "\\pagebreak") {
226 par.insertInset(par.size(), new InsetPagebreak, font, change);
227 } else if (token == "\\clearpage") {
228 par.insertInset(par.size(), new InsetClearPage, font, change);
229 } else if (token == "\\cleardoublepage") {
230 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
231 } else if (token == "\\change_unchanged") {
232 change = Change(Change::UNCHANGED);
233 } else if (token == "\\change_inserted") {
235 istringstream is(lex.getString());
239 if (aid >= bp.author_map.size()) {
240 errorList.push_back(ErrorItem(_("Change tracking error"),
241 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
242 par.id(), 0, par.size()));
243 change = Change(Change::UNCHANGED);
245 change = Change(Change::INSERTED, bp.author_map[aid], ct);
246 } else if (token == "\\change_deleted") {
248 istringstream is(lex.getString());
252 if (aid >= bp.author_map.size()) {
253 errorList.push_back(ErrorItem(_("Change tracking error"),
254 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
255 par.id(), 0, par.size()));
256 change = Change(Change::UNCHANGED);
258 change = Change(Change::DELETED, bp.author_map[aid], ct);
261 errorList.push_back(ErrorItem(_("Unknown token"),
262 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
264 par.id(), 0, par.size()));
269 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
270 ErrorList & errorList)
273 string token = lex.getString();
275 Change change(Change::UNCHANGED);
278 readParToken(buf, par, lex, token, font, change, errorList);
281 token = lex.getString();
286 if (token == "\\end_layout") {
287 //Ok, paragraph finished
291 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
292 if (token == "\\begin_layout" || token == "\\end_document"
293 || token == "\\end_inset" || token == "\\begin_deeper"
294 || token == "\\end_deeper") {
295 lex.pushToken(token);
296 lyxerr << "Paragraph ended in line "
297 << lex.getLineNo() << "\n"
298 << "Missing \\end_layout.\n";
302 // Final change goes to paragraph break:
303 par.setChange(par.size(), change);
305 // Initialize begin_of_body_ on load; redoParagraph maintains
306 par.setBeginOfBody();
312 class TextCompletionList : public CompletionList
316 TextCompletionList(Cursor const & cur)
317 : buf_(cur.buffer()), pos_(0) {}
319 virtual ~TextCompletionList() {}
322 virtual bool sorted() const { return true; }
324 virtual size_t size() const
326 return theWordList().size();
329 virtual docstring const & data(size_t idx) const
331 return theWordList().word(idx);
342 bool Text::empty() const
344 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
345 // FIXME: Should we consider the labeled type as empty too?
346 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
350 double Text::spacing(Buffer const & buffer, Paragraph const & par) const
352 if (par.params().spacing().isDefault())
353 return buffer.params().spacing().getValue();
354 return par.params().spacing().getValue();
358 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
360 BOOST_ASSERT(this == cur.text());
362 Paragraph & cpar = cur.paragraph();
363 pit_type cpit = cur.pit();
365 DocumentClass const & tclass = cur.buffer().params().documentClass();
366 Layout const & layout = cpar.layout();
368 // this is only allowed, if the current paragraph is not empty
369 // or caption and if it has not the keepempty flag active
370 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
371 layout.labeltype != LABEL_SENSITIVE)
374 // a layout change may affect also the following paragraph
375 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
377 // Always break behind a space
378 // It is better to erase the space (Dekel)
379 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
380 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
382 // What should the layout for the new paragraph be?
383 bool keep_layout = inverse_logic ?
384 !layout.isEnvironment()
385 : layout.isEnvironment();
387 // We need to remember this before we break the paragraph, because
388 // that invalidates the layout variable
389 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
391 // we need to set this before we insert the paragraph.
392 bool const isempty = cpar.allowEmpty() && cpar.empty();
394 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
395 cur.pos(), keep_layout);
397 // After this, neither paragraph contains any rows!
400 pit_type next_par = cpit + 1;
402 // well this is the caption hack since one caption is really enough
405 // set to standard-layout
406 //FIXME Check if this should be emptyLayout() in some cases
407 pars_[cpit].applyLayout(tclass.defaultLayout());
409 // set to standard-layout
410 //FIXME Check if this should be emptyLayout() in some cases
411 pars_[next_par].applyLayout(tclass.defaultLayout());
414 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
415 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
416 break; // the character couldn't be deleted physically due to change tracking
419 updateLabels(cur.buffer());
421 // A singlePar update is not enough in this case.
422 cur.updateFlags(Update::Force);
424 // This check is necessary. Otherwise the new empty paragraph will
425 // be deleted automatically. And it is more friendly for the user!
426 if (cur.pos() != 0 || isempty)
427 setCursor(cur, cur.pit() + 1, 0);
429 setCursor(cur, cur.pit(), 0);
433 // insert a character, moves all the following breaks in the
434 // same Paragraph one to the right and make a rebreak
435 void Text::insertChar(Cursor & cur, char_type c)
437 BOOST_ASSERT(this == cur.text());
439 cur.recordUndo(INSERT_UNDO);
441 TextMetrics const & tm = cur.bv().textMetrics(this);
442 Buffer const & buffer = cur.buffer();
443 Paragraph & par = cur.paragraph();
444 // try to remove this
445 pit_type const pit = cur.pit();
447 bool const freeSpacing = par.layout().free_spacing ||
450 if (lyxrc.auto_number) {
451 static docstring const number_operators = from_ascii("+-/*");
452 static docstring const number_unary_operators = from_ascii("+-");
453 static docstring const number_seperators = from_ascii(".,:");
455 if (cur.current_font.fontInfo().number() == FONT_ON) {
456 if (!isDigit(c) && !contains(number_operators, c) &&
457 !(contains(number_seperators, c) &&
459 cur.pos() != cur.lastpos() &&
460 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
461 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
463 number(cur); // Set current_font.number to OFF
464 } else if (isDigit(c) &&
465 cur.real_current_font.isVisibleRightToLeft()) {
466 number(cur); // Set current_font.number to ON
468 if (cur.pos() != 0) {
469 char_type const c = par.getChar(cur.pos() - 1);
470 if (contains(number_unary_operators, c) &&
472 || par.isSeparator(cur.pos() - 2)
473 || par.isNewline(cur.pos() - 2))
475 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
477 } else if (contains(number_seperators, c)
479 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
480 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
487 // In Bidi text, we want spaces to be treated in a special way: spaces
488 // which are between words in different languages should get the
489 // paragraph's language; otherwise, spaces should keep the language
490 // they were originally typed in. This is only in effect while typing;
491 // after the text is already typed in, the user can always go back and
492 // explicitly set the language of a space as desired. But 99.9% of the
493 // time, what we're doing here is what the user actually meant.
495 // The following cases are the ones in which the language of the space
496 // should be changed to match that of the containing paragraph. In the
497 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
498 // represents a space, pipe (|) represents the cursor position (so the
499 // character before it is the one just typed in). The different cases
500 // are depicted logically (not visually), from left to right:
505 // Theoretically, there are other situations that we should, perhaps, deal
506 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
507 // point (to understand why, just try to create this situation...).
509 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
510 // get font in front and behind the space in question. But do NOT
511 // use getFont(cur.pos()) because the character c is not inserted yet
512 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
513 Font const & post_space_font = cur.real_current_font;
514 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
515 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
517 if (pre_space_rtl != post_space_rtl) {
518 // Set the space's language to match the language of the
519 // adjacent character whose direction is the paragraph's
520 // direction; don't touch other properties of the font
521 Language const * lang =
522 (pre_space_rtl == par.isRTL(buffer.params())) ?
523 pre_space_font.language() : post_space_font.language();
525 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
526 space_font.setLanguage(lang);
527 par.setFont(cur.pos() - 1, space_font);
531 // Next check, if there will be two blanks together or a blank at
532 // the beginning of a paragraph.
533 // I decided to handle blanks like normal characters, the main
534 // difference are the special checks when calculating the row.fill
535 // (blank does not count at the end of a row) and the check here
537 // When the free-spacing option is set for the current layout,
538 // disable the double-space checking
539 if (!freeSpacing && isLineSeparatorChar(c)) {
540 if (cur.pos() == 0) {
541 static bool sent_space_message = false;
542 if (!sent_space_message) {
543 cur.message(_("You cannot insert a space at the "
544 "beginning of a paragraph. Please read the Tutorial."));
545 sent_space_message = true;
549 BOOST_ASSERT(cur.pos() > 0);
550 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
551 && !par.isDeleted(cur.pos() - 1)) {
552 static bool sent_space_message = false;
553 if (!sent_space_message) {
554 cur.message(_("You cannot type two spaces this way. "
555 "Please read the Tutorial."));
556 sent_space_message = true;
562 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
563 cur.checkBufferStructure();
565 // cur.updateFlags(Update::Force);
566 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
571 void Text::charInserted(Cursor & cur)
573 Paragraph & par = cur.paragraph();
575 // Here we call finishUndo for every 20 characters inserted.
576 // This is from my experience how emacs does it. (Lgb)
577 static unsigned int counter;
585 // register word if a non-letter was entered
587 && par.isLetter(cur.pos() - 2)
588 && !par.isLetter(cur.pos() - 1)) {
589 // get the word in front of cursor
590 BOOST_ASSERT(this == cur.text());
591 cur.paragraph().updateWords(cur.top());
596 // the cursor set functions have a special mechanism. When they
597 // realize, that you left an empty paragraph, they will delete it.
599 bool Text::cursorForwardOneWord(Cursor & cur)
601 BOOST_ASSERT(this == cur.text());
605 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
609 // Advance through word.
610 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
612 // Skip through trailing nonword stuff.
613 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
616 return setCursor(cur, old.pit(), old.pos());
620 bool Text::cursorBackwardOneWord(Cursor & cur)
622 BOOST_ASSERT(this == cur.text());
626 if (old.pos() == 0 && old.pit() != 0) {
628 old.pos() = old.lastpos();
630 // Skip through initial nonword stuff.
631 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
633 // Advance through word.
634 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
637 return setCursor(cur, old.pit(), old.pos());
641 void Text::selectWord(Cursor & cur, word_location loc)
643 BOOST_ASSERT(this == cur.text());
644 CursorSlice from = cur.top();
645 CursorSlice to = cur.top();
646 getWord(from, to, loc);
647 if (cur.top() != from)
648 setCursor(cur, from.pit(), from.pos());
652 setCursor(cur, to.pit(), to.pos());
657 // Select the word currently under the cursor when no
658 // selection is currently set
659 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
661 BOOST_ASSERT(this == cur.text());
664 selectWord(cur, loc);
665 return cur.selection();
669 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
671 BOOST_ASSERT(this == cur.text());
673 if (!cur.selection())
676 cur.recordUndoSelection();
678 pit_type begPit = cur.selectionBegin().pit();
679 pit_type endPit = cur.selectionEnd().pit();
681 pos_type begPos = cur.selectionBegin().pos();
682 pos_type endPos = cur.selectionEnd().pos();
684 // keep selection info, because endPos becomes invalid after the first loop
685 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
687 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
689 for (pit_type pit = begPit; pit <= endPit; ++pit) {
690 pos_type parSize = pars_[pit].size();
692 // ignore empty paragraphs; otherwise, an assertion will fail for
693 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
697 // do not consider first paragraph if the cursor starts at pos size()
698 if (pit == begPit && begPos == parSize)
701 // do not consider last paragraph if the cursor ends at pos 0
702 if (pit == endPit && endPos == 0)
703 break; // last iteration anyway
705 pos_type left = (pit == begPit ? begPos : 0);
706 pos_type right = (pit == endPit ? endPos : parSize);
709 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
711 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
715 // next, accept/reject imaginary end-of-par characters
717 for (pit_type pit = begPit; pit <= endPit; ++pit) {
718 pos_type pos = pars_[pit].size();
720 // skip if the selection ends before the end-of-par
721 if (pit == endPit && endsBeforeEndOfPar)
722 break; // last iteration anyway
724 // skip if this is not the last paragraph of the document
725 // note: the user should be able to accept/reject the par break of the last par!
726 if (pit == endPit && pit + 1 != int(pars_.size()))
727 break; // last iteration anway
730 if (pars_[pit].isInserted(pos)) {
731 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
732 } else if (pars_[pit].isDeleted(pos)) {
733 if (pit + 1 == int(pars_.size())) {
734 // we cannot remove a par break at the end of the last paragraph;
735 // instead, we mark it unchanged
736 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
738 mergeParagraph(cur.buffer().params(), pars_, pit);
744 if (pars_[pit].isDeleted(pos)) {
745 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
746 } else if (pars_[pit].isInserted(pos)) {
747 if (pit + 1 == int(pars_.size())) {
748 // we mark the par break at the end of the last paragraph unchanged
749 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
751 mergeParagraph(cur.buffer().params(), pars_, pit);
759 // finally, invoke the DEPM
761 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
766 cur.clearSelection();
767 setCursorIntern(cur, begPit, begPos);
768 cur.updateFlags(Update::Force);
769 updateLabels(cur.buffer());
773 void Text::acceptChanges(BufferParams const & bparams)
775 lyx::acceptChanges(pars_, bparams);
776 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
780 void Text::rejectChanges(BufferParams const & bparams)
782 pit_type pars_size = static_cast<pit_type>(pars_.size());
784 // first, reject changes within each individual paragraph
785 // (do not consider end-of-par)
786 for (pit_type pit = 0; pit < pars_size; ++pit) {
787 if (!pars_[pit].empty()) // prevent assertion failure
788 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
791 // next, reject imaginary end-of-par characters
792 for (pit_type pit = 0; pit < pars_size; ++pit) {
793 pos_type pos = pars_[pit].size();
795 if (pars_[pit].isDeleted(pos)) {
796 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
797 } else if (pars_[pit].isInserted(pos)) {
798 if (pit == pars_size - 1) {
799 // we mark the par break at the end of the last
800 // paragraph unchanged
801 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
803 mergeParagraph(bparams, pars_, pit);
810 // finally, invoke the DEPM
811 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
815 void Text::deleteWordForward(Cursor & cur)
817 BOOST_ASSERT(this == cur.text());
818 if (cur.lastpos() == 0)
822 cur.selection() = true;
823 cursorForwardOneWord(cur);
825 cutSelection(cur, true, false);
826 cur.checkBufferStructure();
831 void Text::deleteWordBackward(Cursor & cur)
833 BOOST_ASSERT(this == cur.text());
834 if (cur.lastpos() == 0)
838 cur.selection() = true;
839 cursorBackwardOneWord(cur);
841 cutSelection(cur, true, false);
842 cur.checkBufferStructure();
847 // Kill to end of line.
848 void Text::changeCase(Cursor & cur, TextCase action)
850 BOOST_ASSERT(this == cur.text());
855 if (cur.selection()) {
856 from = cur.selBegin();
861 getWord(from, to, PARTIAL_WORD);
862 cursorForwardOneWord(cur);
865 cur.recordUndoSelection();
867 pit_type begPit = from.pit();
868 pit_type endPit = to.pit();
870 pos_type begPos = from.pos();
871 pos_type endPos = to.pos();
873 pos_type right = 0; // needed after the for loop
875 for (pit_type pit = begPit; pit <= endPit; ++pit) {
876 Paragraph & par = pars_[pit];
877 pos_type const pos = (pit == begPit ? begPos : 0);
878 right = (pit == endPit ? endPos : par.size());
879 par.changeCase(cur.buffer().params(), pos, right, action);
882 // the selection may have changed due to logically-only deleted chars
884 setCursor(cur, begPit, begPos);
886 setCursor(cur, endPit, right);
889 setCursor(cur, endPit, right);
891 cur.checkBufferStructure();
895 bool Text::handleBibitems(Cursor & cur)
897 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
903 BufferParams const & bufparams = cur.buffer().params();
904 Paragraph const & par = cur.paragraph();
905 Cursor prevcur = cur;
908 prevcur.pos() = prevcur.lastpos();
910 Paragraph const & prevpar = prevcur.paragraph();
912 // if a bibitem is deleted, merge with previous paragraph
913 // if this is a bibliography item as well
914 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
915 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
916 mergeParagraph(bufparams, cur.text()->paragraphs(),
918 updateLabels(cur.buffer());
919 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
920 cur.updateFlags(Update::Force);
924 // otherwise reset to default
925 cur.paragraph().setEmptyOrDefaultLayout(bufparams.documentClass());
930 bool Text::erase(Cursor & cur)
932 BOOST_ASSERT(this == cur.text());
933 bool needsUpdate = false;
934 Paragraph & par = cur.paragraph();
936 if (cur.pos() != cur.lastpos()) {
937 // this is the code for a normal delete, not pasting
939 cur.recordUndo(DELETE_UNDO);
940 bool const was_inset = cur.paragraph().isInset(cur.pos());
941 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges))
942 // the character has been logically deleted only => skip it
943 cur.top().forwardPos();
946 updateLabels(cur.buffer());
948 cur.checkBufferStructure();
951 if (cur.pit() == cur.lastpit())
952 return dissolveInset(cur);
954 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
955 par.setChange(cur.pos(), Change(Change::DELETED));
959 setCursorIntern(cur, cur.pit() + 1, 0);
960 needsUpdate = backspacePos0(cur);
964 needsUpdate |= handleBibitems(cur);
967 // Make sure the cursor is correct. Is this really needed?
968 // No, not really... at least not here!
969 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
970 cur.checkBufferStructure();
977 bool Text::backspacePos0(Cursor & cur)
979 BOOST_ASSERT(this == cur.text());
983 bool needsUpdate = false;
985 BufferParams const & bufparams = cur.buffer().params();
986 DocumentClass const & tclass = bufparams.documentClass();
987 ParagraphList & plist = cur.text()->paragraphs();
988 Paragraph const & par = cur.paragraph();
989 Cursor prevcur = cur;
991 prevcur.pos() = prevcur.lastpos();
992 Paragraph const & prevpar = prevcur.paragraph();
994 // is it an empty paragraph?
995 if (cur.lastpos() == 0
996 || (cur.lastpos() == 1 && par.isSeparator(0))) {
997 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
998 plist.erase(boost::next(plist.begin(), cur.pit()));
1001 // is previous par empty?
1002 else if (prevcur.lastpos() == 0
1003 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1004 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1005 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1008 // Pasting is not allowed, if the paragraphs have different
1009 // layouts. I think it is a real bug of all other
1010 // word processors to allow it. It confuses the user.
1011 // Correction: Pasting is always allowed with standard-layout
1012 // or the empty layout.
1013 else if (par.layout() == prevpar.layout()
1014 || tclass.isDefaultLayout(par.layout())
1015 || tclass.isEmptyLayout(par.layout())) {
1016 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1017 mergeParagraph(bufparams, plist, prevcur.pit());
1022 updateLabels(cur.buffer());
1023 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1030 bool Text::backspace(Cursor & cur)
1032 BOOST_ASSERT(this == cur.text());
1033 bool needsUpdate = false;
1034 if (cur.pos() == 0) {
1036 return dissolveInset(cur);
1038 Paragraph & prev_par = pars_[cur.pit() - 1];
1040 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1041 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1042 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1045 // The cursor is at the beginning of a paragraph, so
1046 // the backspace will collapse two paragraphs into one.
1047 needsUpdate = backspacePos0(cur);
1050 // this is the code for a normal backspace, not pasting
1052 cur.recordUndo(DELETE_UNDO);
1053 // We used to do cursorBackwardIntern() here, but it is
1054 // not a good idea since it triggers the auto-delete
1055 // mechanism. So we do a cursorBackwardIntern()-lite,
1056 // without the dreaded mechanism. (JMarc)
1057 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1058 false, cur.boundary());
1059 bool const was_inset = cur.paragraph().isInset(cur.pos());
1060 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1062 updateLabels(cur.buffer());
1064 cur.checkBufferStructure();
1067 if (cur.pos() == cur.lastpos())
1068 cur.setCurrentFont();
1070 needsUpdate |= handleBibitems(cur);
1072 // A singlePar update is not enough in this case.
1073 // cur.updateFlags(Update::Force);
1074 setCursor(cur.top(), cur.pit(), cur.pos());
1080 bool Text::dissolveInset(Cursor & cur) {
1081 BOOST_ASSERT(this == cur.text());
1083 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1086 cur.recordUndoInset();
1088 cur.selHandle(false);
1090 pos_type spos = cur.pos();
1091 pit_type spit = cur.pit();
1092 ParagraphList plist;
1093 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1094 plist = paragraphs();
1096 // store cursor offset
1100 Buffer & b = cur.buffer();
1101 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1102 if (!plist.empty()) {
1103 // ERT paragraphs have the Language latex_language.
1104 // This is invalid outside of ERT, so we need to
1105 // change it to the buffer language.
1106 ParagraphList::iterator it = plist.begin();
1107 ParagraphList::iterator it_end = plist.end();
1108 for (; it != it_end; it++)
1109 it->changeLanguage(b.params(), latex_language, b.language());
1111 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1112 b.errorList("Paste"));
1114 cur.pit() = min(cur.lastpit(), spit);
1115 cur.pos() = min(cur.lastpos(), spos);
1117 cur.clearSelection();
1123 void Text::getWord(CursorSlice & from, CursorSlice & to,
1124 word_location const loc) const
1126 Paragraph const & from_par = pars_[from.pit()];
1128 case WHOLE_WORD_STRICT:
1129 if (from.pos() == 0 || from.pos() == from_par.size()
1130 || !from_par.isLetter(from.pos())
1131 || !from_par.isLetter(from.pos() - 1)) {
1135 // no break here, we go to the next
1138 // If we are already at the beginning of a word, do nothing
1139 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1141 // no break here, we go to the next
1144 // always move the cursor to the beginning of previous word
1145 while (from.pos() && from_par.isLetter(from.pos() - 1))
1149 LYXERR0("Text::getWord: NEXT_WORD not implemented yet");
1152 // no need to move the 'from' cursor
1156 Paragraph const & to_par = pars_[to.pit()];
1157 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1162 void Text::write(Buffer const & buf, ostream & os) const
1164 ParagraphList::const_iterator pit = paragraphs().begin();
1165 ParagraphList::const_iterator end = paragraphs().end();
1167 for (; pit != end; ++pit)
1168 pit->write(os, buf.params(), dth);
1170 // Close begin_deeper
1171 for(; dth > 0; --dth)
1172 os << "\n\\end_deeper";
1176 bool Text::read(Buffer const & buf, Lexer & lex,
1177 ErrorList & errorList, InsetText * insetPtr)
1179 depth_type depth = 0;
1181 while (lex.isOK()) {
1183 string const token = lex.getString();
1188 if (token == "\\end_inset")
1191 if (token == "\\end_body")
1194 if (token == "\\begin_body")
1197 if (token == "\\end_document")
1200 if (token == "\\begin_layout") {
1201 lex.pushToken(token);
1204 par.params().depth(depth);
1205 par.setFont(0, Font(inherit_font, buf.params().language));
1206 par.setInsetOwner(insetPtr);
1207 pars_.push_back(par);
1209 // FIXME: goddamn InsetTabular makes us pass a Buffer
1211 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1213 // register the words in the global word list
1214 CursorSlice sl = CursorSlice(*insetPtr);
1215 sl.pit() = pars_.size() - 1;
1216 pars_.back().updateWords(sl);
1217 } else if (token == "\\begin_deeper") {
1219 } else if (token == "\\end_deeper") {
1221 lex.printError("\\end_deeper: " "depth is already null");
1225 LYXERR0("Handling unknown body token: `" << token << '\'');
1231 // Returns the current font and depth as a message.
1232 docstring Text::currentState(Cursor & cur)
1234 BOOST_ASSERT(this == cur.text());
1235 Buffer & buf = cur.buffer();
1236 Paragraph const & par = cur.paragraph();
1237 odocstringstream os;
1239 if (buf.params().trackChanges)
1240 os << _("[Change Tracking] ");
1242 Change change = par.lookupChange(cur.pos());
1244 if (change.type != Change::UNCHANGED) {
1245 Author const & a = buf.params().authors().get(change.author);
1246 os << _("Change: ") << a.name();
1247 if (!a.email().empty())
1248 os << " (" << a.email() << ")";
1249 // FIXME ctime is english, we should translate that
1250 os << _(" at ") << ctime(&change.changetime);
1254 // I think we should only show changes from the default
1256 // No, from the document font (MV)
1257 Font font = cur.real_current_font;
1258 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1260 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1262 // The paragraph depth
1263 int depth = cur.paragraph().getDepth();
1265 os << bformat(_(", Depth: %1$d"), depth);
1267 // The paragraph spacing, but only if different from
1269 Spacing const & spacing = par.params().spacing();
1270 if (!spacing.isDefault()) {
1271 os << _(", Spacing: ");
1272 switch (spacing.getSpace()) {
1273 case Spacing::Single:
1276 case Spacing::Onehalf:
1279 case Spacing::Double:
1282 case Spacing::Other:
1283 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1285 case Spacing::Default:
1286 // should never happen, do nothing
1291 #ifdef DEVEL_VERSION
1292 os << _(", Inset: ") << &cur.inset();
1293 os << _(", Paragraph: ") << cur.pit();
1294 os << _(", Id: ") << par.id();
1295 os << _(", Position: ") << cur.pos();
1296 // FIXME: Why is the check for par.size() needed?
1297 // We are called with cur.pos() == par.size() quite often.
1298 if (!par.empty() && cur.pos() < par.size()) {
1299 // Force output of code point, not character
1300 size_t const c = par.getChar(cur.pos());
1301 os << _(", Char: 0x") << hex << c;
1303 os << _(", Boundary: ") << cur.boundary();
1304 // Row & row = cur.textRow();
1305 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1311 docstring Text::getPossibleLabel(Cursor & cur) const
1313 pit_type pit = cur.pit();
1315 Layout const * layout = &(pars_[pit].layout());
1318 docstring par_text = pars_[pit].asString(false);
1320 // the return string of math matrices might contain linebreaks
1321 par_text = subst(par_text, '\n', '-');
1322 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1323 if (par_text.empty())
1326 par_text = split(par_text, head, ' ');
1327 // Is it legal to use spaces in labels ?
1333 // No need for a prefix if the user said so.
1334 if (lyxrc.label_init_length <= 0)
1337 // Will contain the label type.
1340 // For section, subsection, etc...
1341 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1342 Layout const * layout2 = &(pars_[pit - 1].layout());
1343 if (layout2->latextype != LATEX_PARAGRAPH) {
1348 if (layout->latextype != LATEX_PARAGRAPH)
1349 name = from_ascii(layout->latexname());
1351 // for captions, we just take the caption type
1352 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1354 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1356 // If none of the above worked, we'll see if we're inside various
1357 // types of insets and take our abbreviation from them.
1359 InsetCode const codes[] = {
1364 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1365 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1367 name = float_inset->name();
1373 // Create a correct prefix for prettyref
1374 if (name == "theorem")
1375 name = from_ascii("thm");
1376 else if (name == "Foot")
1377 name = from_ascii("fn");
1378 else if (name == "listing")
1379 name = from_ascii("lst");
1382 text = name.substr(0, 3) + ':' + text;
1388 void Text::charsTranspose(Cursor & cur)
1390 BOOST_ASSERT(this == cur.text());
1392 pos_type pos = cur.pos();
1394 // If cursor is at beginning or end of paragraph, do nothing.
1395 if (pos == cur.lastpos() || pos == 0)
1398 Paragraph & par = cur.paragraph();
1400 // Get the positions of the characters to be transposed.
1401 pos_type pos1 = pos - 1;
1402 pos_type pos2 = pos;
1404 // In change tracking mode, ignore deleted characters.
1405 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1407 if (pos2 == cur.lastpos())
1410 while (pos1 >= 0 && par.isDeleted(pos1))
1415 // Don't do anything if one of the "characters" is not regular text.
1416 if (par.isInset(pos1) || par.isInset(pos2))
1419 // Store the characters to be transposed (including font information).
1420 char_type char1 = par.getChar(pos1);
1422 par.getFontSettings(cur.buffer().params(), pos1);
1424 char_type char2 = par.getChar(pos2);
1426 par.getFontSettings(cur.buffer().params(), pos2);
1428 // And finally, we are ready to perform the transposition.
1429 // Track the changes if Change Tracking is enabled.
1430 bool const trackChanges = cur.buffer().params().trackChanges;
1434 par.eraseChar(pos2, trackChanges);
1435 par.eraseChar(pos1, trackChanges);
1436 par.insertChar(pos1, char2, font2, trackChanges);
1437 par.insertChar(pos2, char1, font1, trackChanges);
1439 cur.checkBufferStructure();
1441 // After the transposition, move cursor to after the transposition.
1442 setCursor(cur, cur.pit(), pos2);
1447 DocIterator Text::macrocontextPosition() const
1449 return macrocontext_position_;
1453 void Text::setMacrocontextPosition(DocIterator const & pos)
1455 macrocontext_position_ = pos;
1459 docstring Text::previousWord(CursorSlice const & sl) const
1461 CursorSlice from = sl;
1462 CursorSlice to = sl;
1463 getWord(from, to, PREVIOUS_WORD);
1464 if (sl == from || to == from)
1467 Paragraph const & par = sl.paragraph();
1468 return par.asString(from.pos(), to.pos(), false);
1472 bool Text::completionSupported(Cursor const & cur) const
1474 Paragraph const & par = cur.paragraph();
1475 return cur.pos() > 0
1476 && (cur.pos() >= par.size() || !par.isLetter(cur.pos()))
1477 && par.isLetter(cur.pos() - 1);
1481 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1483 return new TextCompletionList(cur);
1487 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1489 BOOST_ASSERT(cur.bv().cursor() == cur);
1491 cur.bv().cursor() = cur;
1492 if (!(cur.disp_.update() & Update::Force))
1493 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
1498 docstring Text::completionPrefix(Cursor const & cur) const
1500 return previousWord(cur.top());