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"
32 #include "DispatchResult.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
37 #include "FontIterator.h"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
48 #include "WordLangTuple.h"
50 #include "insets/InsetText.h"
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetCaption.h"
53 #include "insets/InsetHFill.h"
54 #include "insets/InsetLine.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetNewpage.h"
57 #include "insets/InsetOptArg.h"
58 #include "insets/InsetSpace.h"
59 #include "insets/InsetSpecialChar.h"
60 #include "insets/InsetTabular.h"
62 #include "support/convert.h"
63 #include "support/debug.h"
64 #include "support/docstream.h"
65 #include "support/gettext.h"
66 #include "support/lstrings.h"
67 #include "support/textutils.h"
69 #include <boost/next_prior.hpp>
74 using namespace lyx::support;
78 using cap::cutSelection;
79 using cap::pasteParagraphList;
83 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
84 string const & token, Font & font, Change & change, ErrorList & errorList)
86 BufferParams const & bp = buf.params();
88 if (token[0] != '\\') {
89 docstring dstr = lex.getDocString();
90 par.appendString(dstr, font, change);
92 } else if (token == "\\begin_layout") {
94 docstring layoutname = lex.getDocString();
96 font = Font(inherit_font, bp.language);
97 change = Change(Change::UNCHANGED);
99 DocumentClass const & tclass = bp.documentClass();
101 if (layoutname.empty())
102 layoutname = tclass.defaultLayoutName();
104 if (par.forceEmptyLayout()) {
105 // in this case only the empty layout is allowed
106 layoutname = tclass.emptyLayoutName();
107 } else if (par.useEmptyLayout()) {
108 // in this case, default layout maps to empty layout
109 if (layoutname == tclass.defaultLayoutName())
110 layoutname = tclass.emptyLayoutName();
112 // otherwise, the empty layout maps to the default
113 if (layoutname == tclass.emptyLayoutName())
114 layoutname = tclass.defaultLayoutName();
117 bool hasLayout = tclass.hasLayout(layoutname);
120 errorList.push_back(ErrorItem(_("Unknown layout"),
121 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
122 layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
123 layoutname = par.useEmptyLayout() ?
124 tclass.emptyLayoutName() :
125 tclass.defaultLayoutName();
128 par.setLayout(bp.documentClass()[layoutname]);
130 // Test whether the layout is obsolete.
131 Layout const & layout = par.layout();
132 if (!layout.obsoleted_by().empty())
133 par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
135 par.params().read(lex);
137 } else if (token == "\\end_layout") {
138 LYXERR0("Solitary \\end_layout in line " << lex.getLineNo() << "\n"
139 << "Missing \\begin_layout ?");
140 } else if (token == "\\end_inset") {
141 LYXERR0("Solitary \\end_inset in line " << lex.getLineNo() << "\n"
142 << "Missing \\begin_inset ?");
143 } else if (token == "\\begin_inset") {
144 Inset * inset = readInset(lex, buf);
146 par.insertInset(par.size(), inset, font, change);
149 docstring line = lex.getDocString();
150 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
151 par.id(), 0, par.size()));
153 } else if (token == "\\family") {
155 setLyXFamily(lex.getString(), font.fontInfo());
156 } else if (token == "\\series") {
158 setLyXSeries(lex.getString(), font.fontInfo());
159 } else if (token == "\\shape") {
161 setLyXShape(lex.getString(), font.fontInfo());
162 } else if (token == "\\size") {
164 setLyXSize(lex.getString(), font.fontInfo());
165 } else if (token == "\\lang") {
167 string const tok = lex.getString();
168 Language const * lang = languages.getLanguage(tok);
170 font.setLanguage(lang);
172 font.setLanguage(bp.language);
173 lex.printError("Unknown language `$$Token'");
175 } else if (token == "\\numeric") {
177 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
178 } else if (token == "\\emph") {
180 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
181 } else if (token == "\\bar") {
183 string const tok = lex.getString();
186 font.fontInfo().setUnderbar(FONT_ON);
187 else if (tok == "no")
188 font.fontInfo().setUnderbar(FONT_OFF);
189 else if (tok == "default")
190 font.fontInfo().setUnderbar(FONT_INHERIT);
192 lex.printError("Unknown bar font flag "
194 } else if (token == "\\noun") {
196 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
197 } else if (token == "\\color") {
199 setLyXColor(lex.getString(), font.fontInfo());
200 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
202 // Insets don't make sense in a free-spacing context! ---Kayvan
203 if (par.isFreeSpacing()) {
204 if (token == "\\InsetSpace")
205 par.appendChar(' ', font, change);
206 else if (lex.isOK()) {
208 string const next_token = lex.getString();
209 if (next_token == "\\-")
210 par.appendChar('-', font, change);
212 lex.printError("Token `$$Token' "
214 "paragraph layout!");
218 auto_ptr<Inset> inset;
219 if (token == "\\SpecialChar" )
220 inset.reset(new InsetSpecialChar);
222 inset.reset(new InsetSpace);
224 par.insertInset(par.size(), inset.release(),
227 } else if (token == "\\backslash") {
228 par.appendChar('\\', font, change);
229 } else if (token == "\\linebreak") {
230 auto_ptr<Inset> inset(new InsetLinebreak);
232 par.insertInset(par.size(), inset.release(), font, change);
233 } else if (token == "\\newline") {
234 auto_ptr<Inset> inset(new InsetNewline);
236 par.insertInset(par.size(), inset.release(), font, change);
237 } else if (token == "\\LyXTable") {
238 auto_ptr<Inset> inset(new InsetTabular(buf));
240 par.insertInset(par.size(), inset.release(), font, change);
241 } else if (token == "\\hfill") {
242 par.insertInset(par.size(), new InsetHFill, font, change);
243 } else if (token == "\\lyxline") {
244 par.insertInset(par.size(), new InsetLine, font, change);
245 } else if (token == "\\newpage") {
246 par.insertInset(par.size(), new InsetNewpage, font, change);
247 } else if (token == "\\pagebreak") {
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 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 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: `" << token << '\'');
314 if (token == "\\begin_layout" || token == "\\end_document"
315 || token == "\\end_inset" || token == "\\begin_deeper"
316 || token == "\\end_deeper") {
317 lex.pushToken(token);
318 lyxerr << "Paragraph ended in line "
319 << lex.getLineNo() << "\n"
320 << "Missing \\end_layout.\n";
324 // Final change goes to paragraph break:
325 par.setChange(par.size(), change);
327 // Initialize begin_of_body_ on load; redoParagraph maintains
328 par.setBeginOfBody();
335 bool Text::empty() const
337 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
338 // FIXME: Should we consider the labeled type as empty too?
339 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
343 double Text::spacing(Buffer const & buffer, Paragraph const & par) const
345 if (par.params().spacing().isDefault())
346 return buffer.params().spacing().getValue();
347 return par.params().spacing().getValue();
351 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
353 BOOST_ASSERT(this == cur.text());
355 Paragraph & cpar = cur.paragraph();
356 pit_type cpit = cur.pit();
358 DocumentClass const & tclass = cur.buffer().params().documentClass();
359 Layout const & layout = cpar.layout();
361 // this is only allowed, if the current paragraph is not empty
362 // or caption and if it has not the keepempty flag active
363 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
364 layout.labeltype != LABEL_SENSITIVE)
367 // a layout change may affect also the following paragraph
368 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
370 // Always break behind a space
371 // It is better to erase the space (Dekel)
372 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
373 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
375 // What should the layout for the new paragraph be?
376 bool keep_layout = inverse_logic ?
377 !layout.isEnvironment()
378 : layout.isEnvironment();
380 // We need to remember this before we break the paragraph, because
381 // that invalidates the layout variable
382 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
384 // we need to set this before we insert the paragraph.
385 bool const isempty = cpar.allowEmpty() && cpar.empty();
387 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
388 cur.pos(), keep_layout);
390 // After this, neither paragraph contains any rows!
393 pit_type next_par = cpit + 1;
395 // well this is the caption hack since one caption is really enough
398 // set to standard-layout
399 //FIXME Check if this should be emptyLayout() in some cases
400 pars_[cpit].applyLayout(tclass.defaultLayout());
402 // set to standard-layout
403 //FIXME Check if this should be emptyLayout() in some cases
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());
432 cur.recordUndo(INSERT_UNDO);
434 TextMetrics const & tm = cur.bv().textMetrics(this);
435 Buffer const & buffer = cur.buffer();
436 Paragraph & par = cur.paragraph();
437 // try to remove this
438 pit_type const pit = cur.pit();
440 bool const freeSpacing = par.layout().free_spacing ||
443 if (lyxrc.auto_number) {
444 static docstring const number_operators = from_ascii("+-/*");
445 static docstring const number_unary_operators = from_ascii("+-");
446 static docstring const number_seperators = from_ascii(".,:");
448 if (cur.current_font.fontInfo().number() == FONT_ON) {
449 if (!isDigit(c) && !contains(number_operators, c) &&
450 !(contains(number_seperators, c) &&
452 cur.pos() != cur.lastpos() &&
453 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
454 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
456 number(cur); // Set current_font.number to OFF
457 } else if (isDigit(c) &&
458 cur.real_current_font.isVisibleRightToLeft()) {
459 number(cur); // Set current_font.number to ON
461 if (cur.pos() != 0) {
462 char_type const c = par.getChar(cur.pos() - 1);
463 if (contains(number_unary_operators, c) &&
465 || par.isSeparator(cur.pos() - 2)
466 || par.isNewline(cur.pos() - 2))
468 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
470 } else if (contains(number_seperators, c)
472 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
473 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
480 // In Bidi text, we want spaces to be treated in a special way: spaces
481 // which are between words in different languages should get the
482 // paragraph's language; otherwise, spaces should keep the language
483 // they were originally typed in. This is only in effect while typing;
484 // after the text is already typed in, the user can always go back and
485 // explicitly set the language of a space as desired. But 99.9% of the
486 // time, what we're doing here is what the user actually meant.
488 // The following cases are the ones in which the language of the space
489 // should be changed to match that of the containing paragraph. In the
490 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
491 // represents a space, pipe (|) represents the cursor position (so the
492 // character before it is the one just typed in). The different cases
493 // are depicted logically (not visually), from left to right:
498 // Theoretically, there are other situations that we should, perhaps, deal
499 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
500 // point (to understand why, just try to create this situation...).
502 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
503 // get font in front and behind the space in question. But do NOT
504 // use getFont(cur.pos()) because the character c is not inserted yet
505 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
506 Font const & post_space_font = cur.real_current_font;
507 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
508 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
510 if (pre_space_rtl != post_space_rtl) {
511 // Set the space's language to match the language of the
512 // adjacent character whose direction is the paragraph's
513 // direction; don't touch other properties of the font
514 Language const * lang =
515 (pre_space_rtl == par.isRTL(buffer.params())) ?
516 pre_space_font.language() : post_space_font.language();
518 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
519 space_font.setLanguage(lang);
520 par.setFont(cur.pos() - 1, space_font);
524 // Next check, if there will be two blanks together or a blank at
525 // the beginning of a paragraph.
526 // I decided to handle blanks like normal characters, the main
527 // difference are the special checks when calculating the row.fill
528 // (blank does not count at the end of a row) and the check here
530 // When the free-spacing option is set for the current layout,
531 // disable the double-space checking
532 if (!freeSpacing && isLineSeparatorChar(c)) {
533 if (cur.pos() == 0) {
534 static bool sent_space_message = false;
535 if (!sent_space_message) {
536 cur.message(_("You cannot insert a space at the "
537 "beginning of a paragraph. Please read the Tutorial."));
538 sent_space_message = true;
542 BOOST_ASSERT(cur.pos() > 0);
543 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
544 && !par.isDeleted(cur.pos() - 1)) {
545 static bool sent_space_message = false;
546 if (!sent_space_message) {
547 cur.message(_("You cannot type two spaces this way. "
548 "Please read the Tutorial."));
549 sent_space_message = true;
555 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
556 cur.checkBufferStructure();
558 // cur.updateFlags(Update::Force);
559 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
564 void Text::charInserted(Cursor & cur)
566 Paragraph & par = cur.paragraph();
568 // Here we call finishUndo for every 20 characters inserted.
569 // This is from my experience how emacs does it. (Lgb)
570 static unsigned int counter;
578 // register word if a non-letter was entered
580 && par.isLetter(cur.pos() - 2)
581 && !par.isLetter(cur.pos() - 1)) {
582 // get the word in front of cursor
583 BOOST_ASSERT(this == cur.text());
584 cur.paragraph().updateWords(cur.top());
589 // the cursor set functions have a special mechanism. When they
590 // realize, that you left an empty paragraph, they will delete it.
592 bool Text::cursorForwardOneWord(Cursor & cur)
594 BOOST_ASSERT(this == cur.text());
598 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
602 // Advance through word.
603 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
605 // Skip through trailing nonword stuff.
606 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
609 return setCursor(cur, old.pit(), old.pos());
613 bool Text::cursorBackwardOneWord(Cursor & cur)
615 BOOST_ASSERT(this == cur.text());
619 if (old.pos() == 0 && old.pit() != 0) {
621 old.pos() = old.lastpos();
623 // Skip through initial nonword stuff.
624 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
626 // Advance through word.
627 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
630 return setCursor(cur, old.pit(), old.pos());
634 void Text::selectWord(Cursor & cur, word_location loc)
636 BOOST_ASSERT(this == cur.text());
637 CursorSlice from = cur.top();
638 CursorSlice to = cur.top();
639 getWord(from, to, loc);
640 if (cur.top() != from)
641 setCursor(cur, from.pit(), from.pos());
645 setCursor(cur, to.pit(), to.pos());
650 // Select the word currently under the cursor when no
651 // selection is currently set
652 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
654 BOOST_ASSERT(this == cur.text());
657 selectWord(cur, loc);
658 return cur.selection();
662 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
664 BOOST_ASSERT(this == cur.text());
666 if (!cur.selection())
669 cur.recordUndoSelection();
671 pit_type begPit = cur.selectionBegin().pit();
672 pit_type endPit = cur.selectionEnd().pit();
674 pos_type begPos = cur.selectionBegin().pos();
675 pos_type endPos = cur.selectionEnd().pos();
677 // keep selection info, because endPos becomes invalid after the first loop
678 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
680 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
682 for (pit_type pit = begPit; pit <= endPit; ++pit) {
683 pos_type parSize = pars_[pit].size();
685 // ignore empty paragraphs; otherwise, an assertion will fail for
686 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
690 // do not consider first paragraph if the cursor starts at pos size()
691 if (pit == begPit && begPos == parSize)
694 // do not consider last paragraph if the cursor ends at pos 0
695 if (pit == endPit && endPos == 0)
696 break; // last iteration anyway
698 pos_type left = (pit == begPit ? begPos : 0);
699 pos_type right = (pit == endPit ? endPos : parSize);
702 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
704 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
708 // next, accept/reject imaginary end-of-par characters
710 for (pit_type pit = begPit; pit <= endPit; ++pit) {
711 pos_type pos = pars_[pit].size();
713 // skip if the selection ends before the end-of-par
714 if (pit == endPit && endsBeforeEndOfPar)
715 break; // last iteration anyway
717 // skip if this is not the last paragraph of the document
718 // note: the user should be able to accept/reject the par break of the last par!
719 if (pit == endPit && pit + 1 != int(pars_.size()))
720 break; // last iteration anway
723 if (pars_[pit].isInserted(pos)) {
724 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
725 } else if (pars_[pit].isDeleted(pos)) {
726 if (pit + 1 == int(pars_.size())) {
727 // we cannot remove a par break at the end of the last paragraph;
728 // instead, we mark it unchanged
729 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
731 mergeParagraph(cur.buffer().params(), pars_, pit);
737 if (pars_[pit].isDeleted(pos)) {
738 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
739 } else if (pars_[pit].isInserted(pos)) {
740 if (pit + 1 == int(pars_.size())) {
741 // we mark the par break at the end of the last paragraph unchanged
742 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
744 mergeParagraph(cur.buffer().params(), pars_, pit);
752 // finally, invoke the DEPM
754 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
759 cur.clearSelection();
760 setCursorIntern(cur, begPit, begPos);
761 cur.updateFlags(Update::Force);
762 updateLabels(cur.buffer());
766 void Text::acceptChanges(BufferParams const & bparams)
768 lyx::acceptChanges(pars_, bparams);
769 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
773 void Text::rejectChanges(BufferParams const & bparams)
775 pit_type pars_size = static_cast<pit_type>(pars_.size());
777 // first, reject changes within each individual paragraph
778 // (do not consider end-of-par)
779 for (pit_type pit = 0; pit < pars_size; ++pit) {
780 if (!pars_[pit].empty()) // prevent assertion failure
781 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
784 // next, reject imaginary end-of-par characters
785 for (pit_type pit = 0; pit < pars_size; ++pit) {
786 pos_type pos = pars_[pit].size();
788 if (pars_[pit].isDeleted(pos)) {
789 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
790 } else if (pars_[pit].isInserted(pos)) {
791 if (pit == pars_size - 1) {
792 // we mark the par break at the end of the last
793 // paragraph unchanged
794 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
796 mergeParagraph(bparams, pars_, pit);
803 // finally, invoke the DEPM
804 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
808 void Text::deleteWordForward(Cursor & cur)
810 BOOST_ASSERT(this == cur.text());
811 if (cur.lastpos() == 0)
815 cur.selection() = true;
816 cursorForwardOneWord(cur);
818 cutSelection(cur, true, false);
819 cur.checkBufferStructure();
824 void Text::deleteWordBackward(Cursor & cur)
826 BOOST_ASSERT(this == cur.text());
827 if (cur.lastpos() == 0)
831 cur.selection() = true;
832 cursorBackwardOneWord(cur);
834 cutSelection(cur, true, false);
835 cur.checkBufferStructure();
840 // Kill to end of line.
841 void Text::changeCase(Cursor & cur, TextCase action)
843 BOOST_ASSERT(this == cur.text());
848 if (cur.selection()) {
849 from = cur.selBegin();
854 getWord(from, to, PARTIAL_WORD);
855 cursorForwardOneWord(cur);
858 cur.recordUndoSelection();
860 pit_type begPit = from.pit();
861 pit_type endPit = to.pit();
863 pos_type begPos = from.pos();
864 pos_type endPos = to.pos();
866 pos_type right = 0; // needed after the for loop
868 for (pit_type pit = begPit; pit <= endPit; ++pit) {
869 Paragraph & par = pars_[pit];
870 pos_type const pos = (pit == begPit ? begPos : 0);
871 right = (pit == endPit ? endPos : par.size());
872 par.changeCase(cur.buffer().params(), pos, right, action);
875 // the selection may have changed due to logically-only deleted chars
877 setCursor(cur, begPit, begPos);
879 setCursor(cur, endPit, right);
882 setCursor(cur, endPit, right);
884 cur.checkBufferStructure();
888 bool Text::handleBibitems(Cursor & cur)
890 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
896 BufferParams const & bufparams = cur.buffer().params();
897 Paragraph const & par = cur.paragraph();
898 Cursor prevcur = cur;
901 prevcur.pos() = prevcur.lastpos();
903 Paragraph const & prevpar = prevcur.paragraph();
905 // if a bibitem is deleted, merge with previous paragraph
906 // if this is a bibliography item as well
907 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
908 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
909 mergeParagraph(bufparams, cur.text()->paragraphs(),
911 updateLabels(cur.buffer());
912 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
913 cur.updateFlags(Update::Force);
917 // otherwise reset to default
918 cur.paragraph().setEmptyOrDefaultLayout(bufparams.documentClass());
923 bool Text::erase(Cursor & cur)
925 BOOST_ASSERT(this == cur.text());
926 bool needsUpdate = false;
927 Paragraph & par = cur.paragraph();
929 if (cur.pos() != cur.lastpos()) {
930 // this is the code for a normal delete, not pasting
932 cur.recordUndo(DELETE_UNDO);
933 bool const was_inset = cur.paragraph().isInset(cur.pos());
934 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges))
935 // the character has been logically deleted only => skip it
936 cur.top().forwardPos();
939 updateLabels(cur.buffer());
941 cur.checkBufferStructure();
944 if (cur.pit() == cur.lastpit())
945 return dissolveInset(cur);
947 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
948 par.setChange(cur.pos(), Change(Change::DELETED));
952 setCursorIntern(cur, cur.pit() + 1, 0);
953 needsUpdate = backspacePos0(cur);
957 needsUpdate |= handleBibitems(cur);
960 // Make sure the cursor is correct. Is this really needed?
961 // No, not really... at least not here!
962 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
963 cur.checkBufferStructure();
970 bool Text::backspacePos0(Cursor & cur)
972 BOOST_ASSERT(this == cur.text());
976 bool needsUpdate = false;
978 BufferParams const & bufparams = cur.buffer().params();
979 DocumentClass const & tclass = bufparams.documentClass();
980 ParagraphList & plist = cur.text()->paragraphs();
981 Paragraph const & par = cur.paragraph();
982 Cursor prevcur = cur;
984 prevcur.pos() = prevcur.lastpos();
985 Paragraph const & prevpar = prevcur.paragraph();
987 // is it an empty paragraph?
988 if (cur.lastpos() == 0
989 || (cur.lastpos() == 1 && par.isSeparator(0))) {
990 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
991 plist.erase(boost::next(plist.begin(), cur.pit()));
994 // is previous par empty?
995 else if (prevcur.lastpos() == 0
996 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
997 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
998 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1001 // Pasting is not allowed, if the paragraphs have different
1002 // layouts. I think it is a real bug of all other
1003 // word processors to allow it. It confuses the user.
1004 // Correction: Pasting is always allowed with standard-layout
1005 // or the empty layout.
1006 else if (par.layout() == prevpar.layout()
1007 || tclass.isDefaultLayout(par.layout())
1008 || tclass.isEmptyLayout(par.layout())) {
1009 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1010 mergeParagraph(bufparams, plist, prevcur.pit());
1015 updateLabels(cur.buffer());
1016 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1023 bool Text::backspace(Cursor & cur)
1025 BOOST_ASSERT(this == cur.text());
1026 bool needsUpdate = false;
1027 if (cur.pos() == 0) {
1029 return dissolveInset(cur);
1031 Paragraph & prev_par = pars_[cur.pit() - 1];
1033 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1034 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1035 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1038 // The cursor is at the beginning of a paragraph, so
1039 // the backspace will collapse two paragraphs into one.
1040 needsUpdate = backspacePos0(cur);
1043 // this is the code for a normal backspace, not pasting
1045 cur.recordUndo(DELETE_UNDO);
1046 // We used to do cursorBackwardIntern() here, but it is
1047 // not a good idea since it triggers the auto-delete
1048 // mechanism. So we do a cursorBackwardIntern()-lite,
1049 // without the dreaded mechanism. (JMarc)
1050 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1051 false, cur.boundary());
1052 bool const was_inset = cur.paragraph().isInset(cur.pos());
1053 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1055 updateLabels(cur.buffer());
1057 cur.checkBufferStructure();
1060 if (cur.pos() == cur.lastpos())
1061 cur.setCurrentFont();
1063 needsUpdate |= handleBibitems(cur);
1065 // A singlePar update is not enough in this case.
1066 // cur.updateFlags(Update::Force);
1067 setCursor(cur.top(), cur.pit(), cur.pos());
1073 bool Text::dissolveInset(Cursor & cur) {
1074 BOOST_ASSERT(this == cur.text());
1076 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1079 cur.recordUndoInset();
1081 cur.selHandle(false);
1083 pos_type spos = cur.pos();
1084 pit_type spit = cur.pit();
1085 ParagraphList plist;
1086 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1087 plist = paragraphs();
1089 // store cursor offset
1093 Buffer & b = cur.buffer();
1094 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1095 if (!plist.empty()) {
1096 // ERT paragraphs have the Language latex_language.
1097 // This is invalid outside of ERT, so we need to
1098 // change it to the buffer language.
1099 ParagraphList::iterator it = plist.begin();
1100 ParagraphList::iterator it_end = plist.end();
1101 for (; it != it_end; it++)
1102 it->changeLanguage(b.params(), latex_language, b.language());
1104 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1105 b.errorList("Paste"));
1107 cur.pit() = min(cur.lastpit(), spit);
1108 cur.pos() = min(cur.lastpos(), spos);
1110 cur.clearSelection();
1116 void Text::getWord(CursorSlice & from, CursorSlice & to,
1117 word_location const loc) const
1119 Paragraph const & from_par = pars_[from.pit()];
1121 case WHOLE_WORD_STRICT:
1122 if (from.pos() == 0 || from.pos() == from_par.size()
1123 || !from_par.isLetter(from.pos())
1124 || !from_par.isLetter(from.pos() - 1)) {
1128 // no break here, we go to the next
1131 // If we are already at the beginning of a word, do nothing
1132 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1134 // no break here, we go to the next
1137 // always move the cursor to the beginning of previous word
1138 while (from.pos() && from_par.isLetter(from.pos() - 1))
1142 LYXERR0("Text::getWord: NEXT_WORD not implemented yet");
1145 // no need to move the 'from' cursor
1149 Paragraph const & to_par = pars_[to.pit()];
1150 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1155 void Text::write(Buffer const & buf, ostream & os) const
1157 ParagraphList::const_iterator pit = paragraphs().begin();
1158 ParagraphList::const_iterator end = paragraphs().end();
1160 for (; pit != end; ++pit)
1161 pit->write(os, buf.params(), dth);
1163 // Close begin_deeper
1164 for(; dth > 0; --dth)
1165 os << "\n\\end_deeper";
1169 bool Text::read(Buffer const & buf, Lexer & lex,
1170 ErrorList & errorList, InsetText * insetPtr)
1172 depth_type depth = 0;
1174 while (lex.isOK()) {
1176 string const token = lex.getString();
1181 if (token == "\\end_inset")
1184 if (token == "\\end_body")
1187 if (token == "\\begin_body")
1190 if (token == "\\end_document")
1193 if (token == "\\begin_layout") {
1194 lex.pushToken(token);
1197 par.params().depth(depth);
1198 par.setFont(0, Font(inherit_font, buf.params().language));
1199 par.setInsetOwner(insetPtr);
1200 pars_.push_back(par);
1202 // FIXME: goddamn InsetTabular makes us pass a Buffer
1204 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1206 // register the words in the global word list
1207 CursorSlice sl = CursorSlice(*insetPtr);
1208 sl.pit() = pars_.size() - 1;
1209 pars_.back().updateWords(sl);
1210 } else if (token == "\\begin_deeper") {
1212 } else if (token == "\\end_deeper") {
1214 lex.printError("\\end_deeper: " "depth is already null");
1218 LYXERR0("Handling unknown body token: `" << token << '\'');
1224 // Returns the current font and depth as a message.
1225 docstring Text::currentState(Cursor & cur)
1227 BOOST_ASSERT(this == cur.text());
1228 Buffer & buf = cur.buffer();
1229 Paragraph const & par = cur.paragraph();
1230 odocstringstream os;
1232 if (buf.params().trackChanges)
1233 os << _("[Change Tracking] ");
1235 Change change = par.lookupChange(cur.pos());
1237 if (change.type != Change::UNCHANGED) {
1238 Author const & a = buf.params().authors().get(change.author);
1239 os << _("Change: ") << a.name();
1240 if (!a.email().empty())
1241 os << " (" << a.email() << ")";
1242 // FIXME ctime is english, we should translate that
1243 os << _(" at ") << ctime(&change.changetime);
1247 // I think we should only show changes from the default
1249 // No, from the document font (MV)
1250 Font font = cur.real_current_font;
1251 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1253 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1255 // The paragraph depth
1256 int depth = cur.paragraph().getDepth();
1258 os << bformat(_(", Depth: %1$d"), depth);
1260 // The paragraph spacing, but only if different from
1262 Spacing const & spacing = par.params().spacing();
1263 if (!spacing.isDefault()) {
1264 os << _(", Spacing: ");
1265 switch (spacing.getSpace()) {
1266 case Spacing::Single:
1269 case Spacing::Onehalf:
1272 case Spacing::Double:
1275 case Spacing::Other:
1276 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1278 case Spacing::Default:
1279 // should never happen, do nothing
1284 #ifdef DEVEL_VERSION
1285 os << _(", Inset: ") << &cur.inset();
1286 os << _(", Paragraph: ") << cur.pit();
1287 os << _(", Id: ") << par.id();
1288 os << _(", Position: ") << cur.pos();
1289 // FIXME: Why is the check for par.size() needed?
1290 // We are called with cur.pos() == par.size() quite often.
1291 if (!par.empty() && cur.pos() < par.size()) {
1292 // Force output of code point, not character
1293 size_t const c = par.getChar(cur.pos());
1294 os << _(", Char: 0x") << hex << c;
1296 os << _(", Boundary: ") << cur.boundary();
1297 // Row & row = cur.textRow();
1298 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1304 docstring Text::getPossibleLabel(Cursor & cur) const
1306 pit_type pit = cur.pit();
1308 Layout const * layout = &(pars_[pit].layout());
1311 docstring par_text = pars_[pit].asString(false);
1313 // the return string of math matrices might contain linebreaks
1314 par_text = subst(par_text, '\n', '-');
1315 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1316 if (par_text.empty())
1319 par_text = split(par_text, head, ' ');
1320 // Is it legal to use spaces in labels ?
1326 // No need for a prefix if the user said so.
1327 if (lyxrc.label_init_length <= 0)
1330 // Will contain the label type.
1333 // For section, subsection, etc...
1334 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1335 Layout const * layout2 = &(pars_[pit - 1].layout());
1336 if (layout2->latextype != LATEX_PARAGRAPH) {
1341 if (layout->latextype != LATEX_PARAGRAPH)
1342 name = from_ascii(layout->latexname());
1344 // for captions, we just take the caption type
1345 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1347 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1349 // If none of the above worked, we'll see if we're inside various
1350 // types of insets and take our abbreviation from them.
1352 InsetCode const codes[] = {
1357 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1358 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1360 name = float_inset->name();
1366 // Create a correct prefix for prettyref
1367 if (name == "theorem")
1368 name = from_ascii("thm");
1369 else if (name == "Foot")
1370 name = from_ascii("fn");
1371 else if (name == "listing")
1372 name = from_ascii("lst");
1375 text = name.substr(0, 3) + ':' + text;
1381 void Text::charsTranspose(Cursor & cur)
1383 BOOST_ASSERT(this == cur.text());
1385 pos_type pos = cur.pos();
1387 // If cursor is at beginning or end of paragraph, do nothing.
1388 if (pos == cur.lastpos() || pos == 0)
1391 Paragraph & par = cur.paragraph();
1393 // Get the positions of the characters to be transposed.
1394 pos_type pos1 = pos - 1;
1395 pos_type pos2 = pos;
1397 // In change tracking mode, ignore deleted characters.
1398 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1400 if (pos2 == cur.lastpos())
1403 while (pos1 >= 0 && par.isDeleted(pos1))
1408 // Don't do anything if one of the "characters" is not regular text.
1409 if (par.isInset(pos1) || par.isInset(pos2))
1412 // Store the characters to be transposed (including font information).
1413 char_type char1 = par.getChar(pos1);
1415 par.getFontSettings(cur.buffer().params(), pos1);
1417 char_type char2 = par.getChar(pos2);
1419 par.getFontSettings(cur.buffer().params(), pos2);
1421 // And finally, we are ready to perform the transposition.
1422 // Track the changes if Change Tracking is enabled.
1423 bool const trackChanges = cur.buffer().params().trackChanges;
1427 par.eraseChar(pos2, trackChanges);
1428 par.eraseChar(pos1, trackChanges);
1429 par.insertChar(pos1, char2, font2, trackChanges);
1430 par.insertChar(pos2, char1, font1, trackChanges);
1432 cur.checkBufferStructure();
1434 // After the transposition, move cursor to after the transposition.
1435 setCursor(cur, cur.pit(), pos2);
1440 DocIterator Text::macrocontextPosition() const
1442 return macrocontext_position_;
1446 void Text::setMacrocontextPosition(DocIterator const & pos)
1448 macrocontext_position_ = pos;