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"
45 #include "Paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "TextMetrics.h"
50 #include "WordLangTuple.h"
52 #include "frontends/FontMetrics.h"
53 #include "frontends/Painter.h"
55 #include "insets/InsetText.h"
56 #include "insets/InsetBibitem.h"
57 #include "insets/InsetCaption.h"
58 #include "insets/InsetHFill.h"
59 #include "insets/InsetLine.h"
60 #include "insets/InsetNewline.h"
61 #include "insets/InsetPagebreak.h"
62 #include "insets/InsetOptArg.h"
63 #include "insets/InsetSpace.h"
64 #include "insets/InsetSpecialChar.h"
65 #include "insets/InsetTabular.h"
67 #include "support/lstrings.h"
68 #include "support/textutils.h"
69 #include "support/convert.h"
71 #include <boost/current_function.hpp>
72 #include <boost/next_prior.hpp>
86 using support::bformat;
87 using support::contains;
88 using support::lowercase;
90 using support::uppercase;
92 using cap::cutSelection;
93 using cap::pasteParagraphList;
95 using frontend::FontMetrics;
99 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
100 string const & token, Font & font, Change & change, ErrorList & errorList)
102 BufferParams const & bp = buf.params();
104 if (token[0] != '\\') {
105 docstring dstr = lex.getDocString();
106 par.appendString(dstr, font, change);
108 } else if (token == "\\begin_layout") {
110 docstring layoutname = lex.getDocString();
112 font = Font(Font::ALL_INHERIT, bp.language);
113 change = Change(Change::UNCHANGED);
115 TextClass const & tclass = bp.getTextClass();
117 if (layoutname.empty()) {
118 layoutname = tclass.defaultLayoutName();
121 bool hasLayout = tclass.hasLayout(layoutname);
124 errorList.push_back(ErrorItem(_("Unknown layout"),
125 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
126 layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
127 layoutname = tclass.defaultLayoutName();
130 par.layout(bp.getTextClass()[layoutname]);
132 // Test whether the layout is obsolete.
133 LayoutPtr const & layout = par.layout();
134 if (!layout->obsoleted_by().empty())
135 par.layout(bp.getTextClass()[layout->obsoleted_by()]);
137 par.params().read(lex);
139 } else if (token == "\\end_layout") {
140 lyxerr << BOOST_CURRENT_FUNCTION
141 << ": Solitary \\end_layout in line "
142 << lex.getLineNo() << "\n"
143 << "Missing \\begin_layout?.\n";
144 } else if (token == "\\end_inset") {
145 lyxerr << BOOST_CURRENT_FUNCTION
146 << ": Solitary \\end_inset in line "
147 << lex.getLineNo() << "\n"
148 << "Missing \\begin_inset?.\n";
149 } else if (token == "\\begin_inset") {
150 Inset * inset = readInset(lex, buf);
152 par.insertInset(par.size(), inset, font, change);
155 docstring line = lex.getDocString();
156 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
157 par.id(), 0, par.size()));
159 } else if (token == "\\family") {
161 font.setLyXFamily(lex.getString());
162 } else if (token == "\\series") {
164 font.setLyXSeries(lex.getString());
165 } else if (token == "\\shape") {
167 font.setLyXShape(lex.getString());
168 } else if (token == "\\size") {
170 font.setLyXSize(lex.getString());
171 } else if (token == "\\lang") {
173 string const tok = lex.getString();
174 Language const * lang = languages.getLanguage(tok);
176 font.setLanguage(lang);
178 font.setLanguage(bp.language);
179 lex.printError("Unknown language `$$Token'");
181 } else if (token == "\\numeric") {
183 font.setNumber(font.setLyXMisc(lex.getString()));
184 } else if (token == "\\emph") {
186 font.setEmph(font.setLyXMisc(lex.getString()));
187 } else if (token == "\\bar") {
189 string const tok = lex.getString();
192 font.setUnderbar(Font::ON);
193 else if (tok == "no")
194 font.setUnderbar(Font::OFF);
195 else if (tok == "default")
196 font.setUnderbar(Font::INHERIT);
198 lex.printError("Unknown bar font flag "
200 } else if (token == "\\noun") {
202 font.setNoun(font.setLyXMisc(lex.getString()));
203 } else if (token == "\\color") {
205 font.setLyXColor(lex.getString());
206 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
208 // Insets don't make sense in a free-spacing context! ---Kayvan
209 if (par.isFreeSpacing()) {
210 if (token == "\\InsetSpace")
211 par.appendChar(' ', font, change);
212 else if (lex.isOK()) {
214 string const next_token = lex.getString();
215 if (next_token == "\\-")
216 par.appendChar('-', font, change);
218 lex.printError("Token `$$Token' "
220 "paragraph layout!");
224 auto_ptr<Inset> inset;
225 if (token == "\\SpecialChar" )
226 inset.reset(new InsetSpecialChar);
228 inset.reset(new InsetSpace);
229 inset->read(buf, lex);
230 par.insertInset(par.size(), inset.release(),
233 } else if (token == "\\backslash") {
234 par.appendChar('\\', font, change);
235 } else if (token == "\\newline") {
236 auto_ptr<Inset> inset(new InsetNewline);
237 inset->read(buf, lex);
238 par.insertInset(par.size(), inset.release(), font, change);
239 } else if (token == "\\LyXTable") {
240 auto_ptr<Inset> inset(new InsetTabular(buf));
241 inset->read(buf, lex);
242 par.insertInset(par.size(), inset.release(), font, change);
243 } else if (token == "\\hfill") {
244 par.insertInset(par.size(), new InsetHFill, font, change);
245 } else if (token == "\\lyxline") {
246 par.insertInset(par.size(), new InsetLine, font, change);
247 } else if (token == "\\newpage") {
248 par.insertInset(par.size(), new InsetPagebreak, font, change);
249 } else if (token == "\\clearpage") {
250 par.insertInset(par.size(), new InsetClearPage, font, change);
251 } else if (token == "\\cleardoublepage") {
252 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
253 } else if (token == "\\change_unchanged") {
254 change = Change(Change::UNCHANGED);
255 } else if (token == "\\change_inserted") {
257 std::istringstream is(lex.getString());
261 if (aid >= bp.author_map.size()) {
262 errorList.push_back(ErrorItem(_("Change tracking error"),
263 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
264 par.id(), 0, par.size()));
265 change = Change(Change::UNCHANGED);
267 change = Change(Change::INSERTED, bp.author_map[aid], ct);
268 } else if (token == "\\change_deleted") {
270 std::istringstream is(lex.getString());
274 if (aid >= bp.author_map.size()) {
275 errorList.push_back(ErrorItem(_("Change tracking error"),
276 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
277 par.id(), 0, par.size()));
278 change = Change(Change::UNCHANGED);
280 change = Change(Change::DELETED, bp.author_map[aid], ct);
283 errorList.push_back(ErrorItem(_("Unknown token"),
284 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
286 par.id(), 0, par.size()));
291 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
292 ErrorList & errorList)
295 string token = lex.getString();
297 Change change(Change::UNCHANGED);
300 readParToken(buf, par, lex, token, font, change, errorList);
303 token = lex.getString();
308 if (token == "\\end_layout") {
309 //Ok, paragraph finished
313 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
314 << token << '\'' << endl;
315 if (token == "\\begin_layout" || token == "\\end_document"
316 || token == "\\end_inset" || token == "\\begin_deeper"
317 || token == "\\end_deeper") {
318 lex.pushToken(token);
319 lyxerr << "Paragraph ended in line "
320 << lex.getLineNo() << "\n"
321 << "Missing \\end_layout.\n";
325 // Final change goes to paragraph break:
326 par.setChange(par.size(), change);
328 // Initialize begin_of_body_ on load; redoParagraph maintains
329 par.setBeginOfBody();
336 bool Text::empty() const
338 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
339 // FIXME: Should we consider the labeled type as empty too?
340 && pars_[0].layout()->labeltype == LABEL_NO_LABEL);
344 double Text::spacing(Buffer const & buffer,
345 Paragraph const & par) const
347 if (par.params().spacing().isDefault())
348 return buffer.params().spacing().getValue();
349 return par.params().spacing().getValue();
353 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
355 BOOST_ASSERT(this == cur.text());
357 Paragraph & cpar = cur.paragraph();
358 pit_type cpit = cur.pit();
360 TextClass const & tclass = cur.buffer().params().getTextClass();
361 LayoutPtr const & layout = cpar.layout();
363 // this is only allowed, if the current paragraph is not empty
364 // or caption and if it has not the keepempty flag active
365 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
366 layout->labeltype != LABEL_SENSITIVE)
369 // a layout change may affect also the following paragraph
370 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
372 // Always break behind a space
373 // It is better to erase the space (Dekel)
374 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
375 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
377 // What should the layout for the new paragraph be?
378 bool keep_layout = inverse_logic ?
379 !layout->isEnvironment()
380 : layout->isEnvironment();
382 // We need to remember this before we break the paragraph, because
383 // that invalidates the layout variable
384 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
386 // we need to set this before we insert the paragraph.
387 bool const isempty = cpar.allowEmpty() && cpar.empty();
389 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
390 cur.pos(), keep_layout);
392 // After this, neither paragraph contains any rows!
395 pit_type next_par = cpit + 1;
397 // well this is the caption hack since one caption is really enough
400 // set to standard-layout
401 pars_[cpit].applyLayout(tclass.defaultLayout());
403 // set to standard-layout
404 pars_[next_par].applyLayout(tclass.defaultLayout());
407 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
408 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
409 break; // the character couldn't be deleted physically due to change tracking
412 updateLabels(cur.buffer());
414 // A singlePar update is not enough in this case.
415 cur.updateFlags(Update::Force);
417 // This check is necessary. Otherwise the new empty paragraph will
418 // be deleted automatically. And it is more friendly for the user!
419 if (cur.pos() != 0 || isempty)
420 setCursor(cur, cur.pit() + 1, 0);
422 setCursor(cur, cur.pit(), 0);
426 // insert a character, moves all the following breaks in the
427 // same Paragraph one to the right and make a rebreak
428 void Text::insertChar(Cursor & cur, char_type c)
430 BOOST_ASSERT(this == cur.text());
431 BOOST_ASSERT(c != Paragraph::META_INSET);
433 cur.recordUndo(INSERT_UNDO);
435 TextMetrics const & tm = cur.bv().textMetrics(this);
436 Buffer const & buffer = cur.buffer();
437 Paragraph & par = cur.paragraph();
438 // try to remove this
439 pit_type const pit = cur.pit();
441 bool const freeSpacing = par.layout()->free_spacing ||
444 if (lyxrc.auto_number) {
445 static docstring const number_operators = from_ascii("+-/*");
446 static docstring const number_unary_operators = from_ascii("+-");
447 static docstring const number_seperators = from_ascii(".,:");
449 if (cur.current_font.number() == Font::ON) {
450 if (!isDigit(c) && !contains(number_operators, c) &&
451 !(contains(number_seperators, c) &&
453 cur.pos() != cur.lastpos() &&
454 tm.getDisplayFont(pit, cur.pos()).number() == Font::ON &&
455 tm.getDisplayFont(pit, cur.pos() - 1).number() == Font::ON)
457 number(cur); // Set current_font.number to OFF
458 } else if (isDigit(c) &&
459 cur.real_current_font.isVisibleRightToLeft()) {
460 number(cur); // Set current_font.number to ON
462 if (cur.pos() != 0) {
463 char_type const c = par.getChar(cur.pos() - 1);
464 if (contains(number_unary_operators, c) &&
466 || par.isSeparator(cur.pos() - 2)
467 || par.isNewline(cur.pos() - 2))
469 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
471 } else if (contains(number_seperators, c)
473 && tm.getDisplayFont(pit, cur.pos() - 2).number() == Font::ON) {
474 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
481 // In Bidi text, we want spaces to be treated in a special way: spaces
482 // which are between words in different languages should get the
483 // paragraph's language; otherwise, spaces should keep the language
484 // they were originally typed in. This is only in effect while typing;
485 // after the text is already typed in, the user can always go back and
486 // explicitly set the language of a space as desired. But 99.9% of the
487 // time, what we're doing here is what the user actually meant.
489 // The following cases are the ones in which the language of the space
490 // should be changed to match that of the containing paragraph. In the
491 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
492 // represents a space, pipe (|) represents the cursor position (so the
493 // character before it is the one just typed in). The different cases
494 // are depicted logically (not visually), from left to right:
499 // Theoretically, there are other situations that we should, perhaps, deal
500 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
501 // point (to understand why, just try to create this situation...).
503 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
504 // get font in front and behind the space in question. But do NOT
505 // use getFont(cur.pos()) because the character c is not inserted yet
506 Font const & pre_space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 2);
507 Font const & post_space_font = cur.real_current_font;
508 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
509 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
511 if (pre_space_rtl != post_space_rtl) {
512 // Set the space's language to match the language of the
513 // adjacent character whose direction is the paragraph's
514 // direction; don't touch other properties of the font
515 Language const * lang =
516 (pre_space_rtl == par.isRTL(buffer.params())) ?
517 pre_space_font.language() : post_space_font.language();
519 Font space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 1);
520 space_font.setLanguage(lang);
521 par.setFont(cur.pos() - 1, space_font);
525 // Next check, if there will be two blanks together or a blank at
526 // the beginning of a paragraph.
527 // I decided to handle blanks like normal characters, the main
528 // difference are the special checks when calculating the row.fill
529 // (blank does not count at the end of a row) and the check here
531 // When the free-spacing option is set for the current layout,
532 // disable the double-space checking
533 if (!freeSpacing && isLineSeparatorChar(c)) {
534 if (cur.pos() == 0) {
535 static bool sent_space_message = false;
536 if (!sent_space_message) {
537 cur.message(_("You cannot insert a space at the "
538 "beginning of a paragraph. Please read the Tutorial."));
539 sent_space_message = true;
543 BOOST_ASSERT(cur.pos() > 0);
544 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
545 && !par.isDeleted(cur.pos() - 1)) {
546 static bool sent_space_message = false;
547 if (!sent_space_message) {
548 cur.message(_("You cannot type two spaces this way. "
549 "Please read the Tutorial."));
550 sent_space_message = true;
556 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
557 checkBufferStructure(cur.buffer(), cur);
559 // cur.updateFlags(Update::Force);
560 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
565 void Text::charInserted(Cursor & cur)
567 // Here we call finishUndo for every 20 characters inserted.
568 // This is from my experience how emacs does it. (Lgb)
569 static unsigned int counter;
579 // the cursor set functions have a special mechanism. When they
580 // realize, that you left an empty paragraph, they will delete it.
582 bool Text::cursorRightOneWord(Cursor & cur)
584 BOOST_ASSERT(this == cur.text());
588 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
592 // Advance through word.
593 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
595 // Skip through trailing nonword stuff.
596 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
599 return setCursor(cur, old.pit(), old.pos());
603 bool Text::cursorLeftOneWord(Cursor & cur)
605 BOOST_ASSERT(this == cur.text());
609 if (old.pos() == 0 && old.pit() != 0) {
611 old.pos() = old.lastpos();
613 // Skip through initial nonword stuff.
614 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
616 // Advance through word.
617 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
620 return setCursor(cur, old.pit(), old.pos());
624 void Text::selectWord(Cursor & cur, word_location loc)
626 BOOST_ASSERT(this == cur.text());
627 CursorSlice from = cur.top();
628 CursorSlice to = cur.top();
629 getWord(from, to, loc);
630 if (cur.top() != from)
631 setCursor(cur, from.pit(), from.pos());
635 setCursor(cur, to.pit(), to.pos());
640 // Select the word currently under the cursor when no
641 // selection is currently set
642 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
644 BOOST_ASSERT(this == cur.text());
647 selectWord(cur, loc);
648 return cur.selection();
652 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
654 BOOST_ASSERT(this == cur.text());
656 if (!cur.selection())
659 cur.recordUndoSelection();
661 pit_type begPit = cur.selectionBegin().pit();
662 pit_type endPit = cur.selectionEnd().pit();
664 pos_type begPos = cur.selectionBegin().pos();
665 pos_type endPos = cur.selectionEnd().pos();
667 // keep selection info, because endPos becomes invalid after the first loop
668 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
670 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
672 for (pit_type pit = begPit; pit <= endPit; ++pit) {
673 pos_type parSize = pars_[pit].size();
675 // ignore empty paragraphs; otherwise, an assertion will fail for
676 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
680 // do not consider first paragraph if the cursor starts at pos size()
681 if (pit == begPit && begPos == parSize)
684 // do not consider last paragraph if the cursor ends at pos 0
685 if (pit == endPit && endPos == 0)
686 break; // last iteration anyway
688 pos_type left = (pit == begPit ? begPos : 0);
689 pos_type right = (pit == endPit ? endPos : parSize);
692 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
694 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
698 // next, accept/reject imaginary end-of-par characters
700 for (pit_type pit = begPit; pit <= endPit; ++pit) {
701 pos_type pos = pars_[pit].size();
703 // skip if the selection ends before the end-of-par
704 if (pit == endPit && endsBeforeEndOfPar)
705 break; // last iteration anyway
707 // skip if this is not the last paragraph of the document
708 // note: the user should be able to accept/reject the par break of the last par!
709 if (pit == endPit && pit + 1 != int(pars_.size()))
710 break; // last iteration anway
713 if (pars_[pit].isInserted(pos)) {
714 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
715 } else if (pars_[pit].isDeleted(pos)) {
716 if (pit + 1 == int(pars_.size())) {
717 // we cannot remove a par break at the end of the last paragraph;
718 // instead, we mark it unchanged
719 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
721 mergeParagraph(cur.buffer().params(), pars_, pit);
727 if (pars_[pit].isDeleted(pos)) {
728 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
729 } else if (pars_[pit].isInserted(pos)) {
730 if (pit + 1 == int(pars_.size())) {
731 // we mark the par break at the end of the last paragraph unchanged
732 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
734 mergeParagraph(cur.buffer().params(), pars_, pit);
742 // finally, invoke the DEPM
744 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
749 cur.clearSelection();
750 setCursorIntern(cur, begPit, begPos);
751 cur.updateFlags(Update::Force);
752 updateLabels(cur.buffer());
756 void Text::acceptChanges(BufferParams const & bparams)
758 lyx::acceptChanges(pars_, bparams);
759 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
763 void Text::rejectChanges(BufferParams const & bparams)
765 pit_type pars_size = static_cast<pit_type>(pars_.size());
767 // first, reject changes within each individual paragraph
768 // (do not consider end-of-par)
769 for (pit_type pit = 0; pit < pars_size; ++pit) {
770 if (!pars_[pit].empty()) // prevent assertion failure
771 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
774 // next, reject imaginary end-of-par characters
775 for (pit_type pit = 0; pit < pars_size; ++pit) {
776 pos_type pos = pars_[pit].size();
778 if (pars_[pit].isDeleted(pos)) {
779 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
780 } else if (pars_[pit].isInserted(pos)) {
781 if (pit == pars_size - 1) {
782 // we mark the par break at the end of the last
783 // paragraph unchanged
784 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
786 mergeParagraph(bparams, pars_, pit);
793 // finally, invoke the DEPM
794 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
798 void Text::deleteWordForward(Cursor & cur)
800 BOOST_ASSERT(this == cur.text());
801 if (cur.lastpos() == 0)
805 cur.selection() = true;
806 cursorRightOneWord(cur);
808 cutSelection(cur, true, false);
809 checkBufferStructure(cur.buffer(), cur);
814 void Text::deleteWordBackward(Cursor & cur)
816 BOOST_ASSERT(this == cur.text());
817 if (cur.lastpos() == 0)
821 cur.selection() = true;
822 cursorLeftOneWord(cur);
824 cutSelection(cur, true, false);
825 checkBufferStructure(cur.buffer(), cur);
830 // Kill to end of line.
831 void Text::changeCase(Cursor & cur, Text::TextCase action)
833 BOOST_ASSERT(this == cur.text());
837 if (cur.selection()) {
838 from = cur.selBegin();
842 getWord(from, to, PARTIAL_WORD);
843 cursorRightOneWord(cur);
846 cur.recordUndoSelection();
848 pit_type begPit = from.pit();
849 pit_type endPit = to.pit();
851 pos_type begPos = from.pos();
852 pos_type endPos = to.pos();
854 bool const trackChanges = cur.buffer().params().trackChanges;
856 pos_type right = 0; // needed after the for loop
858 for (pit_type pit = begPit; pit <= endPit; ++pit) {
859 pos_type parSize = pars_[pit].size();
861 pos_type pos = (pit == begPit ? begPos : 0);
862 right = (pit == endPit ? endPos : parSize);
864 // process sequences of modified characters; in change
865 // tracking mode, this approach results in much better
866 // usability than changing case on a char-by-char basis
869 bool capitalize = true;
871 for (; pos < right; ++pos) {
872 char_type oldChar = pars_[pit].getChar(pos);
873 char_type newChar = oldChar;
875 // ignore insets and don't play with deleted text!
876 if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
879 newChar = lowercase(oldChar);
881 case text_capitalization:
883 newChar = uppercase(oldChar);
888 newChar = uppercase(oldChar);
893 if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
894 capitalize = true; // permit capitalization again
897 if (oldChar != newChar) {
901 if (oldChar == newChar || pos == right - 1) {
902 if (oldChar != newChar) {
903 pos++; // step behind the changing area
905 int erasePos = pos - changes.size();
906 for (size_t i = 0; i < changes.size(); i++) {
907 pars_[pit].insertChar(pos, changes[i],
908 pars_[pit].getFontSettings(cur.buffer().params(),
911 if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
914 ++right; // expand selection
922 // the selection may have changed due to logically-only deleted chars
923 setCursor(cur, begPit, begPos);
925 setCursor(cur, endPit, right);
928 checkBufferStructure(cur.buffer(), cur);
932 bool Text::handleBibitems(Cursor & cur)
934 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
936 // if a bibitem is deleted, merge with previous paragraph
937 // if this is a bibliography item as well
938 if (cur.pos() == 0) {
939 BufferParams const & bufparams = cur.buffer().params();
940 Paragraph const & par = cur.paragraph();
941 Cursor prevcur = cur;
944 prevcur.pos() = prevcur.lastpos();
946 Paragraph const & prevpar = prevcur.paragraph();
947 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
948 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
949 mergeParagraph(bufparams, cur.text()->paragraphs(),
951 updateLabels(cur.buffer());
952 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
953 cur.updateFlags(Update::Force);
954 // if not, reset the paragraph to default
956 cur.paragraph().layout(
957 bufparams.getTextClass().defaultLayout());
964 bool Text::erase(Cursor & cur)
966 BOOST_ASSERT(this == cur.text());
967 bool needsUpdate = false;
968 Paragraph & par = cur.paragraph();
970 if (cur.pos() != cur.lastpos()) {
971 // this is the code for a normal delete, not pasting
973 cur.recordUndo(DELETE_UNDO);
974 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
975 // the character has been logically deleted only => skip it
976 cur.top().forwardPos();
978 checkBufferStructure(cur.buffer(), cur);
981 if (cur.pit() == cur.lastpit())
982 return dissolveInset(cur);
984 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
985 par.setChange(cur.pos(), Change(Change::DELETED));
989 setCursorIntern(cur, cur.pit() + 1, 0);
990 needsUpdate = backspacePos0(cur);
994 needsUpdate |= handleBibitems(cur);
997 // Make sure the cursor is correct. Is this really needed?
998 // No, not really... at least not here!
999 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1000 checkBufferStructure(cur.buffer(), cur);
1007 bool Text::backspacePos0(Cursor & cur)
1009 BOOST_ASSERT(this == cur.text());
1013 bool needsUpdate = false;
1015 BufferParams const & bufparams = cur.buffer().params();
1016 TextClass const & tclass = bufparams.getTextClass();
1017 ParagraphList & plist = cur.text()->paragraphs();
1018 Paragraph const & par = cur.paragraph();
1019 Cursor prevcur = cur;
1021 prevcur.pos() = prevcur.lastpos();
1022 Paragraph const & prevpar = prevcur.paragraph();
1024 // is it an empty paragraph?
1025 if (cur.lastpos() == 0
1026 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1027 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1028 plist.erase(boost::next(plist.begin(), cur.pit()));
1031 // is previous par empty?
1032 else if (prevcur.lastpos() == 0
1033 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1034 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1035 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1038 // Pasting is not allowed, if the paragraphs have different
1039 // layouts. I think it is a real bug of all other
1040 // word processors to allow it. It confuses the user.
1041 // Correction: Pasting is always allowed with standard-layout
1042 else if (par.layout() == prevpar.layout()
1043 || par.layout() == tclass.defaultLayout()) {
1044 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1045 mergeParagraph(bufparams, plist, prevcur.pit());
1050 updateLabels(cur.buffer());
1051 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1058 bool Text::backspace(Cursor & cur)
1060 BOOST_ASSERT(this == cur.text());
1061 bool needsUpdate = false;
1062 if (cur.pos() == 0) {
1064 return dissolveInset(cur);
1066 Paragraph & prev_par = pars_[cur.pit() - 1];
1068 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1069 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1070 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1073 // The cursor is at the beginning of a paragraph, so
1074 // the backspace will collapse two paragraphs into one.
1075 needsUpdate = backspacePos0(cur);
1078 // this is the code for a normal backspace, not pasting
1080 cur.recordUndo(DELETE_UNDO);
1081 // We used to do cursorBackwardIntern() here, but it is
1082 // not a good idea since it triggers the auto-delete
1083 // mechanism. So we do a cursorBackwardIntern()-lite,
1084 // without the dreaded mechanism. (JMarc)
1085 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1086 false, cur.boundary());
1087 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1088 checkBufferStructure(cur.buffer(), cur);
1091 if (cur.pos() == cur.lastpos())
1092 cur.setCurrentFont();
1094 needsUpdate |= handleBibitems(cur);
1096 // A singlePar update is not enough in this case.
1097 // cur.updateFlags(Update::Force);
1098 setCursor(cur.top(), cur.pit(), cur.pos());
1104 bool Text::dissolveInset(Cursor & cur) {
1105 BOOST_ASSERT(this == cur.text());
1107 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1110 cur.recordUndoInset();
1111 cur.selHandle(false);
1113 pos_type spos = cur.pos();
1114 pit_type spit = cur.pit();
1115 ParagraphList plist;
1116 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1117 plist = paragraphs();
1119 // store cursor offset
1123 Buffer & b = cur.buffer();
1124 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1125 if (!plist.empty()) {
1126 // ERT paragraphs have the Language latex_language.
1127 // This is invalid outside of ERT, so we need to
1128 // change it to the buffer language.
1129 ParagraphList::iterator it = plist.begin();
1130 ParagraphList::iterator it_end = plist.end();
1131 for (; it != it_end; it++)
1132 it->changeLanguage(b.params(), latex_language, b.language());
1134 pasteParagraphList(cur, plist, b.params().getTextClassPtr(),
1135 b.errorList("Paste"));
1137 cur.pit() = std::min(cur.lastpit(), spit);
1138 cur.pos() = std::min(cur.lastpos(), spos);
1140 cur.clearSelection();
1146 void Text::getWord(CursorSlice & from, CursorSlice & to,
1147 word_location const loc)
1149 Paragraph const & from_par = pars_[from.pit()];
1151 case WHOLE_WORD_STRICT:
1152 if (from.pos() == 0 || from.pos() == from_par.size()
1153 || !from_par.isLetter(from.pos())
1154 || !from_par.isLetter(from.pos() - 1)) {
1158 // no break here, we go to the next
1161 // If we are already at the beginning of a word, do nothing
1162 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1164 // no break here, we go to the next
1167 // always move the cursor to the beginning of previous word
1168 while (from.pos() && from_par.isLetter(from.pos() - 1))
1172 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1176 // no need to move the 'from' cursor
1180 Paragraph & to_par = pars_[to.pit()];
1181 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1186 void Text::write(Buffer const & buf, std::ostream & os) const
1188 ParagraphList::const_iterator pit = paragraphs().begin();
1189 ParagraphList::const_iterator end = paragraphs().end();
1191 for (; pit != end; ++pit)
1192 pit->write(buf, os, buf.params(), dth);
1194 // Close begin_deeper
1195 for(; dth > 0; --dth)
1196 os << "\n\\end_deeper";
1200 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1202 depth_type depth = 0;
1204 while (lex.isOK()) {
1206 string const token = lex.getString();
1211 if (token == "\\end_inset")
1214 if (token == "\\end_body")
1217 if (token == "\\begin_body")
1220 if (token == "\\end_document")
1223 if (token == "\\begin_layout") {
1224 lex.pushToken(token);
1227 par.params().depth(depth);
1228 par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1229 pars_.push_back(par);
1231 // FIXME: goddamn InsetTabular makes us pass a Buffer
1233 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1235 } else if (token == "\\begin_deeper") {
1237 } else if (token == "\\end_deeper") {
1239 lex.printError("\\end_deeper: " "depth is already null");
1244 lyxerr << "Handling unknown body token: `"
1245 << token << '\'' << endl;
1251 // Returns the current font and depth as a message.
1252 docstring Text::currentState(Cursor & cur)
1254 BOOST_ASSERT(this == cur.text());
1255 Buffer & buf = cur.buffer();
1256 Paragraph const & par = cur.paragraph();
1257 odocstringstream os;
1259 if (buf.params().trackChanges)
1260 os << _("[Change Tracking] ");
1262 Change change = par.lookupChange(cur.pos());
1264 if (change.type != Change::UNCHANGED) {
1265 Author const & a = buf.params().authors().get(change.author);
1266 os << _("Change: ") << a.name();
1267 if (!a.email().empty())
1268 os << " (" << a.email() << ")";
1269 // FIXME ctime is english, we should translate that
1270 os << _(" at ") << ctime(&change.changetime);
1274 // I think we should only show changes from the default
1276 // No, from the document font (MV)
1277 Font font = cur.real_current_font;
1278 font.reduce(buf.params().getFont());
1280 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1282 // The paragraph depth
1283 int depth = cur.paragraph().getDepth();
1285 os << bformat(_(", Depth: %1$d"), depth);
1287 // The paragraph spacing, but only if different from
1289 Spacing const & spacing = par.params().spacing();
1290 if (!spacing.isDefault()) {
1291 os << _(", Spacing: ");
1292 switch (spacing.getSpace()) {
1293 case Spacing::Single:
1296 case Spacing::Onehalf:
1299 case Spacing::Double:
1302 case Spacing::Other:
1303 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1305 case Spacing::Default:
1306 // should never happen, do nothing
1311 #ifdef DEVEL_VERSION
1312 os << _(", Inset: ") << &cur.inset();
1313 os << _(", Paragraph: ") << cur.pit();
1314 os << _(", Id: ") << par.id();
1315 os << _(", Position: ") << cur.pos();
1316 // FIXME: Why is the check for par.size() needed?
1317 // We are called with cur.pos() == par.size() quite often.
1318 if (!par.empty() && cur.pos() < par.size()) {
1319 // Force output of code point, not character
1320 size_t const c = par.getChar(cur.pos());
1321 os << _(", Char: 0x") << std::hex << c;
1323 os << _(", Boundary: ") << cur.boundary();
1324 // Row & row = cur.textRow();
1325 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1331 docstring Text::getPossibleLabel(Cursor & cur) const
1333 pit_type pit = cur.pit();
1335 LayoutPtr layout = pars_[pit].layout();
1338 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1339 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1340 if (par_text.empty())
1343 par_text = split(par_text, head, ' ');
1344 // Is it legal to use spaces in labels ?
1350 // No need for a prefix if the user said so.
1351 if (lyxrc.label_init_length <= 0)
1354 // Will contain the label type.
1357 // For section, subsection, etc...
1358 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1359 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1360 if (layout2->latextype != LATEX_PARAGRAPH) {
1365 if (layout->latextype != LATEX_PARAGRAPH)
1366 name = from_ascii(layout->latexname());
1368 // for captions, we just take the caption type
1369 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1371 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1373 // If none of the above worked, we'll see if we're inside various
1374 // types of insets and take our abbreviation from them.
1376 InsetCode const codes[] = {
1381 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1382 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1384 name = float_inset->name();
1390 // Create a correct prefix for prettyref
1391 if (name == "theorem")
1392 name = from_ascii("thm");
1393 else if (name == "Foot")
1394 name = from_ascii("fn");
1395 else if (name == "listing")
1396 name = from_ascii("lst");
1399 text = name.substr(0, 3) + ':' + text;
1405 void Text::charsTranspose(Cursor & cur)
1407 BOOST_ASSERT(this == cur.text());
1409 pos_type pos = cur.pos();
1411 // If cursor is at beginning or end of paragraph, do nothing.
1412 if (pos == cur.lastpos() || pos == 0)
1415 Paragraph & par = cur.paragraph();
1417 // Get the positions of the characters to be transposed.
1418 pos_type pos1 = pos - 1;
1419 pos_type pos2 = pos;
1421 // In change tracking mode, ignore deleted characters.
1422 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1424 if (pos2 == cur.lastpos())
1427 while (pos1 >= 0 && par.isDeleted(pos1))
1432 // Don't do anything if one of the "characters" is not regular text.
1433 if (par.isInset(pos1) || par.isInset(pos2))
1436 // Store the characters to be transposed (including font information).
1437 char_type char1 = par.getChar(pos1);
1439 par.getFontSettings(cur.buffer().params(), pos1);
1441 char_type char2 = par.getChar(pos2);
1443 par.getFontSettings(cur.buffer().params(), pos2);
1445 // And finally, we are ready to perform the transposition.
1446 // Track the changes if Change Tracking is enabled.
1447 bool const trackChanges = cur.buffer().params().trackChanges;
1451 par.eraseChar(pos2, trackChanges);
1452 par.eraseChar(pos1, trackChanges);
1453 par.insertChar(pos1, char2, font2, trackChanges);
1454 par.insertChar(pos2, char1, font1, trackChanges);
1456 checkBufferStructure(cur.buffer(), cur);
1458 // After the transposition, move cursor to after the transposition.
1459 setCursor(cur, cur.pit(), pos2);