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 keep_layout)
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 int preserve_layout = 0;
389 preserve_layout = layout->isEnvironment();
391 // We need to remember this before we break the paragraph, because
392 // that invalidates the layout variable
393 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
395 // we need to set this before we insert the paragraph.
396 bool const isempty = cpar.allowEmpty() && cpar.empty();
398 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
399 cur.pos(), preserve_layout);
401 // After this, neither paragraph contains any rows!
404 pit_type next_par = cpit + 1;
406 // well this is the caption hack since one caption is really enough
409 // set to standard-layout
410 pars_[cpit].applyLayout(tclass.defaultLayout());
412 // set to standard-layout
413 pars_[next_par].applyLayout(tclass.defaultLayout());
416 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
417 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
418 break; // the character couldn't be deleted physically due to change tracking
421 updateLabels(cur.buffer());
423 // A singlePar update is not enough in this case.
424 cur.updateFlags(Update::Force);
426 // This check is necessary. Otherwise the new empty paragraph will
427 // be deleted automatically. And it is more friendly for the user!
428 if (cur.pos() != 0 || isempty)
429 setCursor(cur, cur.pit() + 1, 0);
431 setCursor(cur, cur.pit(), 0);
435 // insert a character, moves all the following breaks in the
436 // same Paragraph one to the right and make a rebreak
437 void Text::insertChar(Cursor & cur, char_type c)
439 BOOST_ASSERT(this == cur.text());
440 BOOST_ASSERT(c != Paragraph::META_INSET);
442 recordUndo(cur, Undo::INSERT);
444 TextMetrics const & tm = cur.bv().textMetrics(this);
445 Buffer const & buffer = cur.buffer();
446 Paragraph & par = cur.paragraph();
447 // try to remove this
448 pit_type const pit = cur.pit();
450 bool const freeSpacing = par.layout()->free_spacing ||
453 if (lyxrc.auto_number) {
454 static docstring const number_operators = from_ascii("+-/*");
455 static docstring const number_unary_operators = from_ascii("+-");
456 static docstring const number_seperators = from_ascii(".,:");
458 if (cur.current_font.number() == Font::ON) {
459 if (!isDigit(c) && !contains(number_operators, c) &&
460 !(contains(number_seperators, c) &&
462 cur.pos() != cur.lastpos() &&
463 tm.getDisplayFont(pit, cur.pos()).number() == Font::ON &&
464 tm.getDisplayFont(pit, cur.pos() - 1).number() == Font::ON)
466 number(cur); // Set current_font.number to OFF
467 } else if (isDigit(c) &&
468 cur.real_current_font.isVisibleRightToLeft()) {
469 number(cur); // Set current_font.number to ON
471 if (cur.pos() != 0) {
472 char_type const c = par.getChar(cur.pos() - 1);
473 if (contains(number_unary_operators, c) &&
475 || par.isSeparator(cur.pos() - 2)
476 || par.isNewline(cur.pos() - 2))
478 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
480 } else if (contains(number_seperators, c)
482 && tm.getDisplayFont(pit, cur.pos() - 2).number() == Font::ON) {
483 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
490 // In Bidi text, we want spaces to be treated in a special way: spaces
491 // which are between words in different languages should get the
492 // paragraph's language; otherwise, spaces should keep the language
493 // they were originally typed in. This is only in effect while typing;
494 // after the text is already typed in, the user can always go back and
495 // explicitly set the language of a space as desired. But 99.9% of the
496 // time, what we're doing here is what the user actually meant.
498 // The following cases are the ones in which the language of the space
499 // should be changed to match that of the containing paragraph. In the
500 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
501 // represents a space, pipe (|) represents the cursor position (so the
502 // character before it is the one just typed in). The different cases
503 // are depicted logically (not visually), from left to right:
508 // Theoretically, there are other situations that we should, perhaps, deal
509 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
510 // point (to understand why, just try to create this situation...).
512 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
513 // get font in front and behind the space in question. But do NOT
514 // use getFont(cur.pos()) because the character c is not inserted yet
515 Font const & pre_space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 2);
516 Font const & post_space_font = cur.real_current_font;
517 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
518 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
520 if (pre_space_rtl != post_space_rtl) {
521 // Set the space's language to match the language of the
522 // adjacent character whose direction is the paragraph's
523 // direction; don't touch other properties of the font
524 Language const * lang =
525 (pre_space_rtl == par.isRTL(buffer.params())) ?
526 pre_space_font.language() : post_space_font.language();
528 Font space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 1);
529 space_font.setLanguage(lang);
530 par.setFont(cur.pos() - 1, space_font);
534 // Next check, if there will be two blanks together or a blank at
535 // the beginning of a paragraph.
536 // I decided to handle blanks like normal characters, the main
537 // difference are the special checks when calculating the row.fill
538 // (blank does not count at the end of a row) and the check here
540 // When the free-spacing option is set for the current layout,
541 // disable the double-space checking
542 if (!freeSpacing && isLineSeparatorChar(c)) {
543 if (cur.pos() == 0) {
544 static bool sent_space_message = false;
545 if (!sent_space_message) {
546 cur.message(_("You cannot insert a space at the "
547 "beginning of a paragraph. Please read the Tutorial."));
548 sent_space_message = true;
552 BOOST_ASSERT(cur.pos() > 0);
553 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
554 && !par.isDeleted(cur.pos() - 1)) {
555 static bool sent_space_message = false;
556 if (!sent_space_message) {
557 cur.message(_("You cannot type two spaces this way. "
558 "Please read the Tutorial."));
559 sent_space_message = true;
565 par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
566 checkBufferStructure(cur.buffer(), cur);
568 // cur.updateFlags(Update::Force);
569 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
574 void Text::charInserted()
576 // Here we call finishUndo for every 20 characters inserted.
577 // This is from my experience how emacs does it. (Lgb)
578 static unsigned int counter;
588 // the cursor set functions have a special mechanism. When they
589 // realize, that you left an empty paragraph, they will delete it.
591 bool Text::cursorRightOneWord(Cursor & cur)
593 BOOST_ASSERT(this == cur.text());
597 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
601 // Advance through word.
602 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
604 // Skip through trailing nonword stuff.
605 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
608 return setCursor(cur, old.pit(), old.pos());
612 bool Text::cursorLeftOneWord(Cursor & cur)
614 BOOST_ASSERT(this == cur.text());
618 if (old.pos() == 0 && old.pit() != 0) {
620 old.pos() = old.lastpos();
622 // Skip through initial nonword stuff.
623 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
625 // Advance through word.
626 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
629 return setCursor(cur, old.pit(), old.pos());
633 void Text::selectWord(Cursor & cur, word_location loc)
635 BOOST_ASSERT(this == cur.text());
636 CursorSlice from = cur.top();
637 CursorSlice to = cur.top();
638 getWord(from, to, loc);
639 if (cur.top() != from)
640 setCursor(cur, from.pit(), from.pos());
644 setCursor(cur, to.pit(), to.pos());
649 // Select the word currently under the cursor when no
650 // selection is currently set
651 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
653 BOOST_ASSERT(this == cur.text());
656 selectWord(cur, loc);
657 return cur.selection();
661 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
663 BOOST_ASSERT(this == cur.text());
665 if (!cur.selection())
668 recordUndoSelection(cur, Undo::ATOMIC);
670 pit_type begPit = cur.selectionBegin().pit();
671 pit_type endPit = cur.selectionEnd().pit();
673 pos_type begPos = cur.selectionBegin().pos();
674 pos_type endPos = cur.selectionEnd().pos();
676 // keep selection info, because endPos becomes invalid after the first loop
677 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
679 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
681 for (pit_type pit = begPit; pit <= endPit; ++pit) {
682 pos_type parSize = pars_[pit].size();
684 // ignore empty paragraphs; otherwise, an assertion will fail for
685 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
689 // do not consider first paragraph if the cursor starts at pos size()
690 if (pit == begPit && begPos == parSize)
693 // do not consider last paragraph if the cursor ends at pos 0
694 if (pit == endPit && endPos == 0)
695 break; // last iteration anyway
697 pos_type left = (pit == begPit ? begPos : 0);
698 pos_type right = (pit == endPit ? endPos : parSize);
701 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
703 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
707 // next, accept/reject imaginary end-of-par characters
709 for (pit_type pit = begPit; pit <= endPit; ++pit) {
710 pos_type pos = pars_[pit].size();
712 // skip if the selection ends before the end-of-par
713 if (pit == endPit && endsBeforeEndOfPar)
714 break; // last iteration anyway
716 // skip if this is not the last paragraph of the document
717 // note: the user should be able to accept/reject the par break of the last par!
718 if (pit == endPit && pit + 1 != int(pars_.size()))
719 break; // last iteration anway
722 if (pars_[pit].isInserted(pos)) {
723 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
724 } else if (pars_[pit].isDeleted(pos)) {
725 if (pit + 1 == int(pars_.size())) {
726 // we cannot remove a par break at the end of the last paragraph;
727 // instead, we mark it unchanged
728 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
730 mergeParagraph(cur.buffer().params(), pars_, pit);
736 if (pars_[pit].isDeleted(pos)) {
737 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
738 } else if (pars_[pit].isInserted(pos)) {
739 if (pit + 1 == int(pars_.size())) {
740 // we mark the par break at the end of the last paragraph unchanged
741 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
743 mergeParagraph(cur.buffer().params(), pars_, pit);
751 // finally, invoke the DEPM
753 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
758 cur.clearSelection();
759 setCursorIntern(cur, begPit, begPos);
760 cur.updateFlags(Update::Force);
761 updateLabels(cur.buffer());
765 void Text::acceptChanges(BufferParams const & bparams)
767 lyx::acceptChanges(pars_, bparams);
768 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
772 void Text::rejectChanges(BufferParams const & bparams)
774 pit_type pars_size = static_cast<pit_type>(pars_.size());
776 // first, reject changes within each individual paragraph
777 // (do not consider end-of-par)
778 for (pit_type pit = 0; pit < pars_size; ++pit) {
779 if (!pars_[pit].empty()) // prevent assertion failure
780 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
783 // next, reject imaginary end-of-par characters
784 for (pit_type pit = 0; pit < pars_size; ++pit) {
785 pos_type pos = pars_[pit].size();
787 if (pars_[pit].isDeleted(pos)) {
788 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
789 } else if (pars_[pit].isInserted(pos)) {
790 if (pit == pars_size - 1) {
791 // we mark the par break at the end of the last
792 // paragraph unchanged
793 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
795 mergeParagraph(bparams, pars_, pit);
802 // finally, invoke the DEPM
803 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
807 void Text::deleteWordForward(Cursor & cur)
809 BOOST_ASSERT(this == cur.text());
810 if (cur.lastpos() == 0)
814 cur.selection() = true;
815 cursorRightOneWord(cur);
817 cutSelection(cur, true, false);
818 checkBufferStructure(cur.buffer(), cur);
823 void Text::deleteWordBackward(Cursor & cur)
825 BOOST_ASSERT(this == cur.text());
826 if (cur.lastpos() == 0)
830 cur.selection() = true;
831 cursorLeftOneWord(cur);
833 cutSelection(cur, true, false);
834 checkBufferStructure(cur.buffer(), cur);
839 // Kill to end of line.
840 void Text::changeCase(Cursor & cur, Text::TextCase action)
842 BOOST_ASSERT(this == cur.text());
846 if (cur.selection()) {
847 from = cur.selBegin();
851 getWord(from, to, PARTIAL_WORD);
852 cursorRightOneWord(cur);
855 recordUndoSelection(cur, Undo::ATOMIC);
857 pit_type begPit = from.pit();
858 pit_type endPit = to.pit();
860 pos_type begPos = from.pos();
861 pos_type endPos = to.pos();
863 bool const trackChanges = cur.buffer().params().trackChanges;
865 pos_type right = 0; // needed after the for loop
867 for (pit_type pit = begPit; pit <= endPit; ++pit) {
868 pos_type parSize = pars_[pit].size();
870 pos_type pos = (pit == begPit ? begPos : 0);
871 right = (pit == endPit ? endPos : parSize);
873 // process sequences of modified characters; in change
874 // tracking mode, this approach results in much better
875 // usability than changing case on a char-by-char basis
878 bool capitalize = true;
880 for (; pos < right; ++pos) {
881 char_type oldChar = pars_[pit].getChar(pos);
882 char_type newChar = oldChar;
884 // ignore insets and don't play with deleted text!
885 if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
888 newChar = lowercase(oldChar);
890 case text_capitalization:
892 newChar = uppercase(oldChar);
897 newChar = uppercase(oldChar);
902 if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
903 capitalize = true; // permit capitalization again
906 if (oldChar != newChar) {
910 if (oldChar == newChar || pos == right - 1) {
911 if (oldChar != newChar) {
912 pos++; // step behind the changing area
914 int erasePos = pos - changes.size();
915 for (size_t i = 0; i < changes.size(); i++) {
916 pars_[pit].insertChar(pos, changes[i],
917 pars_[pit].getFontSettings(cur.buffer().params(),
920 if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
923 ++right; // expand selection
931 // the selection may have changed due to logically-only deleted chars
932 setCursor(cur, begPit, begPos);
934 setCursor(cur, endPit, right);
937 checkBufferStructure(cur.buffer(), cur);
941 bool Text::handleBibitems(Cursor & cur)
943 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
945 // if a bibitem is deleted, merge with previous paragraph
946 // if this is a bibliography item as well
947 if (cur.pos() == 0) {
948 BufferParams const & bufparams = cur.buffer().params();
949 Paragraph const & par = cur.paragraph();
950 Cursor prevcur = cur;
953 prevcur.pos() = prevcur.lastpos();
955 Paragraph const & prevpar = prevcur.paragraph();
956 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
957 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
958 mergeParagraph(bufparams, cur.text()->paragraphs(),
960 updateLabels(cur.buffer());
961 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
962 cur.updateFlags(Update::Force);
963 // if not, reset the paragraph to default
965 cur.paragraph().layout(
966 bufparams.getTextClass().defaultLayout());
973 bool Text::erase(Cursor & cur)
975 BOOST_ASSERT(this == cur.text());
976 bool needsUpdate = false;
977 Paragraph & par = cur.paragraph();
979 if (cur.pos() != cur.lastpos()) {
980 // this is the code for a normal delete, not pasting
982 recordUndo(cur, Undo::DELETE);
983 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
984 // the character has been logically deleted only => skip it
985 cur.top().forwardPos();
987 checkBufferStructure(cur.buffer(), cur);
990 if (cur.pit() == cur.lastpit())
991 return dissolveInset(cur);
993 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
994 par.setChange(cur.pos(), Change(Change::DELETED));
998 setCursorIntern(cur, cur.pit() + 1, 0);
999 needsUpdate = backspacePos0(cur);
1003 needsUpdate |= handleBibitems(cur);
1006 // Make sure the cursor is correct. Is this really needed?
1007 // No, not really... at least not here!
1008 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1009 checkBufferStructure(cur.buffer(), cur);
1016 bool Text::backspacePos0(Cursor & cur)
1018 BOOST_ASSERT(this == cur.text());
1022 bool needsUpdate = false;
1024 BufferParams const & bufparams = cur.buffer().params();
1025 TextClass const & tclass = bufparams.getTextClass();
1026 ParagraphList & plist = cur.text()->paragraphs();
1027 Paragraph const & par = cur.paragraph();
1028 Cursor prevcur = cur;
1030 prevcur.pos() = prevcur.lastpos();
1031 Paragraph const & prevpar = prevcur.paragraph();
1033 // is it an empty paragraph?
1034 if (cur.lastpos() == 0
1035 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1036 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1037 plist.erase(boost::next(plist.begin(), cur.pit()));
1040 // is previous par empty?
1041 else if (prevcur.lastpos() == 0
1042 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1043 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1044 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1047 // Pasting is not allowed, if the paragraphs have different
1048 // layouts. I think it is a real bug of all other
1049 // word processors to allow it. It confuses the user.
1050 // Correction: Pasting is always allowed with standard-layout
1051 else if (par.layout() == prevpar.layout()
1052 || par.layout() == tclass.defaultLayout()) {
1053 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1054 mergeParagraph(bufparams, plist, prevcur.pit());
1059 updateLabels(cur.buffer());
1060 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1067 bool Text::backspace(Cursor & cur)
1069 BOOST_ASSERT(this == cur.text());
1070 bool needsUpdate = false;
1071 if (cur.pos() == 0) {
1073 return dissolveInset(cur);
1075 Paragraph & prev_par = pars_[cur.pit() - 1];
1077 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1078 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1079 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1082 // The cursor is at the beginning of a paragraph, so
1083 // the backspace will collapse two paragraphs into one.
1084 needsUpdate = backspacePos0(cur);
1087 // this is the code for a normal backspace, not pasting
1089 recordUndo(cur, Undo::DELETE);
1090 // We used to do cursorLeftIntern() here, but it is
1091 // not a good idea since it triggers the auto-delete
1092 // mechanism. So we do a cursorLeftIntern()-lite,
1093 // without the dreaded mechanism. (JMarc)
1094 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1095 false, cur.boundary());
1096 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1097 checkBufferStructure(cur.buffer(), cur);
1100 if (cur.pos() == cur.lastpos())
1101 cur.setCurrentFont();
1103 needsUpdate |= handleBibitems(cur);
1105 // A singlePar update is not enough in this case.
1106 // cur.updateFlags(Update::Force);
1107 setCursor(cur.top(), cur.pit(), cur.pos());
1113 bool Text::dissolveInset(Cursor & cur) {
1114 BOOST_ASSERT(this == cur.text());
1116 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1119 recordUndoInset(cur);
1120 cur.selHandle(false);
1122 pos_type spos = cur.pos();
1123 pit_type spit = cur.pit();
1124 ParagraphList plist;
1125 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1126 plist = paragraphs();
1128 // store cursor offset
1132 Buffer & b = cur.buffer();
1133 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1134 if (!plist.empty()) {
1135 // ERT paragraphs have the Language latex_language.
1136 // This is invalid outside of ERT, so we need to
1137 // change it to the buffer language.
1138 ParagraphList::iterator it = plist.begin();
1139 ParagraphList::iterator it_end = plist.end();
1140 for (; it != it_end; it++) {
1141 it->changeLanguage(b.params(), latex_language,
1145 pasteParagraphList(cur, plist, b.params().getTextClassPtr(),
1146 b.errorList("Paste"));
1148 cur.pit() = std::min(cur.lastpit(), spit);
1149 cur.pos() = std::min(cur.lastpos(), spos);
1151 cur.clearSelection();
1157 void Text::getWord(CursorSlice & from, CursorSlice & to,
1158 word_location const loc)
1160 Paragraph const & from_par = pars_[from.pit()];
1162 case WHOLE_WORD_STRICT:
1163 if (from.pos() == 0 || from.pos() == from_par.size()
1164 || !from_par.isLetter(from.pos())
1165 || !from_par.isLetter(from.pos() - 1)) {
1169 // no break here, we go to the next
1172 // If we are already at the beginning of a word, do nothing
1173 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1175 // no break here, we go to the next
1178 // always move the cursor to the beginning of previous word
1179 while (from.pos() && from_par.isLetter(from.pos() - 1))
1183 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1187 // no need to move the 'from' cursor
1191 Paragraph & to_par = pars_[to.pit()];
1192 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1197 void Text::write(Buffer const & buf, std::ostream & os) const
1199 ParagraphList::const_iterator pit = paragraphs().begin();
1200 ParagraphList::const_iterator end = paragraphs().end();
1202 for (; pit != end; ++pit)
1203 pit->write(buf, os, buf.params(), dth);
1205 // Close begin_deeper
1206 for(; dth > 0; --dth)
1207 os << "\n\\end_deeper";
1211 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1213 depth_type depth = 0;
1215 while (lex.isOK()) {
1217 string const token = lex.getString();
1222 if (token == "\\end_inset")
1225 if (token == "\\end_body")
1228 if (token == "\\begin_body")
1231 if (token == "\\end_document")
1234 if (token == "\\begin_layout") {
1235 lex.pushToken(token);
1238 par.params().depth(depth);
1239 par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1240 pars_.push_back(par);
1242 // FIXME: goddamn InsetTabular makes us pass a Buffer
1244 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1246 } else if (token == "\\begin_deeper") {
1248 } else if (token == "\\end_deeper") {
1250 lex.printError("\\end_deeper: " "depth is already null");
1255 lyxerr << "Handling unknown body token: `"
1256 << token << '\'' << endl;
1262 // Returns the current font and depth as a message.
1263 docstring Text::currentState(Cursor & cur)
1265 BOOST_ASSERT(this == cur.text());
1266 Buffer & buf = cur.buffer();
1267 Paragraph const & par = cur.paragraph();
1268 odocstringstream os;
1270 if (buf.params().trackChanges)
1271 os << _("[Change Tracking] ");
1273 Change change = par.lookupChange(cur.pos());
1275 if (change.type != Change::UNCHANGED) {
1276 Author const & a = buf.params().authors().get(change.author);
1277 os << _("Change: ") << a.name();
1278 if (!a.email().empty())
1279 os << " (" << a.email() << ")";
1280 // FIXME ctime is english, we should translate that
1281 os << _(" at ") << ctime(&change.changetime);
1285 // I think we should only show changes from the default
1287 // No, from the document font (MV)
1288 Font font = cur.real_current_font;
1289 font.reduce(buf.params().getFont());
1291 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1293 // The paragraph depth
1294 int depth = cur.paragraph().getDepth();
1296 os << bformat(_(", Depth: %1$d"), depth);
1298 // The paragraph spacing, but only if different from
1300 Spacing const & spacing = par.params().spacing();
1301 if (!spacing.isDefault()) {
1302 os << _(", Spacing: ");
1303 switch (spacing.getSpace()) {
1304 case Spacing::Single:
1307 case Spacing::Onehalf:
1310 case Spacing::Double:
1313 case Spacing::Other:
1314 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1316 case Spacing::Default:
1317 // should never happen, do nothing
1322 #ifdef DEVEL_VERSION
1323 os << _(", Inset: ") << &cur.inset();
1324 os << _(", Paragraph: ") << cur.pit();
1325 os << _(", Id: ") << par.id();
1326 os << _(", Position: ") << cur.pos();
1327 // FIXME: Why is the check for par.size() needed?
1328 // We are called with cur.pos() == par.size() quite often.
1329 if (!par.empty() && cur.pos() < par.size()) {
1330 // Force output of code point, not character
1331 size_t const c = par.getChar(cur.pos());
1332 os << _(", Char: 0x") << std::hex << c;
1334 os << _(", Boundary: ") << cur.boundary();
1335 // Row & row = cur.textRow();
1336 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1342 docstring Text::getPossibleLabel(Cursor & cur) const
1344 pit_type pit = cur.pit();
1346 LayoutPtr layout = pars_[pit].layout();
1349 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1350 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1351 if (par_text.empty())
1354 par_text = split(par_text, head, ' ');
1355 // Is it legal to use spaces in labels ?
1361 // No need for a prefix if the user said so.
1362 if (lyxrc.label_init_length <= 0)
1365 // Will contain the label type.
1368 // For section, subsection, etc...
1369 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1370 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1371 if (layout2->latextype != LATEX_PARAGRAPH) {
1376 if (layout->latextype != LATEX_PARAGRAPH)
1377 name = from_ascii(layout->latexname());
1379 // for captions, we just take the caption type
1380 Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1382 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1384 // If none of the above worked, we'll see if we're inside various
1385 // types of insets and take our abbreviation from them.
1387 Inset::Code const codes[] = {
1392 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1393 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1395 name = float_inset->name();
1401 // Create a correct prefix for prettyref
1402 if (name == "theorem")
1403 name = from_ascii("thm");
1404 else if (name == "Foot")
1405 name = from_ascii("fn");
1406 else if (name == "listing")
1407 name = from_ascii("lst");
1410 text = name.substr(0, 3) + ':' + text;
1416 void Text::charsTranspose(Cursor & cur)
1418 BOOST_ASSERT(this == cur.text());
1420 pos_type pos = cur.pos();
1422 // If cursor is at beginning or end of paragraph, do nothing.
1423 if (pos == cur.lastpos() || pos == 0)
1426 Paragraph & par = cur.paragraph();
1428 // Get the positions of the characters to be transposed.
1429 pos_type pos1 = pos - 1;
1430 pos_type pos2 = pos;
1432 // In change tracking mode, ignore deleted characters.
1433 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1435 if (pos2 == cur.lastpos())
1438 while (pos1 >= 0 && par.isDeleted(pos1))
1443 // Don't do anything if one of the "characters" is not regular text.
1444 if (par.isInset(pos1) || par.isInset(pos2))
1447 // Store the characters to be transposed (including font information).
1448 char_type char1 = par.getChar(pos1);
1450 par.getFontSettings(cur.buffer().params(), pos1);
1452 char_type char2 = par.getChar(pos2);
1454 par.getFontSettings(cur.buffer().params(), pos2);
1456 // And finally, we are ready to perform the transposition.
1457 // Track the changes if Change Tracking is enabled.
1458 bool const trackChanges = cur.buffer().params().trackChanges;
1462 par.eraseChar(pos2, trackChanges);
1463 par.eraseChar(pos1, trackChanges);
1464 par.insertChar(pos1, char2, font2, trackChanges);
1465 par.insertChar(pos2, char1, font1, trackChanges);
1467 checkBufferStructure(cur.buffer(), cur);
1469 // After the transposition, move cursor to after the transposition.
1470 setCursor(cur, cur.pit(), pos2);