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"
30 #include "ParIterator.h"
31 #include "CutAndPaste.h"
33 #include "DispatchResult.h"
35 #include "ErrorList.h"
36 #include "FuncRequest.h"
38 #include "FontIterator.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "TextMetrics.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>
71 #include <boost/next_prior.hpp>
85 using support::bformat;
86 using support::contains;
89 using cap::cutSelection;
90 using cap::pasteParagraphList;
92 using frontend::FontMetrics;
96 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
97 string const & token, Font & font, Change & change, ErrorList & errorList)
99 BufferParams const & bp = buf.params();
101 if (token[0] != '\\') {
102 docstring dstr = lex.getDocString();
103 par.appendString(dstr, font, change);
105 } else if (token == "\\begin_layout") {
107 docstring layoutname = lex.getDocString();
109 font = Font(Font::ALL_INHERIT, bp.language);
110 change = Change(Change::UNCHANGED);
112 TextClass const & tclass = bp.getTextClass();
114 if (layoutname.empty()) {
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 = tclass.defaultLayoutName();
127 par.layout(bp.getTextClass()[layoutname]);
129 // Test whether the layout is obsolete.
130 LayoutPtr const & layout = par.layout();
131 if (!layout->obsoleted_by().empty())
132 par.layout(bp.getTextClass()[layout->obsoleted_by()]);
134 par.params().read(lex);
136 } else if (token == "\\end_layout") {
137 lyxerr << BOOST_CURRENT_FUNCTION
138 << ": Solitary \\end_layout in line "
139 << lex.getLineNo() << "\n"
140 << "Missing \\begin_layout?.\n";
141 } else if (token == "\\end_inset") {
142 lyxerr << BOOST_CURRENT_FUNCTION
143 << ": Solitary \\end_inset in line "
144 << lex.getLineNo() << "\n"
145 << "Missing \\begin_inset?.\n";
146 } else if (token == "\\begin_inset") {
147 Inset * inset = readInset(lex, buf);
149 par.insertInset(par.size(), inset, font, change);
152 docstring line = lex.getDocString();
153 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
154 par.id(), 0, par.size()));
156 } else if (token == "\\family") {
158 font.setLyXFamily(lex.getString());
159 } else if (token == "\\series") {
161 font.setLyXSeries(lex.getString());
162 } else if (token == "\\shape") {
164 font.setLyXShape(lex.getString());
165 } else if (token == "\\size") {
167 font.setLyXSize(lex.getString());
168 } else if (token == "\\lang") {
170 string const tok = lex.getString();
171 Language const * lang = languages.getLanguage(tok);
173 font.setLanguage(lang);
175 font.setLanguage(bp.language);
176 lex.printError("Unknown language `$$Token'");
178 } else if (token == "\\numeric") {
180 font.setNumber(font.setLyXMisc(lex.getString()));
181 } else if (token == "\\emph") {
183 font.setEmph(font.setLyXMisc(lex.getString()));
184 } else if (token == "\\bar") {
186 string const tok = lex.getString();
189 font.setUnderbar(Font::ON);
190 else if (tok == "no")
191 font.setUnderbar(Font::OFF);
192 else if (tok == "default")
193 font.setUnderbar(Font::INHERIT);
195 lex.printError("Unknown bar font flag "
197 } else if (token == "\\noun") {
199 font.setNoun(font.setLyXMisc(lex.getString()));
200 } else if (token == "\\color") {
202 font.setLyXColor(lex.getString());
203 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
205 // Insets don't make sense in a free-spacing context! ---Kayvan
206 if (par.isFreeSpacing()) {
207 if (token == "\\InsetSpace")
208 par.appendChar(' ', font, change);
209 else if (lex.isOK()) {
211 string const next_token = lex.getString();
212 if (next_token == "\\-")
213 par.appendChar('-', font, change);
215 lex.printError("Token `$$Token' "
217 "paragraph layout!");
221 auto_ptr<Inset> inset;
222 if (token == "\\SpecialChar" )
223 inset.reset(new InsetSpecialChar);
225 inset.reset(new InsetSpace);
226 inset->read(buf, lex);
227 par.insertInset(par.size(), inset.release(),
230 } else if (token == "\\backslash") {
231 par.appendChar('\\', font, change);
232 } else if (token == "\\newline") {
233 auto_ptr<Inset> inset(new InsetNewline);
234 inset->read(buf, lex);
235 par.insertInset(par.size(), inset.release(), font, change);
236 } else if (token == "\\LyXTable") {
237 auto_ptr<Inset> inset(new InsetTabular(buf));
238 inset->read(buf, lex);
239 par.insertInset(par.size(), inset.release(), font, change);
240 } else if (token == "\\hfill") {
241 par.insertInset(par.size(), new InsetHFill, font, change);
242 } else if (token == "\\lyxline") {
243 par.insertInset(par.size(), new InsetLine, font, change);
244 } else if (token == "\\newpage") {
245 par.insertInset(par.size(), new InsetPagebreak, font, change);
246 } else if (token == "\\clearpage") {
247 par.insertInset(par.size(), new InsetClearPage, font, change);
248 } else if (token == "\\cleardoublepage") {
249 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
250 } else if (token == "\\change_unchanged") {
251 change = Change(Change::UNCHANGED);
252 } else if (token == "\\change_inserted") {
254 std::istringstream is(lex.getString());
258 if (aid >= bp.author_map.size()) {
259 errorList.push_back(ErrorItem(_("Change tracking error"),
260 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
261 par.id(), 0, par.size()));
262 change = Change(Change::UNCHANGED);
264 change = Change(Change::INSERTED, bp.author_map[aid], ct);
265 } else if (token == "\\change_deleted") {
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 deletion: %1$d\n"), aid),
274 par.id(), 0, par.size()));
275 change = Change(Change::UNCHANGED);
277 change = Change(Change::DELETED, bp.author_map[aid], ct);
280 errorList.push_back(ErrorItem(_("Unknown token"),
281 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
283 par.id(), 0, par.size()));
288 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
289 ErrorList & errorList)
292 string token = lex.getString();
294 Change change(Change::UNCHANGED);
297 readParToken(buf, par, lex, token, font, change, errorList);
300 token = lex.getString();
305 if (token == "\\end_layout") {
306 //Ok, paragraph finished
310 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
311 << token << '\'' << endl;
312 if (token == "\\begin_layout" || token == "\\end_document"
313 || token == "\\end_inset" || token == "\\begin_deeper"
314 || token == "\\end_deeper") {
315 lex.pushToken(token);
316 lyxerr << "Paragraph ended in line "
317 << lex.getLineNo() << "\n"
318 << "Missing \\end_layout.\n";
322 // Final change goes to paragraph break:
323 par.setChange(par.size(), change);
325 // Initialize begin_of_body_ on load; redoParagraph maintains
326 par.setBeginOfBody();
333 bool Text::empty() const
335 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
336 // FIXME: Should we consider the labeled type as empty too?
337 && pars_[0].layout()->labeltype == LABEL_NO_LABEL);
341 double Text::spacing(Buffer const & buffer,
342 Paragraph const & par) const
344 if (par.params().spacing().isDefault())
345 return buffer.params().spacing().getValue();
346 return par.params().spacing().getValue();
350 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
352 BOOST_ASSERT(this == cur.text());
354 Paragraph & cpar = cur.paragraph();
355 pit_type cpit = cur.pit();
357 TextClass const & tclass = cur.buffer().params().getTextClass();
358 LayoutPtr const & layout = cpar.layout();
360 // this is only allowed, if the current paragraph is not empty
361 // or caption and if it has not the keepempty flag active
362 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
363 layout->labeltype != LABEL_SENSITIVE)
366 // a layout change may affect also the following paragraph
367 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
369 // Always break behind a space
370 // It is better to erase the space (Dekel)
371 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
372 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
374 // What should the layout for the new paragraph be?
375 bool keep_layout = inverse_logic ?
376 !layout->isEnvironment()
377 : layout->isEnvironment();
379 // We need to remember this before we break the paragraph, because
380 // that invalidates the layout variable
381 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
383 // we need to set this before we insert the paragraph.
384 bool const isempty = cpar.allowEmpty() && cpar.empty();
386 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
387 cur.pos(), keep_layout);
389 // After this, neither paragraph contains any rows!
392 pit_type next_par = cpit + 1;
394 // well this is the caption hack since one caption is really enough
397 // set to standard-layout
398 pars_[cpit].applyLayout(tclass.defaultLayout());
400 // set to standard-layout
401 pars_[next_par].applyLayout(tclass.defaultLayout());
404 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
405 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
406 break; // the character couldn't be deleted physically due to change tracking
409 updateLabels(cur.buffer());
411 // A singlePar update is not enough in this case.
412 cur.updateFlags(Update::Force);
414 // This check is necessary. Otherwise the new empty paragraph will
415 // be deleted automatically. And it is more friendly for the user!
416 if (cur.pos() != 0 || isempty)
417 setCursor(cur, cur.pit() + 1, 0);
419 setCursor(cur, cur.pit(), 0);
423 // insert a character, moves all the following breaks in the
424 // same Paragraph one to the right and make a rebreak
425 void Text::insertChar(Cursor & cur, char_type c)
427 BOOST_ASSERT(this == cur.text());
429 cur.recordUndo(INSERT_UNDO);
431 TextMetrics const & tm = cur.bv().textMetrics(this);
432 Buffer const & buffer = cur.buffer();
433 Paragraph & par = cur.paragraph();
434 // try to remove this
435 pit_type const pit = cur.pit();
437 bool const freeSpacing = par.layout()->free_spacing ||
440 if (lyxrc.auto_number) {
441 static docstring const number_operators = from_ascii("+-/*");
442 static docstring const number_unary_operators = from_ascii("+-");
443 static docstring const number_seperators = from_ascii(".,:");
445 if (cur.current_font.number() == Font::ON) {
446 if (!isDigit(c) && !contains(number_operators, c) &&
447 !(contains(number_seperators, c) &&
449 cur.pos() != cur.lastpos() &&
450 tm.getDisplayFont(pit, cur.pos()).number() == Font::ON &&
451 tm.getDisplayFont(pit, cur.pos() - 1).number() == Font::ON)
453 number(cur); // Set current_font.number to OFF
454 } else if (isDigit(c) &&
455 cur.real_current_font.isVisibleRightToLeft()) {
456 number(cur); // Set current_font.number to ON
458 if (cur.pos() != 0) {
459 char_type const c = par.getChar(cur.pos() - 1);
460 if (contains(number_unary_operators, c) &&
462 || par.isSeparator(cur.pos() - 2)
463 || par.isNewline(cur.pos() - 2))
465 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
467 } else if (contains(number_seperators, c)
469 && tm.getDisplayFont(pit, cur.pos() - 2).number() == Font::ON) {
470 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
477 // In Bidi text, we want spaces to be treated in a special way: spaces
478 // which are between words in different languages should get the
479 // paragraph's language; otherwise, spaces should keep the language
480 // they were originally typed in. This is only in effect while typing;
481 // after the text is already typed in, the user can always go back and
482 // explicitly set the language of a space as desired. But 99.9% of the
483 // time, what we're doing here is what the user actually meant.
485 // The following cases are the ones in which the language of the space
486 // should be changed to match that of the containing paragraph. In the
487 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
488 // represents a space, pipe (|) represents the cursor position (so the
489 // character before it is the one just typed in). The different cases
490 // are depicted logically (not visually), from left to right:
495 // Theoretically, there are other situations that we should, perhaps, deal
496 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
497 // point (to understand why, just try to create this situation...).
499 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
500 // get font in front and behind the space in question. But do NOT
501 // use getFont(cur.pos()) because the character c is not inserted yet
502 Font const & pre_space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 2);
503 Font const & post_space_font = cur.real_current_font;
504 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
505 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
507 if (pre_space_rtl != post_space_rtl) {
508 // Set the space's language to match the language of the
509 // adjacent character whose direction is the paragraph's
510 // direction; don't touch other properties of the font
511 Language const * lang =
512 (pre_space_rtl == par.isRTL(buffer.params())) ?
513 pre_space_font.language() : post_space_font.language();
515 Font space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 1);
516 space_font.setLanguage(lang);
517 par.setFont(cur.pos() - 1, space_font);
521 // Next check, if there will be two blanks together or a blank at
522 // the beginning of a paragraph.
523 // I decided to handle blanks like normal characters, the main
524 // difference are the special checks when calculating the row.fill
525 // (blank does not count at the end of a row) and the check here
527 // When the free-spacing option is set for the current layout,
528 // disable the double-space checking
529 if (!freeSpacing && isLineSeparatorChar(c)) {
530 if (cur.pos() == 0) {
531 static bool sent_space_message = false;
532 if (!sent_space_message) {
533 cur.message(_("You cannot insert a space at the "
534 "beginning of a paragraph. Please read the Tutorial."));
535 sent_space_message = true;
539 BOOST_ASSERT(cur.pos() > 0);
540 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
541 && !par.isDeleted(cur.pos() - 1)) {
542 static bool sent_space_message = false;
543 if (!sent_space_message) {
544 cur.message(_("You cannot type two spaces this way. "
545 "Please read the Tutorial."));
546 sent_space_message = true;
552 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
553 checkBufferStructure(cur.buffer(), cur);
555 // cur.updateFlags(Update::Force);
556 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
561 void Text::charInserted(Cursor & cur)
563 // Here we call finishUndo for every 20 characters inserted.
564 // This is from my experience how emacs does it. (Lgb)
565 static unsigned int counter;
575 // the cursor set functions have a special mechanism. When they
576 // realize, that you left an empty paragraph, they will delete it.
578 bool Text::cursorRightOneWord(Cursor & cur)
580 BOOST_ASSERT(this == cur.text());
584 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
588 // Advance through word.
589 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
591 // Skip through trailing nonword stuff.
592 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
595 return setCursor(cur, old.pit(), old.pos());
599 bool Text::cursorLeftOneWord(Cursor & cur)
601 BOOST_ASSERT(this == cur.text());
605 if (old.pos() == 0 && old.pit() != 0) {
607 old.pos() = old.lastpos();
609 // Skip through initial nonword stuff.
610 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
612 // Advance through word.
613 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
616 return setCursor(cur, old.pit(), old.pos());
620 void Text::selectWord(Cursor & cur, word_location loc)
622 BOOST_ASSERT(this == cur.text());
623 CursorSlice from = cur.top();
624 CursorSlice to = cur.top();
625 getWord(from, to, loc);
626 if (cur.top() != from)
627 setCursor(cur, from.pit(), from.pos());
631 setCursor(cur, to.pit(), to.pos());
636 // Select the word currently under the cursor when no
637 // selection is currently set
638 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
640 BOOST_ASSERT(this == cur.text());
643 selectWord(cur, loc);
644 return cur.selection();
648 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
650 BOOST_ASSERT(this == cur.text());
652 if (!cur.selection())
655 cur.recordUndoSelection();
657 pit_type begPit = cur.selectionBegin().pit();
658 pit_type endPit = cur.selectionEnd().pit();
660 pos_type begPos = cur.selectionBegin().pos();
661 pos_type endPos = cur.selectionEnd().pos();
663 // keep selection info, because endPos becomes invalid after the first loop
664 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
666 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
668 for (pit_type pit = begPit; pit <= endPit; ++pit) {
669 pos_type parSize = pars_[pit].size();
671 // ignore empty paragraphs; otherwise, an assertion will fail for
672 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
676 // do not consider first paragraph if the cursor starts at pos size()
677 if (pit == begPit && begPos == parSize)
680 // do not consider last paragraph if the cursor ends at pos 0
681 if (pit == endPit && endPos == 0)
682 break; // last iteration anyway
684 pos_type left = (pit == begPit ? begPos : 0);
685 pos_type right = (pit == endPit ? endPos : parSize);
688 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
690 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
694 // next, accept/reject imaginary end-of-par characters
696 for (pit_type pit = begPit; pit <= endPit; ++pit) {
697 pos_type pos = pars_[pit].size();
699 // skip if the selection ends before the end-of-par
700 if (pit == endPit && endsBeforeEndOfPar)
701 break; // last iteration anyway
703 // skip if this is not the last paragraph of the document
704 // note: the user should be able to accept/reject the par break of the last par!
705 if (pit == endPit && pit + 1 != int(pars_.size()))
706 break; // last iteration anway
709 if (pars_[pit].isInserted(pos)) {
710 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
711 } else if (pars_[pit].isDeleted(pos)) {
712 if (pit + 1 == int(pars_.size())) {
713 // we cannot remove a par break at the end of the last paragraph;
714 // instead, we mark it unchanged
715 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
717 mergeParagraph(cur.buffer().params(), pars_, pit);
723 if (pars_[pit].isDeleted(pos)) {
724 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
725 } else if (pars_[pit].isInserted(pos)) {
726 if (pit + 1 == int(pars_.size())) {
727 // we mark the par break at the end of the last paragraph unchanged
728 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
730 mergeParagraph(cur.buffer().params(), pars_, pit);
738 // finally, invoke the DEPM
740 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
745 cur.clearSelection();
746 setCursorIntern(cur, begPit, begPos);
747 cur.updateFlags(Update::Force);
748 updateLabels(cur.buffer());
752 void Text::acceptChanges(BufferParams const & bparams)
754 lyx::acceptChanges(pars_, bparams);
755 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
759 void Text::rejectChanges(BufferParams const & bparams)
761 pit_type pars_size = static_cast<pit_type>(pars_.size());
763 // first, reject changes within each individual paragraph
764 // (do not consider end-of-par)
765 for (pit_type pit = 0; pit < pars_size; ++pit) {
766 if (!pars_[pit].empty()) // prevent assertion failure
767 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
770 // next, reject imaginary end-of-par characters
771 for (pit_type pit = 0; pit < pars_size; ++pit) {
772 pos_type pos = pars_[pit].size();
774 if (pars_[pit].isDeleted(pos)) {
775 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
776 } else if (pars_[pit].isInserted(pos)) {
777 if (pit == pars_size - 1) {
778 // we mark the par break at the end of the last
779 // paragraph unchanged
780 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
782 mergeParagraph(bparams, pars_, pit);
789 // finally, invoke the DEPM
790 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
794 void Text::deleteWordForward(Cursor & cur)
796 BOOST_ASSERT(this == cur.text());
797 if (cur.lastpos() == 0)
801 cur.selection() = true;
802 cursorRightOneWord(cur);
804 cutSelection(cur, true, false);
805 checkBufferStructure(cur.buffer(), cur);
810 void Text::deleteWordBackward(Cursor & cur)
812 BOOST_ASSERT(this == cur.text());
813 if (cur.lastpos() == 0)
817 cur.selection() = true;
818 cursorLeftOneWord(cur);
820 cutSelection(cur, true, false);
821 checkBufferStructure(cur.buffer(), cur);
826 // Kill to end of line.
827 void Text::changeCase(Cursor & cur, TextCase action)
829 BOOST_ASSERT(this == cur.text());
833 if (cur.selection()) {
834 from = cur.selBegin();
838 getWord(from, to, PARTIAL_WORD);
839 cursorRightOneWord(cur);
842 cur.recordUndoSelection();
844 pit_type begPit = from.pit();
845 pit_type endPit = to.pit();
847 pos_type begPos = from.pos();
848 pos_type endPos = to.pos();
850 pos_type right = 0; // needed after the for loop
852 for (pit_type pit = begPit; pit <= endPit; ++pit) {
853 Paragraph & par = pars_[pit];
854 pos_type const pos = (pit == begPit ? begPos : 0);
855 right = (pit == endPit ? endPos : par.size());
856 par.changeCase(cur.buffer().params(), pos, right, action);
859 // the selection may have changed due to logically-only deleted chars
860 setCursor(cur, begPit, begPos);
862 setCursor(cur, endPit, right);
865 checkBufferStructure(cur.buffer(), cur);
869 bool Text::handleBibitems(Cursor & cur)
871 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
873 // if a bibitem is deleted, merge with previous paragraph
874 // if this is a bibliography item as well
875 if (cur.pos() == 0) {
876 BufferParams const & bufparams = cur.buffer().params();
877 Paragraph const & par = cur.paragraph();
878 Cursor prevcur = cur;
881 prevcur.pos() = prevcur.lastpos();
883 Paragraph const & prevpar = prevcur.paragraph();
884 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
885 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
886 mergeParagraph(bufparams, cur.text()->paragraphs(),
888 updateLabels(cur.buffer());
889 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
890 cur.updateFlags(Update::Force);
891 // if not, reset the paragraph to default
893 cur.paragraph().layout(
894 bufparams.getTextClass().defaultLayout());
901 bool Text::erase(Cursor & cur)
903 BOOST_ASSERT(this == cur.text());
904 bool needsUpdate = false;
905 Paragraph & par = cur.paragraph();
907 if (cur.pos() != cur.lastpos()) {
908 // this is the code for a normal delete, not pasting
910 cur.recordUndo(DELETE_UNDO);
911 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
912 // the character has been logically deleted only => skip it
913 cur.top().forwardPos();
915 checkBufferStructure(cur.buffer(), cur);
918 if (cur.pit() == cur.lastpit())
919 return dissolveInset(cur);
921 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
922 par.setChange(cur.pos(), Change(Change::DELETED));
926 setCursorIntern(cur, cur.pit() + 1, 0);
927 needsUpdate = backspacePos0(cur);
931 needsUpdate |= handleBibitems(cur);
934 // Make sure the cursor is correct. Is this really needed?
935 // No, not really... at least not here!
936 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
937 checkBufferStructure(cur.buffer(), cur);
944 bool Text::backspacePos0(Cursor & cur)
946 BOOST_ASSERT(this == cur.text());
950 bool needsUpdate = false;
952 BufferParams const & bufparams = cur.buffer().params();
953 TextClass const & tclass = bufparams.getTextClass();
954 ParagraphList & plist = cur.text()->paragraphs();
955 Paragraph const & par = cur.paragraph();
956 Cursor prevcur = cur;
958 prevcur.pos() = prevcur.lastpos();
959 Paragraph const & prevpar = prevcur.paragraph();
961 // is it an empty paragraph?
962 if (cur.lastpos() == 0
963 || (cur.lastpos() == 1 && par.isSeparator(0))) {
964 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
965 plist.erase(boost::next(plist.begin(), cur.pit()));
968 // is previous par empty?
969 else if (prevcur.lastpos() == 0
970 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
971 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
972 plist.erase(boost::next(plist.begin(), prevcur.pit()));
975 // Pasting is not allowed, if the paragraphs have different
976 // layouts. I think it is a real bug of all other
977 // word processors to allow it. It confuses the user.
978 // Correction: Pasting is always allowed with standard-layout
979 else if (par.layout() == prevpar.layout()
980 || par.layout() == tclass.defaultLayout()) {
981 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
982 mergeParagraph(bufparams, plist, prevcur.pit());
987 updateLabels(cur.buffer());
988 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
995 bool Text::backspace(Cursor & cur)
997 BOOST_ASSERT(this == cur.text());
998 bool needsUpdate = false;
999 if (cur.pos() == 0) {
1001 return dissolveInset(cur);
1003 Paragraph & prev_par = pars_[cur.pit() - 1];
1005 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1006 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1007 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1010 // The cursor is at the beginning of a paragraph, so
1011 // the backspace will collapse two paragraphs into one.
1012 needsUpdate = backspacePos0(cur);
1015 // this is the code for a normal backspace, not pasting
1017 cur.recordUndo(DELETE_UNDO);
1018 // We used to do cursorBackwardIntern() here, but it is
1019 // not a good idea since it triggers the auto-delete
1020 // mechanism. So we do a cursorBackwardIntern()-lite,
1021 // without the dreaded mechanism. (JMarc)
1022 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1023 false, cur.boundary());
1024 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1025 checkBufferStructure(cur.buffer(), cur);
1028 if (cur.pos() == cur.lastpos())
1029 cur.setCurrentFont();
1031 needsUpdate |= handleBibitems(cur);
1033 // A singlePar update is not enough in this case.
1034 // cur.updateFlags(Update::Force);
1035 setCursor(cur.top(), cur.pit(), cur.pos());
1041 bool Text::dissolveInset(Cursor & cur) {
1042 BOOST_ASSERT(this == cur.text());
1044 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1047 cur.recordUndoInset();
1048 cur.selHandle(false);
1050 pos_type spos = cur.pos();
1051 pit_type spit = cur.pit();
1052 ParagraphList plist;
1053 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1054 plist = paragraphs();
1056 // store cursor offset
1060 Buffer & b = cur.buffer();
1061 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1062 if (!plist.empty()) {
1063 // ERT paragraphs have the Language latex_language.
1064 // This is invalid outside of ERT, so we need to
1065 // change it to the buffer language.
1066 ParagraphList::iterator it = plist.begin();
1067 ParagraphList::iterator it_end = plist.end();
1068 for (; it != it_end; it++)
1069 it->changeLanguage(b.params(), latex_language, b.language());
1071 pasteParagraphList(cur, plist, b.params().getTextClassPtr(),
1072 b.errorList("Paste"));
1074 cur.pit() = std::min(cur.lastpit(), spit);
1075 cur.pos() = std::min(cur.lastpos(), spos);
1077 cur.clearSelection();
1083 void Text::getWord(CursorSlice & from, CursorSlice & to,
1084 word_location const loc)
1086 Paragraph const & from_par = pars_[from.pit()];
1088 case WHOLE_WORD_STRICT:
1089 if (from.pos() == 0 || from.pos() == from_par.size()
1090 || !from_par.isLetter(from.pos())
1091 || !from_par.isLetter(from.pos() - 1)) {
1095 // no break here, we go to the next
1098 // If we are already at the beginning of a word, do nothing
1099 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1101 // no break here, we go to the next
1104 // always move the cursor to the beginning of previous word
1105 while (from.pos() && from_par.isLetter(from.pos() - 1))
1109 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1113 // no need to move the 'from' cursor
1117 Paragraph & to_par = pars_[to.pit()];
1118 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1123 void Text::write(Buffer const & buf, std::ostream & os) const
1125 ParagraphList::const_iterator pit = paragraphs().begin();
1126 ParagraphList::const_iterator end = paragraphs().end();
1128 for (; pit != end; ++pit)
1129 pit->write(buf, os, buf.params(), dth);
1131 // Close begin_deeper
1132 for(; dth > 0; --dth)
1133 os << "\n\\end_deeper";
1137 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1139 depth_type depth = 0;
1141 while (lex.isOK()) {
1143 string const token = lex.getString();
1148 if (token == "\\end_inset")
1151 if (token == "\\end_body")
1154 if (token == "\\begin_body")
1157 if (token == "\\end_document")
1160 if (token == "\\begin_layout") {
1161 lex.pushToken(token);
1164 par.params().depth(depth);
1165 par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1166 pars_.push_back(par);
1168 // FIXME: goddamn InsetTabular makes us pass a Buffer
1170 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1172 } else if (token == "\\begin_deeper") {
1174 } else if (token == "\\end_deeper") {
1176 lex.printError("\\end_deeper: " "depth is already null");
1181 lyxerr << "Handling unknown body token: `"
1182 << token << '\'' << endl;
1188 // Returns the current font and depth as a message.
1189 docstring Text::currentState(Cursor & cur)
1191 BOOST_ASSERT(this == cur.text());
1192 Buffer & buf = cur.buffer();
1193 Paragraph const & par = cur.paragraph();
1194 odocstringstream os;
1196 if (buf.params().trackChanges)
1197 os << _("[Change Tracking] ");
1199 Change change = par.lookupChange(cur.pos());
1201 if (change.type != Change::UNCHANGED) {
1202 Author const & a = buf.params().authors().get(change.author);
1203 os << _("Change: ") << a.name();
1204 if (!a.email().empty())
1205 os << " (" << a.email() << ")";
1206 // FIXME ctime is english, we should translate that
1207 os << _(" at ") << ctime(&change.changetime);
1211 // I think we should only show changes from the default
1213 // No, from the document font (MV)
1214 Font font = cur.real_current_font;
1215 font.reduce(buf.params().getFont());
1217 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1219 // The paragraph depth
1220 int depth = cur.paragraph().getDepth();
1222 os << bformat(_(", Depth: %1$d"), depth);
1224 // The paragraph spacing, but only if different from
1226 Spacing const & spacing = par.params().spacing();
1227 if (!spacing.isDefault()) {
1228 os << _(", Spacing: ");
1229 switch (spacing.getSpace()) {
1230 case Spacing::Single:
1233 case Spacing::Onehalf:
1236 case Spacing::Double:
1239 case Spacing::Other:
1240 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1242 case Spacing::Default:
1243 // should never happen, do nothing
1248 #ifdef DEVEL_VERSION
1249 os << _(", Inset: ") << &cur.inset();
1250 os << _(", Paragraph: ") << cur.pit();
1251 os << _(", Id: ") << par.id();
1252 os << _(", Position: ") << cur.pos();
1253 // FIXME: Why is the check for par.size() needed?
1254 // We are called with cur.pos() == par.size() quite often.
1255 if (!par.empty() && cur.pos() < par.size()) {
1256 // Force output of code point, not character
1257 size_t const c = par.getChar(cur.pos());
1258 os << _(", Char: 0x") << std::hex << c;
1260 os << _(", Boundary: ") << cur.boundary();
1261 // Row & row = cur.textRow();
1262 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1268 docstring Text::getPossibleLabel(Cursor & cur) const
1270 pit_type pit = cur.pit();
1272 LayoutPtr layout = pars_[pit].layout();
1275 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1276 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1277 if (par_text.empty())
1280 par_text = split(par_text, head, ' ');
1281 // Is it legal to use spaces in labels ?
1287 // No need for a prefix if the user said so.
1288 if (lyxrc.label_init_length <= 0)
1291 // Will contain the label type.
1294 // For section, subsection, etc...
1295 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1296 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1297 if (layout2->latextype != LATEX_PARAGRAPH) {
1302 if (layout->latextype != LATEX_PARAGRAPH)
1303 name = from_ascii(layout->latexname());
1305 // for captions, we just take the caption type
1306 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1308 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1310 // If none of the above worked, we'll see if we're inside various
1311 // types of insets and take our abbreviation from them.
1313 InsetCode const codes[] = {
1318 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1319 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1321 name = float_inset->name();
1327 // Create a correct prefix for prettyref
1328 if (name == "theorem")
1329 name = from_ascii("thm");
1330 else if (name == "Foot")
1331 name = from_ascii("fn");
1332 else if (name == "listing")
1333 name = from_ascii("lst");
1336 text = name.substr(0, 3) + ':' + text;
1342 void Text::charsTranspose(Cursor & cur)
1344 BOOST_ASSERT(this == cur.text());
1346 pos_type pos = cur.pos();
1348 // If cursor is at beginning or end of paragraph, do nothing.
1349 if (pos == cur.lastpos() || pos == 0)
1352 Paragraph & par = cur.paragraph();
1354 // Get the positions of the characters to be transposed.
1355 pos_type pos1 = pos - 1;
1356 pos_type pos2 = pos;
1358 // In change tracking mode, ignore deleted characters.
1359 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1361 if (pos2 == cur.lastpos())
1364 while (pos1 >= 0 && par.isDeleted(pos1))
1369 // Don't do anything if one of the "characters" is not regular text.
1370 if (par.isInset(pos1) || par.isInset(pos2))
1373 // Store the characters to be transposed (including font information).
1374 char_type char1 = par.getChar(pos1);
1376 par.getFontSettings(cur.buffer().params(), pos1);
1378 char_type char2 = par.getChar(pos2);
1380 par.getFontSettings(cur.buffer().params(), pos2);
1382 // And finally, we are ready to perform the transposition.
1383 // Track the changes if Change Tracking is enabled.
1384 bool const trackChanges = cur.buffer().params().trackChanges;
1388 par.eraseChar(pos2, trackChanges);
1389 par.eraseChar(pos1, trackChanges);
1390 par.insertChar(pos1, char2, font2, trackChanges);
1391 par.insertChar(pos2, char1, font1, trackChanges);
1393 checkBufferStructure(cur.buffer(), cur);
1395 // After the transposition, move cursor to after the transposition.
1396 setCursor(cur, cur.pit(), pos2);