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 "frontends/FontMetrics.h"
51 #include "frontends/Painter.h"
53 #include "insets/InsetText.h"
54 #include "insets/InsetBibitem.h"
55 #include "insets/InsetCaption.h"
56 #include "insets/InsetHFill.h"
57 #include "insets/InsetLine.h"
58 #include "insets/InsetNewline.h"
59 #include "insets/InsetNewpage.h"
60 #include "insets/InsetOptArg.h"
61 #include "insets/InsetSpace.h"
62 #include "insets/InsetSpecialChar.h"
63 #include "insets/InsetTabular.h"
65 #include "support/convert.h"
66 #include "support/debug.h"
67 #include "support/docstream.h"
68 #include "support/gettext.h"
69 #include "support/lstrings.h"
70 #include "support/textutils.h"
72 #include <boost/next_prior.hpp>
80 using support::bformat;
81 using support::contains;
85 using cap::cutSelection;
86 using cap::pasteParagraphList;
88 using frontend::FontMetrics;
92 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
93 string const & token, Font & font, Change & change, ErrorList & errorList)
95 BufferParams const & bp = buf.params();
97 if (token[0] != '\\') {
98 docstring dstr = lex.getDocString();
99 par.appendString(dstr, font, change);
101 } else if (token == "\\begin_layout") {
103 docstring layoutname = lex.getDocString();
105 font = Font(inherit_font, bp.language);
106 change = Change(Change::UNCHANGED);
108 TextClass const & tclass = bp.getTextClass();
110 if (layoutname.empty()) {
111 layoutname = tclass.defaultLayoutName();
114 bool hasLayout = tclass.hasLayout(layoutname);
117 errorList.push_back(ErrorItem(_("Unknown layout"),
118 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
119 layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
120 layoutname = tclass.defaultLayoutName();
123 par.layout(bp.getTextClass()[layoutname]);
125 // Test whether the layout is obsolete.
126 LayoutPtr const & layout = par.layout();
127 if (!layout->obsoleted_by().empty())
128 par.layout(bp.getTextClass()[layout->obsoleted_by()]);
130 par.params().read(lex);
132 } else if (token == "\\end_layout") {
133 LYXERR0("Solitary \\end_layout in line " << lex.getLineNo() << "\n"
134 << "Missing \\begin_layout ?");
135 } else if (token == "\\end_inset") {
136 LYXERR0("Solitary \\end_inset in line " << lex.getLineNo() << "\n"
137 << "Missing \\begin_inset ?");
138 } else if (token == "\\begin_inset") {
139 Inset * inset = readInset(lex, buf);
141 par.insertInset(par.size(), inset, font, change);
144 docstring line = lex.getDocString();
145 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
146 par.id(), 0, par.size()));
148 } else if (token == "\\family") {
150 setLyXFamily(lex.getString(), font.fontInfo());
151 } else if (token == "\\series") {
153 setLyXSeries(lex.getString(), font.fontInfo());
154 } else if (token == "\\shape") {
156 setLyXShape(lex.getString(), font.fontInfo());
157 } else if (token == "\\size") {
159 setLyXSize(lex.getString(), font.fontInfo());
160 } else if (token == "\\lang") {
162 string const tok = lex.getString();
163 Language const * lang = languages.getLanguage(tok);
165 font.setLanguage(lang);
167 font.setLanguage(bp.language);
168 lex.printError("Unknown language `$$Token'");
170 } else if (token == "\\numeric") {
172 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
173 } else if (token == "\\emph") {
175 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
176 } else if (token == "\\bar") {
178 string const tok = lex.getString();
181 font.fontInfo().setUnderbar(FONT_ON);
182 else if (tok == "no")
183 font.fontInfo().setUnderbar(FONT_OFF);
184 else if (tok == "default")
185 font.fontInfo().setUnderbar(FONT_INHERIT);
187 lex.printError("Unknown bar font flag "
189 } else if (token == "\\noun") {
191 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
192 } else if (token == "\\color") {
194 setLyXColor(lex.getString(), font.fontInfo());
195 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
197 // Insets don't make sense in a free-spacing context! ---Kayvan
198 if (par.isFreeSpacing()) {
199 if (token == "\\InsetSpace")
200 par.appendChar(' ', font, change);
201 else if (lex.isOK()) {
203 string const next_token = lex.getString();
204 if (next_token == "\\-")
205 par.appendChar('-', font, change);
207 lex.printError("Token `$$Token' "
209 "paragraph layout!");
213 auto_ptr<Inset> inset;
214 if (token == "\\SpecialChar" )
215 inset.reset(new InsetSpecialChar);
217 inset.reset(new InsetSpace);
218 inset->read(buf, lex);
219 par.insertInset(par.size(), inset.release(),
222 } else if (token == "\\backslash") {
223 par.appendChar('\\', font, change);
224 } else if (token == "\\linebreak") {
225 auto_ptr<Inset> inset(new InsetLinebreak);
226 inset->read(buf, lex);
227 par.insertInset(par.size(), inset.release(), font, change);
228 } else if (token == "\\newline") {
229 auto_ptr<Inset> inset(new InsetNewline);
230 inset->read(buf, lex);
231 par.insertInset(par.size(), inset.release(), font, change);
232 } else if (token == "\\LyXTable") {
233 auto_ptr<Inset> inset(new InsetTabular(buf));
234 inset->read(buf, lex);
235 par.insertInset(par.size(), inset.release(), font, change);
236 } else if (token == "\\hfill") {
237 par.insertInset(par.size(), new InsetHFill, font, change);
238 } else if (token == "\\lyxline") {
239 par.insertInset(par.size(), new InsetLine, font, change);
240 } else if (token == "\\newpage") {
241 par.insertInset(par.size(), new InsetNewpage, font, change);
242 } else if (token == "\\pagebreak") {
243 par.insertInset(par.size(), new InsetPagebreak, font, change);
244 } else if (token == "\\clearpage") {
245 par.insertInset(par.size(), new InsetClearPage, font, change);
246 } else if (token == "\\cleardoublepage") {
247 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
248 } else if (token == "\\change_unchanged") {
249 change = Change(Change::UNCHANGED);
250 } else if (token == "\\change_inserted") {
252 std::istringstream is(lex.getString());
256 if (aid >= bp.author_map.size()) {
257 errorList.push_back(ErrorItem(_("Change tracking error"),
258 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
259 par.id(), 0, par.size()));
260 change = Change(Change::UNCHANGED);
262 change = Change(Change::INSERTED, bp.author_map[aid], ct);
263 } else if (token == "\\change_deleted") {
265 std::istringstream is(lex.getString());
269 if (aid >= bp.author_map.size()) {
270 errorList.push_back(ErrorItem(_("Change tracking error"),
271 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
272 par.id(), 0, par.size()));
273 change = Change(Change::UNCHANGED);
275 change = Change(Change::DELETED, bp.author_map[aid], ct);
278 errorList.push_back(ErrorItem(_("Unknown token"),
279 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
281 par.id(), 0, par.size()));
286 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
287 ErrorList & errorList)
290 string token = lex.getString();
292 Change change(Change::UNCHANGED);
295 readParToken(buf, par, lex, token, font, change, errorList);
298 token = lex.getString();
303 if (token == "\\end_layout") {
304 //Ok, paragraph finished
308 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
309 if (token == "\\begin_layout" || token == "\\end_document"
310 || token == "\\end_inset" || token == "\\begin_deeper"
311 || token == "\\end_deeper") {
312 lex.pushToken(token);
313 lyxerr << "Paragraph ended in line "
314 << lex.getLineNo() << "\n"
315 << "Missing \\end_layout.\n";
319 // Final change goes to paragraph break:
320 par.setChange(par.size(), change);
322 // Initialize begin_of_body_ on load; redoParagraph maintains
323 par.setBeginOfBody();
330 bool Text::empty() const
332 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
333 // FIXME: Should we consider the labeled type as empty too?
334 && pars_[0].layout()->labeltype == LABEL_NO_LABEL);
338 double Text::spacing(Buffer const & buffer,
339 Paragraph const & par) const
341 if (par.params().spacing().isDefault())
342 return buffer.params().spacing().getValue();
343 return par.params().spacing().getValue();
347 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
349 BOOST_ASSERT(this == cur.text());
351 Paragraph & cpar = cur.paragraph();
352 pit_type cpit = cur.pit();
354 TextClass const & tclass = cur.buffer().params().getTextClass();
355 LayoutPtr const & layout = cpar.layout();
357 // this is only allowed, if the current paragraph is not empty
358 // or caption and if it has not the keepempty flag active
359 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
360 layout->labeltype != LABEL_SENSITIVE)
363 // a layout change may affect also the following paragraph
364 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
366 // Always break behind a space
367 // It is better to erase the space (Dekel)
368 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
369 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
371 // What should the layout for the new paragraph be?
372 bool keep_layout = inverse_logic ?
373 !layout->isEnvironment()
374 : layout->isEnvironment();
376 // We need to remember this before we break the paragraph, because
377 // that invalidates the layout variable
378 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
380 // we need to set this before we insert the paragraph.
381 bool const isempty = cpar.allowEmpty() && cpar.empty();
383 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
384 cur.pos(), keep_layout);
386 // After this, neither paragraph contains any rows!
389 pit_type next_par = cpit + 1;
391 // well this is the caption hack since one caption is really enough
394 // set to standard-layout
395 pars_[cpit].applyLayout(tclass.defaultLayout());
397 // set to standard-layout
398 pars_[next_par].applyLayout(tclass.defaultLayout());
401 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
402 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
403 break; // the character couldn't be deleted physically due to change tracking
406 updateLabels(cur.buffer());
408 // A singlePar update is not enough in this case.
409 cur.updateFlags(Update::Force);
411 // This check is necessary. Otherwise the new empty paragraph will
412 // be deleted automatically. And it is more friendly for the user!
413 if (cur.pos() != 0 || isempty)
414 setCursor(cur, cur.pit() + 1, 0);
416 setCursor(cur, cur.pit(), 0);
420 // insert a character, moves all the following breaks in the
421 // same Paragraph one to the right and make a rebreak
422 void Text::insertChar(Cursor & cur, char_type c)
424 BOOST_ASSERT(this == cur.text());
426 cur.recordUndo(INSERT_UNDO);
428 TextMetrics const & tm = cur.bv().textMetrics(this);
429 Buffer const & buffer = cur.buffer();
430 Paragraph & par = cur.paragraph();
431 // try to remove this
432 pit_type const pit = cur.pit();
434 bool const freeSpacing = par.layout()->free_spacing ||
437 if (lyxrc.auto_number) {
438 static docstring const number_operators = from_ascii("+-/*");
439 static docstring const number_unary_operators = from_ascii("+-");
440 static docstring const number_seperators = from_ascii(".,:");
442 if (cur.current_font.fontInfo().number() == FONT_ON) {
443 if (!isDigit(c) && !contains(number_operators, c) &&
444 !(contains(number_seperators, c) &&
446 cur.pos() != cur.lastpos() &&
447 tm.getDisplayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
448 tm.getDisplayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
450 number(cur); // Set current_font.number to OFF
451 } else if (isDigit(c) &&
452 cur.real_current_font.isVisibleRightToLeft()) {
453 number(cur); // Set current_font.number to ON
455 if (cur.pos() != 0) {
456 char_type const c = par.getChar(cur.pos() - 1);
457 if (contains(number_unary_operators, c) &&
459 || par.isSeparator(cur.pos() - 2)
460 || par.isNewline(cur.pos() - 2))
462 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
464 } else if (contains(number_seperators, c)
466 && tm.getDisplayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
467 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
474 // In Bidi text, we want spaces to be treated in a special way: spaces
475 // which are between words in different languages should get the
476 // paragraph's language; otherwise, spaces should keep the language
477 // they were originally typed in. This is only in effect while typing;
478 // after the text is already typed in, the user can always go back and
479 // explicitly set the language of a space as desired. But 99.9% of the
480 // time, what we're doing here is what the user actually meant.
482 // The following cases are the ones in which the language of the space
483 // should be changed to match that of the containing paragraph. In the
484 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
485 // represents a space, pipe (|) represents the cursor position (so the
486 // character before it is the one just typed in). The different cases
487 // are depicted logically (not visually), from left to right:
492 // Theoretically, there are other situations that we should, perhaps, deal
493 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
494 // point (to understand why, just try to create this situation...).
496 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
497 // get font in front and behind the space in question. But do NOT
498 // use getFont(cur.pos()) because the character c is not inserted yet
499 Font const pre_space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 2);
500 Font const & post_space_font = cur.real_current_font;
501 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
502 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
504 if (pre_space_rtl != post_space_rtl) {
505 // Set the space's language to match the language of the
506 // adjacent character whose direction is the paragraph's
507 // direction; don't touch other properties of the font
508 Language const * lang =
509 (pre_space_rtl == par.isRTL(buffer.params())) ?
510 pre_space_font.language() : post_space_font.language();
512 Font space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 1);
513 space_font.setLanguage(lang);
514 par.setFont(cur.pos() - 1, space_font);
518 // Next check, if there will be two blanks together or a blank at
519 // the beginning of a paragraph.
520 // I decided to handle blanks like normal characters, the main
521 // difference are the special checks when calculating the row.fill
522 // (blank does not count at the end of a row) and the check here
524 // When the free-spacing option is set for the current layout,
525 // disable the double-space checking
526 if (!freeSpacing && isLineSeparatorChar(c)) {
527 if (cur.pos() == 0) {
528 static bool sent_space_message = false;
529 if (!sent_space_message) {
530 cur.message(_("You cannot insert a space at the "
531 "beginning of a paragraph. Please read the Tutorial."));
532 sent_space_message = true;
536 BOOST_ASSERT(cur.pos() > 0);
537 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
538 && !par.isDeleted(cur.pos() - 1)) {
539 static bool sent_space_message = false;
540 if (!sent_space_message) {
541 cur.message(_("You cannot type two spaces this way. "
542 "Please read the Tutorial."));
543 sent_space_message = true;
549 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
550 checkBufferStructure(cur.buffer(), cur);
552 // cur.updateFlags(Update::Force);
553 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
558 void Text::charInserted(Cursor & cur)
560 // Here we call finishUndo for every 20 characters inserted.
561 // This is from my experience how emacs does it. (Lgb)
562 static unsigned int counter;
572 // the cursor set functions have a special mechanism. When they
573 // realize, that you left an empty paragraph, they will delete it.
575 bool Text::cursorForwardOneWord(Cursor & cur)
577 BOOST_ASSERT(this == cur.text());
581 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
585 // Advance through word.
586 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
588 // Skip through trailing nonword stuff.
589 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
592 return setCursor(cur, old.pit(), old.pos());
596 bool Text::cursorBackwardOneWord(Cursor & cur)
598 BOOST_ASSERT(this == cur.text());
602 if (old.pos() == 0 && old.pit() != 0) {
604 old.pos() = old.lastpos();
606 // Skip through initial nonword stuff.
607 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
609 // Advance through word.
610 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
613 return setCursor(cur, old.pit(), old.pos());
617 void Text::selectWord(Cursor & cur, word_location loc)
619 BOOST_ASSERT(this == cur.text());
620 CursorSlice from = cur.top();
621 CursorSlice to = cur.top();
622 getWord(from, to, loc);
623 if (cur.top() != from)
624 setCursor(cur, from.pit(), from.pos());
628 setCursor(cur, to.pit(), to.pos());
633 // Select the word currently under the cursor when no
634 // selection is currently set
635 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
637 BOOST_ASSERT(this == cur.text());
640 selectWord(cur, loc);
641 return cur.selection();
645 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
647 BOOST_ASSERT(this == cur.text());
649 if (!cur.selection())
652 cur.recordUndoSelection();
654 pit_type begPit = cur.selectionBegin().pit();
655 pit_type endPit = cur.selectionEnd().pit();
657 pos_type begPos = cur.selectionBegin().pos();
658 pos_type endPos = cur.selectionEnd().pos();
660 // keep selection info, because endPos becomes invalid after the first loop
661 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
663 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
665 for (pit_type pit = begPit; pit <= endPit; ++pit) {
666 pos_type parSize = pars_[pit].size();
668 // ignore empty paragraphs; otherwise, an assertion will fail for
669 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
673 // do not consider first paragraph if the cursor starts at pos size()
674 if (pit == begPit && begPos == parSize)
677 // do not consider last paragraph if the cursor ends at pos 0
678 if (pit == endPit && endPos == 0)
679 break; // last iteration anyway
681 pos_type left = (pit == begPit ? begPos : 0);
682 pos_type right = (pit == endPit ? endPos : parSize);
685 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
687 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
691 // next, accept/reject imaginary end-of-par characters
693 for (pit_type pit = begPit; pit <= endPit; ++pit) {
694 pos_type pos = pars_[pit].size();
696 // skip if the selection ends before the end-of-par
697 if (pit == endPit && endsBeforeEndOfPar)
698 break; // last iteration anyway
700 // skip if this is not the last paragraph of the document
701 // note: the user should be able to accept/reject the par break of the last par!
702 if (pit == endPit && pit + 1 != int(pars_.size()))
703 break; // last iteration anway
706 if (pars_[pit].isInserted(pos)) {
707 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
708 } else if (pars_[pit].isDeleted(pos)) {
709 if (pit + 1 == int(pars_.size())) {
710 // we cannot remove a par break at the end of the last paragraph;
711 // instead, we mark it unchanged
712 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
714 mergeParagraph(cur.buffer().params(), pars_, pit);
720 if (pars_[pit].isDeleted(pos)) {
721 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
722 } else if (pars_[pit].isInserted(pos)) {
723 if (pit + 1 == int(pars_.size())) {
724 // we mark the par break at the end of the last paragraph unchanged
725 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
727 mergeParagraph(cur.buffer().params(), pars_, pit);
735 // finally, invoke the DEPM
737 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
742 cur.clearSelection();
743 setCursorIntern(cur, begPit, begPos);
744 cur.updateFlags(Update::Force);
745 updateLabels(cur.buffer());
749 void Text::acceptChanges(BufferParams const & bparams)
751 lyx::acceptChanges(pars_, bparams);
752 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
756 void Text::rejectChanges(BufferParams const & bparams)
758 pit_type pars_size = static_cast<pit_type>(pars_.size());
760 // first, reject changes within each individual paragraph
761 // (do not consider end-of-par)
762 for (pit_type pit = 0; pit < pars_size; ++pit) {
763 if (!pars_[pit].empty()) // prevent assertion failure
764 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
767 // next, reject imaginary end-of-par characters
768 for (pit_type pit = 0; pit < pars_size; ++pit) {
769 pos_type pos = pars_[pit].size();
771 if (pars_[pit].isDeleted(pos)) {
772 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
773 } else if (pars_[pit].isInserted(pos)) {
774 if (pit == pars_size - 1) {
775 // we mark the par break at the end of the last
776 // paragraph unchanged
777 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
779 mergeParagraph(bparams, pars_, pit);
786 // finally, invoke the DEPM
787 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
791 void Text::deleteWordForward(Cursor & cur)
793 BOOST_ASSERT(this == cur.text());
794 if (cur.lastpos() == 0)
798 cur.selection() = true;
799 cursorForwardOneWord(cur);
801 cutSelection(cur, true, false);
802 checkBufferStructure(cur.buffer(), cur);
807 void Text::deleteWordBackward(Cursor & cur)
809 BOOST_ASSERT(this == cur.text());
810 if (cur.lastpos() == 0)
814 cur.selection() = true;
815 cursorBackwardOneWord(cur);
817 cutSelection(cur, true, false);
818 checkBufferStructure(cur.buffer(), cur);
823 // Kill to end of line.
824 void Text::changeCase(Cursor & cur, TextCase action)
826 BOOST_ASSERT(this == cur.text());
830 if (cur.selection()) {
831 from = cur.selBegin();
835 getWord(from, to, PARTIAL_WORD);
836 cursorForwardOneWord(cur);
839 cur.recordUndoSelection();
841 pit_type begPit = from.pit();
842 pit_type endPit = to.pit();
844 pos_type begPos = from.pos();
845 pos_type endPos = to.pos();
847 pos_type right = 0; // needed after the for loop
849 for (pit_type pit = begPit; pit <= endPit; ++pit) {
850 Paragraph & par = pars_[pit];
851 pos_type const pos = (pit == begPit ? begPos : 0);
852 right = (pit == endPit ? endPos : par.size());
853 par.changeCase(cur.buffer().params(), pos, right, action);
856 // the selection may have changed due to logically-only deleted chars
857 setCursor(cur, begPit, begPos);
859 setCursor(cur, endPit, right);
862 checkBufferStructure(cur.buffer(), cur);
866 bool Text::handleBibitems(Cursor & cur)
868 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
870 // if a bibitem is deleted, merge with previous paragraph
871 // if this is a bibliography item as well
872 if (cur.pos() == 0) {
873 BufferParams const & bufparams = cur.buffer().params();
874 Paragraph const & par = cur.paragraph();
875 Cursor prevcur = cur;
878 prevcur.pos() = prevcur.lastpos();
880 Paragraph const & prevpar = prevcur.paragraph();
881 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
882 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
883 mergeParagraph(bufparams, cur.text()->paragraphs(),
885 updateLabels(cur.buffer());
886 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
887 cur.updateFlags(Update::Force);
888 // if not, reset the paragraph to default
890 cur.paragraph().layout(
891 bufparams.getTextClass().defaultLayout());
898 bool Text::erase(Cursor & cur)
900 BOOST_ASSERT(this == cur.text());
901 bool needsUpdate = false;
902 Paragraph & par = cur.paragraph();
904 if (cur.pos() != cur.lastpos()) {
905 // this is the code for a normal delete, not pasting
907 cur.recordUndo(DELETE_UNDO);
908 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
909 // the character has been logically deleted only => skip it
910 cur.top().forwardPos();
912 checkBufferStructure(cur.buffer(), cur);
915 if (cur.pit() == cur.lastpit())
916 return dissolveInset(cur);
918 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
919 par.setChange(cur.pos(), Change(Change::DELETED));
923 setCursorIntern(cur, cur.pit() + 1, 0);
924 needsUpdate = backspacePos0(cur);
928 needsUpdate |= handleBibitems(cur);
931 // Make sure the cursor is correct. Is this really needed?
932 // No, not really... at least not here!
933 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
934 checkBufferStructure(cur.buffer(), cur);
941 bool Text::backspacePos0(Cursor & cur)
943 BOOST_ASSERT(this == cur.text());
947 bool needsUpdate = false;
949 BufferParams const & bufparams = cur.buffer().params();
950 TextClass const & tclass = bufparams.getTextClass();
951 ParagraphList & plist = cur.text()->paragraphs();
952 Paragraph const & par = cur.paragraph();
953 Cursor prevcur = cur;
955 prevcur.pos() = prevcur.lastpos();
956 Paragraph const & prevpar = prevcur.paragraph();
958 // is it an empty paragraph?
959 if (cur.lastpos() == 0
960 || (cur.lastpos() == 1 && par.isSeparator(0))) {
961 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
962 plist.erase(boost::next(plist.begin(), cur.pit()));
965 // is previous par empty?
966 else if (prevcur.lastpos() == 0
967 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
968 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
969 plist.erase(boost::next(plist.begin(), prevcur.pit()));
972 // Pasting is not allowed, if the paragraphs have different
973 // layouts. I think it is a real bug of all other
974 // word processors to allow it. It confuses the user.
975 // Correction: Pasting is always allowed with standard-layout
976 else if (par.layout() == prevpar.layout()
977 || par.layout() == tclass.defaultLayout()) {
978 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
979 mergeParagraph(bufparams, plist, prevcur.pit());
984 updateLabels(cur.buffer());
985 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
992 bool Text::backspace(Cursor & cur)
994 BOOST_ASSERT(this == cur.text());
995 bool needsUpdate = false;
996 if (cur.pos() == 0) {
998 return dissolveInset(cur);
1000 Paragraph & prev_par = pars_[cur.pit() - 1];
1002 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1003 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1004 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1007 // The cursor is at the beginning of a paragraph, so
1008 // the backspace will collapse two paragraphs into one.
1009 needsUpdate = backspacePos0(cur);
1012 // this is the code for a normal backspace, not pasting
1014 cur.recordUndo(DELETE_UNDO);
1015 // We used to do cursorBackwardIntern() here, but it is
1016 // not a good idea since it triggers the auto-delete
1017 // mechanism. So we do a cursorBackwardIntern()-lite,
1018 // without the dreaded mechanism. (JMarc)
1019 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1020 false, cur.boundary());
1021 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1022 checkBufferStructure(cur.buffer(), cur);
1025 if (cur.pos() == cur.lastpos())
1026 cur.setCurrentFont();
1028 needsUpdate |= handleBibitems(cur);
1030 // A singlePar update is not enough in this case.
1031 // cur.updateFlags(Update::Force);
1032 setCursor(cur.top(), cur.pit(), cur.pos());
1038 bool Text::dissolveInset(Cursor & cur) {
1039 BOOST_ASSERT(this == cur.text());
1041 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1044 cur.recordUndoInset();
1045 cur.selHandle(false);
1047 pos_type spos = cur.pos();
1048 pit_type spit = cur.pit();
1049 ParagraphList plist;
1050 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1051 plist = paragraphs();
1053 // store cursor offset
1057 Buffer & b = cur.buffer();
1058 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1059 if (!plist.empty()) {
1060 // ERT paragraphs have the Language latex_language.
1061 // This is invalid outside of ERT, so we need to
1062 // change it to the buffer language.
1063 ParagraphList::iterator it = plist.begin();
1064 ParagraphList::iterator it_end = plist.end();
1065 for (; it != it_end; it++)
1066 it->changeLanguage(b.params(), latex_language, b.language());
1068 pasteParagraphList(cur, plist, b.params().getTextClassPtr(),
1069 b.errorList("Paste"));
1071 cur.pit() = std::min(cur.lastpit(), spit);
1072 cur.pos() = std::min(cur.lastpos(), spos);
1074 cur.clearSelection();
1080 void Text::getWord(CursorSlice & from, CursorSlice & to,
1081 word_location const loc)
1083 Paragraph const & from_par = pars_[from.pit()];
1085 case WHOLE_WORD_STRICT:
1086 if (from.pos() == 0 || from.pos() == from_par.size()
1087 || !from_par.isLetter(from.pos())
1088 || !from_par.isLetter(from.pos() - 1)) {
1092 // no break here, we go to the next
1095 // If we are already at the beginning of a word, do nothing
1096 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1098 // no break here, we go to the next
1101 // always move the cursor to the beginning of previous word
1102 while (from.pos() && from_par.isLetter(from.pos() - 1))
1106 LYXERR0("Text::getWord: NEXT_WORD not implemented yet");
1109 // no need to move the 'from' cursor
1113 Paragraph & to_par = pars_[to.pit()];
1114 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1119 void Text::write(Buffer const & buf, std::ostream & os) const
1121 ParagraphList::const_iterator pit = paragraphs().begin();
1122 ParagraphList::const_iterator end = paragraphs().end();
1124 for (; pit != end; ++pit)
1125 pit->write(buf, os, buf.params(), dth);
1127 // Close begin_deeper
1128 for(; dth > 0; --dth)
1129 os << "\n\\end_deeper";
1133 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1135 depth_type depth = 0;
1137 while (lex.isOK()) {
1139 string const token = lex.getString();
1144 if (token == "\\end_inset")
1147 if (token == "\\end_body")
1150 if (token == "\\begin_body")
1153 if (token == "\\end_document")
1156 if (token == "\\begin_layout") {
1157 lex.pushToken(token);
1160 par.params().depth(depth);
1161 par.setFont(0, Font(inherit_font, buf.params().language));
1162 pars_.push_back(par);
1164 // FIXME: goddamn InsetTabular makes us pass a Buffer
1166 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1168 } else if (token == "\\begin_deeper") {
1170 } else if (token == "\\end_deeper") {
1172 lex.printError("\\end_deeper: " "depth is already null");
1176 LYXERR0("Handling unknown body token: `" << token << '\'');
1182 // Returns the current font and depth as a message.
1183 docstring Text::currentState(Cursor & cur)
1185 BOOST_ASSERT(this == cur.text());
1186 Buffer & buf = cur.buffer();
1187 Paragraph const & par = cur.paragraph();
1188 odocstringstream os;
1190 if (buf.params().trackChanges)
1191 os << _("[Change Tracking] ");
1193 Change change = par.lookupChange(cur.pos());
1195 if (change.type != Change::UNCHANGED) {
1196 Author const & a = buf.params().authors().get(change.author);
1197 os << _("Change: ") << a.name();
1198 if (!a.email().empty())
1199 os << " (" << a.email() << ")";
1200 // FIXME ctime is english, we should translate that
1201 os << _(" at ") << ctime(&change.changetime);
1205 // I think we should only show changes from the default
1207 // No, from the document font (MV)
1208 Font font = cur.real_current_font;
1209 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1211 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1213 // The paragraph depth
1214 int depth = cur.paragraph().getDepth();
1216 os << bformat(_(", Depth: %1$d"), depth);
1218 // The paragraph spacing, but only if different from
1220 Spacing const & spacing = par.params().spacing();
1221 if (!spacing.isDefault()) {
1222 os << _(", Spacing: ");
1223 switch (spacing.getSpace()) {
1224 case Spacing::Single:
1227 case Spacing::Onehalf:
1230 case Spacing::Double:
1233 case Spacing::Other:
1234 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1236 case Spacing::Default:
1237 // should never happen, do nothing
1242 #ifdef DEVEL_VERSION
1243 os << _(", Inset: ") << &cur.inset();
1244 os << _(", Paragraph: ") << cur.pit();
1245 os << _(", Id: ") << par.id();
1246 os << _(", Position: ") << cur.pos();
1247 // FIXME: Why is the check for par.size() needed?
1248 // We are called with cur.pos() == par.size() quite often.
1249 if (!par.empty() && cur.pos() < par.size()) {
1250 // Force output of code point, not character
1251 size_t const c = par.getChar(cur.pos());
1252 os << _(", Char: 0x") << std::hex << c;
1254 os << _(", Boundary: ") << cur.boundary();
1255 // Row & row = cur.textRow();
1256 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1262 docstring Text::getPossibleLabel(Cursor & cur) const
1264 pit_type pit = cur.pit();
1266 LayoutPtr layout = pars_[pit].layout();
1269 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1271 // the return string of math matrices might contain linebreaks
1272 par_text = subst(par_text, '\n', '-');
1273 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1274 if (par_text.empty())
1277 par_text = split(par_text, head, ' ');
1278 // Is it legal to use spaces in labels ?
1284 // No need for a prefix if the user said so.
1285 if (lyxrc.label_init_length <= 0)
1288 // Will contain the label type.
1291 // For section, subsection, etc...
1292 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1293 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1294 if (layout2->latextype != LATEX_PARAGRAPH) {
1299 if (layout->latextype != LATEX_PARAGRAPH)
1300 name = from_ascii(layout->latexname());
1302 // for captions, we just take the caption type
1303 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1305 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1307 // If none of the above worked, we'll see if we're inside various
1308 // types of insets and take our abbreviation from them.
1310 InsetCode const codes[] = {
1315 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1316 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1318 name = float_inset->name();
1324 // Create a correct prefix for prettyref
1325 if (name == "theorem")
1326 name = from_ascii("thm");
1327 else if (name == "Foot")
1328 name = from_ascii("fn");
1329 else if (name == "listing")
1330 name = from_ascii("lst");
1333 text = name.substr(0, 3) + ':' + text;
1339 void Text::charsTranspose(Cursor & cur)
1341 BOOST_ASSERT(this == cur.text());
1343 pos_type pos = cur.pos();
1345 // If cursor is at beginning or end of paragraph, do nothing.
1346 if (pos == cur.lastpos() || pos == 0)
1349 Paragraph & par = cur.paragraph();
1351 // Get the positions of the characters to be transposed.
1352 pos_type pos1 = pos - 1;
1353 pos_type pos2 = pos;
1355 // In change tracking mode, ignore deleted characters.
1356 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1358 if (pos2 == cur.lastpos())
1361 while (pos1 >= 0 && par.isDeleted(pos1))
1366 // Don't do anything if one of the "characters" is not regular text.
1367 if (par.isInset(pos1) || par.isInset(pos2))
1370 // Store the characters to be transposed (including font information).
1371 char_type char1 = par.getChar(pos1);
1373 par.getFontSettings(cur.buffer().params(), pos1);
1375 char_type char2 = par.getChar(pos2);
1377 par.getFontSettings(cur.buffer().params(), pos2);
1379 // And finally, we are ready to perform the transposition.
1380 // Track the changes if Change Tracking is enabled.
1381 bool const trackChanges = cur.buffer().params().trackChanges;
1385 par.eraseChar(pos2, trackChanges);
1386 par.eraseChar(pos1, trackChanges);
1387 par.insertChar(pos1, char2, font2, trackChanges);
1388 par.insertChar(pos2, char1, font1, trackChanges);
1390 checkBufferStructure(cur.buffer(), cur);
1392 // After the transposition, move cursor to after the transposition.
1393 setCursor(cur, cur.pit(), pos2);