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"
49 #include "WordLangTuple.h"
51 #include "frontends/FontMetrics.h"
52 #include "frontends/Painter.h"
54 #include "insets/InsetText.h"
55 #include "insets/InsetBibitem.h"
56 #include "insets/InsetCaption.h"
57 #include "insets/InsetHFill.h"
58 #include "insets/InsetLine.h"
59 #include "insets/InsetNewline.h"
60 #include "insets/InsetPagebreak.h"
61 #include "insets/InsetOptArg.h"
62 #include "insets/InsetSpace.h"
63 #include "insets/InsetSpecialChar.h"
64 #include "insets/InsetTabular.h"
66 #include "support/lstrings.h"
67 #include "support/textutils.h"
68 #include "support/convert.h"
70 #include <boost/current_function.hpp>
71 #include <boost/next_prior.hpp>
85 using support::bformat;
86 using support::contains;
87 using support::lowercase;
89 using support::uppercase;
91 using cap::cutSelection;
92 using cap::pasteParagraphList;
94 using frontend::FontMetrics;
98 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
99 string const & token, Font & font, Change & change, ErrorList & errorList)
101 BufferParams const & bp = buf.params();
103 if (token[0] != '\\') {
105 string::const_iterator cit = token.begin();
106 for (; cit != token.end(); ++cit)
107 par.insertChar(par.size(), (*cit), font, change);
109 docstring dstr = lex.getDocString();
110 docstring::const_iterator cit = dstr.begin();
111 docstring::const_iterator cend = dstr.end();
112 for (; cit != cend; ++cit)
113 par.insertChar(par.size(), *cit, font, change);
115 } else if (token == "\\begin_layout") {
117 docstring layoutname = lex.getDocString();
119 font = Font(Font::ALL_INHERIT, bp.language);
120 change = Change(Change::UNCHANGED);
122 TextClass const & tclass = bp.getTextClass();
124 if (layoutname.empty()) {
125 layoutname = tclass.defaultLayoutName();
128 bool hasLayout = tclass.hasLayout(layoutname);
131 errorList.push_back(ErrorItem(_("Unknown layout"),
132 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
133 layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
134 layoutname = tclass.defaultLayoutName();
137 par.layout(bp.getTextClass()[layoutname]);
139 // Test whether the layout is obsolete.
140 LayoutPtr const & layout = par.layout();
141 if (!layout->obsoleted_by().empty())
142 par.layout(bp.getTextClass()[layout->obsoleted_by()]);
144 par.params().read(lex);
146 } else if (token == "\\end_layout") {
147 lyxerr << BOOST_CURRENT_FUNCTION
148 << ": Solitary \\end_layout in line "
149 << lex.getLineNo() << "\n"
150 << "Missing \\begin_layout?.\n";
151 } else if (token == "\\end_inset") {
152 lyxerr << BOOST_CURRENT_FUNCTION
153 << ": Solitary \\end_inset in line "
154 << lex.getLineNo() << "\n"
155 << "Missing \\begin_inset?.\n";
156 } else if (token == "\\begin_inset") {
157 Inset * inset = readInset(lex, buf);
159 par.insertInset(par.size(), inset, font, change);
162 docstring line = lex.getDocString();
163 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
164 par.id(), 0, par.size()));
166 } else if (token == "\\family") {
168 font.setLyXFamily(lex.getString());
169 } else if (token == "\\series") {
171 font.setLyXSeries(lex.getString());
172 } else if (token == "\\shape") {
174 font.setLyXShape(lex.getString());
175 } else if (token == "\\size") {
177 font.setLyXSize(lex.getString());
178 } else if (token == "\\lang") {
180 string const tok = lex.getString();
181 Language const * lang = languages.getLanguage(tok);
183 font.setLanguage(lang);
185 font.setLanguage(bp.language);
186 lex.printError("Unknown language `$$Token'");
188 } else if (token == "\\numeric") {
190 font.setNumber(font.setLyXMisc(lex.getString()));
191 } else if (token == "\\emph") {
193 font.setEmph(font.setLyXMisc(lex.getString()));
194 } else if (token == "\\bar") {
196 string const tok = lex.getString();
199 font.setUnderbar(Font::ON);
200 else if (tok == "no")
201 font.setUnderbar(Font::OFF);
202 else if (tok == "default")
203 font.setUnderbar(Font::INHERIT);
205 lex.printError("Unknown bar font flag "
207 } else if (token == "\\noun") {
209 font.setNoun(font.setLyXMisc(lex.getString()));
210 } else if (token == "\\color") {
212 font.setLyXColor(lex.getString());
213 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
215 // Insets don't make sense in a free-spacing context! ---Kayvan
216 if (par.isFreeSpacing()) {
217 if (token == "\\InsetSpace")
218 par.insertChar(par.size(), ' ', font, change);
219 else if (lex.isOK()) {
221 string const next_token = lex.getString();
222 if (next_token == "\\-")
223 par.insertChar(par.size(), '-', font, change);
225 lex.printError("Token `$$Token' "
227 "paragraph layout!");
231 auto_ptr<Inset> inset;
232 if (token == "\\SpecialChar" )
233 inset.reset(new InsetSpecialChar);
235 inset.reset(new InsetSpace);
236 inset->read(buf, lex);
237 par.insertInset(par.size(), inset.release(),
240 } else if (token == "\\backslash") {
241 par.insertChar(par.size(), '\\', font, change);
242 } else if (token == "\\newline") {
243 auto_ptr<Inset> inset(new InsetNewline);
244 inset->read(buf, lex);
245 par.insertInset(par.size(), inset.release(), font, change);
246 } else if (token == "\\LyXTable") {
247 auto_ptr<Inset> inset(new InsetTabular(buf));
248 inset->read(buf, lex);
249 par.insertInset(par.size(), inset.release(), font, change);
250 } else if (token == "\\hfill") {
251 par.insertInset(par.size(), new InsetHFill, font, change);
252 } else if (token == "\\lyxline") {
253 par.insertInset(par.size(), new InsetLine, font, change);
254 } else if (token == "\\newpage") {
255 par.insertInset(par.size(), new InsetPagebreak, font, change);
256 } else if (token == "\\clearpage") {
257 par.insertInset(par.size(), new InsetClearPage, font, change);
258 } else if (token == "\\cleardoublepage") {
259 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
260 } else if (token == "\\change_unchanged") {
261 change = Change(Change::UNCHANGED);
262 } else if (token == "\\change_inserted") {
264 std::istringstream is(lex.getString());
268 if (aid >= bp.author_map.size()) {
269 errorList.push_back(ErrorItem(_("Change tracking error"),
270 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
271 par.id(), 0, par.size()));
272 change = Change(Change::UNCHANGED);
274 change = Change(Change::INSERTED, bp.author_map[aid], ct);
275 } else if (token == "\\change_deleted") {
277 std::istringstream is(lex.getString());
281 if (aid >= bp.author_map.size()) {
282 errorList.push_back(ErrorItem(_("Change tracking error"),
283 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
284 par.id(), 0, par.size()));
285 change = Change(Change::UNCHANGED);
287 change = Change(Change::DELETED, bp.author_map[aid], ct);
290 errorList.push_back(ErrorItem(_("Unknown token"),
291 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
293 par.id(), 0, par.size()));
298 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
299 ErrorList & errorList)
302 string token = lex.getString();
304 Change change(Change::UNCHANGED);
307 readParToken(buf, par, lex, token, font, change, errorList);
310 token = lex.getString();
315 if (token == "\\end_layout") {
316 //Ok, paragraph finished
320 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
321 << token << '\'' << endl;
322 if (token == "\\begin_layout" || token == "\\end_document"
323 || token == "\\end_inset" || token == "\\begin_deeper"
324 || token == "\\end_deeper") {
325 lex.pushToken(token);
326 lyxerr << "Paragraph ended in line "
327 << lex.getLineNo() << "\n"
328 << "Missing \\end_layout.\n";
332 // Final change goes to paragraph break:
333 par.setChange(par.size(), change);
335 // Initialize begin_of_body_ on load; redoParagraph maintains
336 par.setBeginOfBody();
343 bool Text::empty() const
345 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
346 // FIXME: Should we consider the labeled type as empty too?
347 && pars_[0].layout()->labeltype == LABEL_NO_LABEL);
351 double Text::spacing(Buffer const & buffer,
352 Paragraph const & par) const
354 if (par.params().spacing().isDefault())
355 return buffer.params().spacing().getValue();
356 return par.params().spacing().getValue();
360 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
362 BOOST_ASSERT(this == cur.text());
364 Paragraph & cpar = cur.paragraph();
365 pit_type cpit = cur.pit();
367 TextClass const & tclass = cur.buffer().params().getTextClass();
368 LayoutPtr const & layout = cpar.layout();
370 // this is only allowed, if the current paragraph is not empty
371 // or caption and if it has not the keepempty flag active
372 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
373 layout->labeltype != LABEL_SENSITIVE)
376 // a layout change may affect also the following paragraph
377 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
379 // Always break behind a space
380 // It is better to erase the space (Dekel)
381 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
382 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
384 // What should the layout for the new paragraph be?
385 bool keep_layout = inverse_logic ?
386 !layout->isEnvironment()
387 : layout->isEnvironment();
389 // We need to remember this before we break the paragraph, because
390 // that invalidates the layout variable
391 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
393 // we need to set this before we insert the paragraph.
394 bool const isempty = cpar.allowEmpty() && cpar.empty();
396 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
397 cur.pos(), keep_layout);
399 // After this, neither paragraph contains any rows!
402 pit_type next_par = cpit + 1;
404 // well this is the caption hack since one caption is really enough
407 // set to standard-layout
408 pars_[cpit].applyLayout(tclass.defaultLayout());
410 // set to standard-layout
411 pars_[next_par].applyLayout(tclass.defaultLayout());
414 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
415 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
416 break; // the character couldn't be deleted physically due to change tracking
419 updateLabels(cur.buffer());
421 // A singlePar update is not enough in this case.
422 cur.updateFlags(Update::Force);
424 // This check is necessary. Otherwise the new empty paragraph will
425 // be deleted automatically. And it is more friendly for the user!
426 if (cur.pos() != 0 || isempty)
427 setCursor(cur, cur.pit() + 1, 0);
429 setCursor(cur, cur.pit(), 0);
433 // insert a character, moves all the following breaks in the
434 // same Paragraph one to the right and make a rebreak
435 void Text::insertChar(Cursor & cur, char_type c)
437 BOOST_ASSERT(this == cur.text());
438 BOOST_ASSERT(c != Paragraph::META_INSET);
440 recordUndo(cur, Undo::INSERT);
442 TextMetrics const & tm = cur.bv().textMetrics(this);
443 Buffer const & buffer = cur.buffer();
444 Paragraph & par = cur.paragraph();
445 // try to remove this
446 pit_type const pit = cur.pit();
448 bool const freeSpacing = par.layout()->free_spacing ||
451 if (lyxrc.auto_number) {
452 static docstring const number_operators = from_ascii("+-/*");
453 static docstring const number_unary_operators = from_ascii("+-");
454 static docstring const number_seperators = from_ascii(".,:");
456 if (cur.current_font.number() == Font::ON) {
457 if (!isDigit(c) && !contains(number_operators, c) &&
458 !(contains(number_seperators, c) &&
460 cur.pos() != cur.lastpos() &&
461 tm.getDisplayFont(pit, cur.pos()).number() == Font::ON &&
462 tm.getDisplayFont(pit, cur.pos() - 1).number() == Font::ON)
464 number(cur); // Set current_font.number to OFF
465 } else if (isDigit(c) &&
466 cur.real_current_font.isVisibleRightToLeft()) {
467 number(cur); // Set current_font.number to ON
469 if (cur.pos() != 0) {
470 char_type const c = par.getChar(cur.pos() - 1);
471 if (contains(number_unary_operators, c) &&
473 || par.isSeparator(cur.pos() - 2)
474 || par.isNewline(cur.pos() - 2))
476 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
478 } else if (contains(number_seperators, c)
480 && tm.getDisplayFont(pit, cur.pos() - 2).number() == Font::ON) {
481 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
488 // In Bidi text, we want spaces to be treated in a special way: spaces
489 // which are between words in different languages should get the
490 // paragraph's language; otherwise, spaces should keep the language
491 // they were originally typed in. This is only in effect while typing;
492 // after the text is already typed in, the user can always go back and
493 // explicitly set the language of a space as desired. But 99.9% of the
494 // time, what we're doing here is what the user actually meant.
496 // The following cases are the ones in which the language of the space
497 // should be changed to match that of the containing paragraph. In the
498 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
499 // represents a space, pipe (|) represents the cursor position (so the
500 // character before it is the one just typed in). The different cases
501 // are depicted logically (not visually), from left to right:
506 // Theoretically, there are other situations that we should, perhaps, deal
507 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
508 // point (to understand why, just try to create this situation...).
510 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
511 // get font in front and behind the space in question. But do NOT
512 // use getFont(cur.pos()) because the character c is not inserted yet
513 Font const & pre_space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 2);
514 Font const & post_space_font = cur.real_current_font;
515 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
516 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
518 if (pre_space_rtl != post_space_rtl) {
519 // Set the space's language to match the language of the
520 // adjacent character whose direction is the paragraph's
521 // direction; don't touch other properties of the font
522 Language const * lang =
523 (pre_space_rtl == par.isRTL(buffer.params())) ?
524 pre_space_font.language() : post_space_font.language();
526 Font space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 1);
527 space_font.setLanguage(lang);
528 par.setFont(cur.pos() - 1, space_font);
532 // Next check, if there will be two blanks together or a blank at
533 // the beginning of a paragraph.
534 // I decided to handle blanks like normal characters, the main
535 // difference are the special checks when calculating the row.fill
536 // (blank does not count at the end of a row) and the check here
538 // When the free-spacing option is set for the current layout,
539 // disable the double-space checking
540 if (!freeSpacing && isLineSeparatorChar(c)) {
541 if (cur.pos() == 0) {
542 static bool sent_space_message = false;
543 if (!sent_space_message) {
544 cur.message(_("You cannot insert a space at the "
545 "beginning of a paragraph. Please read the Tutorial."));
546 sent_space_message = true;
550 BOOST_ASSERT(cur.pos() > 0);
551 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
552 && !par.isDeleted(cur.pos() - 1)) {
553 static bool sent_space_message = false;
554 if (!sent_space_message) {
555 cur.message(_("You cannot type two spaces this way. "
556 "Please read the Tutorial."));
557 sent_space_message = true;
563 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
564 checkBufferStructure(cur.buffer(), cur);
566 // cur.updateFlags(Update::Force);
567 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
572 void Text::charInserted()
574 // Here we call finishUndo for every 20 characters inserted.
575 // This is from my experience how emacs does it. (Lgb)
576 static unsigned int counter;
586 // the cursor set functions have a special mechanism. When they
587 // realize, that you left an empty paragraph, they will delete it.
589 bool Text::cursorRightOneWord(Cursor & cur)
591 BOOST_ASSERT(this == cur.text());
595 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
599 // Advance through word.
600 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
602 // Skip through trailing nonword stuff.
603 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
606 return setCursor(cur, old.pit(), old.pos());
610 bool Text::cursorLeftOneWord(Cursor & cur)
612 BOOST_ASSERT(this == cur.text());
616 if (old.pos() == 0 && old.pit() != 0) {
618 old.pos() = old.lastpos();
620 // Skip through initial nonword stuff.
621 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
623 // Advance through word.
624 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
627 return setCursor(cur, old.pit(), old.pos());
631 void Text::selectWord(Cursor & cur, word_location loc)
633 BOOST_ASSERT(this == cur.text());
634 CursorSlice from = cur.top();
635 CursorSlice to = cur.top();
636 getWord(from, to, loc);
637 if (cur.top() != from)
638 setCursor(cur, from.pit(), from.pos());
642 setCursor(cur, to.pit(), to.pos());
647 // Select the word currently under the cursor when no
648 // selection is currently set
649 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
651 BOOST_ASSERT(this == cur.text());
654 selectWord(cur, loc);
655 return cur.selection();
659 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
661 BOOST_ASSERT(this == cur.text());
663 if (!cur.selection())
666 recordUndoSelection(cur, Undo::ATOMIC);
668 pit_type begPit = cur.selectionBegin().pit();
669 pit_type endPit = cur.selectionEnd().pit();
671 pos_type begPos = cur.selectionBegin().pos();
672 pos_type endPos = cur.selectionEnd().pos();
674 // keep selection info, because endPos becomes invalid after the first loop
675 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
677 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
679 for (pit_type pit = begPit; pit <= endPit; ++pit) {
680 pos_type parSize = pars_[pit].size();
682 // ignore empty paragraphs; otherwise, an assertion will fail for
683 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
687 // do not consider first paragraph if the cursor starts at pos size()
688 if (pit == begPit && begPos == parSize)
691 // do not consider last paragraph if the cursor ends at pos 0
692 if (pit == endPit && endPos == 0)
693 break; // last iteration anyway
695 pos_type left = (pit == begPit ? begPos : 0);
696 pos_type right = (pit == endPit ? endPos : parSize);
699 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
701 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
705 // next, accept/reject imaginary end-of-par characters
707 for (pit_type pit = begPit; pit <= endPit; ++pit) {
708 pos_type pos = pars_[pit].size();
710 // skip if the selection ends before the end-of-par
711 if (pit == endPit && endsBeforeEndOfPar)
712 break; // last iteration anyway
714 // skip if this is not the last paragraph of the document
715 // note: the user should be able to accept/reject the par break of the last par!
716 if (pit == endPit && pit + 1 != int(pars_.size()))
717 break; // last iteration anway
720 if (pars_[pit].isInserted(pos)) {
721 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
722 } else if (pars_[pit].isDeleted(pos)) {
723 if (pit + 1 == int(pars_.size())) {
724 // we cannot remove a par break at the end of the last paragraph;
725 // instead, we mark it unchanged
726 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
728 mergeParagraph(cur.buffer().params(), pars_, pit);
734 if (pars_[pit].isDeleted(pos)) {
735 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
736 } else if (pars_[pit].isInserted(pos)) {
737 if (pit + 1 == int(pars_.size())) {
738 // we mark the par break at the end of the last paragraph unchanged
739 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
741 mergeParagraph(cur.buffer().params(), pars_, pit);
749 // finally, invoke the DEPM
751 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
756 cur.clearSelection();
757 setCursorIntern(cur, begPit, begPos);
758 cur.updateFlags(Update::Force);
759 updateLabels(cur.buffer());
763 void Text::acceptChanges(BufferParams const & bparams)
765 lyx::acceptChanges(pars_, bparams);
766 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
770 void Text::rejectChanges(BufferParams const & bparams)
772 pit_type pars_size = static_cast<pit_type>(pars_.size());
774 // first, reject changes within each individual paragraph
775 // (do not consider end-of-par)
776 for (pit_type pit = 0; pit < pars_size; ++pit) {
777 if (!pars_[pit].empty()) // prevent assertion failure
778 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
781 // next, reject imaginary end-of-par characters
782 for (pit_type pit = 0; pit < pars_size; ++pit) {
783 pos_type pos = pars_[pit].size();
785 if (pars_[pit].isDeleted(pos)) {
786 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
787 } else if (pars_[pit].isInserted(pos)) {
788 if (pit == pars_size - 1) {
789 // we mark the par break at the end of the last
790 // paragraph unchanged
791 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
793 mergeParagraph(bparams, pars_, pit);
800 // finally, invoke the DEPM
801 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
805 void Text::deleteWordForward(Cursor & cur)
807 BOOST_ASSERT(this == cur.text());
808 if (cur.lastpos() == 0)
812 cur.selection() = true;
813 cursorRightOneWord(cur);
815 cutSelection(cur, true, false);
816 checkBufferStructure(cur.buffer(), cur);
821 void Text::deleteWordBackward(Cursor & cur)
823 BOOST_ASSERT(this == cur.text());
824 if (cur.lastpos() == 0)
828 cur.selection() = true;
829 cursorLeftOneWord(cur);
831 cutSelection(cur, true, false);
832 checkBufferStructure(cur.buffer(), cur);
837 // Kill to end of line.
838 void Text::changeCase(Cursor & cur, Text::TextCase action)
840 BOOST_ASSERT(this == cur.text());
844 if (cur.selection()) {
845 from = cur.selBegin();
849 getWord(from, to, PARTIAL_WORD);
850 cursorRightOneWord(cur);
853 recordUndoSelection(cur, Undo::ATOMIC);
855 pit_type begPit = from.pit();
856 pit_type endPit = to.pit();
858 pos_type begPos = from.pos();
859 pos_type endPos = to.pos();
861 bool const trackChanges = cur.buffer().params().trackChanges;
863 pos_type right = 0; // needed after the for loop
865 for (pit_type pit = begPit; pit <= endPit; ++pit) {
866 pos_type parSize = pars_[pit].size();
868 pos_type pos = (pit == begPit ? begPos : 0);
869 right = (pit == endPit ? endPos : parSize);
871 // process sequences of modified characters; in change
872 // tracking mode, this approach results in much better
873 // usability than changing case on a char-by-char basis
876 bool capitalize = true;
878 for (; pos < right; ++pos) {
879 char_type oldChar = pars_[pit].getChar(pos);
880 char_type newChar = oldChar;
882 // ignore insets and don't play with deleted text!
883 if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
886 newChar = lowercase(oldChar);
888 case text_capitalization:
890 newChar = uppercase(oldChar);
895 newChar = uppercase(oldChar);
900 if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
901 capitalize = true; // permit capitalization again
904 if (oldChar != newChar) {
908 if (oldChar == newChar || pos == right - 1) {
909 if (oldChar != newChar) {
910 pos++; // step behind the changing area
912 int erasePos = pos - changes.size();
913 for (size_t i = 0; i < changes.size(); i++) {
914 pars_[pit].insertChar(pos, changes[i],
915 pars_[pit].getFontSettings(cur.buffer().params(),
918 if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
921 ++right; // expand selection
929 // the selection may have changed due to logically-only deleted chars
930 setCursor(cur, begPit, begPos);
932 setCursor(cur, endPit, right);
935 checkBufferStructure(cur.buffer(), cur);
939 bool Text::handleBibitems(Cursor & cur)
941 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
943 // if a bibitem is deleted, merge with previous paragraph
944 // if this is a bibliography item as well
945 if (cur.pos() == 0) {
946 BufferParams const & bufparams = cur.buffer().params();
947 Paragraph const & par = cur.paragraph();
948 Cursor prevcur = cur;
951 prevcur.pos() = prevcur.lastpos();
953 Paragraph const & prevpar = prevcur.paragraph();
954 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
955 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
956 mergeParagraph(bufparams, cur.text()->paragraphs(),
958 updateLabels(cur.buffer());
959 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
960 cur.updateFlags(Update::Force);
961 // if not, reset the paragraph to default
963 cur.paragraph().layout(
964 bufparams.getTextClass().defaultLayout());
971 bool Text::erase(Cursor & cur)
973 BOOST_ASSERT(this == cur.text());
974 bool needsUpdate = false;
975 Paragraph & par = cur.paragraph();
977 if (cur.pos() != cur.lastpos()) {
978 // this is the code for a normal delete, not pasting
980 recordUndo(cur, Undo::DELETE);
981 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
982 // the character has been logically deleted only => skip it
983 cur.top().forwardPos();
985 checkBufferStructure(cur.buffer(), cur);
988 if (cur.pit() == cur.lastpit())
989 return dissolveInset(cur);
991 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
992 par.setChange(cur.pos(), Change(Change::DELETED));
996 setCursorIntern(cur, cur.pit() + 1, 0);
997 needsUpdate = backspacePos0(cur);
1001 needsUpdate |= handleBibitems(cur);
1004 // Make sure the cursor is correct. Is this really needed?
1005 // No, not really... at least not here!
1006 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1007 checkBufferStructure(cur.buffer(), cur);
1014 bool Text::backspacePos0(Cursor & cur)
1016 BOOST_ASSERT(this == cur.text());
1020 bool needsUpdate = false;
1022 BufferParams const & bufparams = cur.buffer().params();
1023 TextClass const & tclass = bufparams.getTextClass();
1024 ParagraphList & plist = cur.text()->paragraphs();
1025 Paragraph const & par = cur.paragraph();
1026 Cursor prevcur = cur;
1028 prevcur.pos() = prevcur.lastpos();
1029 Paragraph const & prevpar = prevcur.paragraph();
1031 // is it an empty paragraph?
1032 if (cur.lastpos() == 0
1033 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1034 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1035 plist.erase(boost::next(plist.begin(), cur.pit()));
1038 // is previous par empty?
1039 else if (prevcur.lastpos() == 0
1040 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1041 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1042 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1045 // Pasting is not allowed, if the paragraphs have different
1046 // layouts. I think it is a real bug of all other
1047 // word processors to allow it. It confuses the user.
1048 // Correction: Pasting is always allowed with standard-layout
1049 else if (par.layout() == prevpar.layout()
1050 || par.layout() == tclass.defaultLayout()) {
1051 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1052 mergeParagraph(bufparams, plist, prevcur.pit());
1057 updateLabels(cur.buffer());
1058 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1065 bool Text::backspace(Cursor & cur)
1067 BOOST_ASSERT(this == cur.text());
1068 bool needsUpdate = false;
1069 if (cur.pos() == 0) {
1071 return dissolveInset(cur);
1073 Paragraph & prev_par = pars_[cur.pit() - 1];
1075 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1076 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1077 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1080 // The cursor is at the beginning of a paragraph, so
1081 // the backspace will collapse two paragraphs into one.
1082 needsUpdate = backspacePos0(cur);
1085 // this is the code for a normal backspace, not pasting
1087 recordUndo(cur, Undo::DELETE);
1088 // We used to do cursorLeftIntern() here, but it is
1089 // not a good idea since it triggers the auto-delete
1090 // mechanism. So we do a cursorLeftIntern()-lite,
1091 // without the dreaded mechanism. (JMarc)
1092 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1093 false, cur.boundary());
1094 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1095 checkBufferStructure(cur.buffer(), cur);
1098 if (cur.pos() == cur.lastpos())
1099 cur.setCurrentFont();
1101 needsUpdate |= handleBibitems(cur);
1103 // A singlePar update is not enough in this case.
1104 // cur.updateFlags(Update::Force);
1105 setCursor(cur.top(), cur.pit(), cur.pos());
1111 bool Text::dissolveInset(Cursor & cur) {
1112 BOOST_ASSERT(this == cur.text());
1114 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1117 recordUndoInset(cur);
1118 cur.selHandle(false);
1120 pos_type spos = cur.pos();
1121 pit_type spit = cur.pit();
1122 ParagraphList plist;
1123 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1124 plist = paragraphs();
1126 // store cursor offset
1130 Buffer & b = cur.buffer();
1131 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1132 if (!plist.empty()) {
1133 // ERT paragraphs have the Language latex_language.
1134 // This is invalid outside of ERT, so we need to
1135 // change it to the buffer language.
1136 ParagraphList::iterator it = plist.begin();
1137 ParagraphList::iterator it_end = plist.end();
1138 for (; it != it_end; it++) {
1139 it->changeLanguage(b.params(), latex_language,
1143 pasteParagraphList(cur, plist, b.params().getTextClassPtr(),
1144 b.errorList("Paste"));
1146 cur.pit() = std::min(cur.lastpit(), spit);
1147 cur.pos() = std::min(cur.lastpos(), spos);
1149 cur.clearSelection();
1155 void Text::getWord(CursorSlice & from, CursorSlice & to,
1156 word_location const loc)
1158 Paragraph const & from_par = pars_[from.pit()];
1160 case WHOLE_WORD_STRICT:
1161 if (from.pos() == 0 || from.pos() == from_par.size()
1162 || !from_par.isLetter(from.pos())
1163 || !from_par.isLetter(from.pos() - 1)) {
1167 // no break here, we go to the next
1170 // If we are already at the beginning of a word, do nothing
1171 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1173 // no break here, we go to the next
1176 // always move the cursor to the beginning of previous word
1177 while (from.pos() && from_par.isLetter(from.pos() - 1))
1181 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1185 // no need to move the 'from' cursor
1189 Paragraph & to_par = pars_[to.pit()];
1190 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1195 void Text::write(Buffer const & buf, std::ostream & os) const
1197 ParagraphList::const_iterator pit = paragraphs().begin();
1198 ParagraphList::const_iterator end = paragraphs().end();
1200 for (; pit != end; ++pit)
1201 pit->write(buf, os, buf.params(), dth);
1203 // Close begin_deeper
1204 for(; dth > 0; --dth)
1205 os << "\n\\end_deeper";
1209 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1211 depth_type depth = 0;
1213 while (lex.isOK()) {
1215 string const token = lex.getString();
1220 if (token == "\\end_inset")
1223 if (token == "\\end_body")
1226 if (token == "\\begin_body")
1229 if (token == "\\end_document")
1232 if (token == "\\begin_layout") {
1233 lex.pushToken(token);
1236 par.params().depth(depth);
1237 par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1238 pars_.push_back(par);
1240 // FIXME: goddamn InsetTabular makes us pass a Buffer
1242 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1244 } else if (token == "\\begin_deeper") {
1246 } else if (token == "\\end_deeper") {
1248 lex.printError("\\end_deeper: " "depth is already null");
1253 lyxerr << "Handling unknown body token: `"
1254 << token << '\'' << endl;
1260 // Returns the current font and depth as a message.
1261 docstring Text::currentState(Cursor & cur)
1263 BOOST_ASSERT(this == cur.text());
1264 Buffer & buf = cur.buffer();
1265 Paragraph const & par = cur.paragraph();
1266 odocstringstream os;
1268 if (buf.params().trackChanges)
1269 os << _("[Change Tracking] ");
1271 Change change = par.lookupChange(cur.pos());
1273 if (change.type != Change::UNCHANGED) {
1274 Author const & a = buf.params().authors().get(change.author);
1275 os << _("Change: ") << a.name();
1276 if (!a.email().empty())
1277 os << " (" << a.email() << ")";
1278 // FIXME ctime is english, we should translate that
1279 os << _(" at ") << ctime(&change.changetime);
1283 // I think we should only show changes from the default
1285 // No, from the document font (MV)
1286 Font font = cur.real_current_font;
1287 font.reduce(buf.params().getFont());
1289 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1291 // The paragraph depth
1292 int depth = cur.paragraph().getDepth();
1294 os << bformat(_(", Depth: %1$d"), depth);
1296 // The paragraph spacing, but only if different from
1298 Spacing const & spacing = par.params().spacing();
1299 if (!spacing.isDefault()) {
1300 os << _(", Spacing: ");
1301 switch (spacing.getSpace()) {
1302 case Spacing::Single:
1305 case Spacing::Onehalf:
1308 case Spacing::Double:
1311 case Spacing::Other:
1312 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1314 case Spacing::Default:
1315 // should never happen, do nothing
1320 #ifdef DEVEL_VERSION
1321 os << _(", Inset: ") << &cur.inset();
1322 os << _(", Paragraph: ") << cur.pit();
1323 os << _(", Id: ") << par.id();
1324 os << _(", Position: ") << cur.pos();
1325 // FIXME: Why is the check for par.size() needed?
1326 // We are called with cur.pos() == par.size() quite often.
1327 if (!par.empty() && cur.pos() < par.size()) {
1328 // Force output of code point, not character
1329 size_t const c = par.getChar(cur.pos());
1330 os << _(", Char: 0x") << std::hex << c;
1332 os << _(", Boundary: ") << cur.boundary();
1333 // Row & row = cur.textRow();
1334 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1340 docstring Text::getPossibleLabel(Cursor & cur) const
1342 pit_type pit = cur.pit();
1344 LayoutPtr layout = pars_[pit].layout();
1347 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1348 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1349 if (par_text.empty())
1352 par_text = split(par_text, head, ' ');
1353 // Is it legal to use spaces in labels ?
1359 // No need for a prefix if the user said so.
1360 if (lyxrc.label_init_length <= 0)
1363 // Will contain the label type.
1366 // For section, subsection, etc...
1367 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1368 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1369 if (layout2->latextype != LATEX_PARAGRAPH) {
1374 if (layout->latextype != LATEX_PARAGRAPH)
1375 name = from_ascii(layout->latexname());
1377 // for captions, we just take the caption type
1378 Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1380 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1382 // If none of the above worked, we'll see if we're inside various
1383 // types of insets and take our abbreviation from them.
1385 Inset::Code const codes[] = {
1390 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1391 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1393 name = float_inset->name();
1399 // Create a correct prefix for prettyref
1400 if (name == "theorem")
1401 name = from_ascii("thm");
1402 else if (name == "Foot")
1403 name = from_ascii("fn");
1404 else if (name == "listing")
1405 name = from_ascii("lst");
1408 text = name.substr(0, 3) + ':' + text;
1414 void Text::charsTranspose(Cursor & cur)
1416 BOOST_ASSERT(this == cur.text());
1418 pos_type pos = cur.pos();
1420 // If cursor is at beginning or end of paragraph, do nothing.
1421 if (pos == cur.lastpos() || pos == 0)
1424 Paragraph & par = cur.paragraph();
1426 // Get the positions of the characters to be transposed.
1427 pos_type pos1 = pos - 1;
1428 pos_type pos2 = pos;
1430 // In change tracking mode, ignore deleted characters.
1431 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1433 if (pos2 == cur.lastpos())
1436 while (pos1 >= 0 && par.isDeleted(pos1))
1441 // Don't do anything if one of the "characters" is not regular text.
1442 if (par.isInset(pos1) || par.isInset(pos2))
1445 // Store the characters to be transposed (including font information).
1446 char_type char1 = par.getChar(pos1);
1448 par.getFontSettings(cur.buffer().params(), pos1);
1450 char_type char2 = par.getChar(pos2);
1452 par.getFontSettings(cur.buffer().params(), pos2);
1454 // And finally, we are ready to perform the transposition.
1455 // Track the changes if Change Tracking is enabled.
1456 bool const trackChanges = cur.buffer().params().trackChanges;
1460 par.eraseChar(pos2, trackChanges);
1461 par.eraseChar(pos1, trackChanges);
1462 par.insertChar(pos1, char2, font2, trackChanges);
1463 par.insertChar(pos2, char1, font1, trackChanges);
1465 checkBufferStructure(cur.buffer(), cur);
1467 // After the transposition, move cursor to after the transposition.
1468 setCursor(cur, cur.pit(), pos2);