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
12 * \author Jürgen Vigna
14 * Full author contact details are available in file CREDITS.
23 #include "buffer_funcs.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "bufferview_funcs.h"
28 #include "ParIterator.h"
29 #include "CoordCache.h"
30 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
37 #include "FontIterator.h"
45 #include "MetricsInfo.h"
46 #include "Paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "rowpainter.h"
52 #include "WordLangTuple.h"
54 #include "frontends/FontMetrics.h"
55 #include "frontends/Painter.h"
57 #include "insets/InsetText.h"
58 #include "insets/InsetBibitem.h"
59 #include "insets/InsetCaption.h"
60 #include "insets/InsetHFill.h"
61 #include "insets/InsetLine.h"
62 #include "insets/InsetNewline.h"
63 #include "insets/InsetPagebreak.h"
64 #include "insets/InsetOptArg.h"
65 #include "insets/InsetSpace.h"
66 #include "insets/InsetSpecialChar.h"
67 #include "insets/InsetTabular.h"
69 #include "support/lstrings.h"
70 #include "support/textutils.h"
71 #include "support/convert.h"
73 #include <boost/current_function.hpp>
87 using support::bformat;
88 using support::contains;
89 using support::lowercase;
91 using support::uppercase;
93 using cap::cutSelection;
94 using cap::pasteParagraphList;
96 using frontend::FontMetrics;
100 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
101 string const & token, Font & font, Change & change, ErrorList & errorList)
103 BufferParams const & bp = buf.params();
105 if (token[0] != '\\') {
107 string::const_iterator cit = token.begin();
108 for (; cit != token.end(); ++cit)
109 par.insertChar(par.size(), (*cit), font, change);
111 docstring dstr = lex.getDocString();
112 docstring::const_iterator cit = dstr.begin();
113 docstring::const_iterator cend = dstr.end();
114 for (; cit != cend; ++cit)
115 par.insertChar(par.size(), *cit, font, change);
117 } else if (token == "\\begin_layout") {
119 string layoutname = lex.getString();
121 font = Font(Font::ALL_INHERIT, bp.language);
122 change = Change(Change::UNCHANGED);
124 TextClass const & tclass = bp.getTextClass();
126 if (layoutname.empty()) {
127 layoutname = tclass.defaultLayoutName();
130 bool hasLayout = tclass.hasLayout(layoutname);
133 errorList.push_back(ErrorItem(_("Unknown layout"),
134 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
135 from_utf8(layoutname), from_utf8(tclass.name())), par.id(), 0, par.size()));
136 layoutname = tclass.defaultLayoutName();
139 par.layout(bp.getTextClass()[layoutname]);
141 // Test whether the layout is obsolete.
142 Layout_ptr const & layout = par.layout();
143 if (!layout->obsoleted_by().empty())
144 par.layout(bp.getTextClass()[layout->obsoleted_by()]);
146 par.params().read(lex);
148 } else if (token == "\\end_layout") {
149 lyxerr << BOOST_CURRENT_FUNCTION
150 << ": Solitary \\end_layout in line "
151 << lex.getLineNo() << "\n"
152 << "Missing \\begin_layout?.\n";
153 } else if (token == "\\end_inset") {
154 lyxerr << BOOST_CURRENT_FUNCTION
155 << ": Solitary \\end_inset in line "
156 << lex.getLineNo() << "\n"
157 << "Missing \\begin_inset?.\n";
158 } else if (token == "\\begin_inset") {
159 Inset * inset = readInset(lex, buf);
161 par.insertInset(par.size(), inset, font, change);
164 docstring line = lex.getDocString();
165 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
166 par.id(), 0, par.size()));
168 } else if (token == "\\family") {
170 font.setLyXFamily(lex.getString());
171 } else if (token == "\\series") {
173 font.setLyXSeries(lex.getString());
174 } else if (token == "\\shape") {
176 font.setLyXShape(lex.getString());
177 } else if (token == "\\size") {
179 font.setLyXSize(lex.getString());
180 } else if (token == "\\lang") {
182 string const tok = lex.getString();
183 Language const * lang = languages.getLanguage(tok);
185 font.setLanguage(lang);
187 font.setLanguage(bp.language);
188 lex.printError("Unknown language `$$Token'");
190 } else if (token == "\\numeric") {
192 font.setNumber(font.setLyXMisc(lex.getString()));
193 } else if (token == "\\emph") {
195 font.setEmph(font.setLyXMisc(lex.getString()));
196 } else if (token == "\\bar") {
198 string const tok = lex.getString();
201 font.setUnderbar(Font::ON);
202 else if (tok == "no")
203 font.setUnderbar(Font::OFF);
204 else if (tok == "default")
205 font.setUnderbar(Font::INHERIT);
207 lex.printError("Unknown bar font flag "
209 } else if (token == "\\noun") {
211 font.setNoun(font.setLyXMisc(lex.getString()));
212 } else if (token == "\\color") {
214 font.setLyXColor(lex.getString());
215 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
217 // Insets don't make sense in a free-spacing context! ---Kayvan
218 if (par.isFreeSpacing()) {
219 if (token == "\\InsetSpace")
220 par.insertChar(par.size(), ' ', font, change);
221 else if (lex.isOK()) {
223 string const next_token = lex.getString();
224 if (next_token == "\\-")
225 par.insertChar(par.size(), '-', font, change);
227 lex.printError("Token `$$Token' "
229 "paragraph layout!");
233 auto_ptr<Inset> inset;
234 if (token == "\\SpecialChar" )
235 inset.reset(new InsetSpecialChar);
237 inset.reset(new InsetSpace);
238 inset->read(buf, lex);
239 par.insertInset(par.size(), inset.release(),
242 } else if (token == "\\backslash") {
243 par.insertChar(par.size(), '\\', font, change);
244 } else if (token == "\\newline") {
245 auto_ptr<Inset> inset(new InsetNewline);
246 inset->read(buf, lex);
247 par.insertInset(par.size(), inset.release(), font, change);
248 } else if (token == "\\LyXTable") {
249 auto_ptr<Inset> inset(new InsetTabular(buf));
250 inset->read(buf, lex);
251 par.insertInset(par.size(), inset.release(), font, change);
252 } else if (token == "\\hfill") {
253 par.insertInset(par.size(), new InsetHFill, font, change);
254 } else if (token == "\\lyxline") {
255 par.insertInset(par.size(), new InsetLine, font, change);
256 } else if (token == "\\newpage") {
257 par.insertInset(par.size(), new InsetPagebreak, font, change);
258 } else if (token == "\\clearpage") {
259 par.insertInset(par.size(), new InsetClearPage, font, change);
260 } else if (token == "\\cleardoublepage") {
261 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
262 } else if (token == "\\change_unchanged") {
263 change = Change(Change::UNCHANGED);
264 } else if (token == "\\change_inserted") {
266 std::istringstream is(lex.getString());
270 if (aid >= bp.author_map.size()) {
271 errorList.push_back(ErrorItem(_("Change tracking error"),
272 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
273 par.id(), 0, par.size()));
274 change = Change(Change::UNCHANGED);
276 change = Change(Change::INSERTED, bp.author_map[aid], ct);
277 } else if (token == "\\change_deleted") {
279 std::istringstream is(lex.getString());
283 if (aid >= bp.author_map.size()) {
284 errorList.push_back(ErrorItem(_("Change tracking error"),
285 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
286 par.id(), 0, par.size()));
287 change = Change(Change::UNCHANGED);
289 change = Change(Change::DELETED, bp.author_map[aid], ct);
292 errorList.push_back(ErrorItem(_("Unknown token"),
293 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
295 par.id(), 0, par.size()));
300 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
301 ErrorList & errorList)
304 string token = lex.getString();
306 Change change(Change::UNCHANGED);
309 readParToken(buf, par, lex, token, font, change, errorList);
312 token = lex.getString();
317 if (token == "\\end_layout") {
318 //Ok, paragraph finished
322 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
323 << token << '\'' << endl;
324 if (token == "\\begin_layout" || token == "\\end_document"
325 || token == "\\end_inset" || token == "\\begin_deeper"
326 || token == "\\end_deeper") {
327 lex.pushToken(token);
328 lyxerr << "Paragraph ended in line "
329 << lex.getLineNo() << "\n"
330 << "Missing \\end_layout.\n";
334 // Final change goes to paragraph break:
335 par.setChange(par.size(), change);
337 // Initialize begin_of_body_ on load; redoParagraph maintains
338 par.setBeginOfBody();
346 double Text::spacing(Buffer const & buffer,
347 Paragraph const & par) const
349 if (par.params().spacing().isDefault())
350 return buffer.params().spacing().getValue();
351 return par.params().spacing().getValue();
355 int Text::singleWidth(Buffer const & buffer, Paragraph const & par,
358 return singleWidth(par, pos, par.getChar(pos),
359 getFont(buffer, par, pos));
363 int Text::singleWidth(Paragraph const & par,
364 pos_type pos, char_type c, Font const & font) const
366 // The most common case is handled first (Asger)
367 if (isPrintable(c)) {
368 Language const * language = font.language();
369 if (language->rightToLeft()) {
370 if (language->lang() == "arabic" ||
371 language->lang() == "farsi") {
372 if (Encodings::isComposeChar_arabic(c))
374 c = par.transformChar(c, pos);
375 } else if (language->lang() == "hebrew" &&
376 Encodings::isComposeChar_hebrew(c))
379 return theFontMetrics(font).width(c);
382 if (c == Paragraph::META_INSET)
383 return par.getInset(pos)->width();
385 return theFontMetrics(font).width(c);
389 int Text::leftMargin(Buffer const & buffer, int max_width, pit_type pit) const
391 BOOST_ASSERT(pit >= 0);
392 BOOST_ASSERT(pit < int(pars_.size()));
393 return leftMargin(buffer, max_width, pit, pars_[pit].size());
397 int Text::leftMargin(Buffer const & buffer, int max_width,
398 pit_type const pit, pos_type const pos) const
400 BOOST_ASSERT(pit >= 0);
401 BOOST_ASSERT(pit < int(pars_.size()));
402 Paragraph const & par = pars_[pit];
403 BOOST_ASSERT(pos >= 0);
404 BOOST_ASSERT(pos <= par.size());
405 //lyxerr << "Text::leftMargin: pit: " << pit << " pos: " << pos << endl;
406 TextClass const & tclass = buffer.params().getTextClass();
407 Layout_ptr const & layout = par.layout();
409 string parindent = layout->parindent;
413 if (isMainText(buffer))
414 l_margin += changebarMargin();
417 docstring leftm = from_utf8(tclass.leftmargin());
418 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm);
420 if (par.getDepth() != 0) {
421 // find the next level paragraph
422 pit_type newpar = outerHook(pit, pars_);
423 if (newpar != pit_type(pars_.size())) {
424 if (pars_[newpar].layout()->isEnvironment()) {
425 l_margin = leftMargin(buffer, max_width, newpar);
427 if (par.layout() == tclass.defaultLayout()) {
428 if (pars_[newpar].params().noindent())
431 parindent = pars_[newpar].layout()->parindent;
436 // This happens after sections in standard classes. The 1.3.x
437 // code compared depths too, but it does not seem necessary
439 if (par.layout() == tclass.defaultLayout()
440 && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
443 Font const labelfont = getLabelFont(buffer, par);
444 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
446 switch (layout->margintype) {
448 if (!layout->leftmargin.empty()) {
450 docstring leftm = from_utf8(layout->leftmargin);
451 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm);
453 if (!par.getLabelstring().empty()) {
455 docstring labin = from_utf8(layout->labelindent);
456 l_margin += labelfont_metrics.signedWidth(labin);
457 docstring labstr = par.getLabelstring();
458 l_margin += labelfont_metrics.width(labstr);
459 docstring labsep = from_utf8(layout->labelsep);
460 l_margin += labelfont_metrics.width(labsep);
464 case MARGIN_MANUAL: {
466 docstring labin = from_utf8(layout->labelindent);
467 l_margin += labelfont_metrics.signedWidth(labin);
468 // The width of an empty par, even with manual label, should be 0
469 if (!par.empty() && pos >= par.beginOfBody()) {
470 if (!par.getLabelWidthString().empty()) {
471 docstring labstr = par.getLabelWidthString();
472 l_margin += labelfont_metrics.width(labstr);
473 docstring labsep = from_utf8(layout->labelsep);
474 l_margin += labelfont_metrics.width(labsep);
480 case MARGIN_STATIC: {
482 docstring leftm = from_utf8(layout->leftmargin);
483 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm)
484 * 4 / (par.getDepth() + 4);
488 case MARGIN_FIRST_DYNAMIC:
489 if (layout->labeltype == LABEL_MANUAL) {
490 if (pos >= par.beginOfBody()) {
492 l_margin += labelfont_metrics.signedWidth(
493 from_utf8(layout->leftmargin));
496 l_margin += labelfont_metrics.signedWidth(
497 from_utf8(layout->labelindent));
500 // Special case to fix problems with
502 || (layout->labeltype == LABEL_STATIC
503 && layout->latextype == LATEX_ENVIRONMENT
504 && !isFirstInSequence(pit, pars_))) {
506 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->leftmargin));
507 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
508 && layout->labeltype != LABEL_BIBLIO
509 && layout->labeltype !=
510 LABEL_CENTERED_TOP_ENVIRONMENT) {
511 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->labelindent));
512 l_margin += labelfont_metrics.width(from_utf8(layout->labelsep));
513 l_margin += labelfont_metrics.width(par.getLabelstring());
517 case MARGIN_RIGHT_ADDRESS_BOX: {
519 // ok, a terrible hack. The left margin depends on the widest
520 // row in this paragraph.
521 RowList::iterator rit = par.rows().begin();
522 RowList::iterator end = par.rows().end();
524 #warning This is wrong.
526 int minfill = max_width;
527 for ( ; rit != end; ++rit)
528 if (rit->fill() < minfill)
529 minfill = rit->fill();
530 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
533 // also wrong, but much shorter.
534 l_margin += max_width / 2;
539 if (!par.params().leftIndent().zero())
540 l_margin += par.params().leftIndent().inPixels(max_width);
544 if (par.params().align() == LYX_ALIGN_LAYOUT)
545 align = layout->align;
547 align = par.params().align();
549 // set the correct parindent
551 && (layout->labeltype == LABEL_NO_LABEL
552 || layout->labeltype == LABEL_TOP_ENVIRONMENT
553 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
554 || (layout->labeltype == LABEL_STATIC
555 && layout->latextype == LATEX_ENVIRONMENT
556 && !isFirstInSequence(pit, pars_)))
557 && align == LYX_ALIGN_BLOCK
558 && !par.params().noindent()
559 // in some insets, paragraphs are never indented
560 && !(par.inInset() && par.inInset()->neverIndent(buffer))
561 // display style insets are always centered, omit indentation
564 && par.getInset(pos)->display())
565 && (par.layout() != tclass.defaultLayout()
566 || buffer.params().paragraph_separation ==
567 BufferParams::PARSEP_INDENT))
569 docstring din = from_utf8(parindent);
570 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(din);
577 Color_color Text::backgroundColor() const
579 return Color_color(Color::color(background_color_));
583 void Text::breakParagraph(Cursor & cur, bool keep_layout)
585 BOOST_ASSERT(this == cur.text());
587 Paragraph & cpar = cur.paragraph();
588 pit_type cpit = cur.pit();
590 TextClass const & tclass = cur.buffer().params().getTextClass();
591 Layout_ptr const & layout = cpar.layout();
593 // this is only allowed, if the current paragraph is not empty
594 // or caption and if it has not the keepempty flag active
595 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
596 layout->labeltype != LABEL_SENSITIVE)
599 // a layout change may affect also the following paragraph
600 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
602 // Always break behind a space
603 // It is better to erase the space (Dekel)
604 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
605 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
607 // What should the layout for the new paragraph be?
608 int preserve_layout = 0;
612 preserve_layout = layout->isEnvironment();
614 // We need to remember this before we break the paragraph, because
615 // that invalidates the layout variable
616 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
618 // we need to set this before we insert the paragraph.
619 bool const isempty = cpar.allowEmpty() && cpar.empty();
621 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
622 cur.pos(), preserve_layout);
624 // After this, neither paragraph contains any rows!
627 pit_type next_par = cpit + 1;
629 // well this is the caption hack since one caption is really enough
632 // set to standard-layout
633 pars_[cpit].applyLayout(tclass.defaultLayout());
635 // set to standard-layout
636 pars_[next_par].applyLayout(tclass.defaultLayout());
639 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
640 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
641 break; // the character couldn't be deleted physically due to change tracking
644 ParIterator current_it(cur);
645 ParIterator last_it(cur);
649 updateLabels(cur.buffer(), current_it, last_it);
651 // A singlePar update is not enough in this case.
652 cur.updateFlags(Update::Force);
654 // This check is necessary. Otherwise the new empty paragraph will
655 // be deleted automatically. And it is more friendly for the user!
656 if (cur.pos() != 0 || isempty)
657 setCursor(cur, cur.pit() + 1, 0);
659 setCursor(cur, cur.pit(), 0);
663 // insert a character, moves all the following breaks in the
664 // same Paragraph one to the right and make a rebreak
665 void Text::insertChar(Cursor & cur, char_type c)
667 BOOST_ASSERT(this == cur.text());
668 BOOST_ASSERT(c != Paragraph::META_INSET);
670 recordUndo(cur, Undo::INSERT);
672 Buffer const & buffer = cur.buffer();
673 Paragraph & par = cur.paragraph();
674 // try to remove this
675 pit_type const pit = cur.pit();
677 bool const freeSpacing = par.layout()->free_spacing ||
680 if (lyxrc.auto_number) {
681 static docstring const number_operators = from_ascii("+-/*");
682 static docstring const number_unary_operators = from_ascii("+-");
683 static docstring const number_seperators = from_ascii(".,:");
685 if (current_font.number() == Font::ON) {
686 if (!isDigit(c) && !contains(number_operators, c) &&
687 !(contains(number_seperators, c) &&
689 cur.pos() != cur.lastpos() &&
690 getFont(buffer, par, cur.pos()).number() == Font::ON &&
691 getFont(buffer, par, cur.pos() - 1).number() == Font::ON)
693 number(cur); // Set current_font.number to OFF
694 } else if (isDigit(c) &&
695 real_current_font.isVisibleRightToLeft()) {
696 number(cur); // Set current_font.number to ON
698 if (cur.pos() != 0) {
699 char_type const c = par.getChar(cur.pos() - 1);
700 if (contains(number_unary_operators, c) &&
702 || par.isSeparator(cur.pos() - 2)
703 || par.isNewline(cur.pos() - 2))
705 setCharFont(buffer, pit, cur.pos() - 1, current_font);
706 } else if (contains(number_seperators, c)
708 && getFont(buffer, par, cur.pos() - 2).number() == Font::ON) {
709 setCharFont(buffer, pit, cur.pos() - 1, current_font);
715 // First check, if there will be two blanks together or a blank at
716 // the beginning of a paragraph.
717 // I decided to handle blanks like normal characters, the main
718 // difference are the special checks when calculating the row.fill
719 // (blank does not count at the end of a row) and the check here
721 // When the free-spacing option is set for the current layout,
722 // disable the double-space checking
723 if (!freeSpacing && isLineSeparatorChar(c)) {
724 if (cur.pos() == 0) {
725 static bool sent_space_message = false;
726 if (!sent_space_message) {
727 cur.message(_("You cannot insert a space at the "
728 "beginning of a paragraph. Please read the Tutorial."));
729 sent_space_message = true;
733 BOOST_ASSERT(cur.pos() > 0);
734 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
735 && !par.isDeleted(cur.pos() - 1)) {
736 static bool sent_space_message = false;
737 if (!sent_space_message) {
738 cur.message(_("You cannot type two spaces this way. "
739 "Please read the Tutorial."));
740 sent_space_message = true;
746 par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
747 checkBufferStructure(cur.buffer(), cur);
749 // cur.updateFlags(Update::Force);
750 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
755 void Text::charInserted()
757 // Here we call finishUndo for every 20 characters inserted.
758 // This is from my experience how emacs does it. (Lgb)
759 static unsigned int counter;
769 // the cursor set functions have a special mechanism. When they
770 // realize, that you left an empty paragraph, they will delete it.
772 bool Text::cursorRightOneWord(Cursor & cur)
774 BOOST_ASSERT(this == cur.text());
778 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
782 // Advance through word.
783 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
785 // Skip through trailing nonword stuff.
786 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
789 return setCursor(cur, old.pit(), old.pos());
793 bool Text::cursorLeftOneWord(Cursor & cur)
795 BOOST_ASSERT(this == cur.text());
799 if (old.pos() == 0 && old.pit() != 0) {
801 old.pos() = old.lastpos();
803 // Skip through initial nonword stuff.
804 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
806 // Advance through word.
807 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
810 return setCursor(cur, old.pit(), old.pos());
814 void Text::selectWord(Cursor & cur, word_location loc)
816 BOOST_ASSERT(this == cur.text());
817 CursorSlice from = cur.top();
818 CursorSlice to = cur.top();
819 getWord(from, to, loc);
820 if (cur.top() != from)
821 setCursor(cur, from.pit(), from.pos());
825 setCursor(cur, to.pit(), to.pos());
827 cap::saveSelection(cur);
831 // Select the word currently under the cursor when no
832 // selection is currently set
833 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
835 BOOST_ASSERT(this == cur.text());
838 selectWord(cur, loc);
839 return cur.selection();
843 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
845 BOOST_ASSERT(this == cur.text());
847 if (!cur.selection())
850 recordUndoSelection(cur, Undo::ATOMIC);
852 pit_type begPit = cur.selectionBegin().pit();
853 pit_type endPit = cur.selectionEnd().pit();
855 pos_type begPos = cur.selectionBegin().pos();
856 pos_type endPos = cur.selectionEnd().pos();
858 // keep selection info, because endPos becomes invalid after the first loop
859 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
861 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
863 for (pit_type pit = begPit; pit <= endPit; ++pit) {
864 pos_type parSize = pars_[pit].size();
866 // ignore empty paragraphs; otherwise, an assertion will fail for
867 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
871 // do not consider first paragraph if the cursor starts at pos size()
872 if (pit == begPit && begPos == parSize)
875 // do not consider last paragraph if the cursor ends at pos 0
876 if (pit == endPit && endPos == 0)
877 break; // last iteration anyway
879 pos_type left = (pit == begPit ? begPos : 0);
880 pos_type right = (pit == endPit ? endPos : parSize);
883 pars_[pit].acceptChanges(cur.buffer().params(), left, right);
885 pars_[pit].rejectChanges(cur.buffer().params(), left, right);
889 // next, accept/reject imaginary end-of-par characters
891 for (pit_type pit = begPit; pit <= endPit; ++pit) {
892 pos_type pos = pars_[pit].size();
894 // skip if the selection ends before the end-of-par
895 if (pit == endPit && endsBeforeEndOfPar)
896 break; // last iteration anyway
898 // skip if this is not the last paragraph of the document
899 // note: the user should be able to accept/reject the par break of the last par!
900 if (pit == endPit && pit + 1 != int(pars_.size()))
901 break; // last iteration anway
904 if (pars_[pit].isInserted(pos)) {
905 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
906 } else if (pars_[pit].isDeleted(pos)) {
907 if (pit + 1 == int(pars_.size())) {
908 // we cannot remove a par break at the end of the last paragraph;
909 // instead, we mark it unchanged
910 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
912 mergeParagraph(cur.buffer().params(), pars_, pit);
918 if (pars_[pit].isDeleted(pos)) {
919 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
920 } else if (pars_[pit].isInserted(pos)) {
921 if (pit + 1 == int(pars_.size())) {
922 // we mark the par break at the end of the last paragraph unchanged
923 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
925 mergeParagraph(cur.buffer().params(), pars_, pit);
933 // finally, invoke the DEPM
935 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
940 cur.clearSelection();
941 setCursorIntern(cur, begPit, begPos);
942 cur.updateFlags(Update::Force);
943 updateLabels(cur.buffer());
947 void Text::acceptChanges(BufferParams const & bparams)
949 pit_type pars_size = static_cast<pit_type>(pars_.size());
951 // first, accept changes within each individual paragraph
952 // (do not consider end-of-par)
953 for (pit_type pit = 0; pit < pars_size; ++pit) {
954 if (!pars_[pit].empty()) // prevent assertion failure
955 pars_[pit].acceptChanges(bparams, 0, pars_[pit].size());
958 // next, accept imaginary end-of-par characters
959 for (pit_type pit = 0; pit < pars_size; ++pit) {
960 pos_type pos = pars_[pit].size();
962 if (pars_[pit].isInserted(pos)) {
963 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
964 } else if (pars_[pit].isDeleted(pos)) {
965 if (pit == pars_size - 1) {
966 // we cannot remove a par break at the end of the last
967 // paragraph; instead, we mark it unchanged
968 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
970 mergeParagraph(bparams, pars_, pit);
977 // finally, invoke the DEPM
978 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
982 void Text::rejectChanges(BufferParams const & bparams)
984 pit_type pars_size = static_cast<pit_type>(pars_.size());
986 // first, reject changes within each individual paragraph
987 // (do not consider end-of-par)
988 for (pit_type pit = 0; pit < pars_size; ++pit) {
989 if (!pars_[pit].empty()) // prevent assertion failure
990 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
993 // next, reject imaginary end-of-par characters
994 for (pit_type pit = 0; pit < pars_size; ++pit) {
995 pos_type pos = pars_[pit].size();
997 if (pars_[pit].isDeleted(pos)) {
998 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
999 } else if (pars_[pit].isInserted(pos)) {
1000 if (pit == pars_size - 1) {
1001 // we mark the par break at the end of the last
1002 // paragraph unchanged
1003 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1005 mergeParagraph(bparams, pars_, pit);
1012 // finally, invoke the DEPM
1013 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
1017 // Delete from cursor up to the end of the current or next word.
1018 void Text::deleteWordForward(Cursor & cur)
1020 BOOST_ASSERT(this == cur.text());
1021 if (cur.lastpos() == 0)
1025 cur.selection() = true;
1026 cursorRightOneWord(cur);
1028 cutSelection(cur, true, false);
1029 checkBufferStructure(cur.buffer(), cur);
1034 // Delete from cursor to start of current or prior word.
1035 void Text::deleteWordBackward(Cursor & cur)
1037 BOOST_ASSERT(this == cur.text());
1038 if (cur.lastpos() == 0)
1042 cur.selection() = true;
1043 cursorLeftOneWord(cur);
1045 cutSelection(cur, true, false);
1046 checkBufferStructure(cur.buffer(), cur);
1051 // Kill to end of line.
1052 void Text::deleteLineForward(Cursor & cur)
1054 BOOST_ASSERT(this == cur.text());
1055 if (cur.lastpos() == 0) {
1056 // Paragraph is empty, so we just go to the right
1060 cur.selection() = true; // to avoid deletion
1063 // What is this test for ??? (JMarc)
1064 if (!cur.selection())
1065 deleteWordForward(cur);
1067 cutSelection(cur, true, false);
1068 checkBufferStructure(cur.buffer(), cur);
1073 void Text::changeCase(Cursor & cur, Text::TextCase action)
1075 BOOST_ASSERT(this == cur.text());
1079 if (cur.selection()) {
1080 from = cur.selBegin();
1084 getWord(from, to, PARTIAL_WORD);
1085 cursorRightOneWord(cur);
1088 recordUndoSelection(cur, Undo::ATOMIC);
1090 pit_type begPit = from.pit();
1091 pit_type endPit = to.pit();
1093 pos_type begPos = from.pos();
1094 pos_type endPos = to.pos();
1096 bool const trackChanges = cur.buffer().params().trackChanges;
1098 pos_type right = 0; // needed after the for loop
1100 for (pit_type pit = begPit; pit <= endPit; ++pit) {
1101 pos_type parSize = pars_[pit].size();
1103 pos_type pos = (pit == begPit ? begPos : 0);
1104 right = (pit == endPit ? endPos : parSize);
1106 // process sequences of modified characters; in change
1107 // tracking mode, this approach results in much better
1108 // usability than changing case on a char-by-char basis
1111 bool capitalize = true;
1113 for (; pos < right; ++pos) {
1114 char_type oldChar = pars_[pit].getChar(pos);
1115 char_type newChar = oldChar;
1117 // ignore insets and don't play with deleted text!
1118 if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
1120 case text_lowercase:
1121 newChar = lowercase(oldChar);
1123 case text_capitalization:
1125 newChar = uppercase(oldChar);
1129 case text_uppercase:
1130 newChar = uppercase(oldChar);
1135 if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
1136 capitalize = true; // permit capitalization again
1139 if (oldChar != newChar) {
1143 if (oldChar == newChar || pos == right - 1) {
1144 if (oldChar != newChar) {
1145 pos++; // step behind the changing area
1147 int erasePos = pos - changes.size();
1148 for (size_t i = 0; i < changes.size(); i++) {
1149 pars_[pit].insertChar(pos, changes[i],
1150 pars_[pit].getFontSettings(cur.buffer().params(),
1153 if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
1156 ++right; // expand selection
1164 // the selection may have changed due to logically-only deleted chars
1165 setCursor(cur, begPit, begPos);
1167 setCursor(cur, endPit, right);
1170 checkBufferStructure(cur.buffer(), cur);
1174 bool Text::handleBibitems(Cursor & cur)
1176 if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
1178 // if a bibitem is deleted, merge with previous paragraph
1179 // if this is a bibliography item as well
1180 if (cur.pos() == 0) {
1181 BufferParams const & bufparams = cur.buffer().params();
1182 Paragraph const & par = cur.paragraph();
1183 Cursor prevcur = cur;
1184 if (cur.pit() > 0) {
1186 prevcur.pos() = prevcur.lastpos();
1188 Paragraph const & prevpar = prevcur.paragraph();
1189 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1190 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1191 mergeParagraph(bufparams, cur.text()->paragraphs(),
1193 updateLabels(cur.buffer());
1194 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1195 cur.updateFlags(Update::Force);
1196 // if not, reset the paragraph to default
1198 cur.paragraph().layout(
1199 bufparams.getTextClass().defaultLayout());
1206 bool Text::erase(Cursor & cur)
1208 BOOST_ASSERT(this == cur.text());
1209 bool needsUpdate = false;
1210 Paragraph & par = cur.paragraph();
1212 if (cur.pos() != cur.lastpos()) {
1213 // this is the code for a normal delete, not pasting
1215 recordUndo(cur, Undo::DELETE);
1216 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
1217 // the character has been logically deleted only => skip it
1218 cur.forwardPosNoDescend();
1220 checkBufferStructure(cur.buffer(), cur);
1223 if (cur.pit() == cur.lastpit())
1224 return dissolveInset(cur);
1226 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1227 par.setChange(cur.pos(), Change(Change::DELETED));
1231 setCursorIntern(cur, cur.pit() + 1, 0);
1232 needsUpdate = backspacePos0(cur);
1236 needsUpdate |= handleBibitems(cur);
1239 // Make sure the cursor is correct. Is this really needed?
1240 // No, not really... at least not here!
1241 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1242 checkBufferStructure(cur.buffer(), cur);
1249 bool Text::backspacePos0(Cursor & cur)
1251 BOOST_ASSERT(this == cur.text());
1255 bool needsUpdate = false;
1257 BufferParams const & bufparams = cur.buffer().params();
1258 TextClass const & tclass = bufparams.getTextClass();
1259 ParagraphList & plist = cur.text()->paragraphs();
1260 Paragraph const & par = cur.paragraph();
1261 Cursor prevcur = cur;
1263 prevcur.pos() = prevcur.lastpos();
1264 Paragraph const & prevpar = prevcur.paragraph();
1266 // is it an empty paragraph?
1267 if (cur.lastpos() == 0
1268 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1269 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1270 plist.erase(boost::next(plist.begin(), cur.pit()));
1273 // is previous par empty?
1274 else if (prevcur.lastpos() == 0
1275 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1276 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1277 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1280 // Pasting is not allowed, if the paragraphs have different
1281 // layouts. I think it is a real bug of all other
1282 // word processors to allow it. It confuses the user.
1283 // Correction: Pasting is always allowed with standard-layout
1284 else if (par.layout() == prevpar.layout()
1285 || par.layout() == tclass.defaultLayout()) {
1286 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1287 mergeParagraph(bufparams, plist, prevcur.pit());
1292 updateLabels(cur.buffer());
1293 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1300 bool Text::backspace(Cursor & cur)
1302 BOOST_ASSERT(this == cur.text());
1303 bool needsUpdate = false;
1304 if (cur.pos() == 0) {
1306 return dissolveInset(cur);
1308 Paragraph & prev_par = pars_[cur.pit() - 1];
1310 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1311 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1312 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1315 // The cursor is at the beginning of a paragraph, so
1316 // the backspace will collapse two paragraphs into one.
1317 needsUpdate = backspacePos0(cur);
1320 // this is the code for a normal backspace, not pasting
1322 recordUndo(cur, Undo::DELETE);
1323 // We used to do cursorLeftIntern() here, but it is
1324 // not a good idea since it triggers the auto-delete
1325 // mechanism. So we do a cursorLeftIntern()-lite,
1326 // without the dreaded mechanism. (JMarc)
1327 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1328 false, cur.boundary());
1329 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1330 checkBufferStructure(cur.buffer(), cur);
1333 if (cur.pos() == cur.lastpos())
1334 setCurrentFont(cur);
1336 needsUpdate |= handleBibitems(cur);
1338 // A singlePar update is not enough in this case.
1339 // cur.updateFlags(Update::Force);
1340 setCursor(cur.top(), cur.pit(), cur.pos());
1346 bool Text::dissolveInset(Cursor & cur) {
1347 BOOST_ASSERT(this == cur.text());
1349 if (isMainText(*cur.bv().buffer()) || cur.inset().nargs() != 1)
1352 recordUndoInset(cur);
1353 cur.selHandle(false);
1355 pos_type spos = cur.pos();
1356 pit_type spit = cur.pit();
1357 ParagraphList plist;
1358 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1359 plist = paragraphs();
1361 // store cursor offset
1365 Buffer & b = cur.buffer();
1366 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1367 if (!plist.empty()) {
1368 // ERT paragraphs have the Language latex_language.
1369 // This is invalid outside of ERT, so we need to
1370 // change it to the buffer language.
1371 ParagraphList::iterator it = plist.begin();
1372 ParagraphList::iterator it_end = plist.end();
1373 for (; it != it_end; it++) {
1374 it->changeLanguage(b.params(), latex_language,
1378 pasteParagraphList(cur, plist, b.params().textclass,
1379 b.errorList("Paste"));
1381 cur.pit() = std::min(cur.lastpit(), spit);
1382 cur.pos() = std::min(cur.lastpos(), spos);
1384 cur.clearSelection();
1390 // only used for inset right now. should also be used for main text
1391 void Text::draw(PainterInfo & pi, int x, int y) const
1393 paintTextInset(*this, pi, x, y);
1397 // only used for inset right now. should also be used for main text
1398 void Text::drawSelection(PainterInfo & pi, int x, int) const
1400 Cursor & cur = pi.base.bv->cursor();
1401 if (!cur.selection())
1403 if (!ptr_cmp(cur.text(), this))
1406 LYXERR(Debug::DEBUG)
1407 << BOOST_CURRENT_FUNCTION
1408 << "draw selection at " << x
1411 DocIterator beg = cur.selectionBegin();
1412 DocIterator end = cur.selectionEnd();
1414 BufferView & bv = *pi.base.bv;
1415 Buffer const & buffer = *bv.buffer();
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 Paragraph const & par1 = pars_[beg.pit()];
1423 Paragraph const & par2 = pars_[end.pit()];
1424 TextMetrics const & tm = bv.textMetrics(this);
1425 ParagraphMetrics const & pm1 = tm.parMetrics(beg.pit());
1426 ParagraphMetrics const & pm2 = tm.parMetrics(end.pit());
1428 bool const above = (bv_funcs::status(&bv, beg)
1429 == bv_funcs::CUR_ABOVE);
1430 bool const below = (bv_funcs::status(&bv, end)
1431 == bv_funcs::CUR_BELOW);
1439 Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
1440 y1 = bv_funcs::getPos(bv, beg, beg.boundary()).y_ - row1.ascent();
1441 y2 = y1 + row1.height();
1442 int const startx = cursorX(bv, beg.top(), beg.boundary());
1443 if (!isRTL(buffer, par1)) {
1445 x2 = 0 + tm.width();
1455 Y1 = bv.workHeight();
1456 Y2 = bv.workHeight();
1460 Row const & row2 = pm2.getRow(end.pos(), end.boundary());
1461 Y1 = bv_funcs::getPos(bv, end, end.boundary()).y_ - row2.ascent();
1462 Y2 = Y1 + row2.height();
1463 int const endx = cursorX(bv, end.top(), end.boundary());
1464 if (!isRTL(buffer, par2)) {
1470 X2 = 0 + tm.width();
1474 if (!above && !below && &pm1.getRow(beg.pos(), beg.boundary())
1475 == &pm2.getRow(end.pos(), end.boundary()))
1477 // paint only one rectangle
1478 int const b( !isRTL(*bv.buffer(), par1) ? x + x1 : x + X1 );
1479 int const w( !isRTL(*bv.buffer(), par1) ? X2 - x1 : x2 - X1 );
1480 pi.pain.fillRectangle(b, y1, w, y2 - y1, Color::selection);
1484 LYXERR(Debug::DEBUG) << " y1: " << y1 << " y2: " << y2
1485 << "X1:" << X1 << " x2: " << X2 << " wid: " << tm.width()
1488 // paint upper rectangle
1489 pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
1491 // paint bottom rectangle
1492 pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
1494 // paint center rectangle
1495 pi.pain.fillRectangle(x, y2, tm.width(),
1496 Y1 - y2, Color::selection);
1500 bool Text::isLastRow(pit_type pit, Row const & row) const
1502 return row.endpos() >= pars_[pit].size()
1503 && pit + 1 == pit_type(paragraphs().size());
1507 bool Text::isFirstRow(pit_type pit, Row const & row) const
1509 return row.pos() == 0 && pit == 0;
1513 void Text::getWord(CursorSlice & from, CursorSlice & to,
1514 word_location const loc)
1516 Paragraph const & from_par = pars_[from.pit()];
1518 case WHOLE_WORD_STRICT:
1519 if (from.pos() == 0 || from.pos() == from_par.size()
1520 || !from_par.isLetter(from.pos())
1521 || !from_par.isLetter(from.pos() - 1)) {
1525 // no break here, we go to the next
1528 // If we are already at the beginning of a word, do nothing
1529 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1531 // no break here, we go to the next
1534 // always move the cursor to the beginning of previous word
1535 while (from.pos() && from_par.isLetter(from.pos() - 1))
1539 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1543 // no need to move the 'from' cursor
1547 Paragraph & to_par = pars_[to.pit()];
1548 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1553 void Text::write(Buffer const & buf, std::ostream & os) const
1555 ParagraphList::const_iterator pit = paragraphs().begin();
1556 ParagraphList::const_iterator end = paragraphs().end();
1558 for (; pit != end; ++pit)
1559 pit->write(buf, os, buf.params(), dth);
1563 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1565 depth_type depth = 0;
1567 while (lex.isOK()) {
1569 string const token = lex.getString();
1574 if (token == "\\end_inset")
1577 if (token == "\\end_body")
1580 if (token == "\\begin_body")
1583 if (token == "\\end_document")
1586 if (token == "\\begin_layout") {
1587 lex.pushToken(token);
1590 par.params().depth(depth);
1591 par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1592 pars_.push_back(par);
1594 // FIXME: goddamn InsetTabular makes us pass a Buffer
1596 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1598 } else if (token == "\\begin_deeper") {
1600 } else if (token == "\\end_deeper") {
1602 lex.printError("\\end_deeper: " "depth is already null");
1607 lyxerr << "Handling unknown body token: `"
1608 << token << '\'' << endl;
1614 int Text::cursorX(BufferView const & bv, CursorSlice const & sl,
1615 bool boundary) const
1617 TextMetrics const & tm = bv.textMetrics(sl.text());
1618 pit_type const pit = sl.pit();
1619 Paragraph const & par = pars_[pit];
1620 ParagraphMetrics const & pm = tm.parMetrics(pit);
1621 if (pm.rows().empty())
1624 pos_type ppos = sl.pos();
1625 // Correct position in front of big insets
1626 bool const boundary_correction = ppos != 0 && boundary;
1627 if (boundary_correction)
1630 Row const & row = pm.getRow(sl.pos(), boundary);
1632 pos_type cursor_vpos = 0;
1634 Buffer const & buffer = *bv.buffer();
1635 RowMetrics const m = tm.computeRowMetrics(pit, row);
1638 pos_type const row_pos = row.pos();
1639 pos_type const end = row.endpos();
1642 cursor_vpos = row_pos;
1643 else if (ppos >= end)
1644 cursor_vpos = isRTL(buffer, par) ? row_pos : end;
1645 else if (ppos > row_pos && ppos >= end)
1646 // Place cursor after char at (logical) position pos - 1
1647 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1648 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1650 // Place cursor before char at (logical) position ppos
1651 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1652 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1654 pos_type body_pos = par.beginOfBody();
1656 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1659 // Use font span to speed things up, see below
1662 FontMetrics const & labelfm = theFontMetrics(
1663 getLabelFont(buffer, par));
1665 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1666 pos_type pos = bidi.vis2log(vpos);
1667 if (body_pos > 0 && pos == body_pos - 1) {
1669 docstring const lsep = from_utf8(par.layout()->labelsep);
1670 x += m.label_hfill + labelfm.width(lsep);
1671 if (par.isLineSeparator(body_pos - 1))
1672 x -= singleWidth(buffer, par, body_pos - 1);
1675 // Use font span to speed things up, see above
1676 if (pos < font_span.first || pos > font_span.last) {
1677 font_span = par.fontSpan(pos);
1678 font = getFont(buffer, par, pos);
1681 x += singleWidth(par, pos, par.getChar(pos), font);
1683 if (par.hfillExpansion(row, pos))
1684 x += (pos >= body_pos) ? m.hfill : m.label_hfill;
1685 else if (par.isSeparator(pos) && pos >= body_pos)
1689 // see correction above
1690 if (boundary_correction)
1691 if (getFont(buffer, par, ppos).isVisibleRightToLeft())
1692 x -= singleWidth(buffer, par, ppos);
1694 x += singleWidth(buffer, par, ppos);
1696 // Make sure inside an inset we always count from the left
1697 // edge (bidi!) -- MV
1698 if (sl.pos() < par.size()) {
1699 font = getFont(buffer, par, sl.pos());
1700 if (!boundary && font.isVisibleRightToLeft()
1701 && par.isInset(sl.pos()))
1702 x -= par.getInset(sl.pos())->width();
1708 int Text::cursorY(BufferView const & bv, CursorSlice const & sl, bool boundary) const
1710 //lyxerr << "Text::cursorY: boundary: " << boundary << std::endl;
1711 ParagraphMetrics const & pm = bv.parMetrics(this, sl.pit());
1712 if (pm.rows().empty())
1716 h -= bv.parMetrics(this, 0).rows()[0].ascent();
1717 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1718 h += bv.parMetrics(this, pit).height();
1721 if (pos && boundary)
1723 size_t const rend = pm.pos2row(pos);
1724 for (size_t rit = 0; rit != rend; ++rit)
1725 h += pm.rows()[rit].height();
1726 h += pm.rows()[rend].ascent();
1731 // Returns the current font and depth as a message.
1732 docstring Text::currentState(Cursor & cur)
1734 BOOST_ASSERT(this == cur.text());
1735 Buffer & buf = cur.buffer();
1736 Paragraph const & par = cur.paragraph();
1737 odocstringstream os;
1739 if (buf.params().trackChanges)
1740 os << _("[Change Tracking] ");
1742 Change change = par.lookupChange(cur.pos());
1744 if (change.type != Change::UNCHANGED) {
1745 Author const & a = buf.params().authors().get(change.author);
1746 os << _("Change: ") << a.name();
1747 if (!a.email().empty())
1748 os << " (" << a.email() << ")";
1749 // FIXME ctime is english, we should translate that
1750 os << _(" at ") << ctime(&change.changetime);
1754 // I think we should only show changes from the default
1756 // No, from the document font (MV)
1757 Font font = real_current_font;
1758 font.reduce(buf.params().getFont());
1760 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1762 // The paragraph depth
1763 int depth = cur.paragraph().getDepth();
1765 os << bformat(_(", Depth: %1$d"), depth);
1767 // The paragraph spacing, but only if different from
1769 Spacing const & spacing = par.params().spacing();
1770 if (!spacing.isDefault()) {
1771 os << _(", Spacing: ");
1772 switch (spacing.getSpace()) {
1773 case Spacing::Single:
1776 case Spacing::Onehalf:
1779 case Spacing::Double:
1782 case Spacing::Other:
1783 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1785 case Spacing::Default:
1786 // should never happen, do nothing
1791 #ifdef DEVEL_VERSION
1792 os << _(", Inset: ") << &cur.inset();
1793 os << _(", Paragraph: ") << cur.pit();
1794 os << _(", Id: ") << par.id();
1795 os << _(", Position: ") << cur.pos();
1796 // FIXME: Why is the check for par.size() needed?
1797 // We are called with cur.pos() == par.size() quite often.
1798 if (!par.empty() && cur.pos() < par.size()) {
1799 // Force output of code point, not character
1800 size_t const c = par.getChar(cur.pos());
1801 os << _(", Char: 0x") << std::hex << c;
1803 os << _(", Boundary: ") << cur.boundary();
1804 // Row & row = cur.textRow();
1805 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1811 docstring Text::getPossibleLabel(Cursor & cur) const
1813 pit_type pit = cur.pit();
1815 Layout_ptr layout = pars_[pit].layout();
1818 docstring par_text = pars_[pit].asString(cur.buffer(), false);
1819 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1820 if (par_text.empty())
1823 par_text = split(par_text, head, ' ');
1824 // Is it legal to use spaces in labels ?
1830 // No need for a prefix if the user said so.
1831 if (lyxrc.label_init_length <= 0)
1834 // Will contain the label type.
1837 // For section, subsection, etc...
1838 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1839 Layout_ptr const & layout2 = pars_[pit - 1].layout();
1840 if (layout2->latextype != LATEX_PARAGRAPH) {
1845 if (layout->latextype != LATEX_PARAGRAPH)
1846 name = from_ascii(layout->latexname());
1848 // for captions, we just take the caption type
1849 Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1851 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1853 // If none of the above worked, we'll see if we're inside various
1854 // types of insets and take our abbreviation from them.
1856 Inset::Code const codes[] = {
1861 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1862 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1864 name = float_inset->name();
1870 // Create a correct prefix for prettyref
1871 if (name == "theorem")
1872 name = from_ascii("thm");
1873 else if (name == "Foot")
1874 name = from_ascii("fn");
1875 else if (name == "listing")
1876 name = from_ascii("lst");
1879 text = name.substr(0, 3) + ':' + text;
1885 void Text::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1887 BOOST_ASSERT(this == cur.text());
1888 pit_type pit = getPitNearY(cur.bv(), y);
1890 TextMetrics const & tm = cur.bv().textMetrics(this);
1891 ParagraphMetrics const & pm = tm.parMetrics(pit);
1893 int yy = cur.bv().coordCache().get(this, pit).y_ - pm.ascent();
1894 LYXERR(Debug::DEBUG)
1895 << BOOST_CURRENT_FUNCTION
1899 << " yy: " << yy << endl;
1902 BOOST_ASSERT(pm.rows().size());
1903 for (; r < int(pm.rows().size()) - 1; ++r) {
1904 Row const & row = pm.rows()[r];
1905 if (int(yy + row.height()) > y)
1910 Row const & row = pm.rows()[r];
1912 LYXERR(Debug::DEBUG)
1913 << BOOST_CURRENT_FUNCTION
1915 << " from pos: " << row.pos()
1920 pos_type const pos = row.pos()
1921 + tm.getColumnNearX(pit, row, xx, bound);
1923 LYXERR(Debug::DEBUG)
1924 << BOOST_CURRENT_FUNCTION
1925 << ": setting cursor pit: " << pit
1929 setCursor(cur, pit, pos, true, bound);
1930 // remember new position.
1935 void Text::charsTranspose(Cursor & cur)
1937 BOOST_ASSERT(this == cur.text());
1939 pos_type pos = cur.pos();
1941 // If cursor is at beginning or end of paragraph, do nothing.
1942 if (pos == cur.lastpos() || pos == 0)
1945 Paragraph & par = cur.paragraph();
1947 // Get the positions of the characters to be transposed.
1948 pos_type pos1 = pos - 1;
1949 pos_type pos2 = pos;
1951 // In change tracking mode, ignore deleted characters.
1952 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1954 if (pos2 == cur.lastpos())
1957 while (pos1 >= 0 && par.isDeleted(pos1))
1962 // Don't do anything if one of the "characters" is not regular text.
1963 if (par.isInset(pos1) || par.isInset(pos2))
1966 // Store the characters to be transposed (including font information).
1967 char_type char1 = par.getChar(pos1);
1969 par.getFontSettings(cur.buffer().params(), pos1);
1971 char_type char2 = par.getChar(pos2);
1973 par.getFontSettings(cur.buffer().params(), pos2);
1975 // And finally, we are ready to perform the transposition.
1976 // Track the changes if Change Tracking is enabled.
1977 bool const trackChanges = cur.buffer().params().trackChanges;
1981 par.eraseChar(pos2, trackChanges);
1982 par.eraseChar(pos1, trackChanges);
1983 par.insertChar(pos1, char2, font2, trackChanges);
1984 par.insertChar(pos2, char1, font1, trackChanges);
1986 checkBufferStructure(cur.buffer(), cur);
1988 // After the transposition, move cursor to after the transposition.
1989 setCursor(cur, cur.pit(), pos2);