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 "ParIterator.h"
30 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
37 #include "FontIterator.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
49 #include "WordLangTuple.h"
51 #include "frontends/FontMetrics.h"
52 #include "frontends/Painter.h"
54 #include "insets/InsetText.h"
55 #include "insets/InsetBibitem.h"
56 #include "insets/InsetCaption.h"
57 #include "insets/InsetHFill.h"
58 #include "insets/InsetLine.h"
59 #include "insets/InsetNewline.h"
60 #include "insets/InsetPagebreak.h"
61 #include "insets/InsetOptArg.h"
62 #include "insets/InsetSpace.h"
63 #include "insets/InsetSpecialChar.h"
64 #include "insets/InsetTabular.h"
66 #include "support/lstrings.h"
67 #include "support/textutils.h"
68 #include "support/convert.h"
70 #include <boost/current_function.hpp>
84 using support::bformat;
85 using support::contains;
86 using support::lowercase;
88 using support::uppercase;
90 using cap::cutSelection;
91 using cap::pasteParagraphList;
93 using frontend::FontMetrics;
97 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
98 string const & token, Font & font, Change & change, ErrorList & errorList)
100 BufferParams const & bp = buf.params();
102 if (token[0] != '\\') {
104 string::const_iterator cit = token.begin();
105 for (; cit != token.end(); ++cit)
106 par.insertChar(par.size(), (*cit), font, change);
108 docstring dstr = lex.getDocString();
109 docstring::const_iterator cit = dstr.begin();
110 docstring::const_iterator cend = dstr.end();
111 for (; cit != cend; ++cit)
112 par.insertChar(par.size(), *cit, font, change);
114 } else if (token == "\\begin_layout") {
116 docstring layoutname = lex.getDocString();
118 font = Font(Font::ALL_INHERIT, bp.language);
119 change = Change(Change::UNCHANGED);
121 TextClass const & tclass = bp.getTextClass();
123 if (layoutname.empty()) {
124 layoutname = tclass.defaultLayoutName();
127 bool hasLayout = tclass.hasLayout(layoutname);
130 errorList.push_back(ErrorItem(_("Unknown layout"),
131 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
132 layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
133 layoutname = tclass.defaultLayoutName();
136 par.layout(bp.getTextClass()[layoutname]);
138 // Test whether the layout is obsolete.
139 LayoutPtr const & layout = par.layout();
140 if (!layout->obsoleted_by().empty())
141 par.layout(bp.getTextClass()[layout->obsoleted_by()]);
143 par.params().read(lex);
145 } else if (token == "\\end_layout") {
146 lyxerr << BOOST_CURRENT_FUNCTION
147 << ": Solitary \\end_layout in line "
148 << lex.getLineNo() << "\n"
149 << "Missing \\begin_layout?.\n";
150 } else if (token == "\\end_inset") {
151 lyxerr << BOOST_CURRENT_FUNCTION
152 << ": Solitary \\end_inset in line "
153 << lex.getLineNo() << "\n"
154 << "Missing \\begin_inset?.\n";
155 } else if (token == "\\begin_inset") {
156 Inset * inset = readInset(lex, buf);
158 par.insertInset(par.size(), inset, font, change);
161 docstring line = lex.getDocString();
162 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
163 par.id(), 0, par.size()));
165 } else if (token == "\\family") {
167 font.setLyXFamily(lex.getString());
168 } else if (token == "\\series") {
170 font.setLyXSeries(lex.getString());
171 } else if (token == "\\shape") {
173 font.setLyXShape(lex.getString());
174 } else if (token == "\\size") {
176 font.setLyXSize(lex.getString());
177 } else if (token == "\\lang") {
179 string const tok = lex.getString();
180 Language const * lang = languages.getLanguage(tok);
182 font.setLanguage(lang);
184 font.setLanguage(bp.language);
185 lex.printError("Unknown language `$$Token'");
187 } else if (token == "\\numeric") {
189 font.setNumber(font.setLyXMisc(lex.getString()));
190 } else if (token == "\\emph") {
192 font.setEmph(font.setLyXMisc(lex.getString()));
193 } else if (token == "\\bar") {
195 string const tok = lex.getString();
198 font.setUnderbar(Font::ON);
199 else if (tok == "no")
200 font.setUnderbar(Font::OFF);
201 else if (tok == "default")
202 font.setUnderbar(Font::INHERIT);
204 lex.printError("Unknown bar font flag "
206 } else if (token == "\\noun") {
208 font.setNoun(font.setLyXMisc(lex.getString()));
209 } else if (token == "\\color") {
211 font.setLyXColor(lex.getString());
212 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
214 // Insets don't make sense in a free-spacing context! ---Kayvan
215 if (par.isFreeSpacing()) {
216 if (token == "\\InsetSpace")
217 par.insertChar(par.size(), ' ', font, change);
218 else if (lex.isOK()) {
220 string const next_token = lex.getString();
221 if (next_token == "\\-")
222 par.insertChar(par.size(), '-', font, change);
224 lex.printError("Token `$$Token' "
226 "paragraph layout!");
230 auto_ptr<Inset> inset;
231 if (token == "\\SpecialChar" )
232 inset.reset(new InsetSpecialChar);
234 inset.reset(new InsetSpace);
235 inset->read(buf, lex);
236 par.insertInset(par.size(), inset.release(),
239 } else if (token == "\\backslash") {
240 par.insertChar(par.size(), '\\', font, change);
241 } else if (token == "\\newline") {
242 auto_ptr<Inset> inset(new InsetNewline);
243 inset->read(buf, lex);
244 par.insertInset(par.size(), inset.release(), font, change);
245 } else if (token == "\\LyXTable") {
246 auto_ptr<Inset> inset(new InsetTabular(buf));
247 inset->read(buf, lex);
248 par.insertInset(par.size(), inset.release(), font, change);
249 } else if (token == "\\hfill") {
250 par.insertInset(par.size(), new InsetHFill, font, change);
251 } else if (token == "\\lyxline") {
252 par.insertInset(par.size(), new InsetLine, font, change);
253 } else if (token == "\\newpage") {
254 par.insertInset(par.size(), new InsetPagebreak, font, change);
255 } else if (token == "\\clearpage") {
256 par.insertInset(par.size(), new InsetClearPage, font, change);
257 } else if (token == "\\cleardoublepage") {
258 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
259 } else if (token == "\\change_unchanged") {
260 change = Change(Change::UNCHANGED);
261 } else if (token == "\\change_inserted") {
263 std::istringstream is(lex.getString());
267 if (aid >= bp.author_map.size()) {
268 errorList.push_back(ErrorItem(_("Change tracking error"),
269 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
270 par.id(), 0, par.size()));
271 change = Change(Change::UNCHANGED);
273 change = Change(Change::INSERTED, bp.author_map[aid], ct);
274 } else if (token == "\\change_deleted") {
276 std::istringstream is(lex.getString());
280 if (aid >= bp.author_map.size()) {
281 errorList.push_back(ErrorItem(_("Change tracking error"),
282 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
283 par.id(), 0, par.size()));
284 change = Change(Change::UNCHANGED);
286 change = Change(Change::DELETED, bp.author_map[aid], ct);
289 errorList.push_back(ErrorItem(_("Unknown token"),
290 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
292 par.id(), 0, par.size()));
297 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
298 ErrorList & errorList)
301 string token = lex.getString();
303 Change change(Change::UNCHANGED);
306 readParToken(buf, par, lex, token, font, change, errorList);
309 token = lex.getString();
314 if (token == "\\end_layout") {
315 //Ok, paragraph finished
319 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
320 << token << '\'' << endl;
321 if (token == "\\begin_layout" || token == "\\end_document"
322 || token == "\\end_inset" || token == "\\begin_deeper"
323 || token == "\\end_deeper") {
324 lex.pushToken(token);
325 lyxerr << "Paragraph ended in line "
326 << lex.getLineNo() << "\n"
327 << "Missing \\end_layout.\n";
331 // Final change goes to paragraph break:
332 par.setChange(par.size(), change);
334 // Initialize begin_of_body_ on load; redoParagraph maintains
335 par.setBeginOfBody();
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,
351 Paragraph const & par) const
353 if (par.params().spacing().isDefault())
354 return buffer.params().spacing().getValue();
355 return par.params().spacing().getValue();
359 Color_color Text::backgroundColor() const
361 return Color_color(Color::color(background_color_));
365 void Text::breakParagraph(Cursor & cur, bool keep_layout)
367 BOOST_ASSERT(this == cur.text());
369 Paragraph & cpar = cur.paragraph();
370 pit_type cpit = cur.pit();
372 TextClass const & tclass = cur.buffer().params().getTextClass();
373 LayoutPtr const & layout = cpar.layout();
375 // this is only allowed, if the current paragraph is not empty
376 // or caption and if it has not the keepempty flag active
377 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
378 layout->labeltype != LABEL_SENSITIVE)
381 // a layout change may affect also the following paragraph
382 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
384 // Always break behind a space
385 // It is better to erase the space (Dekel)
386 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
387 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
389 // What should the layout for the new paragraph be?
390 int preserve_layout = 0;
394 preserve_layout = layout->isEnvironment();
396 // We need to remember this before we break the paragraph, because
397 // that invalidates the layout variable
398 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
400 // we need to set this before we insert the paragraph.
401 bool const isempty = cpar.allowEmpty() && cpar.empty();
403 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
404 cur.pos(), preserve_layout);
406 // After this, neither paragraph contains any rows!
409 pit_type next_par = cpit + 1;
411 // well this is the caption hack since one caption is really enough
414 // set to standard-layout
415 pars_[cpit].applyLayout(tclass.defaultLayout());
417 // set to standard-layout
418 pars_[next_par].applyLayout(tclass.defaultLayout());
421 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
422 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
423 break; // the character couldn't be deleted physically due to change tracking
426 updateLabels(cur.buffer());
428 // A singlePar update is not enough in this case.
429 cur.updateFlags(Update::Force);
431 // This check is necessary. Otherwise the new empty paragraph will
432 // be deleted automatically. And it is more friendly for the user!
433 if (cur.pos() != 0 || isempty)
434 setCursor(cur, cur.pit() + 1, 0);
436 setCursor(cur, cur.pit(), 0);
440 // insert a character, moves all the following breaks in the
441 // same Paragraph one to the right and make a rebreak
442 void Text::insertChar(Cursor & cur, char_type c)
444 BOOST_ASSERT(this == cur.text());
445 BOOST_ASSERT(c != Paragraph::META_INSET);
447 recordUndo(cur, Undo::INSERT);
449 Buffer const & buffer = cur.buffer();
450 Paragraph & par = cur.paragraph();
451 // try to remove this
452 pit_type const pit = cur.pit();
454 bool const freeSpacing = par.layout()->free_spacing ||
457 if (lyxrc.auto_number) {
458 static docstring const number_operators = from_ascii("+-/*");
459 static docstring const number_unary_operators = from_ascii("+-");
460 static docstring const number_seperators = from_ascii(".,:");
462 if (current_font.number() == Font::ON) {
463 if (!isDigit(c) && !contains(number_operators, c) &&
464 !(contains(number_seperators, c) &&
466 cur.pos() != cur.lastpos() &&
467 getFont(buffer, par, cur.pos()).number() == Font::ON &&
468 getFont(buffer, par, cur.pos() - 1).number() == Font::ON)
470 number(cur); // Set current_font.number to OFF
471 } else if (isDigit(c) &&
472 real_current_font.isVisibleRightToLeft()) {
473 number(cur); // Set current_font.number to ON
475 if (cur.pos() != 0) {
476 char_type const c = par.getChar(cur.pos() - 1);
477 if (contains(number_unary_operators, c) &&
479 || par.isSeparator(cur.pos() - 2)
480 || par.isNewline(cur.pos() - 2))
482 setCharFont(buffer, pit, cur.pos() - 1, current_font);
483 } else if (contains(number_seperators, c)
485 && getFont(buffer, par, cur.pos() - 2).number() == Font::ON) {
486 setCharFont(buffer, pit, cur.pos() - 1, current_font);
492 // In Bidi text, we want spaces to be treated in a special way: spaces
493 // which are between words in different languages should get the
494 // paragraph's language; otherwise, spaces should keep the language
495 // they were originally typed in. This is only in effect while typing;
496 // after the text is already typed in, the user can always go back and
497 // explicitly set the language of a space as desired. But 99.9% of the
498 // time, what we're doing here is what the user actually meant.
500 // The following cases are the ones in which the language of the space
501 // should be changed to match that of the containing paragraph. In the
502 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
503 // represents a space, pipe (|) represents the cursor position (so the
504 // character before it is the one just typed in). The different cases
505 // are depicted logically (not visually), from left to right:
510 // Theoretically, there are other situations that we should, perhaps, deal
511 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
512 // point (to understand why, just try to create this situation...).
514 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
515 // get font in front and behind the space in question. But do NOT
516 // use getFont(cur.pos()) because the character c is not inserted yet
517 Font const & pre_space_font = getFont(buffer, par, cur.pos() - 2);
518 Font const & post_space_font = real_current_font;
519 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
520 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
522 if (pre_space_rtl != post_space_rtl) {
523 // Set the space's language to match the language of the
524 // adjacent character whose direction is the paragraph's
525 // direction; don't touch other properties of the font
526 Language const * lang =
527 (pre_space_rtl == par.isRightToLeftPar(buffer.params())) ?
528 pre_space_font.language() : post_space_font.language();
530 Font space_font = getFont(buffer, par, cur.pos() - 1);
531 space_font.setLanguage(lang);
532 par.setFont(cur.pos() - 1, space_font);
536 // Next check, if there will be two blanks together or a blank at
537 // the beginning of a paragraph.
538 // I decided to handle blanks like normal characters, the main
539 // difference are the special checks when calculating the row.fill
540 // (blank does not count at the end of a row) and the check here
542 // When the free-spacing option is set for the current layout,
543 // disable the double-space checking
544 if (!freeSpacing && isLineSeparatorChar(c)) {
545 if (cur.pos() == 0) {
546 static bool sent_space_message = false;
547 if (!sent_space_message) {
548 cur.message(_("You cannot insert a space at the "
549 "beginning of a paragraph. Please read the Tutorial."));
550 sent_space_message = true;
554 BOOST_ASSERT(cur.pos() > 0);
555 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
556 && !par.isDeleted(cur.pos() - 1)) {
557 static bool sent_space_message = false;
558 if (!sent_space_message) {
559 cur.message(_("You cannot type two spaces this way. "
560 "Please read the Tutorial."));
561 sent_space_message = true;
567 par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
568 checkBufferStructure(cur.buffer(), cur);
570 // cur.updateFlags(Update::Force);
571 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
576 void Text::charInserted()
578 // Here we call finishUndo for every 20 characters inserted.
579 // This is from my experience how emacs does it. (Lgb)
580 static unsigned int counter;
590 // the cursor set functions have a special mechanism. When they
591 // realize, that you left an empty paragraph, they will delete it.
593 bool Text::cursorRightOneWord(Cursor & cur)
595 BOOST_ASSERT(this == cur.text());
599 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
603 // Advance through word.
604 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
606 // Skip through trailing nonword stuff.
607 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
610 return setCursor(cur, old.pit(), old.pos());
614 bool Text::cursorLeftOneWord(Cursor & cur)
616 BOOST_ASSERT(this == cur.text());
620 if (old.pos() == 0 && old.pit() != 0) {
622 old.pos() = old.lastpos();
624 // Skip through initial nonword stuff.
625 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
627 // Advance through word.
628 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
631 return setCursor(cur, old.pit(), old.pos());
635 void Text::selectWord(Cursor & cur, word_location loc)
637 BOOST_ASSERT(this == cur.text());
638 CursorSlice from = cur.top();
639 CursorSlice to = cur.top();
640 getWord(from, to, loc);
641 if (cur.top() != from)
642 setCursor(cur, from.pit(), from.pos());
646 setCursor(cur, to.pit(), to.pos());
651 // Select the word currently under the cursor when no
652 // selection is currently set
653 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
655 BOOST_ASSERT(this == cur.text());
658 selectWord(cur, loc);
659 return cur.selection();
663 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
665 BOOST_ASSERT(this == cur.text());
667 if (!cur.selection())
670 recordUndoSelection(cur, Undo::ATOMIC);
672 pit_type begPit = cur.selectionBegin().pit();
673 pit_type endPit = cur.selectionEnd().pit();
675 pos_type begPos = cur.selectionBegin().pos();
676 pos_type endPos = cur.selectionEnd().pos();
678 // keep selection info, because endPos becomes invalid after the first loop
679 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
681 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
683 for (pit_type pit = begPit; pit <= endPit; ++pit) {
684 pos_type parSize = pars_[pit].size();
686 // ignore empty paragraphs; otherwise, an assertion will fail for
687 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
691 // do not consider first paragraph if the cursor starts at pos size()
692 if (pit == begPit && begPos == parSize)
695 // do not consider last paragraph if the cursor ends at pos 0
696 if (pit == endPit && endPos == 0)
697 break; // last iteration anyway
699 pos_type left = (pit == begPit ? begPos : 0);
700 pos_type right = (pit == endPit ? endPos : parSize);
703 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
705 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
709 // next, accept/reject imaginary end-of-par characters
711 for (pit_type pit = begPit; pit <= endPit; ++pit) {
712 pos_type pos = pars_[pit].size();
714 // skip if the selection ends before the end-of-par
715 if (pit == endPit && endsBeforeEndOfPar)
716 break; // last iteration anyway
718 // skip if this is not the last paragraph of the document
719 // note: the user should be able to accept/reject the par break of the last par!
720 if (pit == endPit && pit + 1 != int(pars_.size()))
721 break; // last iteration anway
724 if (pars_[pit].isInserted(pos)) {
725 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
726 } else if (pars_[pit].isDeleted(pos)) {
727 if (pit + 1 == int(pars_.size())) {
728 // we cannot remove a par break at the end of the last paragraph;
729 // instead, we mark it unchanged
730 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
732 mergeParagraph(cur.buffer().params(), pars_, pit);
738 if (pars_[pit].isDeleted(pos)) {
739 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
740 } else if (pars_[pit].isInserted(pos)) {
741 if (pit + 1 == int(pars_.size())) {
742 // we mark the par break at the end of the last paragraph unchanged
743 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
745 mergeParagraph(cur.buffer().params(), pars_, pit);
753 // finally, invoke the DEPM
755 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
760 cur.clearSelection();
761 setCursorIntern(cur, begPit, begPos);
762 cur.updateFlags(Update::Force);
763 updateLabels(cur.buffer());
767 void Text::acceptChanges(BufferParams const & bparams)
769 lyx::acceptChanges(pars_, bparams);
770 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
774 void Text::rejectChanges(BufferParams const & bparams)
776 pit_type pars_size = static_cast<pit_type>(pars_.size());
778 // first, reject changes within each individual paragraph
779 // (do not consider end-of-par)
780 for (pit_type pit = 0; pit < pars_size; ++pit) {
781 if (!pars_[pit].empty()) // prevent assertion failure
782 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
785 // next, reject imaginary end-of-par characters
786 for (pit_type pit = 0; pit < pars_size; ++pit) {
787 pos_type pos = pars_[pit].size();
789 if (pars_[pit].isDeleted(pos)) {
790 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
791 } else if (pars_[pit].isInserted(pos)) {
792 if (pit == pars_size - 1) {
793 // we mark the par break at the end of the last
794 // paragraph unchanged
795 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
797 mergeParagraph(bparams, pars_, pit);
804 // finally, invoke the DEPM
805 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
809 void Text::deleteWordForward(Cursor & cur)
811 BOOST_ASSERT(this == cur.text());
812 if (cur.lastpos() == 0)
816 cur.selection() = true;
817 cursorRightOneWord(cur);
819 cutSelection(cur, true, false);
820 checkBufferStructure(cur.buffer(), cur);
825 void Text::deleteWordBackward(Cursor & cur)
827 BOOST_ASSERT(this == cur.text());
828 if (cur.lastpos() == 0)
832 cur.selection() = true;
833 cursorLeftOneWord(cur);
835 cutSelection(cur, true, false);
836 checkBufferStructure(cur.buffer(), cur);
841 // Kill to end of line.
842 void Text::changeCase(Cursor & cur, Text::TextCase action)
844 BOOST_ASSERT(this == cur.text());
848 if (cur.selection()) {
849 from = cur.selBegin();
853 getWord(from, to, PARTIAL_WORD);
854 cursorRightOneWord(cur);
857 recordUndoSelection(cur, Undo::ATOMIC);
859 pit_type begPit = from.pit();
860 pit_type endPit = to.pit();
862 pos_type begPos = from.pos();
863 pos_type endPos = to.pos();
865 bool const trackChanges = cur.buffer().params().trackChanges;
867 pos_type right = 0; // needed after the for loop
869 for (pit_type pit = begPit; pit <= endPit; ++pit) {
870 pos_type parSize = pars_[pit].size();
872 pos_type pos = (pit == begPit ? begPos : 0);
873 right = (pit == endPit ? endPos : parSize);
875 // process sequences of modified characters; in change
876 // tracking mode, this approach results in much better
877 // usability than changing case on a char-by-char basis
880 bool capitalize = true;
882 for (; pos < right; ++pos) {
883 char_type oldChar = pars_[pit].getChar(pos);
884 char_type newChar = oldChar;
886 // ignore insets and don't play with deleted text!
887 if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
890 newChar = lowercase(oldChar);
892 case text_capitalization:
894 newChar = uppercase(oldChar);
899 newChar = uppercase(oldChar);
904 if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
905 capitalize = true; // permit capitalization again
908 if (oldChar != newChar) {
912 if (oldChar == newChar || pos == right - 1) {
913 if (oldChar != newChar) {
914 pos++; // step behind the changing area
916 int erasePos = pos - changes.size();
917 for (size_t i = 0; i < changes.size(); i++) {
918 pars_[pit].insertChar(pos, changes[i],
919 pars_[pit].getFontSettings(cur.buffer().params(),
922 if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
925 ++right; // expand selection
933 // the selection may have changed due to logically-only deleted chars
934 setCursor(cur, begPit, begPos);
936 setCursor(cur, endPit, right);
939 checkBufferStructure(cur.buffer(), cur);
943 bool Text::handleBibitems(Cursor & cur)
945 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
947 // if a bibitem is deleted, merge with previous paragraph
948 // if this is a bibliography item as well
949 if (cur.pos() == 0) {
950 BufferParams const & bufparams = cur.buffer().params();
951 Paragraph const & par = cur.paragraph();
952 Cursor prevcur = cur;
955 prevcur.pos() = prevcur.lastpos();
957 Paragraph const & prevpar = prevcur.paragraph();
958 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
959 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
960 mergeParagraph(bufparams, cur.text()->paragraphs(),
962 updateLabels(cur.buffer());
963 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
964 cur.updateFlags(Update::Force);
965 // if not, reset the paragraph to default
967 cur.paragraph().layout(
968 bufparams.getTextClass().defaultLayout());
975 bool Text::erase(Cursor & cur)
977 BOOST_ASSERT(this == cur.text());
978 bool needsUpdate = false;
979 Paragraph & par = cur.paragraph();
981 if (cur.pos() != cur.lastpos()) {
982 // this is the code for a normal delete, not pasting
984 recordUndo(cur, Undo::DELETE);
985 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
986 // the character has been logically deleted only => skip it
987 cur.top().forwardPos();
989 checkBufferStructure(cur.buffer(), cur);
992 if (cur.pit() == cur.lastpit())
993 return dissolveInset(cur);
995 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
996 par.setChange(cur.pos(), Change(Change::DELETED));
1000 setCursorIntern(cur, cur.pit() + 1, 0);
1001 needsUpdate = backspacePos0(cur);
1005 needsUpdate |= handleBibitems(cur);
1008 // Make sure the cursor is correct. Is this really needed?
1009 // No, not really... at least not here!
1010 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1011 checkBufferStructure(cur.buffer(), cur);
1018 bool Text::backspacePos0(Cursor & cur)
1020 BOOST_ASSERT(this == cur.text());
1024 bool needsUpdate = false;
1026 BufferParams const & bufparams = cur.buffer().params();
1027 TextClass const & tclass = bufparams.getTextClass();
1028 ParagraphList & plist = cur.text()->paragraphs();
1029 Paragraph const & par = cur.paragraph();
1030 Cursor prevcur = cur;
1032 prevcur.pos() = prevcur.lastpos();
1033 Paragraph const & prevpar = prevcur.paragraph();
1035 // is it an empty paragraph?
1036 if (cur.lastpos() == 0
1037 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1038 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1039 plist.erase(boost::next(plist.begin(), cur.pit()));
1042 // is previous par empty?
1043 else if (prevcur.lastpos() == 0
1044 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1045 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1046 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1049 // Pasting is not allowed, if the paragraphs have different
1050 // layouts. I think it is a real bug of all other
1051 // word processors to allow it. It confuses the user.
1052 // Correction: Pasting is always allowed with standard-layout
1053 else if (par.layout() == prevpar.layout()
1054 || par.layout() == tclass.defaultLayout()) {
1055 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1056 mergeParagraph(bufparams, plist, prevcur.pit());
1061 updateLabels(cur.buffer());
1062 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1069 bool Text::backspace(Cursor & cur)
1071 BOOST_ASSERT(this == cur.text());
1072 bool needsUpdate = false;
1073 if (cur.pos() == 0) {
1075 return dissolveInset(cur);
1077 Paragraph & prev_par = pars_[cur.pit() - 1];
1079 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1080 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1081 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1084 // The cursor is at the beginning of a paragraph, so
1085 // the backspace will collapse two paragraphs into one.
1086 needsUpdate = backspacePos0(cur);
1089 // this is the code for a normal backspace, not pasting
1091 recordUndo(cur, Undo::DELETE);
1092 // We used to do cursorLeftIntern() here, but it is
1093 // not a good idea since it triggers the auto-delete
1094 // mechanism. So we do a cursorLeftIntern()-lite,
1095 // without the dreaded mechanism. (JMarc)
1096 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1097 false, cur.boundary());
1098 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1099 checkBufferStructure(cur.buffer(), cur);
1102 if (cur.pos() == cur.lastpos())
1103 setCurrentFont(cur);
1105 needsUpdate |= handleBibitems(cur);
1107 // A singlePar update is not enough in this case.
1108 // cur.updateFlags(Update::Force);
1109 setCursor(cur.top(), cur.pit(), cur.pos());
1115 bool Text::dissolveInset(Cursor & cur) {
1116 BOOST_ASSERT(this == cur.text());
1118 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1121 recordUndoInset(cur);
1122 cur.selHandle(false);
1124 pos_type spos = cur.pos();
1125 pit_type spit = cur.pit();
1126 ParagraphList plist;
1127 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1128 plist = paragraphs();
1130 // store cursor offset
1134 Buffer & b = cur.buffer();
1135 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1136 if (!plist.empty()) {
1137 // ERT paragraphs have the Language latex_language.
1138 // This is invalid outside of ERT, so we need to
1139 // change it to the buffer language.
1140 ParagraphList::iterator it = plist.begin();
1141 ParagraphList::iterator it_end = plist.end();
1142 for (; it != it_end; it++) {
1143 it->changeLanguage(b.params(), latex_language,
1147 pasteParagraphList(cur, plist, b.params().getTextClass_ptr(),
1148 b.errorList("Paste"));
1150 cur.pit() = std::min(cur.lastpit(), spit);
1151 cur.pos() = std::min(cur.lastpos(), spos);
1153 cur.clearSelection();
1159 void Text::getWord(CursorSlice & from, CursorSlice & to,
1160 word_location const loc)
1162 Paragraph const & from_par = pars_[from.pit()];
1164 case WHOLE_WORD_STRICT:
1165 if (from.pos() == 0 || from.pos() == from_par.size()
1166 || !from_par.isLetter(from.pos())
1167 || !from_par.isLetter(from.pos() - 1)) {
1171 // no break here, we go to the next
1174 // If we are already at the beginning of a word, do nothing
1175 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1177 // no break here, we go to the next
1180 // always move the cursor to the beginning of previous word
1181 while (from.pos() && from_par.isLetter(from.pos() - 1))
1185 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1189 // no need to move the 'from' cursor
1193 Paragraph & to_par = pars_[to.pit()];
1194 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1199 void Text::write(Buffer const & buf, std::ostream & os) const
1201 ParagraphList::const_iterator pit = paragraphs().begin();
1202 ParagraphList::const_iterator end = paragraphs().end();
1204 for (; pit != end; ++pit)
1205 pit->write(buf, os, buf.params(), dth);
1207 // Close begin_deeper
1208 for(; dth > 0; --dth)
1209 os << "\n\\end_deeper";
1213 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1215 depth_type depth = 0;
1217 while (lex.isOK()) {
1219 string const token = lex.getString();
1224 if (token == "\\end_inset")
1227 if (token == "\\end_body")
1230 if (token == "\\begin_body")
1233 if (token == "\\end_document")
1236 if (token == "\\begin_layout") {
1237 lex.pushToken(token);
1240 par.params().depth(depth);
1241 par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1242 pars_.push_back(par);
1244 // FIXME: goddamn InsetTabular makes us pass a Buffer
1246 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1248 } else if (token == "\\begin_deeper") {
1250 } else if (token == "\\end_deeper") {
1252 lex.printError("\\end_deeper: " "depth is already null");
1257 lyxerr << "Handling unknown body token: `"
1258 << token << '\'' << endl;
1264 // Returns the current font and depth as a message.
1265 docstring Text::currentState(Cursor & cur)
1267 BOOST_ASSERT(this == cur.text());
1268 Buffer & buf = cur.buffer();
1269 Paragraph const & par = cur.paragraph();
1270 odocstringstream os;
1272 if (buf.params().trackChanges)
1273 os << _("[Change Tracking] ");
1275 Change change = par.lookupChange(cur.pos());
1277 if (change.type != Change::UNCHANGED) {
1278 Author const & a = buf.params().authors().get(change.author);
1279 os << _("Change: ") << a.name();
1280 if (!a.email().empty())
1281 os << " (" << a.email() << ")";
1282 // FIXME ctime is english, we should translate that
1283 os << _(" at ") << ctime(&change.changetime);
1287 // I think we should only show changes from the default
1289 // No, from the document font (MV)
1290 Font font = real_current_font;
1291 font.reduce(buf.params().getFont());
1293 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1295 // The paragraph depth
1296 int depth = cur.paragraph().getDepth();
1298 os << bformat(_(", Depth: %1$d"), depth);
1300 // The paragraph spacing, but only if different from
1302 Spacing const & spacing = par.params().spacing();
1303 if (!spacing.isDefault()) {
1304 os << _(", Spacing: ");
1305 switch (spacing.getSpace()) {
1306 case Spacing::Single:
1309 case Spacing::Onehalf:
1312 case Spacing::Double:
1315 case Spacing::Other:
1316 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1318 case Spacing::Default:
1319 // should never happen, do nothing
1324 #ifdef DEVEL_VERSION
1325 os << _(", Inset: ") << &cur.inset();
1326 os << _(", Paragraph: ") << cur.pit();
1327 os << _(", Id: ") << par.id();
1328 os << _(", Position: ") << cur.pos();
1329 // FIXME: Why is the check for par.size() needed?
1330 // We are called with cur.pos() == par.size() quite often.
1331 if (!par.empty() && cur.pos() < par.size()) {
1332 // Force output of code point, not character
1333 size_t const c = par.getChar(cur.pos());
1334 os << _(", Char: 0x") << std::hex << c;
1336 os << _(", Boundary: ") << cur.boundary();
1337 // Row & row = cur.textRow();
1338 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1344 docstring Text::getPossibleLabel(Cursor & cur) const
1346 pit_type pit = cur.pit();
1348 LayoutPtr layout = pars_[pit].layout();
1351 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1352 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1353 if (par_text.empty())
1356 par_text = split(par_text, head, ' ');
1357 // Is it legal to use spaces in labels ?
1363 // No need for a prefix if the user said so.
1364 if (lyxrc.label_init_length <= 0)
1367 // Will contain the label type.
1370 // For section, subsection, etc...
1371 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1372 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1373 if (layout2->latextype != LATEX_PARAGRAPH) {
1378 if (layout->latextype != LATEX_PARAGRAPH)
1379 name = from_ascii(layout->latexname());
1381 // for captions, we just take the caption type
1382 Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1384 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1386 // If none of the above worked, we'll see if we're inside various
1387 // types of insets and take our abbreviation from them.
1389 Inset::Code const codes[] = {
1394 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1395 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1397 name = float_inset->name();
1403 // Create a correct prefix for prettyref
1404 if (name == "theorem")
1405 name = from_ascii("thm");
1406 else if (name == "Foot")
1407 name = from_ascii("fn");
1408 else if (name == "listing")
1409 name = from_ascii("lst");
1412 text = name.substr(0, 3) + ':' + text;
1418 void Text::charsTranspose(Cursor & cur)
1420 BOOST_ASSERT(this == cur.text());
1422 pos_type pos = cur.pos();
1424 // If cursor is at beginning or end of paragraph, do nothing.
1425 if (pos == cur.lastpos() || pos == 0)
1428 Paragraph & par = cur.paragraph();
1430 // Get the positions of the characters to be transposed.
1431 pos_type pos1 = pos - 1;
1432 pos_type pos2 = pos;
1434 // In change tracking mode, ignore deleted characters.
1435 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1437 if (pos2 == cur.lastpos())
1440 while (pos1 >= 0 && par.isDeleted(pos1))
1445 // Don't do anything if one of the "characters" is not regular text.
1446 if (par.isInset(pos1) || par.isInset(pos2))
1449 // Store the characters to be transposed (including font information).
1450 char_type char1 = par.getChar(pos1);
1452 par.getFontSettings(cur.buffer().params(), pos1);
1454 char_type char2 = par.getChar(pos2);
1456 par.getFontSettings(cur.buffer().params(), pos2);
1458 // And finally, we are ready to perform the transposition.
1459 // Track the changes if Change Tracking is enabled.
1460 bool const trackChanges = cur.buffer().params().trackChanges;
1464 par.eraseChar(pos2, trackChanges);
1465 par.eraseChar(pos1, trackChanges);
1466 par.insertChar(pos1, char2, font2, trackChanges);
1467 par.insertChar(pos2, char1, font1, trackChanges);
1469 checkBufferStructure(cur.buffer(), cur);
1471 // After the transposition, move cursor to after the transposition.
1472 setCursor(cur, cur.pit(), pos2);