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"
28 #include "bufferview_funcs.h"
30 #include "ParIterator.h"
31 #include "CoordCache.h"
32 #include "CutAndPaste.h"
34 #include "DispatchResult.h"
36 #include "ErrorList.h"
37 #include "FuncRequest.h"
39 #include "FontIterator.h"
47 #include "MetricsInfo.h"
48 #include "Paragraph.h"
49 #include "paragraph_funcs.h"
50 #include "ParagraphParameters.h"
53 #include "WordLangTuple.h"
55 #include "frontends/FontMetrics.h"
56 #include "frontends/Painter.h"
58 #include "insets/InsetText.h"
59 #include "insets/InsetBibitem.h"
60 #include "insets/InsetCaption.h"
61 #include "insets/InsetHFill.h"
62 #include "insets/InsetLine.h"
63 #include "insets/InsetNewline.h"
64 #include "insets/InsetPagebreak.h"
65 #include "insets/InsetOptArg.h"
66 #include "insets/InsetSpace.h"
67 #include "insets/InsetSpecialChar.h"
68 #include "insets/InsetTabular.h"
70 #include "support/lstrings.h"
71 #include "support/textutils.h"
72 #include "support/convert.h"
74 #include <boost/current_function.hpp>
88 using support::bformat;
89 using support::contains;
90 using support::lowercase;
92 using support::uppercase;
94 using cap::cutSelection;
95 using cap::pasteParagraphList;
97 using frontend::FontMetrics;
101 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
102 string const & token, Font & font, Change & change, ErrorList & errorList)
104 BufferParams const & bp = buf.params();
106 if (token[0] != '\\') {
108 string::const_iterator cit = token.begin();
109 for (; cit != token.end(); ++cit)
110 par.insertChar(par.size(), (*cit), font, change);
112 docstring dstr = lex.getDocString();
113 docstring::const_iterator cit = dstr.begin();
114 docstring::const_iterator cend = dstr.end();
115 for (; cit != cend; ++cit)
116 par.insertChar(par.size(), *cit, font, change);
118 } else if (token == "\\begin_layout") {
120 docstring layoutname = lex.getDocString();
122 font = Font(Font::ALL_INHERIT, bp.language);
123 change = Change(Change::UNCHANGED);
125 TextClass const & tclass = bp.getTextClass();
127 if (layoutname.empty()) {
128 layoutname = tclass.defaultLayoutName();
131 bool hasLayout = tclass.hasLayout(layoutname);
134 errorList.push_back(ErrorItem(_("Unknown layout"),
135 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
136 layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
137 layoutname = tclass.defaultLayoutName();
140 par.layout(bp.getTextClass()[layoutname]);
142 // Test whether the layout is obsolete.
143 LayoutPtr const & layout = par.layout();
144 if (!layout->obsoleted_by().empty())
145 par.layout(bp.getTextClass()[layout->obsoleted_by()]);
147 par.params().read(lex);
149 } else if (token == "\\end_layout") {
150 lyxerr << BOOST_CURRENT_FUNCTION
151 << ": Solitary \\end_layout in line "
152 << lex.getLineNo() << "\n"
153 << "Missing \\begin_layout?.\n";
154 } else if (token == "\\end_inset") {
155 lyxerr << BOOST_CURRENT_FUNCTION
156 << ": Solitary \\end_inset in line "
157 << lex.getLineNo() << "\n"
158 << "Missing \\begin_inset?.\n";
159 } else if (token == "\\begin_inset") {
160 Inset * inset = readInset(lex, buf);
162 par.insertInset(par.size(), inset, font, change);
165 docstring line = lex.getDocString();
166 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
167 par.id(), 0, par.size()));
169 } else if (token == "\\family") {
171 font.setLyXFamily(lex.getString());
172 } else if (token == "\\series") {
174 font.setLyXSeries(lex.getString());
175 } else if (token == "\\shape") {
177 font.setLyXShape(lex.getString());
178 } else if (token == "\\size") {
180 font.setLyXSize(lex.getString());
181 } else if (token == "\\lang") {
183 string const tok = lex.getString();
184 Language const * lang = languages.getLanguage(tok);
186 font.setLanguage(lang);
188 font.setLanguage(bp.language);
189 lex.printError("Unknown language `$$Token'");
191 } else if (token == "\\numeric") {
193 font.setNumber(font.setLyXMisc(lex.getString()));
194 } else if (token == "\\emph") {
196 font.setEmph(font.setLyXMisc(lex.getString()));
197 } else if (token == "\\bar") {
199 string const tok = lex.getString();
202 font.setUnderbar(Font::ON);
203 else if (tok == "no")
204 font.setUnderbar(Font::OFF);
205 else if (tok == "default")
206 font.setUnderbar(Font::INHERIT);
208 lex.printError("Unknown bar font flag "
210 } else if (token == "\\noun") {
212 font.setNoun(font.setLyXMisc(lex.getString()));
213 } else if (token == "\\color") {
215 font.setLyXColor(lex.getString());
216 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
218 // Insets don't make sense in a free-spacing context! ---Kayvan
219 if (par.isFreeSpacing()) {
220 if (token == "\\InsetSpace")
221 par.insertChar(par.size(), ' ', font, change);
222 else if (lex.isOK()) {
224 string const next_token = lex.getString();
225 if (next_token == "\\-")
226 par.insertChar(par.size(), '-', font, change);
228 lex.printError("Token `$$Token' "
230 "paragraph layout!");
234 auto_ptr<Inset> inset;
235 if (token == "\\SpecialChar" )
236 inset.reset(new InsetSpecialChar);
238 inset.reset(new InsetSpace);
239 inset->read(buf, lex);
240 par.insertInset(par.size(), inset.release(),
243 } else if (token == "\\backslash") {
244 par.insertChar(par.size(), '\\', font, change);
245 } else if (token == "\\newline") {
246 auto_ptr<Inset> inset(new InsetNewline);
247 inset->read(buf, lex);
248 par.insertInset(par.size(), inset.release(), font, change);
249 } else if (token == "\\LyXTable") {
250 auto_ptr<Inset> inset(new InsetTabular(buf));
251 inset->read(buf, lex);
252 par.insertInset(par.size(), inset.release(), font, change);
253 } else if (token == "\\hfill") {
254 par.insertInset(par.size(), new InsetHFill, font, change);
255 } else if (token == "\\lyxline") {
256 par.insertInset(par.size(), new InsetLine, font, change);
257 } else if (token == "\\newpage") {
258 par.insertInset(par.size(), new InsetPagebreak, font, change);
259 } else if (token == "\\clearpage") {
260 par.insertInset(par.size(), new InsetClearPage, font, change);
261 } else if (token == "\\cleardoublepage") {
262 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
263 } else if (token == "\\change_unchanged") {
264 change = Change(Change::UNCHANGED);
265 } else if (token == "\\change_inserted") {
267 std::istringstream is(lex.getString());
271 if (aid >= bp.author_map.size()) {
272 errorList.push_back(ErrorItem(_("Change tracking error"),
273 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
274 par.id(), 0, par.size()));
275 change = Change(Change::UNCHANGED);
277 change = Change(Change::INSERTED, bp.author_map[aid], ct);
278 } else if (token == "\\change_deleted") {
280 std::istringstream is(lex.getString());
284 if (aid >= bp.author_map.size()) {
285 errorList.push_back(ErrorItem(_("Change tracking error"),
286 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
287 par.id(), 0, par.size()));
288 change = Change(Change::UNCHANGED);
290 change = Change(Change::DELETED, bp.author_map[aid], ct);
293 errorList.push_back(ErrorItem(_("Unknown token"),
294 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
296 par.id(), 0, par.size()));
301 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
302 ErrorList & errorList)
305 string token = lex.getString();
307 Change change(Change::UNCHANGED);
310 readParToken(buf, par, lex, token, font, change, errorList);
313 token = lex.getString();
318 if (token == "\\end_layout") {
319 //Ok, paragraph finished
323 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
324 << token << '\'' << endl;
325 if (token == "\\begin_layout" || token == "\\end_document"
326 || token == "\\end_inset" || token == "\\begin_deeper"
327 || token == "\\end_deeper") {
328 lex.pushToken(token);
329 lyxerr << "Paragraph ended in line "
330 << lex.getLineNo() << "\n"
331 << "Missing \\end_layout.\n";
335 // Final change goes to paragraph break:
336 par.setChange(par.size(), change);
338 // Initialize begin_of_body_ on load; redoParagraph maintains
339 par.setBeginOfBody();
346 bool Text::empty() const
348 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
349 // FIXME: Should we consider the labeled type as empty too?
350 && pars_[0].layout()->labeltype == LABEL_NO_LABEL);
354 double Text::spacing(Buffer const & buffer,
355 Paragraph const & par) const
357 if (par.params().spacing().isDefault())
358 return buffer.params().spacing().getValue();
359 return par.params().spacing().getValue();
363 Color_color Text::backgroundColor() const
365 return Color_color(Color::color(background_color_));
369 void Text::breakParagraph(Cursor & cur, bool keep_layout)
371 BOOST_ASSERT(this == cur.text());
373 Paragraph & cpar = cur.paragraph();
374 pit_type cpit = cur.pit();
376 TextClass const & tclass = cur.buffer().params().getTextClass();
377 LayoutPtr const & layout = cpar.layout();
379 // this is only allowed, if the current paragraph is not empty
380 // or caption and if it has not the keepempty flag active
381 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
382 layout->labeltype != LABEL_SENSITIVE)
385 // a layout change may affect also the following paragraph
386 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
388 // Always break behind a space
389 // It is better to erase the space (Dekel)
390 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
391 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
393 // What should the layout for the new paragraph be?
394 int preserve_layout = 0;
398 preserve_layout = layout->isEnvironment();
400 // We need to remember this before we break the paragraph, because
401 // that invalidates the layout variable
402 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
404 // we need to set this before we insert the paragraph.
405 bool const isempty = cpar.allowEmpty() && cpar.empty();
407 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
408 cur.pos(), preserve_layout);
410 // After this, neither paragraph contains any rows!
413 pit_type next_par = cpit + 1;
415 // well this is the caption hack since one caption is really enough
418 // set to standard-layout
419 pars_[cpit].applyLayout(tclass.defaultLayout());
421 // set to standard-layout
422 pars_[next_par].applyLayout(tclass.defaultLayout());
425 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
426 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
427 break; // the character couldn't be deleted physically due to change tracking
430 updateLabels(cur.buffer());
432 // A singlePar update is not enough in this case.
433 cur.updateFlags(Update::Force);
435 // This check is necessary. Otherwise the new empty paragraph will
436 // be deleted automatically. And it is more friendly for the user!
437 if (cur.pos() != 0 || isempty)
438 setCursor(cur, cur.pit() + 1, 0);
440 setCursor(cur, cur.pit(), 0);
444 // insert a character, moves all the following breaks in the
445 // same Paragraph one to the right and make a rebreak
446 void Text::insertChar(Cursor & cur, char_type c)
448 BOOST_ASSERT(this == cur.text());
449 BOOST_ASSERT(c != Paragraph::META_INSET);
451 recordUndo(cur, Undo::INSERT);
453 Buffer const & buffer = cur.buffer();
454 Paragraph & par = cur.paragraph();
455 // try to remove this
456 pit_type const pit = cur.pit();
458 bool const freeSpacing = par.layout()->free_spacing ||
461 if (lyxrc.auto_number) {
462 static docstring const number_operators = from_ascii("+-/*");
463 static docstring const number_unary_operators = from_ascii("+-");
464 static docstring const number_seperators = from_ascii(".,:");
466 if (current_font.number() == Font::ON) {
467 if (!isDigit(c) && !contains(number_operators, c) &&
468 !(contains(number_seperators, c) &&
470 cur.pos() != cur.lastpos() &&
471 getFont(buffer, par, cur.pos()).number() == Font::ON &&
472 getFont(buffer, par, cur.pos() - 1).number() == Font::ON)
474 number(cur); // Set current_font.number to OFF
475 } else if (isDigit(c) &&
476 real_current_font.isVisibleRightToLeft()) {
477 number(cur); // Set current_font.number to ON
479 if (cur.pos() != 0) {
480 char_type const c = par.getChar(cur.pos() - 1);
481 if (contains(number_unary_operators, c) &&
483 || par.isSeparator(cur.pos() - 2)
484 || par.isNewline(cur.pos() - 2))
486 setCharFont(buffer, pit, cur.pos() - 1, current_font);
487 } else if (contains(number_seperators, c)
489 && getFont(buffer, par, cur.pos() - 2).number() == Font::ON) {
490 setCharFont(buffer, pit, cur.pos() - 1, current_font);
496 // In Bidi text, we want spaces to be treated in a special way: spaces
497 // which are between words in different languages should get the
498 // paragraph's language; otherwise, spaces should keep the language
499 // they were originally typed in. This is only in effect while typing;
500 // after the text is already typed in, the user can always go back and
501 // explicitly set the language of a space as desired. But 99.9% of the
502 // time, what we're doing here is what the user actually meant.
504 // The following cases are the ones in which the language of the space
505 // should be changed to match that of the containing paragraph. In the
506 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
507 // represents a space, pipe (|) represents the cursor position (so the
508 // character before it is the one just typed in). The different cases
509 // are depicted logically (not visually), from left to right:
514 // Theoretically, there are other situations that we should, perhaps, deal
515 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
516 // point (to understand why, just try to create this situation...).
518 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
519 // get font in front and behind the space in question. But do NOT
520 // use getFont(cur.pos()) because the character c is not inserted yet
521 Font const & pre_space_font = getFont(buffer, par, cur.pos() - 2);
522 Font const & post_space_font = real_current_font;
523 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
524 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
526 if (pre_space_rtl != post_space_rtl) {
527 // Set the space's language to match the language of the
528 // adjacent character whose direction is the paragraph's
529 // direction; don't touch other properties of the font
530 Language const * lang =
531 (pre_space_rtl == par.isRightToLeftPar(buffer.params())) ?
532 pre_space_font.language() : post_space_font.language();
534 Font space_font = getFont(buffer, par, cur.pos() - 1);
535 space_font.setLanguage(lang);
536 par.setFont(cur.pos() - 1, space_font);
540 // Next check, if there will be two blanks together or a blank at
541 // the beginning of a paragraph.
542 // I decided to handle blanks like normal characters, the main
543 // difference are the special checks when calculating the row.fill
544 // (blank does not count at the end of a row) and the check here
546 // When the free-spacing option is set for the current layout,
547 // disable the double-space checking
548 if (!freeSpacing && isLineSeparatorChar(c)) {
549 if (cur.pos() == 0) {
550 static bool sent_space_message = false;
551 if (!sent_space_message) {
552 cur.message(_("You cannot insert a space at the "
553 "beginning of a paragraph. Please read the Tutorial."));
554 sent_space_message = true;
558 BOOST_ASSERT(cur.pos() > 0);
559 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
560 && !par.isDeleted(cur.pos() - 1)) {
561 static bool sent_space_message = false;
562 if (!sent_space_message) {
563 cur.message(_("You cannot type two spaces this way. "
564 "Please read the Tutorial."));
565 sent_space_message = true;
571 par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
572 checkBufferStructure(cur.buffer(), cur);
574 // cur.updateFlags(Update::Force);
575 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
580 void Text::charInserted()
582 // Here we call finishUndo for every 20 characters inserted.
583 // This is from my experience how emacs does it. (Lgb)
584 static unsigned int counter;
594 // the cursor set functions have a special mechanism. When they
595 // realize, that you left an empty paragraph, they will delete it.
597 bool Text::cursorRightOneWord(Cursor & cur)
599 BOOST_ASSERT(this == cur.text());
603 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
607 // Advance through word.
608 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
610 // Skip through trailing nonword stuff.
611 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
614 return setCursor(cur, old.pit(), old.pos());
618 bool Text::cursorLeftOneWord(Cursor & cur)
620 BOOST_ASSERT(this == cur.text());
624 if (old.pos() == 0 && old.pit() != 0) {
626 old.pos() = old.lastpos();
628 // Skip through initial nonword stuff.
629 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
631 // Advance through word.
632 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
635 return setCursor(cur, old.pit(), old.pos());
639 void Text::selectWord(Cursor & cur, word_location loc)
641 BOOST_ASSERT(this == cur.text());
642 CursorSlice from = cur.top();
643 CursorSlice to = cur.top();
644 getWord(from, to, loc);
645 if (cur.top() != from)
646 setCursor(cur, from.pit(), from.pos());
650 setCursor(cur, to.pit(), to.pos());
655 // Select the word currently under the cursor when no
656 // selection is currently set
657 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
659 BOOST_ASSERT(this == cur.text());
662 selectWord(cur, loc);
663 return cur.selection();
667 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
669 BOOST_ASSERT(this == cur.text());
671 if (!cur.selection())
674 recordUndoSelection(cur, Undo::ATOMIC);
676 pit_type begPit = cur.selectionBegin().pit();
677 pit_type endPit = cur.selectionEnd().pit();
679 pos_type begPos = cur.selectionBegin().pos();
680 pos_type endPos = cur.selectionEnd().pos();
682 // keep selection info, because endPos becomes invalid after the first loop
683 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
685 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
687 for (pit_type pit = begPit; pit <= endPit; ++pit) {
688 pos_type parSize = pars_[pit].size();
690 // ignore empty paragraphs; otherwise, an assertion will fail for
691 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
695 // do not consider first paragraph if the cursor starts at pos size()
696 if (pit == begPit && begPos == parSize)
699 // do not consider last paragraph if the cursor ends at pos 0
700 if (pit == endPit && endPos == 0)
701 break; // last iteration anyway
703 pos_type left = (pit == begPit ? begPos : 0);
704 pos_type right = (pit == endPit ? endPos : parSize);
707 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
709 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
713 // next, accept/reject imaginary end-of-par characters
715 for (pit_type pit = begPit; pit <= endPit; ++pit) {
716 pos_type pos = pars_[pit].size();
718 // skip if the selection ends before the end-of-par
719 if (pit == endPit && endsBeforeEndOfPar)
720 break; // last iteration anyway
722 // skip if this is not the last paragraph of the document
723 // note: the user should be able to accept/reject the par break of the last par!
724 if (pit == endPit && pit + 1 != int(pars_.size()))
725 break; // last iteration anway
728 if (pars_[pit].isInserted(pos)) {
729 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
730 } else if (pars_[pit].isDeleted(pos)) {
731 if (pit + 1 == int(pars_.size())) {
732 // we cannot remove a par break at the end of the last paragraph;
733 // instead, we mark it unchanged
734 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
736 mergeParagraph(cur.buffer().params(), pars_, pit);
742 if (pars_[pit].isDeleted(pos)) {
743 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
744 } else if (pars_[pit].isInserted(pos)) {
745 if (pit + 1 == int(pars_.size())) {
746 // we mark the par break at the end of the last paragraph unchanged
747 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
749 mergeParagraph(cur.buffer().params(), pars_, pit);
757 // finally, invoke the DEPM
759 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
764 cur.clearSelection();
765 setCursorIntern(cur, begPit, begPos);
766 cur.updateFlags(Update::Force);
767 updateLabels(cur.buffer());
771 void Text::acceptChanges(BufferParams const & bparams)
773 lyx::acceptChanges(pars_, bparams);
774 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
778 void Text::rejectChanges(BufferParams const & bparams)
780 pit_type pars_size = static_cast<pit_type>(pars_.size());
782 // first, reject changes within each individual paragraph
783 // (do not consider end-of-par)
784 for (pit_type pit = 0; pit < pars_size; ++pit) {
785 if (!pars_[pit].empty()) // prevent assertion failure
786 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
789 // next, reject imaginary end-of-par characters
790 for (pit_type pit = 0; pit < pars_size; ++pit) {
791 pos_type pos = pars_[pit].size();
793 if (pars_[pit].isDeleted(pos)) {
794 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
795 } else if (pars_[pit].isInserted(pos)) {
796 if (pit == pars_size - 1) {
797 // we mark the par break at the end of the last
798 // paragraph unchanged
799 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
801 mergeParagraph(bparams, pars_, pit);
808 // finally, invoke the DEPM
809 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
813 void Text::deleteWordForward(Cursor & cur)
815 BOOST_ASSERT(this == cur.text());
816 if (cur.lastpos() == 0)
820 cur.selection() = true;
821 cursorRightOneWord(cur);
823 cutSelection(cur, true, false);
824 checkBufferStructure(cur.buffer(), cur);
829 void Text::deleteWordBackward(Cursor & cur)
831 BOOST_ASSERT(this == cur.text());
832 if (cur.lastpos() == 0)
836 cur.selection() = true;
837 cursorLeftOneWord(cur);
839 cutSelection(cur, true, false);
840 checkBufferStructure(cur.buffer(), cur);
845 // Kill to end of line.
846 void Text::changeCase(Cursor & cur, Text::TextCase action)
848 BOOST_ASSERT(this == cur.text());
852 if (cur.selection()) {
853 from = cur.selBegin();
857 getWord(from, to, PARTIAL_WORD);
858 cursorRightOneWord(cur);
861 recordUndoSelection(cur, Undo::ATOMIC);
863 pit_type begPit = from.pit();
864 pit_type endPit = to.pit();
866 pos_type begPos = from.pos();
867 pos_type endPos = to.pos();
869 bool const trackChanges = cur.buffer().params().trackChanges;
871 pos_type right = 0; // needed after the for loop
873 for (pit_type pit = begPit; pit <= endPit; ++pit) {
874 pos_type parSize = pars_[pit].size();
876 pos_type pos = (pit == begPit ? begPos : 0);
877 right = (pit == endPit ? endPos : parSize);
879 // process sequences of modified characters; in change
880 // tracking mode, this approach results in much better
881 // usability than changing case on a char-by-char basis
884 bool capitalize = true;
886 for (; pos < right; ++pos) {
887 char_type oldChar = pars_[pit].getChar(pos);
888 char_type newChar = oldChar;
890 // ignore insets and don't play with deleted text!
891 if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
894 newChar = lowercase(oldChar);
896 case text_capitalization:
898 newChar = uppercase(oldChar);
903 newChar = uppercase(oldChar);
908 if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
909 capitalize = true; // permit capitalization again
912 if (oldChar != newChar) {
916 if (oldChar == newChar || pos == right - 1) {
917 if (oldChar != newChar) {
918 pos++; // step behind the changing area
920 int erasePos = pos - changes.size();
921 for (size_t i = 0; i < changes.size(); i++) {
922 pars_[pit].insertChar(pos, changes[i],
923 pars_[pit].getFontSettings(cur.buffer().params(),
926 if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
929 ++right; // expand selection
937 // the selection may have changed due to logically-only deleted chars
938 setCursor(cur, begPit, begPos);
940 setCursor(cur, endPit, right);
943 checkBufferStructure(cur.buffer(), cur);
947 bool Text::handleBibitems(Cursor & cur)
949 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
951 // if a bibitem is deleted, merge with previous paragraph
952 // if this is a bibliography item as well
953 if (cur.pos() == 0) {
954 BufferParams const & bufparams = cur.buffer().params();
955 Paragraph const & par = cur.paragraph();
956 Cursor prevcur = cur;
959 prevcur.pos() = prevcur.lastpos();
961 Paragraph const & prevpar = prevcur.paragraph();
962 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
963 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
964 mergeParagraph(bufparams, cur.text()->paragraphs(),
966 updateLabels(cur.buffer());
967 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
968 cur.updateFlags(Update::Force);
969 // if not, reset the paragraph to default
971 cur.paragraph().layout(
972 bufparams.getTextClass().defaultLayout());
979 bool Text::erase(Cursor & cur)
981 BOOST_ASSERT(this == cur.text());
982 bool needsUpdate = false;
983 Paragraph & par = cur.paragraph();
985 if (cur.pos() != cur.lastpos()) {
986 // this is the code for a normal delete, not pasting
988 recordUndo(cur, Undo::DELETE);
989 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
990 // the character has been logically deleted only => skip it
991 cur.top().forwardPos();
993 checkBufferStructure(cur.buffer(), cur);
996 if (cur.pit() == cur.lastpit())
997 return dissolveInset(cur);
999 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1000 par.setChange(cur.pos(), Change(Change::DELETED));
1004 setCursorIntern(cur, cur.pit() + 1, 0);
1005 needsUpdate = backspacePos0(cur);
1009 needsUpdate |= handleBibitems(cur);
1012 // Make sure the cursor is correct. Is this really needed?
1013 // No, not really... at least not here!
1014 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1015 checkBufferStructure(cur.buffer(), cur);
1022 bool Text::backspacePos0(Cursor & cur)
1024 BOOST_ASSERT(this == cur.text());
1028 bool needsUpdate = false;
1030 BufferParams const & bufparams = cur.buffer().params();
1031 TextClass const & tclass = bufparams.getTextClass();
1032 ParagraphList & plist = cur.text()->paragraphs();
1033 Paragraph const & par = cur.paragraph();
1034 Cursor prevcur = cur;
1036 prevcur.pos() = prevcur.lastpos();
1037 Paragraph const & prevpar = prevcur.paragraph();
1039 // is it an empty paragraph?
1040 if (cur.lastpos() == 0
1041 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1042 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1043 plist.erase(boost::next(plist.begin(), cur.pit()));
1046 // is previous par empty?
1047 else if (prevcur.lastpos() == 0
1048 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1049 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1050 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1053 // Pasting is not allowed, if the paragraphs have different
1054 // layouts. I think it is a real bug of all other
1055 // word processors to allow it. It confuses the user.
1056 // Correction: Pasting is always allowed with standard-layout
1057 else if (par.layout() == prevpar.layout()
1058 || par.layout() == tclass.defaultLayout()) {
1059 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1060 mergeParagraph(bufparams, plist, prevcur.pit());
1065 updateLabels(cur.buffer());
1066 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1073 bool Text::backspace(Cursor & cur)
1075 BOOST_ASSERT(this == cur.text());
1076 bool needsUpdate = false;
1077 if (cur.pos() == 0) {
1079 return dissolveInset(cur);
1081 Paragraph & prev_par = pars_[cur.pit() - 1];
1083 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1084 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1085 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1088 // The cursor is at the beginning of a paragraph, so
1089 // the backspace will collapse two paragraphs into one.
1090 needsUpdate = backspacePos0(cur);
1093 // this is the code for a normal backspace, not pasting
1095 recordUndo(cur, Undo::DELETE);
1096 // We used to do cursorLeftIntern() here, but it is
1097 // not a good idea since it triggers the auto-delete
1098 // mechanism. So we do a cursorLeftIntern()-lite,
1099 // without the dreaded mechanism. (JMarc)
1100 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1101 false, cur.boundary());
1102 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1103 checkBufferStructure(cur.buffer(), cur);
1106 if (cur.pos() == cur.lastpos())
1107 setCurrentFont(cur);
1109 needsUpdate |= handleBibitems(cur);
1111 // A singlePar update is not enough in this case.
1112 // cur.updateFlags(Update::Force);
1113 setCursor(cur.top(), cur.pit(), cur.pos());
1119 bool Text::dissolveInset(Cursor & cur) {
1120 BOOST_ASSERT(this == cur.text());
1122 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1125 recordUndoInset(cur);
1126 cur.selHandle(false);
1128 pos_type spos = cur.pos();
1129 pit_type spit = cur.pit();
1130 ParagraphList plist;
1131 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1132 plist = paragraphs();
1134 // store cursor offset
1138 Buffer & b = cur.buffer();
1139 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1140 if (!plist.empty()) {
1141 // ERT paragraphs have the Language latex_language.
1142 // This is invalid outside of ERT, so we need to
1143 // change it to the buffer language.
1144 ParagraphList::iterator it = plist.begin();
1145 ParagraphList::iterator it_end = plist.end();
1146 for (; it != it_end; it++) {
1147 it->changeLanguage(b.params(), latex_language,
1151 pasteParagraphList(cur, plist, b.params().getTextClass_ptr(),
1152 b.errorList("Paste"));
1154 cur.pit() = std::min(cur.lastpit(), spit);
1155 cur.pos() = std::min(cur.lastpos(), spos);
1157 cur.clearSelection();
1163 void Text::getWord(CursorSlice & from, CursorSlice & to,
1164 word_location const loc)
1166 Paragraph const & from_par = pars_[from.pit()];
1168 case WHOLE_WORD_STRICT:
1169 if (from.pos() == 0 || from.pos() == from_par.size()
1170 || !from_par.isLetter(from.pos())
1171 || !from_par.isLetter(from.pos() - 1)) {
1175 // no break here, we go to the next
1178 // If we are already at the beginning of a word, do nothing
1179 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1181 // no break here, we go to the next
1184 // always move the cursor to the beginning of previous word
1185 while (from.pos() && from_par.isLetter(from.pos() - 1))
1189 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1193 // no need to move the 'from' cursor
1197 Paragraph & to_par = pars_[to.pit()];
1198 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1203 void Text::write(Buffer const & buf, std::ostream & os) const
1205 ParagraphList::const_iterator pit = paragraphs().begin();
1206 ParagraphList::const_iterator end = paragraphs().end();
1208 for (; pit != end; ++pit)
1209 pit->write(buf, os, buf.params(), dth);
1211 // Close begin_deeper
1212 for(; dth > 0; --dth)
1213 os << "\n\\end_deeper";
1217 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1219 depth_type depth = 0;
1221 while (lex.isOK()) {
1223 string const token = lex.getString();
1228 if (token == "\\end_inset")
1231 if (token == "\\end_body")
1234 if (token == "\\begin_body")
1237 if (token == "\\end_document")
1240 if (token == "\\begin_layout") {
1241 lex.pushToken(token);
1244 par.params().depth(depth);
1245 par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1246 pars_.push_back(par);
1248 // FIXME: goddamn InsetTabular makes us pass a Buffer
1250 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1252 } else if (token == "\\begin_deeper") {
1254 } else if (token == "\\end_deeper") {
1256 lex.printError("\\end_deeper: " "depth is already null");
1261 lyxerr << "Handling unknown body token: `"
1262 << token << '\'' << endl;
1268 // Returns the current font and depth as a message.
1269 docstring Text::currentState(Cursor & cur)
1271 BOOST_ASSERT(this == cur.text());
1272 Buffer & buf = cur.buffer();
1273 Paragraph const & par = cur.paragraph();
1274 odocstringstream os;
1276 if (buf.params().trackChanges)
1277 os << _("[Change Tracking] ");
1279 Change change = par.lookupChange(cur.pos());
1281 if (change.type != Change::UNCHANGED) {
1282 Author const & a = buf.params().authors().get(change.author);
1283 os << _("Change: ") << a.name();
1284 if (!a.email().empty())
1285 os << " (" << a.email() << ")";
1286 // FIXME ctime is english, we should translate that
1287 os << _(" at ") << ctime(&change.changetime);
1291 // I think we should only show changes from the default
1293 // No, from the document font (MV)
1294 Font font = real_current_font;
1295 font.reduce(buf.params().getFont());
1297 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1299 // The paragraph depth
1300 int depth = cur.paragraph().getDepth();
1302 os << bformat(_(", Depth: %1$d"), depth);
1304 // The paragraph spacing, but only if different from
1306 Spacing const & spacing = par.params().spacing();
1307 if (!spacing.isDefault()) {
1308 os << _(", Spacing: ");
1309 switch (spacing.getSpace()) {
1310 case Spacing::Single:
1313 case Spacing::Onehalf:
1316 case Spacing::Double:
1319 case Spacing::Other:
1320 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1322 case Spacing::Default:
1323 // should never happen, do nothing
1328 #ifdef DEVEL_VERSION
1329 os << _(", Inset: ") << &cur.inset();
1330 os << _(", Paragraph: ") << cur.pit();
1331 os << _(", Id: ") << par.id();
1332 os << _(", Position: ") << cur.pos();
1333 // FIXME: Why is the check for par.size() needed?
1334 // We are called with cur.pos() == par.size() quite often.
1335 if (!par.empty() && cur.pos() < par.size()) {
1336 // Force output of code point, not character
1337 size_t const c = par.getChar(cur.pos());
1338 os << _(", Char: 0x") << std::hex << c;
1340 os << _(", Boundary: ") << cur.boundary();
1341 // Row & row = cur.textRow();
1342 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1348 docstring Text::getPossibleLabel(Cursor & cur) const
1350 pit_type pit = cur.pit();
1352 LayoutPtr layout = pars_[pit].layout();
1355 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1356 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1357 if (par_text.empty())
1360 par_text = split(par_text, head, ' ');
1361 // Is it legal to use spaces in labels ?
1367 // No need for a prefix if the user said so.
1368 if (lyxrc.label_init_length <= 0)
1371 // Will contain the label type.
1374 // For section, subsection, etc...
1375 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1376 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1377 if (layout2->latextype != LATEX_PARAGRAPH) {
1382 if (layout->latextype != LATEX_PARAGRAPH)
1383 name = from_ascii(layout->latexname());
1385 // for captions, we just take the caption type
1386 Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1388 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1390 // If none of the above worked, we'll see if we're inside various
1391 // types of insets and take our abbreviation from them.
1393 Inset::Code const codes[] = {
1398 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1399 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1401 name = float_inset->name();
1407 // Create a correct prefix for prettyref
1408 if (name == "theorem")
1409 name = from_ascii("thm");
1410 else if (name == "Foot")
1411 name = from_ascii("fn");
1412 else if (name == "listing")
1413 name = from_ascii("lst");
1416 text = name.substr(0, 3) + ':' + text;
1422 void Text::charsTranspose(Cursor & cur)
1424 BOOST_ASSERT(this == cur.text());
1426 pos_type pos = cur.pos();
1428 // If cursor is at beginning or end of paragraph, do nothing.
1429 if (pos == cur.lastpos() || pos == 0)
1432 Paragraph & par = cur.paragraph();
1434 // Get the positions of the characters to be transposed.
1435 pos_type pos1 = pos - 1;
1436 pos_type pos2 = pos;
1438 // In change tracking mode, ignore deleted characters.
1439 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1441 if (pos2 == cur.lastpos())
1444 while (pos1 >= 0 && par.isDeleted(pos1))
1449 // Don't do anything if one of the "characters" is not regular text.
1450 if (par.isInset(pos1) || par.isInset(pos2))
1453 // Store the characters to be transposed (including font information).
1454 char_type char1 = par.getChar(pos1);
1456 par.getFontSettings(cur.buffer().params(), pos1);
1458 char_type char2 = par.getChar(pos2);
1460 par.getFontSettings(cur.buffer().params(), pos2);
1462 // And finally, we are ready to perform the transposition.
1463 // Track the changes if Change Tracking is enabled.
1464 bool const trackChanges = cur.buffer().params().trackChanges;
1468 par.eraseChar(pos2, trackChanges);
1469 par.eraseChar(pos1, trackChanges);
1470 par.insertChar(pos1, char2, font2, trackChanges);
1471 par.insertChar(pos2, char1, font1, trackChanges);
1473 checkBufferStructure(cur.buffer(), cur);
1475 // After the transposition, move cursor to after the transposition.
1476 setCursor(cur, cur.pit(), pos2);