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 Jean-Marc Lasgouttes
10 * \author André Pönitz
11 * \author Stefan Schimanski
13 * \author Jürgen Vigna
15 * Full author contact details are available in file CREDITS.
24 #include "buffer_funcs.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "bufferview_funcs.h"
29 #include "ParIterator.h"
30 #include "CoordCache.h"
31 #include "CutAndPaste.h"
33 #include "DispatchResult.h"
35 #include "ErrorList.h"
36 #include "FuncRequest.h"
38 #include "FontIterator.h"
46 #include "MetricsInfo.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "rowpainter.h"
53 #include "WordLangTuple.h"
55 #include "frontends/FontMetrics.h"
56 #include "frontends/Painter.h"
58 #include "insets/InsetText.h"
59 #include "insets/InsetBibitem.h"
60 #include "insets/InsetCaption.h"
61 #include "insets/InsetHFill.h"
62 #include "insets/InsetLine.h"
63 #include "insets/InsetNewline.h"
64 #include "insets/InsetPagebreak.h"
65 #include "insets/InsetOptArg.h"
66 #include "insets/InsetSpace.h"
67 #include "insets/InsetSpecialChar.h"
68 #include "insets/InsetTabular.h"
70 #include "support/lstrings.h"
71 #include "support/textutils.h"
72 #include "support/convert.h"
74 #include <boost/current_function.hpp>
88 using support::bformat;
89 using support::contains;
90 using support::lowercase;
92 using support::uppercase;
94 using cap::cutSelection;
95 using cap::pasteParagraphList;
97 using frontend::FontMetrics;
101 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
102 string const & token, Font & font, Change & change, ErrorList & errorList)
104 BufferParams const & bp = buf.params();
106 if (token[0] != '\\') {
108 string::const_iterator cit = token.begin();
109 for (; cit != token.end(); ++cit)
110 par.insertChar(par.size(), (*cit), font, change);
112 docstring dstr = lex.getDocString();
113 docstring::const_iterator cit = dstr.begin();
114 docstring::const_iterator cend = dstr.end();
115 for (; cit != cend; ++cit)
116 par.insertChar(par.size(), *cit, font, change);
118 } else if (token == "\\begin_layout") {
120 string layoutname = lex.getString();
122 font = Font(Font::ALL_INHERIT, bp.language);
123 change = Change(Change::UNCHANGED);
125 TextClass const & tclass = bp.getTextClass();
127 if (layoutname.empty()) {
128 layoutname = tclass.defaultLayoutName();
131 bool hasLayout = tclass.hasLayout(layoutname);
134 errorList.push_back(ErrorItem(_("Unknown layout"),
135 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
136 from_utf8(layoutname), from_utf8(tclass.name())), par.id(), 0, par.size()));
137 layoutname = tclass.defaultLayoutName();
140 par.layout(bp.getTextClass()[layoutname]);
142 // Test whether the layout is obsolete.
143 Layout_ptr const & layout = par.layout();
144 if (!layout->obsoleted_by().empty())
145 par.layout(bp.getTextClass()[layout->obsoleted_by()]);
147 par.params().read(lex);
149 } else if (token == "\\end_layout") {
150 lyxerr << BOOST_CURRENT_FUNCTION
151 << ": Solitary \\end_layout in line "
152 << lex.getLineNo() << "\n"
153 << "Missing \\begin_layout?.\n";
154 } else if (token == "\\end_inset") {
155 lyxerr << BOOST_CURRENT_FUNCTION
156 << ": Solitary \\end_inset in line "
157 << lex.getLineNo() << "\n"
158 << "Missing \\begin_inset?.\n";
159 } else if (token == "\\begin_inset") {
160 Inset * inset = readInset(lex, buf);
162 par.insertInset(par.size(), inset, font, change);
165 docstring line = lex.getDocString();
166 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
167 par.id(), 0, par.size()));
169 } else if (token == "\\family") {
171 font.setLyXFamily(lex.getString());
172 } else if (token == "\\series") {
174 font.setLyXSeries(lex.getString());
175 } else if (token == "\\shape") {
177 font.setLyXShape(lex.getString());
178 } else if (token == "\\size") {
180 font.setLyXSize(lex.getString());
181 } else if (token == "\\lang") {
183 string const tok = lex.getString();
184 Language const * lang = languages.getLanguage(tok);
186 font.setLanguage(lang);
188 font.setLanguage(bp.language);
189 lex.printError("Unknown language `$$Token'");
191 } else if (token == "\\numeric") {
193 font.setNumber(font.setLyXMisc(lex.getString()));
194 } else if (token == "\\emph") {
196 font.setEmph(font.setLyXMisc(lex.getString()));
197 } else if (token == "\\bar") {
199 string const tok = lex.getString();
202 font.setUnderbar(Font::ON);
203 else if (tok == "no")
204 font.setUnderbar(Font::OFF);
205 else if (tok == "default")
206 font.setUnderbar(Font::INHERIT);
208 lex.printError("Unknown bar font flag "
210 } else if (token == "\\noun") {
212 font.setNoun(font.setLyXMisc(lex.getString()));
213 } else if (token == "\\color") {
215 font.setLyXColor(lex.getString());
216 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
218 // Insets don't make sense in a free-spacing context! ---Kayvan
219 if (par.isFreeSpacing()) {
220 if (token == "\\InsetSpace")
221 par.insertChar(par.size(), ' ', font, change);
222 else if (lex.isOK()) {
224 string const next_token = lex.getString();
225 if (next_token == "\\-")
226 par.insertChar(par.size(), '-', font, change);
228 lex.printError("Token `$$Token' "
230 "paragraph layout!");
234 auto_ptr<Inset> inset;
235 if (token == "\\SpecialChar" )
236 inset.reset(new InsetSpecialChar);
238 inset.reset(new InsetSpace);
239 inset->read(buf, lex);
240 par.insertInset(par.size(), inset.release(),
243 } else if (token == "\\backslash") {
244 par.insertChar(par.size(), '\\', font, change);
245 } else if (token == "\\newline") {
246 auto_ptr<Inset> inset(new InsetNewline);
247 inset->read(buf, lex);
248 par.insertInset(par.size(), inset.release(), font, change);
249 } else if (token == "\\LyXTable") {
250 auto_ptr<Inset> inset(new InsetTabular(buf));
251 inset->read(buf, lex);
252 par.insertInset(par.size(), inset.release(), font, change);
253 } else if (token == "\\hfill") {
254 par.insertInset(par.size(), new InsetHFill, font, change);
255 } else if (token == "\\lyxline") {
256 par.insertInset(par.size(), new InsetLine, font, change);
257 } else if (token == "\\newpage") {
258 par.insertInset(par.size(), new InsetPagebreak, font, change);
259 } else if (token == "\\clearpage") {
260 par.insertInset(par.size(), new InsetClearPage, font, change);
261 } else if (token == "\\cleardoublepage") {
262 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
263 } else if (token == "\\change_unchanged") {
264 change = Change(Change::UNCHANGED);
265 } else if (token == "\\change_inserted") {
267 std::istringstream is(lex.getString());
271 if (aid >= bp.author_map.size()) {
272 errorList.push_back(ErrorItem(_("Change tracking error"),
273 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
274 par.id(), 0, par.size()));
275 change = Change(Change::UNCHANGED);
277 change = Change(Change::INSERTED, bp.author_map[aid], ct);
278 } else if (token == "\\change_deleted") {
280 std::istringstream is(lex.getString());
284 if (aid >= bp.author_map.size()) {
285 errorList.push_back(ErrorItem(_("Change tracking error"),
286 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
287 par.id(), 0, par.size()));
288 change = Change(Change::UNCHANGED);
290 change = Change(Change::DELETED, bp.author_map[aid], ct);
293 errorList.push_back(ErrorItem(_("Unknown token"),
294 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
296 par.id(), 0, par.size()));
301 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
302 ErrorList & errorList)
305 string token = lex.getString();
307 Change change(Change::UNCHANGED);
310 readParToken(buf, par, lex, token, font, change, errorList);
313 token = lex.getString();
318 if (token == "\\end_layout") {
319 //Ok, paragraph finished
323 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
324 << token << '\'' << endl;
325 if (token == "\\begin_layout" || token == "\\end_document"
326 || token == "\\end_inset" || token == "\\begin_deeper"
327 || token == "\\end_deeper") {
328 lex.pushToken(token);
329 lyxerr << "Paragraph ended in line "
330 << lex.getLineNo() << "\n"
331 << "Missing \\end_layout.\n";
335 // Final change goes to paragraph break:
336 par.setChange(par.size(), change);
338 // Initialize begin_of_body_ on load; redoParagraph maintains
339 par.setBeginOfBody();
347 double Text::spacing(Buffer const & buffer,
348 Paragraph const & par) const
350 if (par.params().spacing().isDefault())
351 return buffer.params().spacing().getValue();
352 return par.params().spacing().getValue();
356 int Text::singleWidth(Buffer const & buffer, Paragraph const & par,
359 return singleWidth(par, pos, par.getChar(pos),
360 getFont(buffer, par, pos));
364 int Text::singleWidth(Paragraph const & par,
365 pos_type pos, char_type c, Font const & font) const
367 // The most common case is handled first (Asger)
368 if (isPrintable(c)) {
369 Language const * language = font.language();
370 if (language->rightToLeft()) {
371 if (language->lang() == "arabic" ||
372 language->lang() == "farsi") {
373 if (Encodings::isComposeChar_arabic(c))
375 c = par.transformChar(c, pos);
376 } else if (language->lang() == "hebrew" &&
377 Encodings::isComposeChar_hebrew(c))
380 return theFontMetrics(font).width(c);
383 if (c == Paragraph::META_INSET)
384 return par.getInset(pos)->width();
386 return theFontMetrics(font).width(c);
390 int Text::leftMargin(Buffer const & buffer, int max_width, pit_type pit) const
392 BOOST_ASSERT(pit >= 0);
393 BOOST_ASSERT(pit < int(pars_.size()));
394 return leftMargin(buffer, max_width, pit, pars_[pit].size());
398 int Text::leftMargin(Buffer const & buffer, int max_width,
399 pit_type const pit, pos_type const pos) const
401 BOOST_ASSERT(pit >= 0);
402 BOOST_ASSERT(pit < int(pars_.size()));
403 Paragraph const & par = pars_[pit];
404 BOOST_ASSERT(pos >= 0);
405 BOOST_ASSERT(pos <= par.size());
406 //lyxerr << "Text::leftMargin: pit: " << pit << " pos: " << pos << endl;
407 TextClass const & tclass = buffer.params().getTextClass();
408 Layout_ptr const & layout = par.layout();
410 string parindent = layout->parindent;
414 if (isMainText(buffer))
415 l_margin += changebarMargin();
418 docstring leftm = from_utf8(tclass.leftmargin());
419 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm);
421 if (par.getDepth() != 0) {
422 // find the next level paragraph
423 pit_type newpar = outerHook(pit, pars_);
424 if (newpar != pit_type(pars_.size())) {
425 if (pars_[newpar].layout()->isEnvironment()) {
426 l_margin = leftMargin(buffer, max_width, newpar);
428 if (par.layout() == tclass.defaultLayout()) {
429 if (pars_[newpar].params().noindent())
432 parindent = pars_[newpar].layout()->parindent;
437 // This happens after sections in standard classes. The 1.3.x
438 // code compared depths too, but it does not seem necessary
440 if (par.layout() == tclass.defaultLayout()
441 && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
444 Font const labelfont = getLabelFont(buffer, par);
445 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
447 switch (layout->margintype) {
449 if (!layout->leftmargin.empty()) {
451 docstring leftm = from_utf8(layout->leftmargin);
452 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm);
454 if (!par.getLabelstring().empty()) {
456 docstring labin = from_utf8(layout->labelindent);
457 l_margin += labelfont_metrics.signedWidth(labin);
458 docstring labstr = par.getLabelstring();
459 l_margin += labelfont_metrics.width(labstr);
460 docstring labsep = from_utf8(layout->labelsep);
461 l_margin += labelfont_metrics.width(labsep);
465 case MARGIN_MANUAL: {
467 docstring labin = from_utf8(layout->labelindent);
468 l_margin += labelfont_metrics.signedWidth(labin);
469 // The width of an empty par, even with manual label, should be 0
470 if (!par.empty() && pos >= par.beginOfBody()) {
471 if (!par.getLabelWidthString().empty()) {
472 docstring labstr = par.getLabelWidthString();
473 l_margin += labelfont_metrics.width(labstr);
474 docstring labsep = from_utf8(layout->labelsep);
475 l_margin += labelfont_metrics.width(labsep);
481 case MARGIN_STATIC: {
483 docstring leftm = from_utf8(layout->leftmargin);
484 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm)
485 * 4 / (par.getDepth() + 4);
489 case MARGIN_FIRST_DYNAMIC:
490 if (layout->labeltype == LABEL_MANUAL) {
491 if (pos >= par.beginOfBody()) {
493 l_margin += labelfont_metrics.signedWidth(
494 from_utf8(layout->leftmargin));
497 l_margin += labelfont_metrics.signedWidth(
498 from_utf8(layout->labelindent));
501 // Special case to fix problems with
503 || (layout->labeltype == LABEL_STATIC
504 && layout->latextype == LATEX_ENVIRONMENT
505 && !isFirstInSequence(pit, pars_))) {
507 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->leftmargin));
508 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
509 && layout->labeltype != LABEL_BIBLIO
510 && layout->labeltype !=
511 LABEL_CENTERED_TOP_ENVIRONMENT) {
512 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->labelindent));
513 l_margin += labelfont_metrics.width(from_utf8(layout->labelsep));
514 l_margin += labelfont_metrics.width(par.getLabelstring());
518 case MARGIN_RIGHT_ADDRESS_BOX: {
520 // ok, a terrible hack. The left margin depends on the widest
521 // row in this paragraph.
522 RowList::iterator rit = par.rows().begin();
523 RowList::iterator end = par.rows().end();
525 #warning This is wrong.
527 int minfill = max_width;
528 for ( ; rit != end; ++rit)
529 if (rit->fill() < minfill)
530 minfill = rit->fill();
531 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
534 // also wrong, but much shorter.
535 l_margin += max_width / 2;
540 if (!par.params().leftIndent().zero())
541 l_margin += par.params().leftIndent().inPixels(max_width);
545 if (par.params().align() == LYX_ALIGN_LAYOUT)
546 align = layout->align;
548 align = par.params().align();
550 // set the correct parindent
552 && (layout->labeltype == LABEL_NO_LABEL
553 || layout->labeltype == LABEL_TOP_ENVIRONMENT
554 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
555 || (layout->labeltype == LABEL_STATIC
556 && layout->latextype == LATEX_ENVIRONMENT
557 && !isFirstInSequence(pit, pars_)))
558 && align == LYX_ALIGN_BLOCK
559 && !par.params().noindent()
560 // in some insets, paragraphs are never indented
561 && !(par.inInset() && par.inInset()->neverIndent(buffer))
562 // display style insets are always centered, omit indentation
565 && par.getInset(pos)->display())
566 && (par.layout() != tclass.defaultLayout()
567 || buffer.params().paragraph_separation ==
568 BufferParams::PARSEP_INDENT))
570 docstring din = from_utf8(parindent);
571 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(din);
578 Color_color Text::backgroundColor() const
580 return Color_color(Color::color(background_color_));
584 void Text::breakParagraph(Cursor & cur, bool keep_layout)
586 BOOST_ASSERT(this == cur.text());
588 Paragraph & cpar = cur.paragraph();
589 pit_type cpit = cur.pit();
591 TextClass const & tclass = cur.buffer().params().getTextClass();
592 Layout_ptr const & layout = cpar.layout();
594 // this is only allowed, if the current paragraph is not empty
595 // or caption and if it has not the keepempty flag active
596 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
597 layout->labeltype != LABEL_SENSITIVE)
600 // a layout change may affect also the following paragraph
601 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
603 // Always break behind a space
604 // It is better to erase the space (Dekel)
605 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
606 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
608 // What should the layout for the new paragraph be?
609 int preserve_layout = 0;
613 preserve_layout = layout->isEnvironment();
615 // We need to remember this before we break the paragraph, because
616 // that invalidates the layout variable
617 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
619 // we need to set this before we insert the paragraph.
620 bool const isempty = cpar.allowEmpty() && cpar.empty();
622 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
623 cur.pos(), preserve_layout);
625 // After this, neither paragraph contains any rows!
628 pit_type next_par = cpit + 1;
630 // well this is the caption hack since one caption is really enough
633 // set to standard-layout
634 pars_[cpit].applyLayout(tclass.defaultLayout());
636 // set to standard-layout
637 pars_[next_par].applyLayout(tclass.defaultLayout());
640 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
641 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
642 break; // the character couldn't be deleted physically due to change tracking
645 ParIterator current_it(cur);
646 ParIterator last_it(cur);
650 updateLabels(cur.buffer(), current_it, last_it);
652 // A singlePar update is not enough in this case.
653 cur.updateFlags(Update::Force);
655 // This check is necessary. Otherwise the new empty paragraph will
656 // be deleted automatically. And it is more friendly for the user!
657 if (cur.pos() != 0 || isempty)
658 setCursor(cur, cur.pit() + 1, 0);
660 setCursor(cur, cur.pit(), 0);
664 // insert a character, moves all the following breaks in the
665 // same Paragraph one to the right and make a rebreak
666 void Text::insertChar(Cursor & cur, char_type c)
668 BOOST_ASSERT(this == cur.text());
669 BOOST_ASSERT(c != Paragraph::META_INSET);
671 recordUndo(cur, Undo::INSERT);
673 Buffer const & buffer = cur.buffer();
674 Paragraph & par = cur.paragraph();
675 // try to remove this
676 pit_type const pit = cur.pit();
678 bool const freeSpacing = par.layout()->free_spacing ||
681 if (lyxrc.auto_number) {
682 static docstring const number_operators = from_ascii("+-/*");
683 static docstring const number_unary_operators = from_ascii("+-");
684 static docstring const number_seperators = from_ascii(".,:");
686 if (current_font.number() == Font::ON) {
687 if (!isDigit(c) && !contains(number_operators, c) &&
688 !(contains(number_seperators, c) &&
690 cur.pos() != cur.lastpos() &&
691 getFont(buffer, par, cur.pos()).number() == Font::ON &&
692 getFont(buffer, par, cur.pos() - 1).number() == Font::ON)
694 number(cur); // Set current_font.number to OFF
695 } else if (isDigit(c) &&
696 real_current_font.isVisibleRightToLeft()) {
697 number(cur); // Set current_font.number to ON
699 if (cur.pos() != 0) {
700 char_type const c = par.getChar(cur.pos() - 1);
701 if (contains(number_unary_operators, c) &&
703 || par.isSeparator(cur.pos() - 2)
704 || par.isNewline(cur.pos() - 2))
706 setCharFont(buffer, pit, cur.pos() - 1, current_font);
707 } else if (contains(number_seperators, c)
709 && getFont(buffer, par, cur.pos() - 2).number() == Font::ON) {
710 setCharFont(buffer, pit, cur.pos() - 1, current_font);
716 // First check, if there will be two blanks together or a blank at
717 // the beginning of a paragraph.
718 // I decided to handle blanks like normal characters, the main
719 // difference are the special checks when calculating the row.fill
720 // (blank does not count at the end of a row) and the check here
722 // When the free-spacing option is set for the current layout,
723 // disable the double-space checking
724 if (!freeSpacing && isLineSeparatorChar(c)) {
725 if (cur.pos() == 0) {
726 static bool sent_space_message = false;
727 if (!sent_space_message) {
728 cur.message(_("You cannot insert a space at the "
729 "beginning of a paragraph. Please read the Tutorial."));
730 sent_space_message = true;
734 BOOST_ASSERT(cur.pos() > 0);
735 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
736 && !par.isDeleted(cur.pos() - 1)) {
737 static bool sent_space_message = false;
738 if (!sent_space_message) {
739 cur.message(_("You cannot type two spaces this way. "
740 "Please read the Tutorial."));
741 sent_space_message = true;
747 par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
748 checkBufferStructure(cur.buffer(), cur);
750 // cur.updateFlags(Update::Force);
751 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
756 void Text::charInserted()
758 // Here we call finishUndo for every 20 characters inserted.
759 // This is from my experience how emacs does it. (Lgb)
760 static unsigned int counter;
770 // the cursor set functions have a special mechanism. When they
771 // realize, that you left an empty paragraph, they will delete it.
773 bool Text::cursorRightOneWord(Cursor & cur)
775 BOOST_ASSERT(this == cur.text());
779 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
783 // Advance through word.
784 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
786 // Skip through trailing nonword stuff.
787 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
790 return setCursor(cur, old.pit(), old.pos());
794 bool Text::cursorLeftOneWord(Cursor & cur)
796 BOOST_ASSERT(this == cur.text());
800 if (old.pos() == 0 && old.pit() != 0) {
802 old.pos() = old.lastpos();
804 // Skip through initial nonword stuff.
805 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
807 // Advance through word.
808 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
811 return setCursor(cur, old.pit(), old.pos());
815 void Text::selectWord(Cursor & cur, word_location loc)
817 BOOST_ASSERT(this == cur.text());
818 CursorSlice from = cur.top();
819 CursorSlice to = cur.top();
820 getWord(from, to, loc);
821 if (cur.top() != from)
822 setCursor(cur, from.pit(), from.pos());
826 setCursor(cur, to.pit(), to.pos());
828 cap::saveSelection(cur);
832 // Select the word currently under the cursor when no
833 // selection is currently set
834 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
836 BOOST_ASSERT(this == cur.text());
839 selectWord(cur, loc);
840 return cur.selection();
844 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
846 BOOST_ASSERT(this == cur.text());
848 if (!cur.selection())
851 recordUndoSelection(cur, Undo::ATOMIC);
853 pit_type begPit = cur.selectionBegin().pit();
854 pit_type endPit = cur.selectionEnd().pit();
856 pos_type begPos = cur.selectionBegin().pos();
857 pos_type endPos = cur.selectionEnd().pos();
859 // keep selection info, because endPos becomes invalid after the first loop
860 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
862 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
864 for (pit_type pit = begPit; pit <= endPit; ++pit) {
865 pos_type parSize = pars_[pit].size();
867 // ignore empty paragraphs; otherwise, an assertion will fail for
868 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
872 // do not consider first paragraph if the cursor starts at pos size()
873 if (pit == begPit && begPos == parSize)
876 // do not consider last paragraph if the cursor ends at pos 0
877 if (pit == endPit && endPos == 0)
878 break; // last iteration anyway
880 pos_type left = (pit == begPit ? begPos : 0);
881 pos_type right = (pit == endPit ? endPos : parSize);
884 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
886 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
890 // next, accept/reject imaginary end-of-par characters
892 for (pit_type pit = begPit; pit <= endPit; ++pit) {
893 pos_type pos = pars_[pit].size();
895 // skip if the selection ends before the end-of-par
896 if (pit == endPit && endsBeforeEndOfPar)
897 break; // last iteration anyway
899 // skip if this is not the last paragraph of the document
900 // note: the user should be able to accept/reject the par break of the last par!
901 if (pit == endPit && pit + 1 != int(pars_.size()))
902 break; // last iteration anway
905 if (pars_[pit].isInserted(pos)) {
906 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
907 } else if (pars_[pit].isDeleted(pos)) {
908 if (pit + 1 == int(pars_.size())) {
909 // we cannot remove a par break at the end of the last paragraph;
910 // instead, we mark it unchanged
911 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
913 mergeParagraph(cur.buffer().params(), pars_, pit);
919 if (pars_[pit].isDeleted(pos)) {
920 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
921 } else if (pars_[pit].isInserted(pos)) {
922 if (pit + 1 == int(pars_.size())) {
923 // we mark the par break at the end of the last paragraph unchanged
924 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
926 mergeParagraph(cur.buffer().params(), pars_, pit);
934 // finally, invoke the DEPM
936 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
941 cur.clearSelection();
942 setCursorIntern(cur, begPit, begPos);
943 cur.updateFlags(Update::Force);
944 updateLabels(cur.buffer());
948 void Text::acceptChanges(BufferParams const & bparams)
950 pit_type pars_size = static_cast<pit_type>(pars_.size());
952 // first, accept changes within each individual paragraph
953 // (do not consider end-of-par)
954 for (pit_type pit = 0; pit < pars_size; ++pit) {
955 if (!pars_[pit].empty()) // prevent assertion failure
956 pars_[pit].acceptChanges(bparams, 0, pars_[pit].size());
959 // next, accept imaginary end-of-par characters
960 for (pit_type pit = 0; pit < pars_size; ++pit) {
961 pos_type pos = pars_[pit].size();
963 if (pars_[pit].isInserted(pos)) {
964 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
965 } else if (pars_[pit].isDeleted(pos)) {
966 if (pit == pars_size - 1) {
967 // we cannot remove a par break at the end of the last
968 // paragraph; instead, we mark it unchanged
969 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
971 mergeParagraph(bparams, pars_, pit);
978 // finally, invoke the DEPM
979 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
983 void Text::rejectChanges(BufferParams const & bparams)
985 pit_type pars_size = static_cast<pit_type>(pars_.size());
987 // first, reject changes within each individual paragraph
988 // (do not consider end-of-par)
989 for (pit_type pit = 0; pit < pars_size; ++pit) {
990 if (!pars_[pit].empty()) // prevent assertion failure
991 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
994 // next, reject imaginary end-of-par characters
995 for (pit_type pit = 0; pit < pars_size; ++pit) {
996 pos_type pos = pars_[pit].size();
998 if (pars_[pit].isDeleted(pos)) {
999 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1000 } else if (pars_[pit].isInserted(pos)) {
1001 if (pit == pars_size - 1) {
1002 // we mark the par break at the end of the last
1003 // paragraph unchanged
1004 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1006 mergeParagraph(bparams, pars_, pit);
1013 // finally, invoke the DEPM
1014 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1018 // Delete from cursor up to the end of the current or next word.
1019 void Text::deleteWordForward(Cursor & cur)
1021 BOOST_ASSERT(this == cur.text());
1022 if (cur.lastpos() == 0)
1026 cur.selection() = true;
1027 cursorRightOneWord(cur);
1029 cutSelection(cur, true, false);
1030 checkBufferStructure(cur.buffer(), cur);
1035 // Delete from cursor to start of current or prior word.
1036 void Text::deleteWordBackward(Cursor & cur)
1038 BOOST_ASSERT(this == cur.text());
1039 if (cur.lastpos() == 0)
1043 cur.selection() = true;
1044 cursorLeftOneWord(cur);
1046 cutSelection(cur, true, false);
1047 checkBufferStructure(cur.buffer(), cur);
1052 // Kill to end of line.
1053 void Text::deleteLineForward(Cursor & cur)
1055 BOOST_ASSERT(this == cur.text());
1056 if (cur.lastpos() == 0) {
1057 // Paragraph is empty, so we just go to the right
1061 cur.selection() = true; // to avoid deletion
1064 // What is this test for ??? (JMarc)
1065 if (!cur.selection())
1066 deleteWordForward(cur);
1068 cutSelection(cur, true, false);
1069 checkBufferStructure(cur.buffer(), cur);
1074 void Text::changeCase(Cursor & cur, Text::TextCase action)
1076 BOOST_ASSERT(this == cur.text());
1080 if (cur.selection()) {
1081 from = cur.selBegin();
1085 getWord(from, to, PARTIAL_WORD);
1086 cursorRightOneWord(cur);
1089 recordUndoSelection(cur, Undo::ATOMIC);
1091 pit_type begPit = from.pit();
1092 pit_type endPit = to.pit();
1094 pos_type begPos = from.pos();
1095 pos_type endPos = to.pos();
1097 bool const trackChanges = cur.buffer().params().trackChanges;
1099 pos_type right = 0; // needed after the for loop
1101 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1102 pos_type parSize = pars_[pit].size();
1104 pos_type pos = (pit == begPit ? begPos : 0);
1105 right = (pit == endPit ? endPos : parSize);
1107 // process sequences of modified characters; in change
1108 // tracking mode, this approach results in much better
1109 // usability than changing case on a char-by-char basis
1112 bool capitalize = true;
1114 for (; pos < right; ++pos) {
1115 char_type oldChar = pars_[pit].getChar(pos);
1116 char_type newChar = oldChar;
1118 // ignore insets and don't play with deleted text!
1119 if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
1121 case text_lowercase:
1122 newChar = lowercase(oldChar);
1124 case text_capitalization:
1126 newChar = uppercase(oldChar);
1130 case text_uppercase:
1131 newChar = uppercase(oldChar);
1136 if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
1137 capitalize = true; // permit capitalization again
1140 if (oldChar != newChar) {
1144 if (oldChar == newChar || pos == right - 1) {
1145 if (oldChar != newChar) {
1146 pos++; // step behind the changing area
1148 int erasePos = pos - changes.size();
1149 for (size_t i = 0; i < changes.size(); i++) {
1150 pars_[pit].insertChar(pos, changes[i],
1151 pars_[pit].getFontSettings(cur.buffer().params(),
1154 if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
1157 ++right; // expand selection
1165 // the selection may have changed due to logically-only deleted chars
1166 setCursor(cur, begPit, begPos);
1168 setCursor(cur, endPit, right);
1171 checkBufferStructure(cur.buffer(), cur);
1175 bool Text::handleBibitems(Cursor & cur)
1177 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
1179 // if a bibitem is deleted, merge with previous paragraph
1180 // if this is a bibliography item as well
1181 if (cur.pos() == 0) {
1182 BufferParams const & bufparams = cur.buffer().params();
1183 Paragraph const & par = cur.paragraph();
1184 Cursor prevcur = cur;
1185 if (cur.pit() > 0) {
1187 prevcur.pos() = prevcur.lastpos();
1189 Paragraph const & prevpar = prevcur.paragraph();
1190 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1191 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1192 mergeParagraph(bufparams, cur.text()->paragraphs(),
1194 updateLabels(cur.buffer());
1195 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1196 cur.updateFlags(Update::Force);
1197 // if not, reset the paragraph to default
1199 cur.paragraph().layout(
1200 bufparams.getTextClass().defaultLayout());
1207 bool Text::erase(Cursor & cur)
1209 BOOST_ASSERT(this == cur.text());
1210 bool needsUpdate = false;
1211 Paragraph & par = cur.paragraph();
1213 if (cur.pos() != cur.lastpos()) {
1214 // this is the code for a normal delete, not pasting
1216 recordUndo(cur, Undo::DELETE);
1217 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
1218 // the character has been logically deleted only => skip it
1219 cur.forwardPosNoDescend();
1221 checkBufferStructure(cur.buffer(), cur);
1224 if (cur.pit() == cur.lastpit())
1225 return dissolveInset(cur);
1227 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1228 par.setChange(cur.pos(), Change(Change::DELETED));
1232 setCursorIntern(cur, cur.pit() + 1, 0);
1233 needsUpdate = backspacePos0(cur);
1237 needsUpdate |= handleBibitems(cur);
1240 // Make sure the cursor is correct. Is this really needed?
1241 // No, not really... at least not here!
1242 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1243 checkBufferStructure(cur.buffer(), cur);
1250 bool Text::backspacePos0(Cursor & cur)
1252 BOOST_ASSERT(this == cur.text());
1256 bool needsUpdate = false;
1258 BufferParams const & bufparams = cur.buffer().params();
1259 TextClass const & tclass = bufparams.getTextClass();
1260 ParagraphList & plist = cur.text()->paragraphs();
1261 Paragraph const & par = cur.paragraph();
1262 Cursor prevcur = cur;
1264 prevcur.pos() = prevcur.lastpos();
1265 Paragraph const & prevpar = prevcur.paragraph();
1267 // is it an empty paragraph?
1268 if (cur.lastpos() == 0
1269 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1270 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1271 plist.erase(boost::next(plist.begin(), cur.pit()));
1274 // is previous par empty?
1275 else if (prevcur.lastpos() == 0
1276 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1277 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1278 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1281 // Pasting is not allowed, if the paragraphs have different
1282 // layouts. I think it is a real bug of all other
1283 // word processors to allow it. It confuses the user.
1284 // Correction: Pasting is always allowed with standard-layout
1285 else if (par.layout() == prevpar.layout()
1286 || par.layout() == tclass.defaultLayout()) {
1287 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1288 mergeParagraph(bufparams, plist, prevcur.pit());
1293 updateLabels(cur.buffer());
1294 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1301 bool Text::backspace(Cursor & cur)
1303 BOOST_ASSERT(this == cur.text());
1304 bool needsUpdate = false;
1305 if (cur.pos() == 0) {
1307 return dissolveInset(cur);
1309 Paragraph & prev_par = pars_[cur.pit() - 1];
1311 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1312 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1313 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1316 // The cursor is at the beginning of a paragraph, so
1317 // the backspace will collapse two paragraphs into one.
1318 needsUpdate = backspacePos0(cur);
1321 // this is the code for a normal backspace, not pasting
1323 recordUndo(cur, Undo::DELETE);
1324 // We used to do cursorLeftIntern() here, but it is
1325 // not a good idea since it triggers the auto-delete
1326 // mechanism. So we do a cursorLeftIntern()-lite,
1327 // without the dreaded mechanism. (JMarc)
1328 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1329 false, cur.boundary());
1330 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1331 checkBufferStructure(cur.buffer(), cur);
1334 if (cur.pos() == cur.lastpos())
1335 setCurrentFont(cur);
1337 needsUpdate |= handleBibitems(cur);
1339 // A singlePar update is not enough in this case.
1340 // cur.updateFlags(Update::Force);
1341 setCursor(cur.top(), cur.pit(), cur.pos());
1347 bool Text::dissolveInset(Cursor & cur) {
1348 BOOST_ASSERT(this == cur.text());
1350 if (isMainText(*cur.bv().buffer()) || cur.inset().nargs() != 1)
1353 recordUndoInset(cur);
1354 cur.selHandle(false);
1356 pos_type spos = cur.pos();
1357 pit_type spit = cur.pit();
1358 ParagraphList plist;
1359 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1360 plist = paragraphs();
1362 // store cursor offset
1366 Buffer & b = cur.buffer();
1367 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1368 if (!plist.empty()) {
1369 // ERT paragraphs have the Language latex_language.
1370 // This is invalid outside of ERT, so we need to
1371 // change it to the buffer language.
1372 ParagraphList::iterator it = plist.begin();
1373 ParagraphList::iterator it_end = plist.end();
1374 for (; it != it_end; it++) {
1375 it->changeLanguage(b.params(), latex_language,
1379 pasteParagraphList(cur, plist, b.params().textclass,
1380 b.errorList("Paste"));
1382 cur.pit() = std::min(cur.lastpit(), spit);
1383 cur.pos() = std::min(cur.lastpos(), spos);
1385 cur.clearSelection();
1391 // only used for inset right now. should also be used for main text
1392 void Text::draw(PainterInfo & pi, int x, int y) const
1394 paintTextInset(*this, pi, x, y);
1398 // only used for inset right now. should also be used for main text
1399 void Text::drawSelection(PainterInfo & pi, int x, int) const
1401 Cursor & cur = pi.base.bv->cursor();
1402 if (!cur.selection())
1404 if (!ptr_cmp(cur.text(), this))
1407 LYXERR(Debug::DEBUG)
1408 << BOOST_CURRENT_FUNCTION
1409 << "draw selection at " << x
1412 DocIterator beg = cur.selectionBegin();
1413 DocIterator end = cur.selectionEnd();
1415 BufferView & bv = *pi.base.bv;
1417 // the selection doesn't touch the visible screen?
1418 if (bv_funcs::status(&bv, beg) == bv_funcs::CUR_BELOW
1419 || bv_funcs::status(&bv, end) == bv_funcs::CUR_ABOVE)
1422 TextMetrics const & tm = bv.textMetrics(this);
1423 ParagraphMetrics const & pm1 = tm.parMetrics(beg.pit());
1424 ParagraphMetrics const & pm2 = tm.parMetrics(end.pit());
1425 Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
1426 Row const & row2 = pm2.getRow(end.pos(), end.boundary());
1430 bool const clipAbove =
1431 (bv_funcs::status(&bv, beg) == bv_funcs::CUR_ABOVE);
1435 middleTop = bv_funcs::getPos(bv, beg, beg.boundary()).y_ + row1.descent();
1439 bool const clipBelow =
1440 (bv_funcs::status(&bv, end) == bv_funcs::CUR_BELOW);
1442 middleBottom = bv.workHeight();
1444 middleBottom = bv_funcs::getPos(bv, end, end.boundary()).y_ - row2.ascent();
1446 // start and end in the same line?
1447 if (!(clipAbove || clipBelow) && &row1 == &row2)
1448 // then only draw this row's selection
1449 drawRowSelection(pi, x, row1, beg, end, false, false);
1453 DocIterator begRowEnd = beg;
1454 begRowEnd.pos() = row1.endpos();
1455 begRowEnd.boundary(true);
1457 // draw upper rectangle
1458 drawRowSelection(pi, x, row1, beg, begRowEnd, false, true);
1461 if (middleTop < middleBottom) {
1462 // draw middle rectangle
1463 pi.pain.fillRectangle(x, middleTop,
1464 tm.width(), middleBottom - middleTop,
1470 DocIterator endRowBeg = end;
1471 endRowBeg.pos() = row2.pos();
1472 endRowBeg.boundary(false);
1474 // draw low rectangle
1475 drawRowSelection(pi, x, row2, endRowBeg, end, true, false);
1481 void Text::drawRowSelection(PainterInfo & pi, int x, Row const & row,
1482 DocIterator const & beg, DocIterator const & end,
1483 bool drawOnBegMargin, bool drawOnEndMargin) const
1485 BufferView & bv = *pi.base.bv;
1486 Buffer & buffer = *bv.buffer();
1487 TextMetrics const & tm = bv.textMetrics(this);
1488 DocIterator cur = beg;
1489 int x1 = cursorX(bv, beg.top(), beg.boundary());
1490 int x2 = cursorX(bv, end.top(), end.boundary());
1491 int y1 = bv_funcs::getPos(bv, cur, cur.boundary()).y_ - row.ascent();
1492 int y2 = y1 + row.height();
1495 if (drawOnBegMargin) {
1496 if (isRTL(buffer, beg.paragraph()))
1497 pi.pain.fillRectangle(x + x1, y1, tm.width() - x1, y2 - y1, Color::selection);
1499 pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color::selection);
1502 if (drawOnEndMargin) {
1503 if (isRTL(buffer, beg.paragraph()))
1504 pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color::selection);
1506 pi.pain.fillRectangle(x + x2, y1, tm.width() - x2, y2 - y1, Color::selection);
1509 // if we are on a boundary from the beginning, it's probably
1510 // a RTL boundary and we jump to the other side directly as this
1511 // segement is 0-size and confuses the logic below
1513 cur.boundary(false);
1515 // go through row and draw from RTL boundary to RTL boundary
1517 bool drawNow = false;
1519 // simplified cursorRight code below which does not
1520 // descend into insets and which does not go into the
1521 // next line. Compare the logic with the original cursorRight
1523 // if left of boundary -> just jump to right side
1524 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
1525 if (cur.boundary()) {
1526 cur.boundary(false);
1527 } else if (bidi.isBoundary(buffer, cur.paragraph(), cur.pos() + 1)) {
1528 // in front of RTL boundary -> Stay on this side of the boundary because:
1529 // ab|cDDEEFFghi -> abc|DDEEFFghi
1538 if (cur.pos() == row.endpos())
1543 // the previous segment was just drawn, now the next starts
1544 x1 = cursorX(bv, cur.top(), cur.boundary());
1547 if (!(cur < end) || drawNow) {
1548 x2 = cursorX(bv, cur.top(), cur.boundary());
1549 pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
1552 // reset x1, so it is set again next round (which will be on the
1553 // right side of a boundary or at the selection end)
1561 bool Text::isLastRow(pit_type pit, Row const & row) const
1563 return row.endpos() >= pars_[pit].size()
1564 && pit + 1 == pit_type(paragraphs().size());
1568 bool Text::isFirstRow(pit_type pit, Row const & row) const
1570 return row.pos() == 0 && pit == 0;
1574 void Text::getWord(CursorSlice & from, CursorSlice & to,
1575 word_location const loc)
1577 Paragraph const & from_par = pars_[from.pit()];
1579 case WHOLE_WORD_STRICT:
1580 if (from.pos() == 0 || from.pos() == from_par.size()
1581 || !from_par.isLetter(from.pos())
1582 || !from_par.isLetter(from.pos() - 1)) {
1586 // no break here, we go to the next
1589 // If we are already at the beginning of a word, do nothing
1590 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1592 // no break here, we go to the next
1595 // always move the cursor to the beginning of previous word
1596 while (from.pos() && from_par.isLetter(from.pos() - 1))
1600 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1604 // no need to move the 'from' cursor
1608 Paragraph & to_par = pars_[to.pit()];
1609 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1614 void Text::write(Buffer const & buf, std::ostream & os) const
1616 ParagraphList::const_iterator pit = paragraphs().begin();
1617 ParagraphList::const_iterator end = paragraphs().end();
1619 for (; pit != end; ++pit)
1620 pit->write(buf, os, buf.params(), dth);
1624 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1626 depth_type depth = 0;
1628 while (lex.isOK()) {
1630 string const token = lex.getString();
1635 if (token == "\\end_inset")
1638 if (token == "\\end_body")
1641 if (token == "\\begin_body")
1644 if (token == "\\end_document")
1647 if (token == "\\begin_layout") {
1648 lex.pushToken(token);
1651 par.params().depth(depth);
1652 par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1653 pars_.push_back(par);
1655 // FIXME: goddamn InsetTabular makes us pass a Buffer
1657 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1659 } else if (token == "\\begin_deeper") {
1661 } else if (token == "\\end_deeper") {
1663 lex.printError("\\end_deeper: " "depth is already null");
1668 lyxerr << "Handling unknown body token: `"
1669 << token << '\'' << endl;
1675 int Text::cursorX(BufferView const & bv, CursorSlice const & sl,
1676 bool boundary) const
1678 TextMetrics const & tm = bv.textMetrics(sl.text());
1679 pit_type const pit = sl.pit();
1680 Paragraph const & par = pars_[pit];
1681 ParagraphMetrics const & pm = tm.parMetrics(pit);
1682 if (pm.rows().empty())
1685 pos_type ppos = sl.pos();
1686 // Correct position in front of big insets
1687 bool const boundary_correction = ppos != 0 && boundary;
1688 if (boundary_correction)
1691 Row const & row = pm.getRow(sl.pos(), boundary);
1693 pos_type cursor_vpos = 0;
1695 Buffer const & buffer = *bv.buffer();
1696 RowMetrics const m = tm.computeRowMetrics(pit, row);
1699 pos_type const row_pos = row.pos();
1700 pos_type const end = row.endpos();
1703 cursor_vpos = row_pos;
1704 else if (ppos >= end)
1705 cursor_vpos = isRTL(buffer, par) ? row_pos : end;
1706 else if (ppos > row_pos && ppos >= end)
1707 // Place cursor after char at (logical) position pos - 1
1708 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1709 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1711 // Place cursor before char at (logical) position ppos
1712 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1713 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1715 pos_type body_pos = par.beginOfBody();
1717 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1720 // Use font span to speed things up, see below
1723 FontMetrics const & labelfm = theFontMetrics(
1724 getLabelFont(buffer, par));
1726 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1727 pos_type pos = bidi.vis2log(vpos);
1728 if (body_pos > 0 && pos == body_pos - 1) {
1730 docstring const lsep = from_utf8(par.layout()->labelsep);
1731 x += m.label_hfill + labelfm.width(lsep);
1732 if (par.isLineSeparator(body_pos - 1))
1733 x -= singleWidth(buffer, par, body_pos - 1);
1736 // Use font span to speed things up, see above
1737 if (pos < font_span.first || pos > font_span.last) {
1738 font_span = par.fontSpan(pos);
1739 font = getFont(buffer, par, pos);
1742 x += singleWidth(par, pos, par.getChar(pos), font);
1744 if (par.hfillExpansion(row, pos))
1745 x += (pos >= body_pos) ? m.hfill : m.label_hfill;
1746 else if (par.isSeparator(pos) && pos >= body_pos)
1750 // see correction above
1751 if (boundary_correction) {
1752 if (isRTL(buffer, sl, boundary))
1753 x -= singleWidth(buffer, par, ppos);
1755 x += singleWidth(buffer, par, ppos);
1762 int Text::cursorY(BufferView const & bv, CursorSlice const & sl, bool boundary) const
1764 //lyxerr << "Text::cursorY: boundary: " << boundary << std::endl;
1765 ParagraphMetrics const & pm = bv.parMetrics(this, sl.pit());
1766 if (pm.rows().empty())
1770 h -= bv.parMetrics(this, 0).rows()[0].ascent();
1771 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1772 h += bv.parMetrics(this, pit).height();
1775 if (pos && boundary)
1777 size_t const rend = pm.pos2row(pos);
1778 for (size_t rit = 0; rit != rend; ++rit)
1779 h += pm.rows()[rit].height();
1780 h += pm.rows()[rend].ascent();
1785 // Returns the current font and depth as a message.
1786 docstring Text::currentState(Cursor & cur)
1788 BOOST_ASSERT(this == cur.text());
1789 Buffer & buf = cur.buffer();
1790 Paragraph const & par = cur.paragraph();
1791 odocstringstream os;
1793 if (buf.params().trackChanges)
1794 os << _("[Change Tracking] ");
1796 Change change = par.lookupChange(cur.pos());
1798 if (change.type != Change::UNCHANGED) {
1799 Author const & a = buf.params().authors().get(change.author);
1800 os << _("Change: ") << a.name();
1801 if (!a.email().empty())
1802 os << " (" << a.email() << ")";
1803 // FIXME ctime is english, we should translate that
1804 os << _(" at ") << ctime(&change.changetime);
1808 // I think we should only show changes from the default
1810 // No, from the document font (MV)
1811 Font font = real_current_font;
1812 font.reduce(buf.params().getFont());
1814 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1816 // The paragraph depth
1817 int depth = cur.paragraph().getDepth();
1819 os << bformat(_(", Depth: %1$d"), depth);
1821 // The paragraph spacing, but only if different from
1823 Spacing const & spacing = par.params().spacing();
1824 if (!spacing.isDefault()) {
1825 os << _(", Spacing: ");
1826 switch (spacing.getSpace()) {
1827 case Spacing::Single:
1830 case Spacing::Onehalf:
1833 case Spacing::Double:
1836 case Spacing::Other:
1837 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1839 case Spacing::Default:
1840 // should never happen, do nothing
1845 #ifdef DEVEL_VERSION
1846 os << _(", Inset: ") << &cur.inset();
1847 os << _(", Paragraph: ") << cur.pit();
1848 os << _(", Id: ") << par.id();
1849 os << _(", Position: ") << cur.pos();
1850 // FIXME: Why is the check for par.size() needed?
1851 // We are called with cur.pos() == par.size() quite often.
1852 if (!par.empty() && cur.pos() < par.size()) {
1853 // Force output of code point, not character
1854 size_t const c = par.getChar(cur.pos());
1855 os << _(", Char: 0x") << std::hex << c;
1857 os << _(", Boundary: ") << cur.boundary();
1858 // Row & row = cur.textRow();
1859 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1865 docstring Text::getPossibleLabel(Cursor & cur) const
1867 pit_type pit = cur.pit();
1869 Layout_ptr layout = pars_[pit].layout();
1872 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1873 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1874 if (par_text.empty())
1877 par_text = split(par_text, head, ' ');
1878 // Is it legal to use spaces in labels ?
1884 // No need for a prefix if the user said so.
1885 if (lyxrc.label_init_length <= 0)
1888 // Will contain the label type.
1891 // For section, subsection, etc...
1892 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1893 Layout_ptr const & layout2 = pars_[pit - 1].layout();
1894 if (layout2->latextype != LATEX_PARAGRAPH) {
1899 if (layout->latextype != LATEX_PARAGRAPH)
1900 name = from_ascii(layout->latexname());
1902 // for captions, we just take the caption type
1903 Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1905 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1907 // If none of the above worked, we'll see if we're inside various
1908 // types of insets and take our abbreviation from them.
1910 Inset::Code const codes[] = {
1915 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1916 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1918 name = float_inset->name();
1924 // Create a correct prefix for prettyref
1925 if (name == "theorem")
1926 name = from_ascii("thm");
1927 else if (name == "Foot")
1928 name = from_ascii("fn");
1929 else if (name == "listing")
1930 name = from_ascii("lst");
1933 text = name.substr(0, 3) + ':' + text;
1939 void Text::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1941 BOOST_ASSERT(this == cur.text());
1942 pit_type pit = getPitNearY(cur.bv(), y);
1944 TextMetrics const & tm = cur.bv().textMetrics(this);
1945 ParagraphMetrics const & pm = tm.parMetrics(pit);
1947 int yy = cur.bv().coordCache().get(this, pit).y_ - pm.ascent();
1948 LYXERR(Debug::DEBUG)
1949 << BOOST_CURRENT_FUNCTION
1953 << " yy: " << yy << endl;
1956 BOOST_ASSERT(pm.rows().size());
1957 for (; r < int(pm.rows().size()) - 1; ++r) {
1958 Row const & row = pm.rows()[r];
1959 if (int(yy + row.height()) > y)
1964 Row const & row = pm.rows()[r];
1966 LYXERR(Debug::DEBUG)
1967 << BOOST_CURRENT_FUNCTION
1969 << " from pos: " << row.pos()
1974 pos_type const pos = row.pos()
1975 + tm.getColumnNearX(pit, row, xx, bound);
1977 LYXERR(Debug::DEBUG)
1978 << BOOST_CURRENT_FUNCTION
1979 << ": setting cursor pit: " << pit
1983 setCursor(cur, pit, pos, true, bound);
1984 // remember new position.
1989 void Text::charsTranspose(Cursor & cur)
1991 BOOST_ASSERT(this == cur.text());
1993 pos_type pos = cur.pos();
1995 // If cursor is at beginning or end of paragraph, do nothing.
1996 if (pos == cur.lastpos() || pos == 0)
1999 Paragraph & par = cur.paragraph();
2001 // Get the positions of the characters to be transposed.
2002 pos_type pos1 = pos - 1;
2003 pos_type pos2 = pos;
2005 // In change tracking mode, ignore deleted characters.
2006 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2008 if (pos2 == cur.lastpos())
2011 while (pos1 >= 0 && par.isDeleted(pos1))
2016 // Don't do anything if one of the "characters" is not regular text.
2017 if (par.isInset(pos1) || par.isInset(pos2))
2020 // Store the characters to be transposed (including font information).
2021 char_type char1 = par.getChar(pos1);
2023 par.getFontSettings(cur.buffer().params(), pos1);
2025 char_type char2 = par.getChar(pos2);
2027 par.getFontSettings(cur.buffer().params(), pos2);
2029 // And finally, we are ready to perform the transposition.
2030 // Track the changes if Change Tracking is enabled.
2031 bool const trackChanges = cur.buffer().params().trackChanges;
2035 par.eraseChar(pos2, trackChanges);
2036 par.eraseChar(pos1, trackChanges);
2037 par.insertChar(pos1, char2, font2, trackChanges);
2038 par.insertChar(pos2, char1, font1, trackChanges);
2040 checkBufferStructure(cur.buffer(), cur);
2042 // After the transposition, move cursor to after the transposition.
2043 setCursor(cur, cur.pit(), pos2);