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"
29 #include "ParIterator.h"
30 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
37 #include "FontIterator.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #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] != '\\') {
106 string::const_iterator cit = token.begin();
107 for (; cit != token.end(); ++cit)
108 par.insertChar(par.size(), (*cit), font, change);
110 docstring dstr = lex.getDocString();
111 docstring::const_iterator cit = dstr.begin();
112 docstring::const_iterator cend = dstr.end();
113 for (; cit != cend; ++cit)
114 par.insertChar(par.size(), *cit, font, change);
116 } else if (token == "\\begin_layout") {
118 docstring layoutname = lex.getDocString();
120 font = Font(Font::ALL_INHERIT, bp.language);
121 change = Change(Change::UNCHANGED);
123 TextClass const & tclass = bp.getTextClass();
125 if (layoutname.empty()) {
126 layoutname = tclass.defaultLayoutName();
129 bool hasLayout = tclass.hasLayout(layoutname);
132 errorList.push_back(ErrorItem(_("Unknown layout"),
133 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
134 layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
135 layoutname = tclass.defaultLayoutName();
138 par.layout(bp.getTextClass()[layoutname]);
140 // Test whether the layout is obsolete.
141 LayoutPtr const & layout = par.layout();
142 if (!layout->obsoleted_by().empty())
143 par.layout(bp.getTextClass()[layout->obsoleted_by()]);
145 par.params().read(lex);
147 } else if (token == "\\end_layout") {
148 lyxerr << BOOST_CURRENT_FUNCTION
149 << ": Solitary \\end_layout in line "
150 << lex.getLineNo() << "\n"
151 << "Missing \\begin_layout?.\n";
152 } else if (token == "\\end_inset") {
153 lyxerr << BOOST_CURRENT_FUNCTION
154 << ": Solitary \\end_inset in line "
155 << lex.getLineNo() << "\n"
156 << "Missing \\begin_inset?.\n";
157 } else if (token == "\\begin_inset") {
158 Inset * inset = readInset(lex, buf);
160 par.insertInset(par.size(), inset, font, change);
163 docstring line = lex.getDocString();
164 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
165 par.id(), 0, par.size()));
167 } else if (token == "\\family") {
169 font.setLyXFamily(lex.getString());
170 } else if (token == "\\series") {
172 font.setLyXSeries(lex.getString());
173 } else if (token == "\\shape") {
175 font.setLyXShape(lex.getString());
176 } else if (token == "\\size") {
178 font.setLyXSize(lex.getString());
179 } else if (token == "\\lang") {
181 string const tok = lex.getString();
182 Language const * lang = languages.getLanguage(tok);
184 font.setLanguage(lang);
186 font.setLanguage(bp.language);
187 lex.printError("Unknown language `$$Token'");
189 } else if (token == "\\numeric") {
191 font.setNumber(font.setLyXMisc(lex.getString()));
192 } else if (token == "\\emph") {
194 font.setEmph(font.setLyXMisc(lex.getString()));
195 } else if (token == "\\bar") {
197 string const tok = lex.getString();
200 font.setUnderbar(Font::ON);
201 else if (tok == "no")
202 font.setUnderbar(Font::OFF);
203 else if (tok == "default")
204 font.setUnderbar(Font::INHERIT);
206 lex.printError("Unknown bar font flag "
208 } else if (token == "\\noun") {
210 font.setNoun(font.setLyXMisc(lex.getString()));
211 } else if (token == "\\color") {
213 font.setLyXColor(lex.getString());
214 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
216 // Insets don't make sense in a free-spacing context! ---Kayvan
217 if (par.isFreeSpacing()) {
218 if (token == "\\InsetSpace")
219 par.insertChar(par.size(), ' ', font, change);
220 else if (lex.isOK()) {
222 string const next_token = lex.getString();
223 if (next_token == "\\-")
224 par.insertChar(par.size(), '-', font, change);
226 lex.printError("Token `$$Token' "
228 "paragraph layout!");
232 auto_ptr<Inset> inset;
233 if (token == "\\SpecialChar" )
234 inset.reset(new InsetSpecialChar);
236 inset.reset(new InsetSpace);
237 inset->read(buf, lex);
238 par.insertInset(par.size(), inset.release(),
241 } else if (token == "\\backslash") {
242 par.insertChar(par.size(), '\\', font, change);
243 } else if (token == "\\newline") {
244 auto_ptr<Inset> inset(new InsetNewline);
245 inset->read(buf, lex);
246 par.insertInset(par.size(), inset.release(), font, change);
247 } else if (token == "\\LyXTable") {
248 auto_ptr<Inset> inset(new InsetTabular(buf));
249 inset->read(buf, lex);
250 par.insertInset(par.size(), inset.release(), font, change);
251 } else if (token == "\\hfill") {
252 par.insertInset(par.size(), new InsetHFill, font, change);
253 } else if (token == "\\lyxline") {
254 par.insertInset(par.size(), new InsetLine, font, change);
255 } else if (token == "\\newpage") {
256 par.insertInset(par.size(), new InsetPagebreak, font, change);
257 } else if (token == "\\clearpage") {
258 par.insertInset(par.size(), new InsetClearPage, font, change);
259 } else if (token == "\\cleardoublepage") {
260 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
261 } else if (token == "\\change_unchanged") {
262 change = Change(Change::UNCHANGED);
263 } else if (token == "\\change_inserted") {
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 insertion: %1$d\n"), aid),
272 par.id(), 0, par.size()));
273 change = Change(Change::UNCHANGED);
275 change = Change(Change::INSERTED, bp.author_map[aid], ct);
276 } else if (token == "\\change_deleted") {
278 std::istringstream is(lex.getString());
282 if (aid >= bp.author_map.size()) {
283 errorList.push_back(ErrorItem(_("Change tracking error"),
284 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
285 par.id(), 0, par.size()));
286 change = Change(Change::UNCHANGED);
288 change = Change(Change::DELETED, bp.author_map[aid], ct);
291 errorList.push_back(ErrorItem(_("Unknown token"),
292 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
294 par.id(), 0, par.size()));
299 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
300 ErrorList & errorList)
303 string token = lex.getString();
305 Change change(Change::UNCHANGED);
308 readParToken(buf, par, lex, token, font, change, errorList);
311 token = lex.getString();
316 if (token == "\\end_layout") {
317 //Ok, paragraph finished
321 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
322 << token << '\'' << endl;
323 if (token == "\\begin_layout" || token == "\\end_document"
324 || token == "\\end_inset" || token == "\\begin_deeper"
325 || token == "\\end_deeper") {
326 lex.pushToken(token);
327 lyxerr << "Paragraph ended in line "
328 << lex.getLineNo() << "\n"
329 << "Missing \\end_layout.\n";
333 // Final change goes to paragraph break:
334 par.setChange(par.size(), change);
336 // Initialize begin_of_body_ on load; redoParagraph maintains
337 par.setBeginOfBody();
344 bool Text::empty() const
346 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
347 // FIXME: Should we consider the labeled type as empty too?
348 && pars_[0].layout()->labeltype == LABEL_NO_LABEL);
352 double Text::spacing(Buffer const & buffer,
353 Paragraph const & par) const
355 if (par.params().spacing().isDefault())
356 return buffer.params().spacing().getValue();
357 return par.params().spacing().getValue();
361 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
363 BOOST_ASSERT(this == cur.text());
365 Paragraph & cpar = cur.paragraph();
366 pit_type cpit = cur.pit();
368 TextClass const & tclass = cur.buffer().params().getTextClass();
369 LayoutPtr const & layout = cpar.layout();
371 // this is only allowed, if the current paragraph is not empty
372 // or caption and if it has not the keepempty flag active
373 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
374 layout->labeltype != LABEL_SENSITIVE)
377 // a layout change may affect also the following paragraph
378 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
380 // Always break behind a space
381 // It is better to erase the space (Dekel)
382 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
383 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
385 // What should the layout for the new paragraph be?
386 bool keep_layout = inverse_logic ?
387 !layout->isEnvironment()
388 : layout->isEnvironment();
390 // We need to remember this before we break the paragraph, because
391 // that invalidates the layout variable
392 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
394 // we need to set this before we insert the paragraph.
395 bool const isempty = cpar.allowEmpty() && cpar.empty();
397 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
398 cur.pos(), keep_layout);
400 // After this, neither paragraph contains any rows!
403 pit_type next_par = cpit + 1;
405 // well this is the caption hack since one caption is really enough
408 // set to standard-layout
409 pars_[cpit].applyLayout(tclass.defaultLayout());
411 // set to standard-layout
412 pars_[next_par].applyLayout(tclass.defaultLayout());
415 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
416 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
417 break; // the character couldn't be deleted physically due to change tracking
420 updateLabels(cur.buffer());
422 // A singlePar update is not enough in this case.
423 cur.updateFlags(Update::Force);
425 // This check is necessary. Otherwise the new empty paragraph will
426 // be deleted automatically. And it is more friendly for the user!
427 if (cur.pos() != 0 || isempty)
428 setCursor(cur, cur.pit() + 1, 0);
430 setCursor(cur, cur.pit(), 0);
434 // insert a character, moves all the following breaks in the
435 // same Paragraph one to the right and make a rebreak
436 void Text::insertChar(Cursor & cur, char_type c)
438 BOOST_ASSERT(this == cur.text());
439 BOOST_ASSERT(c != Paragraph::META_INSET);
441 recordUndo(cur, Undo::INSERT);
443 TextMetrics const & tm = cur.bv().textMetrics(this);
444 Buffer const & buffer = cur.buffer();
445 Paragraph & par = cur.paragraph();
446 // try to remove this
447 pit_type const pit = cur.pit();
449 bool const freeSpacing = par.layout()->free_spacing ||
452 if (lyxrc.auto_number) {
453 static docstring const number_operators = from_ascii("+-/*");
454 static docstring const number_unary_operators = from_ascii("+-");
455 static docstring const number_seperators = from_ascii(".,:");
457 if (cur.current_font.number() == Font::ON) {
458 if (!isDigit(c) && !contains(number_operators, c) &&
459 !(contains(number_seperators, c) &&
461 cur.pos() != cur.lastpos() &&
462 tm.getDisplayFont(pit, cur.pos()).number() == Font::ON &&
463 tm.getDisplayFont(pit, cur.pos() - 1).number() == Font::ON)
465 number(cur); // Set current_font.number to OFF
466 } else if (isDigit(c) &&
467 cur.real_current_font.isVisibleRightToLeft()) {
468 number(cur); // Set current_font.number to ON
470 if (cur.pos() != 0) {
471 char_type const c = par.getChar(cur.pos() - 1);
472 if (contains(number_unary_operators, c) &&
474 || par.isSeparator(cur.pos() - 2)
475 || par.isNewline(cur.pos() - 2))
477 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
479 } else if (contains(number_seperators, c)
481 && tm.getDisplayFont(pit, cur.pos() - 2).number() == Font::ON) {
482 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
489 // In Bidi text, we want spaces to be treated in a special way: spaces
490 // which are between words in different languages should get the
491 // paragraph's language; otherwise, spaces should keep the language
492 // they were originally typed in. This is only in effect while typing;
493 // after the text is already typed in, the user can always go back and
494 // explicitly set the language of a space as desired. But 99.9% of the
495 // time, what we're doing here is what the user actually meant.
497 // The following cases are the ones in which the language of the space
498 // should be changed to match that of the containing paragraph. In the
499 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
500 // represents a space, pipe (|) represents the cursor position (so the
501 // character before it is the one just typed in). The different cases
502 // are depicted logically (not visually), from left to right:
507 // Theoretically, there are other situations that we should, perhaps, deal
508 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
509 // point (to understand why, just try to create this situation...).
511 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
512 // get font in front and behind the space in question. But do NOT
513 // use getFont(cur.pos()) because the character c is not inserted yet
514 Font const & pre_space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 2);
515 Font const & post_space_font = cur.real_current_font;
516 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
517 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
519 if (pre_space_rtl != post_space_rtl) {
520 // Set the space's language to match the language of the
521 // adjacent character whose direction is the paragraph's
522 // direction; don't touch other properties of the font
523 Language const * lang =
524 (pre_space_rtl == par.isRTL(buffer.params())) ?
525 pre_space_font.language() : post_space_font.language();
527 Font space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 1);
528 space_font.setLanguage(lang);
529 par.setFont(cur.pos() - 1, space_font);
533 // Next check, if there will be two blanks together or a blank at
534 // the beginning of a paragraph.
535 // I decided to handle blanks like normal characters, the main
536 // difference are the special checks when calculating the row.fill
537 // (blank does not count at the end of a row) and the check here
539 // When the free-spacing option is set for the current layout,
540 // disable the double-space checking
541 if (!freeSpacing && isLineSeparatorChar(c)) {
542 if (cur.pos() == 0) {
543 static bool sent_space_message = false;
544 if (!sent_space_message) {
545 cur.message(_("You cannot insert a space at the "
546 "beginning of a paragraph. Please read the Tutorial."));
547 sent_space_message = true;
551 BOOST_ASSERT(cur.pos() > 0);
552 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
553 && !par.isDeleted(cur.pos() - 1)) {
554 static bool sent_space_message = false;
555 if (!sent_space_message) {
556 cur.message(_("You cannot type two spaces this way. "
557 "Please read the Tutorial."));
558 sent_space_message = true;
564 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
565 checkBufferStructure(cur.buffer(), cur);
567 // cur.updateFlags(Update::Force);
568 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
573 void Text::charInserted()
575 // Here we call finishUndo for every 20 characters inserted.
576 // This is from my experience how emacs does it. (Lgb)
577 static unsigned int counter;
587 // the cursor set functions have a special mechanism. When they
588 // realize, that you left an empty paragraph, they will delete it.
590 bool Text::cursorRightOneWord(Cursor & cur)
592 BOOST_ASSERT(this == cur.text());
596 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
600 // Advance through word.
601 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
603 // Skip through trailing nonword stuff.
604 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
607 return setCursor(cur, old.pit(), old.pos());
611 bool Text::cursorLeftOneWord(Cursor & cur)
613 BOOST_ASSERT(this == cur.text());
617 if (old.pos() == 0 && old.pit() != 0) {
619 old.pos() = old.lastpos();
621 // Skip through initial nonword stuff.
622 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
624 // Advance through word.
625 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
628 return setCursor(cur, old.pit(), old.pos());
632 void Text::selectWord(Cursor & cur, word_location loc)
634 BOOST_ASSERT(this == cur.text());
635 CursorSlice from = cur.top();
636 CursorSlice to = cur.top();
637 getWord(from, to, loc);
638 if (cur.top() != from)
639 setCursor(cur, from.pit(), from.pos());
643 setCursor(cur, to.pit(), to.pos());
648 // Select the word currently under the cursor when no
649 // selection is currently set
650 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
652 BOOST_ASSERT(this == cur.text());
655 selectWord(cur, loc);
656 return cur.selection();
660 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
662 BOOST_ASSERT(this == cur.text());
664 if (!cur.selection())
667 recordUndoSelection(cur, Undo::ATOMIC);
669 pit_type begPit = cur.selectionBegin().pit();
670 pit_type endPit = cur.selectionEnd().pit();
672 pos_type begPos = cur.selectionBegin().pos();
673 pos_type endPos = cur.selectionEnd().pos();
675 // keep selection info, because endPos becomes invalid after the first loop
676 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
678 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
680 for (pit_type pit = begPit; pit <= endPit; ++pit) {
681 pos_type parSize = pars_[pit].size();
683 // ignore empty paragraphs; otherwise, an assertion will fail for
684 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
688 // do not consider first paragraph if the cursor starts at pos size()
689 if (pit == begPit && begPos == parSize)
692 // do not consider last paragraph if the cursor ends at pos 0
693 if (pit == endPit && endPos == 0)
694 break; // last iteration anyway
696 pos_type left = (pit == begPit ? begPos : 0);
697 pos_type right = (pit == endPit ? endPos : parSize);
700 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
702 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
706 // next, accept/reject imaginary end-of-par characters
708 for (pit_type pit = begPit; pit <= endPit; ++pit) {
709 pos_type pos = pars_[pit].size();
711 // skip if the selection ends before the end-of-par
712 if (pit == endPit && endsBeforeEndOfPar)
713 break; // last iteration anyway
715 // skip if this is not the last paragraph of the document
716 // note: the user should be able to accept/reject the par break of the last par!
717 if (pit == endPit && pit + 1 != int(pars_.size()))
718 break; // last iteration anway
721 if (pars_[pit].isInserted(pos)) {
722 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
723 } else if (pars_[pit].isDeleted(pos)) {
724 if (pit + 1 == int(pars_.size())) {
725 // we cannot remove a par break at the end of the last paragraph;
726 // instead, we mark it unchanged
727 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
729 mergeParagraph(cur.buffer().params(), pars_, pit);
735 if (pars_[pit].isDeleted(pos)) {
736 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
737 } else if (pars_[pit].isInserted(pos)) {
738 if (pit + 1 == int(pars_.size())) {
739 // we mark the par break at the end of the last paragraph unchanged
740 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
742 mergeParagraph(cur.buffer().params(), pars_, pit);
750 // finally, invoke the DEPM
752 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
757 cur.clearSelection();
758 setCursorIntern(cur, begPit, begPos);
759 cur.updateFlags(Update::Force);
760 updateLabels(cur.buffer());
764 void Text::acceptChanges(BufferParams const & bparams)
766 lyx::acceptChanges(pars_, bparams);
767 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
771 void Text::rejectChanges(BufferParams const & bparams)
773 pit_type pars_size = static_cast<pit_type>(pars_.size());
775 // first, reject changes within each individual paragraph
776 // (do not consider end-of-par)
777 for (pit_type pit = 0; pit < pars_size; ++pit) {
778 if (!pars_[pit].empty()) // prevent assertion failure
779 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
782 // next, reject imaginary end-of-par characters
783 for (pit_type pit = 0; pit < pars_size; ++pit) {
784 pos_type pos = pars_[pit].size();
786 if (pars_[pit].isDeleted(pos)) {
787 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
788 } else if (pars_[pit].isInserted(pos)) {
789 if (pit == pars_size - 1) {
790 // we mark the par break at the end of the last
791 // paragraph unchanged
792 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
794 mergeParagraph(bparams, pars_, pit);
801 // finally, invoke the DEPM
802 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
806 void Text::deleteWordForward(Cursor & cur)
808 BOOST_ASSERT(this == cur.text());
809 if (cur.lastpos() == 0)
813 cur.selection() = true;
814 cursorRightOneWord(cur);
816 cutSelection(cur, true, false);
817 checkBufferStructure(cur.buffer(), cur);
822 void Text::deleteWordBackward(Cursor & cur)
824 BOOST_ASSERT(this == cur.text());
825 if (cur.lastpos() == 0)
829 cur.selection() = true;
830 cursorLeftOneWord(cur);
832 cutSelection(cur, true, false);
833 checkBufferStructure(cur.buffer(), cur);
838 // Kill to end of line.
839 void Text::changeCase(Cursor & cur, Text::TextCase action)
841 BOOST_ASSERT(this == cur.text());
845 if (cur.selection()) {
846 from = cur.selBegin();
850 getWord(from, to, PARTIAL_WORD);
851 cursorRightOneWord(cur);
854 recordUndoSelection(cur, Undo::ATOMIC);
856 pit_type begPit = from.pit();
857 pit_type endPit = to.pit();
859 pos_type begPos = from.pos();
860 pos_type endPos = to.pos();
862 bool const trackChanges = cur.buffer().params().trackChanges;
864 pos_type right = 0; // needed after the for loop
866 for (pit_type pit = begPit; pit <= endPit; ++pit) {
867 pos_type parSize = pars_[pit].size();
869 pos_type pos = (pit == begPit ? begPos : 0);
870 right = (pit == endPit ? endPos : parSize);
872 // process sequences of modified characters; in change
873 // tracking mode, this approach results in much better
874 // usability than changing case on a char-by-char basis
877 bool capitalize = true;
879 for (; pos < right; ++pos) {
880 char_type oldChar = pars_[pit].getChar(pos);
881 char_type newChar = oldChar;
883 // ignore insets and don't play with deleted text!
884 if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
887 newChar = lowercase(oldChar);
889 case text_capitalization:
891 newChar = uppercase(oldChar);
896 newChar = uppercase(oldChar);
901 if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
902 capitalize = true; // permit capitalization again
905 if (oldChar != newChar) {
909 if (oldChar == newChar || pos == right - 1) {
910 if (oldChar != newChar) {
911 pos++; // step behind the changing area
913 int erasePos = pos - changes.size();
914 for (size_t i = 0; i < changes.size(); i++) {
915 pars_[pit].insertChar(pos, changes[i],
916 pars_[pit].getFontSettings(cur.buffer().params(),
919 if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
922 ++right; // expand selection
930 // the selection may have changed due to logically-only deleted chars
931 setCursor(cur, begPit, begPos);
933 setCursor(cur, endPit, right);
936 checkBufferStructure(cur.buffer(), cur);
940 bool Text::handleBibitems(Cursor & cur)
942 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
944 // if a bibitem is deleted, merge with previous paragraph
945 // if this is a bibliography item as well
946 if (cur.pos() == 0) {
947 BufferParams const & bufparams = cur.buffer().params();
948 Paragraph const & par = cur.paragraph();
949 Cursor prevcur = cur;
952 prevcur.pos() = prevcur.lastpos();
954 Paragraph const & prevpar = prevcur.paragraph();
955 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
956 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
957 mergeParagraph(bufparams, cur.text()->paragraphs(),
959 updateLabels(cur.buffer());
960 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
961 cur.updateFlags(Update::Force);
962 // if not, reset the paragraph to default
964 cur.paragraph().layout(
965 bufparams.getTextClass().defaultLayout());
972 bool Text::erase(Cursor & cur)
974 BOOST_ASSERT(this == cur.text());
975 bool needsUpdate = false;
976 Paragraph & par = cur.paragraph();
978 if (cur.pos() != cur.lastpos()) {
979 // this is the code for a normal delete, not pasting
981 recordUndo(cur, Undo::DELETE);
982 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
983 // the character has been logically deleted only => skip it
984 cur.top().forwardPos();
986 checkBufferStructure(cur.buffer(), cur);
989 if (cur.pit() == cur.lastpit())
990 return dissolveInset(cur);
992 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
993 par.setChange(cur.pos(), Change(Change::DELETED));
997 setCursorIntern(cur, cur.pit() + 1, 0);
998 needsUpdate = backspacePos0(cur);
1002 needsUpdate |= handleBibitems(cur);
1005 // Make sure the cursor is correct. Is this really needed?
1006 // No, not really... at least not here!
1007 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1008 checkBufferStructure(cur.buffer(), cur);
1015 bool Text::backspacePos0(Cursor & cur)
1017 BOOST_ASSERT(this == cur.text());
1021 bool needsUpdate = false;
1023 BufferParams const & bufparams = cur.buffer().params();
1024 TextClass const & tclass = bufparams.getTextClass();
1025 ParagraphList & plist = cur.text()->paragraphs();
1026 Paragraph const & par = cur.paragraph();
1027 Cursor prevcur = cur;
1029 prevcur.pos() = prevcur.lastpos();
1030 Paragraph const & prevpar = prevcur.paragraph();
1032 // is it an empty paragraph?
1033 if (cur.lastpos() == 0
1034 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1035 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1036 plist.erase(boost::next(plist.begin(), cur.pit()));
1039 // is previous par empty?
1040 else if (prevcur.lastpos() == 0
1041 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1042 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1043 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1046 // Pasting is not allowed, if the paragraphs have different
1047 // layouts. I think it is a real bug of all other
1048 // word processors to allow it. It confuses the user.
1049 // Correction: Pasting is always allowed with standard-layout
1050 else if (par.layout() == prevpar.layout()
1051 || par.layout() == tclass.defaultLayout()) {
1052 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1053 mergeParagraph(bufparams, plist, prevcur.pit());
1058 updateLabels(cur.buffer());
1059 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1066 bool Text::backspace(Cursor & cur)
1068 BOOST_ASSERT(this == cur.text());
1069 bool needsUpdate = false;
1070 if (cur.pos() == 0) {
1072 return dissolveInset(cur);
1074 Paragraph & prev_par = pars_[cur.pit() - 1];
1076 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1077 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1078 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1081 // The cursor is at the beginning of a paragraph, so
1082 // the backspace will collapse two paragraphs into one.
1083 needsUpdate = backspacePos0(cur);
1086 // this is the code for a normal backspace, not pasting
1088 recordUndo(cur, Undo::DELETE);
1089 // We used to do cursorLeftIntern() here, but it is
1090 // not a good idea since it triggers the auto-delete
1091 // mechanism. So we do a cursorLeftIntern()-lite,
1092 // without the dreaded mechanism. (JMarc)
1093 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1094 false, cur.boundary());
1095 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1096 checkBufferStructure(cur.buffer(), cur);
1099 if (cur.pos() == cur.lastpos())
1100 cur.setCurrentFont();
1102 needsUpdate |= handleBibitems(cur);
1104 // A singlePar update is not enough in this case.
1105 // cur.updateFlags(Update::Force);
1106 setCursor(cur.top(), cur.pit(), cur.pos());
1112 bool Text::dissolveInset(Cursor & cur) {
1113 BOOST_ASSERT(this == cur.text());
1115 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1118 recordUndoInset(cur);
1119 cur.selHandle(false);
1121 pos_type spos = cur.pos();
1122 pit_type spit = cur.pit();
1123 ParagraphList plist;
1124 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1125 plist = paragraphs();
1127 // store cursor offset
1131 Buffer & b = cur.buffer();
1132 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1133 if (!plist.empty()) {
1134 // ERT paragraphs have the Language latex_language.
1135 // This is invalid outside of ERT, so we need to
1136 // change it to the buffer language.
1137 ParagraphList::iterator it = plist.begin();
1138 ParagraphList::iterator it_end = plist.end();
1139 for (; it != it_end; it++) {
1140 it->changeLanguage(b.params(), latex_language,
1144 pasteParagraphList(cur, plist, b.params().getTextClassPtr(),
1145 b.errorList("Paste"));
1147 cur.pit() = std::min(cur.lastpit(), spit);
1148 cur.pos() = std::min(cur.lastpos(), spos);
1150 cur.clearSelection();
1156 void Text::getWord(CursorSlice & from, CursorSlice & to,
1157 word_location const loc)
1159 Paragraph const & from_par = pars_[from.pit()];
1161 case WHOLE_WORD_STRICT:
1162 if (from.pos() == 0 || from.pos() == from_par.size()
1163 || !from_par.isLetter(from.pos())
1164 || !from_par.isLetter(from.pos() - 1)) {
1168 // no break here, we go to the next
1171 // If we are already at the beginning of a word, do nothing
1172 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1174 // no break here, we go to the next
1177 // always move the cursor to the beginning of previous word
1178 while (from.pos() && from_par.isLetter(from.pos() - 1))
1182 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1186 // no need to move the 'from' cursor
1190 Paragraph & to_par = pars_[to.pit()];
1191 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1196 void Text::write(Buffer const & buf, std::ostream & os) const
1198 ParagraphList::const_iterator pit = paragraphs().begin();
1199 ParagraphList::const_iterator end = paragraphs().end();
1201 for (; pit != end; ++pit)
1202 pit->write(buf, os, buf.params(), dth);
1204 // Close begin_deeper
1205 for(; dth > 0; --dth)
1206 os << "\n\\end_deeper";
1210 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1212 depth_type depth = 0;
1214 while (lex.isOK()) {
1216 string const token = lex.getString();
1221 if (token == "\\end_inset")
1224 if (token == "\\end_body")
1227 if (token == "\\begin_body")
1230 if (token == "\\end_document")
1233 if (token == "\\begin_layout") {
1234 lex.pushToken(token);
1237 par.params().depth(depth);
1238 par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1239 pars_.push_back(par);
1241 // FIXME: goddamn InsetTabular makes us pass a Buffer
1243 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1245 } else if (token == "\\begin_deeper") {
1247 } else if (token == "\\end_deeper") {
1249 lex.printError("\\end_deeper: " "depth is already null");
1254 lyxerr << "Handling unknown body token: `"
1255 << token << '\'' << endl;
1261 // Returns the current font and depth as a message.
1262 docstring Text::currentState(Cursor & cur)
1264 BOOST_ASSERT(this == cur.text());
1265 Buffer & buf = cur.buffer();
1266 Paragraph const & par = cur.paragraph();
1267 odocstringstream os;
1269 if (buf.params().trackChanges)
1270 os << _("[Change Tracking] ");
1272 Change change = par.lookupChange(cur.pos());
1274 if (change.type != Change::UNCHANGED) {
1275 Author const & a = buf.params().authors().get(change.author);
1276 os << _("Change: ") << a.name();
1277 if (!a.email().empty())
1278 os << " (" << a.email() << ")";
1279 // FIXME ctime is english, we should translate that
1280 os << _(" at ") << ctime(&change.changetime);
1284 // I think we should only show changes from the default
1286 // No, from the document font (MV)
1287 Font font = cur.real_current_font;
1288 font.reduce(buf.params().getFont());
1290 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1292 // The paragraph depth
1293 int depth = cur.paragraph().getDepth();
1295 os << bformat(_(", Depth: %1$d"), depth);
1297 // The paragraph spacing, but only if different from
1299 Spacing const & spacing = par.params().spacing();
1300 if (!spacing.isDefault()) {
1301 os << _(", Spacing: ");
1302 switch (spacing.getSpace()) {
1303 case Spacing::Single:
1306 case Spacing::Onehalf:
1309 case Spacing::Double:
1312 case Spacing::Other:
1313 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1315 case Spacing::Default:
1316 // should never happen, do nothing
1321 #ifdef DEVEL_VERSION
1322 os << _(", Inset: ") << &cur.inset();
1323 os << _(", Paragraph: ") << cur.pit();
1324 os << _(", Id: ") << par.id();
1325 os << _(", Position: ") << cur.pos();
1326 // FIXME: Why is the check for par.size() needed?
1327 // We are called with cur.pos() == par.size() quite often.
1328 if (!par.empty() && cur.pos() < par.size()) {
1329 // Force output of code point, not character
1330 size_t const c = par.getChar(cur.pos());
1331 os << _(", Char: 0x") << std::hex << c;
1333 os << _(", Boundary: ") << cur.boundary();
1334 // Row & row = cur.textRow();
1335 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1341 docstring Text::getPossibleLabel(Cursor & cur) const
1343 pit_type pit = cur.pit();
1345 LayoutPtr layout = pars_[pit].layout();
1348 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1349 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1350 if (par_text.empty())
1353 par_text = split(par_text, head, ' ');
1354 // Is it legal to use spaces in labels ?
1360 // No need for a prefix if the user said so.
1361 if (lyxrc.label_init_length <= 0)
1364 // Will contain the label type.
1367 // For section, subsection, etc...
1368 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1369 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1370 if (layout2->latextype != LATEX_PARAGRAPH) {
1375 if (layout->latextype != LATEX_PARAGRAPH)
1376 name = from_ascii(layout->latexname());
1378 // for captions, we just take the caption type
1379 Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1381 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1383 // If none of the above worked, we'll see if we're inside various
1384 // types of insets and take our abbreviation from them.
1386 Inset::Code const codes[] = {
1391 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1392 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1394 name = float_inset->name();
1400 // Create a correct prefix for prettyref
1401 if (name == "theorem")
1402 name = from_ascii("thm");
1403 else if (name == "Foot")
1404 name = from_ascii("fn");
1405 else if (name == "listing")
1406 name = from_ascii("lst");
1409 text = name.substr(0, 3) + ':' + text;
1415 void Text::charsTranspose(Cursor & cur)
1417 BOOST_ASSERT(this == cur.text());
1419 pos_type pos = cur.pos();
1421 // If cursor is at beginning or end of paragraph, do nothing.
1422 if (pos == cur.lastpos() || pos == 0)
1425 Paragraph & par = cur.paragraph();
1427 // Get the positions of the characters to be transposed.
1428 pos_type pos1 = pos - 1;
1429 pos_type pos2 = pos;
1431 // In change tracking mode, ignore deleted characters.
1432 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1434 if (pos2 == cur.lastpos())
1437 while (pos1 >= 0 && par.isDeleted(pos1))
1442 // Don't do anything if one of the "characters" is not regular text.
1443 if (par.isInset(pos1) || par.isInset(pos2))
1446 // Store the characters to be transposed (including font information).
1447 char_type char1 = par.getChar(pos1);
1449 par.getFontSettings(cur.buffer().params(), pos1);
1451 char_type char2 = par.getChar(pos2);
1453 par.getFontSettings(cur.buffer().params(), pos2);
1455 // And finally, we are ready to perform the transposition.
1456 // Track the changes if Change Tracking is enabled.
1457 bool const trackChanges = cur.buffer().params().trackChanges;
1461 par.eraseChar(pos2, trackChanges);
1462 par.eraseChar(pos1, trackChanges);
1463 par.insertChar(pos1, char2, font2, trackChanges);
1464 par.insertChar(pos2, char1, font1, trackChanges);
1466 checkBufferStructure(cur.buffer(), cur);
1468 // After the transposition, move cursor to after the transposition.
1469 setCursor(cur, cur.pit(), pos2);