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"
27 #include "pariterator.h"
28 #include "coordcache.h"
29 #include "CutAndPaste.h"
31 #include "dispatchresult.h"
33 #include "errorlist.h"
34 #include "funcrequest.h"
36 #include "FontIterator.h"
40 #include "lyxlength.h"
44 #include "metricsinfo.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "rowpainter.h"
51 #include "WordLangTuple.h"
53 #include "frontends/FontMetrics.h"
54 #include "frontends/Painter.h"
56 #include "insets/insettext.h"
57 #include "insets/insetbibitem.h"
58 #include "insets/insethfill.h"
59 #include "insets/insetlatexaccent.h"
60 #include "insets/insetline.h"
61 #include "insets/insetnewline.h"
62 #include "insets/insetpagebreak.h"
63 #include "insets/insetoptarg.h"
64 #include "insets/insetspace.h"
65 #include "insets/insetspecialchar.h"
66 #include "insets/insettabular.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
70 #include "support/convert.h"
72 #include <boost/current_function.hpp>
79 using support::bformat;
80 using support::contains;
81 using support::lowercase;
83 using support::uppercase;
85 using cap::cutSelection;
86 using cap::pasteParagraphList;
88 using frontend::FontMetrics;
101 int numberOfSeparators(Paragraph const & par, Row const & row)
103 pos_type const first = max(row.pos(), par.beginOfBody());
104 pos_type const last = row.endpos() - 1;
106 for (pos_type p = first; p < last; ++p) {
107 if (par.isSeparator(p))
114 int numberOfLabelHfills(Paragraph const & par, Row const & row)
116 pos_type last = row.endpos() - 1;
117 pos_type first = row.pos();
119 // hfill *DO* count at the beginning of paragraphs!
121 while (first < last && par.isHfill(first))
125 last = min(last, par.beginOfBody());
127 for (pos_type p = first; p < last; ++p) {
135 int numberOfHfills(Paragraph const & par, Row const & row)
137 pos_type const last = row.endpos();
138 pos_type first = row.pos();
140 // hfill *DO* count at the beginning of paragraphs!
142 while (first < last && par.isHfill(first))
146 first = max(first, par.beginOfBody());
149 for (pos_type p = first; p < last; ++p) {
157 void readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
158 string const & token, LyXFont & font, Change & change, ErrorList & errorList)
160 BufferParams const & bp = buf.params();
162 if (token[0] != '\\') {
164 string::const_iterator cit = token.begin();
165 for (; cit != token.end(); ++cit)
166 par.insertChar(par.size(), (*cit), font, change);
168 docstring dstr = lex.getDocString();
169 docstring::const_iterator cit = dstr.begin();
170 docstring::const_iterator cend = dstr.end();
171 for (; cit != cend; ++cit)
172 par.insertChar(par.size(), *cit, font, change);
174 } else if (token == "\\begin_layout") {
176 string layoutname = lex.getString();
178 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
179 change = Change(Change::UNCHANGED);
181 LyXTextClass const & tclass = bp.getLyXTextClass();
183 if (layoutname.empty()) {
184 layoutname = tclass.defaultLayoutName();
187 bool hasLayout = tclass.hasLayout(layoutname);
190 errorList.push_back(ErrorItem(_("Unknown layout"),
191 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
192 from_utf8(layoutname), from_utf8(tclass.name())), par.id(), 0, par.size()));
193 layoutname = tclass.defaultLayoutName();
196 par.layout(bp.getLyXTextClass()[layoutname]);
198 // Test whether the layout is obsolete.
199 LyXLayout_ptr const & layout = par.layout();
200 if (!layout->obsoleted_by().empty())
201 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
203 par.params().read(lex);
205 } else if (token == "\\end_layout") {
206 lyxerr << BOOST_CURRENT_FUNCTION
207 << ": Solitary \\end_layout in line "
208 << lex.getLineNo() << "\n"
209 << "Missing \\begin_layout?.\n";
210 } else if (token == "\\end_inset") {
211 lyxerr << BOOST_CURRENT_FUNCTION
212 << ": Solitary \\end_inset in line "
213 << lex.getLineNo() << "\n"
214 << "Missing \\begin_inset?.\n";
215 } else if (token == "\\begin_inset") {
216 InsetBase * inset = readInset(lex, buf);
218 par.insertInset(par.size(), inset, font, change);
221 docstring line = from_utf8(lex.getString());
222 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
223 par.id(), 0, par.size()));
225 } else if (token == "\\family") {
227 font.setLyXFamily(lex.getString());
228 } else if (token == "\\series") {
230 font.setLyXSeries(lex.getString());
231 } else if (token == "\\shape") {
233 font.setLyXShape(lex.getString());
234 } else if (token == "\\size") {
236 font.setLyXSize(lex.getString());
237 } else if (token == "\\lang") {
239 string const tok = lex.getString();
240 Language const * lang = languages.getLanguage(tok);
242 font.setLanguage(lang);
244 font.setLanguage(bp.language);
245 lex.printError("Unknown language `$$Token'");
247 } else if (token == "\\numeric") {
249 font.setNumber(font.setLyXMisc(lex.getString()));
250 } else if (token == "\\emph") {
252 font.setEmph(font.setLyXMisc(lex.getString()));
253 } else if (token == "\\bar") {
255 string const tok = lex.getString();
258 font.setUnderbar(LyXFont::ON);
259 else if (tok == "no")
260 font.setUnderbar(LyXFont::OFF);
261 else if (tok == "default")
262 font.setUnderbar(LyXFont::INHERIT);
264 lex.printError("Unknown bar font flag "
266 } else if (token == "\\noun") {
268 font.setNoun(font.setLyXMisc(lex.getString()));
269 } else if (token == "\\color") {
271 font.setLyXColor(lex.getString());
272 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
274 // Insets don't make sense in a free-spacing context! ---Kayvan
275 if (par.isFreeSpacing()) {
276 if (token == "\\InsetSpace")
277 par.insertChar(par.size(), ' ', font, change);
278 else if (lex.isOK()) {
280 string const next_token = lex.getString();
281 if (next_token == "\\-")
282 par.insertChar(par.size(), '-', font, change);
284 lex.printError("Token `$$Token' "
286 "paragraph layout!");
290 auto_ptr<InsetBase> inset;
291 if (token == "\\SpecialChar" )
292 inset.reset(new InsetSpecialChar);
294 inset.reset(new InsetSpace);
295 inset->read(buf, lex);
296 par.insertInset(par.size(), inset.release(),
299 } else if (token == "\\i") {
300 auto_ptr<InsetBase> inset(new InsetLatexAccent);
301 inset->read(buf, lex);
302 par.insertInset(par.size(), inset.release(), font, change);
303 } else if (token == "\\backslash") {
304 par.insertChar(par.size(), '\\', font, change);
305 } else if (token == "\\newline") {
306 auto_ptr<InsetBase> inset(new InsetNewline);
307 inset->read(buf, lex);
308 par.insertInset(par.size(), inset.release(), font, change);
309 } else if (token == "\\LyXTable") {
310 auto_ptr<InsetBase> inset(new InsetTabular(buf));
311 inset->read(buf, lex);
312 par.insertInset(par.size(), inset.release(), font, change);
313 } else if (token == "\\hfill") {
314 par.insertInset(par.size(), new InsetHFill, font, change);
315 } else if (token == "\\lyxline") {
316 par.insertInset(par.size(), new InsetLine, font, change);
317 } else if (token == "\\newpage") {
318 par.insertInset(par.size(), new InsetPagebreak, font, change);
319 } else if (token == "\\change_unchanged") {
320 // Hack ! Needed for empty paragraphs :/
321 // FIXME: change tracking (MG)
322 // set empty 'par' to INSERTED???
323 change = Change(Change::UNCHANGED);
324 } else if (token == "\\change_inserted") {
326 std::istringstream is(lex.getString());
330 if (aid >= bp.author_map.size()) {
331 errorList.push_back(ErrorItem(_("Change tracking error"),
332 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
333 par.id(), 0, par.size()));
334 change = Change(Change::UNCHANGED);
336 change = Change(Change::INSERTED, bp.author_map[aid], ct);
337 } else if (token == "\\change_deleted") {
339 std::istringstream is(lex.getString());
343 if (aid >= bp.author_map.size()) {
344 errorList.push_back(ErrorItem(_("Change tracking error"),
345 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
346 par.id(), 0, par.size()));
347 change = Change(Change::UNCHANGED);
349 change = Change(Change::DELETED, bp.author_map[aid], ct);
352 errorList.push_back(ErrorItem(_("Unknown token"),
353 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
354 from_utf8(lex.getString())),
355 par.id(), 0, par.size()));
360 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex,
361 ErrorList & errorList)
364 string token = lex.getString();
366 Change change(Change::UNCHANGED);
369 readParToken(buf, par, lex, token, font, change, errorList);
372 token = lex.getString();
377 if (token == "\\end_layout") {
378 //Ok, paragraph finished
382 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
383 << token << '\'' << endl;
384 if (token == "\\begin_layout" || token == "\\end_document"
385 || token == "\\end_inset" || token == "\\begin_deeper"
386 || token == "\\end_deeper") {
387 lex.pushToken(token);
388 lyxerr << "Paragraph ended in line "
389 << lex.getLineNo() << "\n"
390 << "Missing \\end_layout.\n";
394 // Final change goes to paragraph break:
395 par.setChange(par.size(), change);
397 // Initialize begin_of_body_ on load; redoParagraph maintains
398 par.setBeginOfBody();
406 BufferView * LyXText::bv() const
408 BOOST_ASSERT(bv_owner != 0);
413 double LyXText::spacing(Paragraph const & par) const
415 if (par.params().spacing().isDefault())
416 return bv()->buffer()->params().spacing().getValue();
417 return par.params().spacing().getValue();
421 int LyXText::width() const
427 int LyXText::height() const
429 return dim_.height();
433 int LyXText::singleWidth(Paragraph const & par, pos_type pos) const
435 return singleWidth(par, pos, par.getChar(pos), getFont(par, pos));
439 int LyXText::singleWidth(Paragraph const & par,
440 pos_type pos, char_type c, LyXFont const & font) const
442 // The most common case is handled first (Asger)
443 if (isPrintable(c)) {
444 Language const * language = font.language();
445 if (language->rightToLeft()) {
446 if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
447 lyxrc.font_norm_type == LyXRC::ISO_10646_1)
448 && language->lang() == "arabic") {
449 if (Encodings::isComposeChar_arabic(c))
451 c = par.transformChar(c, pos);
452 } else if (language->lang() == "hebrew" &&
453 Encodings::isComposeChar_hebrew(c))
456 return theFontMetrics(font).width(c);
459 if (c == Paragraph::META_INSET)
460 return par.getInset(pos)->width();
462 return theFontMetrics(font).width(c);
466 int LyXText::leftMargin(pit_type pit) const
468 BOOST_ASSERT(pit >= 0);
469 BOOST_ASSERT(pit < int(pars_.size()));
470 return leftMargin(pit, pars_[pit].size());
474 int LyXText::leftMargin(pit_type const pit, pos_type const pos) const
476 BOOST_ASSERT(pit >= 0);
477 BOOST_ASSERT(pit < int(pars_.size()));
478 Paragraph const & par = pars_[pit];
479 BOOST_ASSERT(pos >= 0);
480 BOOST_ASSERT(pos <= par.size());
481 //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
482 BufferParams const & params = bv()->buffer()->params();
483 LyXTextClass const & tclass = params.getLyXTextClass();
484 LyXLayout_ptr const & layout = par.layout();
486 string parindent = layout->parindent;
491 l_margin += changebarMargin();
494 docstring leftm = from_utf8(tclass.leftmargin());
495 l_margin += theFontMetrics(params.getFont()).signedWidth(leftm);
497 if (par.getDepth() != 0) {
498 // find the next level paragraph
499 pit_type newpar = outerHook(pit, pars_);
500 if (newpar != pit_type(pars_.size())) {
501 if (pars_[newpar].layout()->isEnvironment()) {
502 l_margin = leftMargin(newpar);
504 if (par.layout() == tclass.defaultLayout()) {
505 if (pars_[newpar].params().noindent())
508 parindent = pars_[newpar].layout()->parindent;
513 // This happens after sections in standard classes. The 1.3.x
514 // code compared depths too, but it does not seem necessary
516 if (par.layout() == tclass.defaultLayout()
517 && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
520 LyXFont const labelfont = getLabelFont(par);
521 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
523 switch (layout->margintype) {
525 if (!layout->leftmargin.empty()) {
527 docstring leftm = from_utf8(layout->leftmargin);
528 l_margin += theFontMetrics(params.getFont()).signedWidth(leftm);
530 if (!par.getLabelstring().empty()) {
532 docstring labin = from_utf8(layout->labelindent);
533 l_margin += labelfont_metrics.signedWidth(labin);
534 docstring labstr = par.getLabelstring();
535 l_margin += labelfont_metrics.width(labstr);
536 docstring labsep = from_utf8(layout->labelsep);
537 l_margin += labelfont_metrics.width(labsep);
541 case MARGIN_MANUAL: {
543 docstring labin = from_utf8(layout->labelindent);
544 l_margin += labelfont_metrics.signedWidth(labin);
545 // The width of an empty par, even with manual label, should be 0
546 if (!par.empty() && pos >= par.beginOfBody()) {
547 if (!par.getLabelWidthString().empty()) {
548 docstring labstr = par.getLabelWidthString();
549 l_margin += labelfont_metrics.width(labstr);
550 docstring labsep = from_utf8(layout->labelsep);
551 l_margin += labelfont_metrics.width(labsep);
557 case MARGIN_STATIC: {
559 docstring leftm = from_utf8(layout->leftmargin);
560 l_margin += theFontMetrics(params.getFont()).signedWidth(leftm)
561 * 4 / (par.getDepth() + 4);
565 case MARGIN_FIRST_DYNAMIC:
566 if (layout->labeltype == LABEL_MANUAL) {
567 if (pos >= par.beginOfBody()) {
569 l_margin += labelfont_metrics.signedWidth(
570 from_utf8(layout->leftmargin));
573 l_margin += labelfont_metrics.signedWidth(
574 from_utf8(layout->labelindent));
577 // Special case to fix problems with
579 || (layout->labeltype == LABEL_STATIC
580 && layout->latextype == LATEX_ENVIRONMENT
581 && !isFirstInSequence(pit, pars_))) {
583 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->leftmargin));
584 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
585 && layout->labeltype != LABEL_BIBLIO
586 && layout->labeltype !=
587 LABEL_CENTERED_TOP_ENVIRONMENT) {
588 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->labelindent));
589 l_margin += labelfont_metrics.width(from_utf8(layout->labelsep));
590 l_margin += labelfont_metrics.width(par.getLabelstring());
594 case MARGIN_RIGHT_ADDRESS_BOX: {
596 // ok, a terrible hack. The left margin depends on the widest
597 // row in this paragraph.
598 RowList::iterator rit = par.rows().begin();
599 RowList::iterator end = par.rows().end();
601 #warning This is wrong.
603 int minfill = maxwidth_;
604 for ( ; rit != end; ++rit)
605 if (rit->fill() < minfill)
606 minfill = rit->fill();
607 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
610 // also wrong, but much shorter.
611 l_margin += maxwidth_ / 2;
616 if (!par.params().leftIndent().zero())
617 l_margin += par.params().leftIndent().inPixels(maxwidth_);
621 if (par.params().align() == LYX_ALIGN_LAYOUT)
622 align = layout->align;
624 align = par.params().align();
626 // set the correct parindent
628 && (layout->labeltype == LABEL_NO_LABEL
629 || layout->labeltype == LABEL_TOP_ENVIRONMENT
630 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
631 || (layout->labeltype == LABEL_STATIC
632 && layout->latextype == LATEX_ENVIRONMENT
633 && !isFirstInSequence(pit, pars_)))
634 && align == LYX_ALIGN_BLOCK
635 && !par.params().noindent()
636 // in some insets, paragraphs are never indented
637 && !(par.inInset() && par.inInset()->neverIndent())
638 // display style insets are always centered, omit indentation
641 && par.getInset(pos)->display())
642 && (par.layout() != tclass.defaultLayout()
643 || bv()->buffer()->params().paragraph_separation ==
644 BufferParams::PARSEP_INDENT))
646 docstring din = from_utf8(parindent);
647 l_margin += theFontMetrics(params.getFont()).signedWidth(din);
654 int LyXText::rightMargin(Paragraph const & par) const
656 // FIXME: the correct way is to only call rightMargin() only
657 // within the main LyXText. The following test is thus bogus.
658 LyXText const & text = bv()->buffer()->text();
659 // We do not want rightmargins on inner texts.
663 BufferParams const & params = bv()->buffer()->params();
664 LyXTextClass const & tclass = params.getLyXTextClass();
665 docstring trmarg = from_utf8(tclass.rightmargin());
666 docstring lrmarg = from_utf8(par.layout()->rightmargin);
667 FontMetrics const & fm = theFontMetrics(params.getFont());
670 + fm.signedWidth(trmarg)
671 + fm.signedWidth(lrmarg)
672 * 4 / (par.getDepth() + 4);
678 int LyXText::labelEnd(pit_type const pit) const
680 // labelEnd is only needed if the layout fills a flushleft label.
681 if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
683 // return the beginning of the body
684 return leftMargin(pit);
690 // this needs special handling - only newlines count as a break point
691 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
693 pos_type const end = par.size();
696 if (par.isNewline(i))
705 void LyXText::rowBreakPoint(pit_type const pit, Row & row) const
707 Paragraph const & par = pars_[pit];
708 pos_type const end = par.size();
709 pos_type const pos = row.pos();
715 // maximum pixel width of a row
716 int width = maxwidth_ - rightMargin(par); // - leftMargin(pit, row);
722 LyXLayout_ptr const & layout = par.layout();
724 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
725 row.endpos(addressBreakPoint(pos, par));
729 pos_type const body_pos = par.beginOfBody();
732 // Now we iterate through until we reach the right margin
733 // or the end of the par, then choose the possible break
736 int const left = leftMargin(pit, pos);
739 // pixel width since last breakpoint
742 FontIterator fi = FontIterator(*this, par, pos);
743 pos_type point = end;
745 FontMetrics const & fm = theFontMetrics(getLabelFont(par));
746 for ( ; i < end; ++i, ++fi) {
747 char_type const c = par.getChar(i);
748 int thiswidth = singleWidth(par, i, c, *fi);
750 // add the auto-hfill from label end to the body
751 if (body_pos && i == body_pos) {
752 docstring lsep = from_utf8(layout->labelsep);
753 int add = fm.width(lsep);
754 if (par.isLineSeparator(i - 1))
755 add -= singleWidth(par, i - 1);
757 add = std::max(add, labelEnd(pit) - x);
762 chunkwidth += thiswidth;
764 // break before a character that will fall off
765 // the right of the row
767 // if no break before, break here
768 if (point == end || chunkwidth >= width - left) {
775 // exit on last registered breakpoint:
779 if (par.isNewline(i)) {
785 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
790 if (par.isInset(i) && par.getInset(i)->display()) {
796 if (!par.isInset(i) || par.getInset(i)->isChar()) {
797 // some insets are line separators too
798 if (par.isLineSeparator(i)) {
799 // register breakpoint:
806 // maybe found one, but the par is short enough.
807 if (i == end && x < width)
810 // manual labels cannot be broken in LaTeX. But we
811 // want to make our on-screen rendering of footnotes
813 if (body_pos && point < body_pos)
820 void LyXText::setRowWidth(pit_type const pit, Row & row) const
822 // get the pure distance
823 pos_type const end = row.endpos();
825 Paragraph const & par = pars_[pit];
826 docstring const labelsep = from_utf8(par.layout()->labelsep);
827 int w = leftMargin(pit, row.pos());
829 pos_type const body_pos = par.beginOfBody();
830 pos_type i = row.pos();
832 FontMetrics const & fm = theFontMetrics(getLabelFont(par));
835 FontIterator fi = FontIterator(*this, par, i);
836 for ( ; i < end; ++i, ++fi) {
837 if (body_pos > 0 && i == body_pos) {
838 w += fm.width(labelsep);
839 if (par.isLineSeparator(i - 1))
840 w -= singleWidth(par, i - 1);
841 w = max(w, labelEnd(pit));
843 char_type const c = par.getChar(i);
844 w += singleWidth(par, i, c, *fi);
848 if (body_pos > 0 && body_pos >= end) {
849 w += fm.width(labelsep);
850 if (end > 0 && par.isLineSeparator(end - 1))
851 w -= singleWidth(par, end - 1);
852 w = max(w, labelEnd(pit));
855 row.width(w + rightMargin(par));
859 // returns the minimum space a manual label needs on the screen in pixel
860 int LyXText::labelFill(Paragraph const & par, Row const & row) const
862 pos_type last = par.beginOfBody();
864 BOOST_ASSERT(last > 0);
866 // -1 because a label ends with a space that is in the label
869 // a separator at this end does not count
870 if (par.isLineSeparator(last))
874 for (pos_type i = row.pos(); i <= last; ++i)
875 w += singleWidth(par, i);
877 docstring const & label = par.params().labelWidthString();
881 FontMetrics const & fm = theFontMetrics(getLabelFont(par));
883 return max(0, fm.width(label) - w);
887 LColor_color LyXText::backgroundColor() const
889 return LColor_color(LColor::color(background_color_));
893 void LyXText::setHeightOfRow(pit_type const pit, Row & row)
895 Paragraph const & par = pars_[pit];
896 // get the maximum ascent and the maximum descent
897 double layoutasc = 0;
898 double layoutdesc = 0;
899 double const dh = defaultRowHeight();
901 // ok, let us initialize the maxasc and maxdesc value.
902 // Only the fontsize count. The other properties
903 // are taken from the layoutfont. Nicer on the screen :)
904 LyXLayout_ptr const & layout = par.layout();
906 // as max get the first character of this row then it can
907 // increase but not decrease the height. Just some point to
908 // start with so we don't have to do the assignment below too
910 LyXFont font = getFont(par, row.pos());
911 LyXFont::FONT_SIZE const tmpsize = font.size();
912 font = getLayoutFont(pit);
913 LyXFont::FONT_SIZE const size = font.size();
914 font.setSize(tmpsize);
916 LyXFont labelfont = getLabelFont(par);
918 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
919 FontMetrics const & fontmetrics = theFontMetrics(font);
921 // these are minimum values
922 double const spacing_val = layout->spacing.getValue() * spacing(par);
923 //lyxerr << "spacing_val = " << spacing_val << endl;
924 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
925 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
927 // insets may be taller
928 InsetList::const_iterator ii = par.insetlist.begin();
929 InsetList::const_iterator iend = par.insetlist.end();
930 for ( ; ii != iend; ++ii) {
931 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
932 maxasc = max(maxasc, ii->inset->ascent());
933 maxdesc = max(maxdesc, ii->inset->descent());
937 // Check if any custom fonts are larger (Asger)
938 // This is not completely correct, but we can live with the small,
939 // cosmetic error for now.
941 pos_type const pos_end = row.endpos();
943 LyXFont::FONT_SIZE maxsize =
944 par.highestFontInRange(row.pos(), pos_end, size);
945 if (maxsize > font.size()) {
946 font.setSize(maxsize);
947 maxasc = max(maxasc, fontmetrics.maxAscent());
948 maxdesc = max(maxdesc, fontmetrics.maxDescent());
951 // This is nicer with box insets:
958 if (row.pos() == 0) {
959 BufferParams const & bufparams = bv()->buffer()->params();
960 // some parksips VERY EASY IMPLEMENTATION
961 if (bv()->buffer()->params().paragraph_separation
962 == BufferParams::PARSEP_SKIP
964 && ((layout->isParagraph() && par.getDepth() == 0)
965 || (pars_[pit - 1].layout()->isParagraph()
966 && pars_[pit - 1].getDepth() == 0)))
968 maxasc += bufparams.getDefSkip().inPixels(*bv());
971 if (par.params().startOfAppendix())
972 maxasc += int(3 * dh);
974 // This is special code for the chapter, since the label of this
975 // layout is printed in an extra row
976 if (layout->counter == "chapter"
977 && !par.params().labelString().empty()) {
978 labeladdon = int(labelfont_metrics.maxHeight()
979 * layout->spacing.getValue()
983 // special code for the top label
984 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
985 || layout->labeltype == LABEL_BIBLIO
986 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
987 && isFirstInSequence(pit, paragraphs())
988 && !par.getLabelstring().empty())
991 labelfont_metrics.maxHeight()
992 * layout->spacing.getValue()
994 + (layout->topsep + layout->labelbottomsep) * dh);
997 // Add the layout spaces, for example before and after
998 // a section, or between the items of a itemize or enumerate
1001 pit_type prev = depthHook(pit, pars_, par.getDepth());
1003 && pars_[prev].layout() == layout
1004 && pars_[prev].getDepth() == par.getDepth()
1005 && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
1007 layoutasc = layout->itemsep * dh;
1008 } else if (pit != 0 || row.pos() != 0) {
1009 if (layout->topsep > 0)
1010 layoutasc = layout->topsep * dh;
1013 prev = outerHook(pit, pars_);
1014 if (prev != pit_type(pars_.size())) {
1015 maxasc += int(pars_[prev].layout()->parsep * dh);
1016 } else if (pit != 0) {
1017 if (pars_[pit - 1].getDepth() != 0 ||
1018 pars_[pit - 1].layout() == layout) {
1019 maxasc += int(layout->parsep * dh);
1024 // is it a bottom line?
1025 if (row.endpos() >= par.size()) {
1026 // add the layout spaces, for example before and after
1027 // a section, or between the items of a itemize or enumerate
1029 pit_type nextpit = pit + 1;
1030 if (nextpit != pit_type(pars_.size())) {
1031 pit_type cpit = pit;
1035 if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
1036 usual = pars_[cpit].layout()->bottomsep * dh;
1037 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
1038 if (pars_[cpit].layout() != pars_[nextpit].layout()
1039 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1041 unusual = pars_[cpit].layout()->bottomsep * dh;
1043 layoutdesc = max(unusual, usual);
1044 } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
1045 if (pars_[cpit].layout() != pars_[nextpit].layout()
1046 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1047 layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
1052 // incalculate the layout spaces
1053 maxasc += int(layoutasc * 2 / (2 + pars_[pit].getDepth()));
1054 maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
1056 // FIXME: the correct way is to do the following is to move the
1057 // following code in another method specially tailored for the
1058 // main LyXText. The following test is thus bogus.
1059 LyXText const & text = bv_owner->buffer()->text();
1060 // Top and bottom margin of the document (only at top-level)
1061 if (&text == this) {
1062 if (pit == 0 && row.pos() == 0)
1064 if (pit + 1 == pit_type(pars_.size()) &&
1065 row.endpos() == par.size())
1069 row.ascent(maxasc + labeladdon);
1070 row.descent(maxdesc);
1078 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1080 BOOST_ASSERT(this == cur.text());
1082 Paragraph & cpar = cur.paragraph();
1083 pit_type cpit = cur.pit();
1085 LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1086 LyXLayout_ptr const & layout = cpar.layout();
1088 // this is only allowed, if the current paragraph is not empty
1089 // or caption and if it has not the keepempty flag active
1090 if (cur.lastpos() == 0 && !cpar.allowEmpty()
1091 && layout->labeltype != LABEL_SENSITIVE)
1094 // a layout change may affect also the following paragraph
1095 recUndo(cur.pit(), undoSpan(cur.pit()) - 1);
1097 // Always break behind a space
1098 // It is better to erase the space (Dekel)
1099 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1100 // FIXME: change tracking (MG)
1101 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1103 // How should the layout for the new paragraph be?
1104 int preserve_layout = 0;
1106 preserve_layout = 2;
1108 preserve_layout = layout->isEnvironment();
1110 // We need to remember this before we break the paragraph, because
1111 // that invalidates the layout variable
1112 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1114 // we need to set this before we insert the paragraph.
1115 bool const isempty = cpar.allowEmpty() && cpar.empty();
1117 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1118 cur.pos(), preserve_layout);
1120 // After this, neither paragraph contains any rows!
1123 pit_type next_par = cpit + 1;
1125 // well this is the caption hack since one caption is really enough
1128 // set to standard-layout
1129 pars_[cpit].applyLayout(tclass.defaultLayout());
1131 // set to standard-layout
1132 pars_[next_par].applyLayout(tclass.defaultLayout());
1135 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1136 // FIXME: change tracking (MG)
1137 pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges);
1139 ParIterator current_it(cur);
1140 ParIterator last_it(cur);
1144 updateLabels(cur.buffer(), current_it, last_it);
1146 // Mark "carriage return" as inserted if change tracking:
1147 if (cur.buffer().params().trackChanges) {
1148 // FIXME: Change tracking (MG)
1149 cur.paragraph().setChange(cur.paragraph().size(),
1150 Change(Change::INSERTED));
1153 // This check is necessary. Otherwise the new empty paragraph will
1154 // be deleted automatically. And it is more friendly for the user!
1155 if (cur.pos() != 0 || isempty)
1156 setCursor(cur, cur.pit() + 1, 0);
1158 setCursor(cur, cur.pit(), 0);
1162 // insert a character, moves all the following breaks in the
1163 // same Paragraph one to the right and make a rebreak
1164 void LyXText::insertChar(LCursor & cur, char_type c)
1166 BOOST_ASSERT(this == cur.text());
1167 BOOST_ASSERT(c != Paragraph::META_INSET);
1169 recordUndo(cur, Undo::INSERT);
1171 Paragraph & par = cur.paragraph();
1172 // try to remove this
1173 pit_type const pit = cur.pit();
1175 bool const freeSpacing = par.layout()->free_spacing ||
1176 par.isFreeSpacing();
1178 if (lyxrc.auto_number) {
1179 static docstring const number_operators = from_ascii("+-/*");
1180 static docstring const number_unary_operators = from_ascii("+-");
1181 static docstring const number_seperators = from_ascii(".,:");
1183 if (current_font.number() == LyXFont::ON) {
1184 if (!isDigit(c) && !contains(number_operators, c) &&
1185 !(contains(number_seperators, c) &&
1187 cur.pos() != cur.lastpos() &&
1188 getFont(par, cur.pos()).number() == LyXFont::ON &&
1189 getFont(par, cur.pos() - 1).number() == LyXFont::ON)
1191 number(cur); // Set current_font.number to OFF
1192 } else if (isDigit(c) &&
1193 real_current_font.isVisibleRightToLeft()) {
1194 number(cur); // Set current_font.number to ON
1196 if (cur.pos() != 0) {
1197 char_type const c = par.getChar(cur.pos() - 1);
1198 if (contains(number_unary_operators, c) &&
1200 || par.isSeparator(cur.pos() - 2)
1201 || par.isNewline(cur.pos() - 2))
1203 setCharFont(pit, cur.pos() - 1, current_font);
1204 } else if (contains(number_seperators, c)
1206 && getFont(par, cur.pos() - 2).number() == LyXFont::ON) {
1207 setCharFont(pit, cur.pos() - 1, current_font);
1213 // First check, if there will be two blanks together or a blank at
1214 // the beginning of a paragraph.
1215 // I decided to handle blanks like normal characters, the main
1216 // difference are the special checks when calculating the row.fill
1217 // (blank does not count at the end of a row) and the check here
1219 // When the free-spacing option is set for the current layout,
1220 // disable the double-space checking
1221 if (!freeSpacing && isLineSeparatorChar(c)) {
1222 if (cur.pos() == 0) {
1223 static bool sent_space_message = false;
1224 if (!sent_space_message) {
1225 cur.message(_("You cannot insert a space at the "
1226 "beginning of a paragraph. Please read the Tutorial."));
1227 sent_space_message = true;
1231 BOOST_ASSERT(cur.pos() > 0);
1232 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
1233 && !par.isDeleted(cur.pos() - 1)) {
1234 static bool sent_space_message = false;
1235 if (!sent_space_message) {
1236 cur.message(_("You cannot type two spaces this way. "
1237 "Please read the Tutorial."));
1238 sent_space_message = true;
1244 par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
1245 setCursor(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1250 void LyXText::charInserted()
1252 // Here we call finishUndo for every 20 characters inserted.
1253 // This is from my experience how emacs does it. (Lgb)
1254 static unsigned int counter;
1265 LyXText::computeRowMetrics(pit_type const pit, Row const & row) const
1268 Paragraph const & par = pars_[pit];
1270 double w = dim_.wid - row.width();
1272 bool const is_rtl = isRTL(par);
1274 result.x = rightMargin(par);
1276 result.x = leftMargin(pit, row.pos());
1278 // is there a manual margin with a manual label
1279 LyXLayout_ptr const & layout = par.layout();
1281 if (layout->margintype == MARGIN_MANUAL
1282 && layout->labeltype == LABEL_MANUAL) {
1283 /// We might have real hfills in the label part
1284 int nlh = numberOfLabelHfills(par, row);
1286 // A manual label par (e.g. List) has an auto-hfill
1287 // between the label text and the body of the
1289 // But we don't want to do this auto hfill if the par
1294 if (nlh && !par.getLabelWidthString().empty())
1295 result.label_hfill = labelFill(par, row) / double(nlh);
1298 // are there any hfills in the row?
1299 int const nh = numberOfHfills(par, row);
1303 result.hfill = w / nh;
1304 // we don't have to look at the alignment if it is ALIGN_LEFT and
1305 // if the row is already larger then the permitted width as then
1306 // we force the LEFT_ALIGN'edness!
1307 } else if (int(row.width()) < maxwidth_) {
1308 // is it block, flushleft or flushright?
1309 // set x how you need it
1311 if (par.params().align() == LYX_ALIGN_LAYOUT)
1312 align = layout->align;
1314 align = par.params().align();
1316 // Display-style insets should always be on a centred row
1317 // The test on par.size() is to catch zero-size pars, which
1318 // would trigger the assert in Paragraph::getInset().
1319 //inset = par.size() ? par.getInset(row.pos()) : 0;
1321 && par.isInset(row.pos())
1322 && par.getInset(row.pos())->display())
1324 align = LYX_ALIGN_CENTER;
1328 case LYX_ALIGN_BLOCK: {
1329 int const ns = numberOfSeparators(par, row);
1330 bool disp_inset = false;
1331 if (row.endpos() < par.size()) {
1332 InsetBase const * in = par.getInset(row.endpos());
1334 disp_inset = in->display();
1336 // If we have separators, this is not the last row of a
1337 // par, does not end in newline, and is not row above a
1338 // display inset... then stretch it
1340 && row.endpos() < par.size()
1341 && !par.isNewline(row.endpos() - 1)
1344 result.separator = w / ns;
1345 } else if (is_rtl) {
1350 case LYX_ALIGN_RIGHT:
1353 case LYX_ALIGN_CENTER:
1359 bidi.computeTables(par, *bv()->buffer(), row);
1361 pos_type body_pos = par.beginOfBody();
1362 pos_type end = row.endpos();
1365 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1367 docstring const lsep = from_utf8(layout->labelsep);
1368 result.x += theFontMetrics(getLabelFont(par)).width(lsep);
1369 if (body_pos <= end)
1370 result.x += result.label_hfill;
1378 // the cursor set functions have a special mechanism. When they
1379 // realize, that you left an empty paragraph, they will delete it.
1381 bool LyXText::cursorRightOneWord(LCursor & cur)
1383 BOOST_ASSERT(this == cur.text());
1387 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1391 // Advance through word.
1392 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1394 // Skip through trailing nonword stuff.
1395 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1398 return setCursor(cur, old.pit(), old.pos());
1402 bool LyXText::cursorLeftOneWord(LCursor & cur)
1404 BOOST_ASSERT(this == cur.text());
1408 if (old.pos() == 0 && old.pit() != 0) {
1410 old.pos() = old.lastpos();
1412 // Skip through initial nonword stuff.
1413 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
1415 // Advance through word.
1416 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
1419 return setCursor(cur, old.pit(), old.pos());
1423 void LyXText::selectWord(LCursor & cur, word_location loc)
1425 BOOST_ASSERT(this == cur.text());
1426 CursorSlice from = cur.top();
1427 CursorSlice to = cur.top();
1428 getWord(from, to, loc);
1429 if (cur.top() != from)
1430 setCursor(cur, from.pit(), from.pos());
1434 setCursor(cur, to.pit(), to.pos());
1439 // Select the word currently under the cursor when no
1440 // selection is currently set
1441 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1443 BOOST_ASSERT(this == cur.text());
1444 if (cur.selection())
1446 selectWord(cur, loc);
1447 return cur.selection();
1451 void LyXText::acceptChange(LCursor & cur)
1453 BOOST_ASSERT(this == cur.text());
1454 if (!cur.selection() && cur.lastpos() != 0)
1457 recordUndoSelection(cur, Undo::INSERT);
1459 DocIterator it = cur.selectionBegin();
1460 DocIterator et = cur.selectionEnd();
1461 pit_type pit = it.pit();
1462 bool isDeleted = pars_[pit].isDeleted(it.pos());
1463 for (; pit <= et.pit(); ++pit) {
1464 pos_type left = ( pit == it.pit() ? it.pos() : 0 );
1466 ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1467 pars_[pit].acceptChanges(left, right);
1470 ParagraphList & plist = paragraphs();
1471 if (it.pit() + 1 < et.pit())
1472 pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1473 boost::next(plist.begin(), et.pit()));
1475 // Paragraph merge if appropriate:
1476 // FIXME: change tracking (MG)
1477 if (pars_[it.pit()].isDeleted(pars_[it.pit()].size())) {
1478 setCursorIntern(cur, it.pit() + 1, 0);
1483 cur.clearSelection();
1484 setCursorIntern(cur, it.pit(), 0);
1488 void LyXText::rejectChange(LCursor & cur)
1490 BOOST_ASSERT(this == cur.text());
1491 if (!cur.selection() && cur.lastpos() != 0)
1494 recordUndoSelection(cur, Undo::INSERT);
1496 DocIterator it = cur.selectionBegin();
1497 DocIterator et = cur.selectionEnd();
1498 pit_type pit = it.pit();
1499 bool isInserted = pars_[pit].isInserted(it.pos());
1500 for (; pit <= et.pit(); ++pit) {
1501 pos_type left = ( pit == it.pit() ? it.pos() : 0 );
1503 ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1504 pars_[pit].rejectChanges(left, right);
1507 ParagraphList & plist = paragraphs();
1508 if (it.pit() + 1 < et.pit())
1509 pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1510 boost::next(plist.begin(), et.pit()));
1511 // Paragraph merge if appropriate:
1512 // FIXME: change tracking (MG)
1513 if (pars_[it.pit()].isInserted(pars_[it.pit()].size())) {
1514 setCursorIntern(cur, it.pit() + 1, 0);
1519 cur.clearSelection();
1520 setCursorIntern(cur, it.pit(), 0);
1524 // Delete from cursor up to the end of the current or next word.
1525 void LyXText::deleteWordForward(LCursor & cur)
1527 BOOST_ASSERT(this == cur.text());
1528 if (cur.lastpos() == 0)
1532 cur.selection() = true;
1533 cursorRightOneWord(cur);
1535 cutSelection(cur, true, false);
1540 // Delete from cursor to start of current or prior word.
1541 void LyXText::deleteWordBackward(LCursor & cur)
1543 BOOST_ASSERT(this == cur.text());
1544 if (cur.lastpos() == 0)
1548 cur.selection() = true;
1549 cursorLeftOneWord(cur);
1551 cutSelection(cur, true, false);
1556 // Kill to end of line.
1557 void LyXText::deleteLineForward(LCursor & cur)
1559 BOOST_ASSERT(this == cur.text());
1560 if (cur.lastpos() == 0) {
1561 // Paragraph is empty, so we just go to the right
1565 cur.selection() = true; // to avoid deletion
1568 // What is this test for ??? (JMarc)
1569 if (!cur.selection())
1570 deleteWordForward(cur);
1572 cutSelection(cur, true, false);
1577 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1579 BOOST_ASSERT(this == cur.text());
1583 if (cur.selection()) {
1584 from = cur.selBegin();
1588 getWord(from, to, PARTIAL_WORD);
1589 cursorRightOneWord(cur);
1592 recordUndoSelection(cur);
1594 pos_type pos = from.pos();
1595 int par = from.pit();
1597 while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1599 if (pos == pars_[pit].size()) {
1604 char_type c = pars_[pit].getChar(pos);
1605 if (c != Paragraph::META_INSET) {
1607 case text_lowercase:
1610 case text_capitalization:
1612 action = text_lowercase;
1614 case text_uppercase:
1620 // FIXME: change tracking (MG)
1621 // sorry but we are no longer allowed to set a single character directly
1622 // we have to rewrite this method in terms of erase&insert operations
1623 //pars_[pit].setChar(pos, c);
1629 bool LyXText::erase(LCursor & cur)
1631 BOOST_ASSERT(this == cur.text());
1632 bool needsUpdate = false;
1634 if (cur.pos() != cur.lastpos()) {
1635 recordUndo(cur, Undo::DELETE, cur.pit());
1636 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1637 needsUpdate = backspace(cur);
1638 // FIXME: change tracking (MG)
1639 if (cur.paragraph().isDeleted(cur.pos()))
1641 } else if (cur.pit() != cur.lastpit()) {
1644 setCursorIntern(cur, cur.pit() + 1, 0, false, false);
1645 if (pars_[cur.pit()].layout() == pars_[scur.pit()].layout()) {
1646 recordUndo(scur, Undo::DELETE, scur.pit());
1647 needsUpdate = backspace(cur);
1648 if (cur.buffer().params().trackChanges) {
1649 // FIXME: Change tracking (MG)
1650 // move forward after the paragraph break is DELETED
1651 Paragraph & par = cur.paragraph();
1652 // FIXME: change tracking (MG)
1653 if (par.isDeleted(par.size()))
1654 setCursorIntern(cur, cur.pit() + 1, 0);
1657 setCursorIntern(scur, scur.pit(), scur.pos(), false, scur.boundary());
1660 needsUpdate = dissolveInset(cur);
1666 bool LyXText::backspacePos0(LCursor & cur)
1668 BOOST_ASSERT(this == cur.text());
1669 bool needsUpdate = false;
1671 Paragraph & par = cur.paragraph();
1672 // is it an empty paragraph?
1673 pos_type lastpos = cur.lastpos();
1674 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1675 // This is an empty paragraph and we delete it just
1676 // by moving the cursor one step
1677 // left and let the DeleteEmptyParagraphMechanism
1678 // handle the actual deletion of the paragraph.
1680 if (cur.pit() != 0) {
1681 // For KeepEmpty layouts we need to get
1682 // rid of the keepEmpty setting first.
1683 // And the only way to do this is to
1684 // reset the layout to something
1685 // else: f.ex. the default layout.
1686 if (par.allowEmpty()) {
1687 Buffer & buf = cur.buffer();
1688 BufferParams const & bparams = buf.params();
1689 par.layout(bparams.getLyXTextClass().defaultLayout());
1698 recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1700 pit_type tmppit = cur.pit();
1701 // We used to do cursorLeftIntern() here, but it is
1702 // not a good idea since it triggers the auto-delete
1703 // mechanism. So we do a cursorLeftIntern()-lite,
1704 // without the dreaded mechanism. (JMarc)
1705 if (cur.pit() != 0) {
1706 // steps into the above paragraph.
1707 setCursorIntern(cur, cur.pit() - 1,
1708 pars_[cur.pit() - 1].size(),
1712 // Pasting is not allowed, if the paragraphs have different
1713 // layout. I think it is a real bug of all other
1714 // word processors to allow it. It confuses the user.
1715 // Correction: Pasting is always allowed with standard-layout
1716 // Correction (Jug 20050717): Remove check about alignment!
1717 Buffer & buf = cur.buffer();
1718 BufferParams const & bufparams = buf.params();
1719 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1720 pit_type const cpit = cur.pit();
1723 && (pars_[cpit].layout() == pars_[tmppit].layout()
1724 || pars_[tmppit].layout() == tclass.defaultLayout()))
1726 mergeParagraph(bufparams, pars_, cpit);
1729 if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1732 // the counters may have changed
1733 ParIterator par_it(cur);
1734 updateLabels(cur.buffer(), par_it);
1736 setCursor(cur, cur.pit(), cur.pos(), false);
1742 bool LyXText::backspace(LCursor & cur)
1744 BOOST_ASSERT(this == cur.text());
1745 bool needsUpdate = false;
1746 if (cur.pos() == 0) {
1748 return dissolveInset(cur);
1750 // The cursor is at the beginning of a paragraph, so
1751 // the the backspace will collapse two paragraphs into
1754 if (cur.pit() != 0 && cur.buffer().params().trackChanges) {
1755 // FIXME: Change tracking (MG)
1756 // Previous paragraph, mark "carriage return" as
1758 Paragraph & par = pars_[cur.pit() - 1];
1759 // Take care of a just inserted para break:
1760 // FIXME: change tracking (MG)
1761 if (!par.isInserted(par.size())) {
1762 // FIXME: change tracking (MG)
1763 par.setChange(par.size(), Change(Change::DELETED));
1764 setCursorIntern(cur, cur.pit() - 1, par.size());
1769 needsUpdate = backspacePos0(cur);
1772 // this is the code for a normal backspace, not pasting
1774 recordUndo(cur, Undo::DELETE);
1775 // We used to do cursorLeftIntern() here, but it is
1776 // not a good idea since it triggers the auto-delete
1777 // mechanism. So we do a cursorLeftIntern()-lite,
1778 // without the dreaded mechanism. (JMarc)
1779 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1780 false, cur.boundary());
1781 // FIXME: change tracking (MG)
1782 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1785 if (cur.pos() == cur.lastpos())
1786 setCurrentFont(cur);
1788 setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1794 bool LyXText::dissolveInset(LCursor & cur) {
1795 BOOST_ASSERT(this == cur.text());
1797 if (isMainText() || cur.inset().nargs() != 1)
1800 recordUndoInset(cur);
1801 cur.selHandle(false);
1803 pos_type spos = cur.pos();
1804 pit_type spit = cur.pit();
1805 ParagraphList plist;
1806 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1807 plist = paragraphs();
1809 // store cursor offset
1813 Buffer & b = cur.buffer();
1814 // FIXME: change tracking (MG)
1815 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1816 if (!plist.empty()) {
1817 pasteParagraphList(cur, plist, b.params().textclass,
1818 b.errorList("Paste"));
1820 cur.pit() = std::min(cur.lastpit(), spit);
1821 cur.pos() = std::min(cur.lastpos(), spos);
1823 cur.clearSelection();
1829 Row const & LyXText::firstRow() const
1831 return *paragraphs().front().rows().begin();
1835 bool LyXText::redoParagraph(pit_type const pit)
1837 // remove rows of paragraph, keep track of height changes
1838 Paragraph & par = pars_[pit];
1840 // Add bibitem insets if necessary
1841 if (par.layout()->labeltype == LABEL_BIBLIO) {
1842 bool hasbibitem(false);
1843 if (!par.insetlist.empty()
1844 // Insist on it being in pos 0
1845 && par.getChar(0) == Paragraph::META_INSET) {
1846 InsetBase * inset = par.insetlist.begin()->inset;
1847 if (inset->lyxCode() == InsetBase::BIBITEM_CODE)
1851 InsetBibitem * inset(new
1852 InsetBibitem(InsetCommandParams("bibitem")));
1853 // FIXME: change tracking (MG)
1854 par.insertInset(0, static_cast<InsetBase *>(inset), Change(Change::INSERTED));
1855 bv()->cursor().posRight();
1860 // FIXME: We should always use getFont(), see documentation of
1861 // noFontChange() in insetbase.h.
1862 LyXFont const bufferfont = bv()->buffer()->params().getFont();
1863 InsetList::iterator ii = par.insetlist.begin();
1864 InsetList::iterator iend = par.insetlist.end();
1865 for (; ii != iend; ++ii) {
1867 int const w = maxwidth_ - leftMargin(pit, ii->pos) - rightMargin(par);
1868 LyXFont const & font = ii->inset->noFontChange() ?
1870 getFont(par, ii->pos);
1871 MetricsInfo mi(bv(), font, w);
1872 ii->inset->metrics(mi, dim);
1875 // rebreak the paragraph
1879 par.setBeginOfBody();
1883 rowBreakPoint(pit, row);
1884 setRowWidth(pit, row);
1885 setHeightOfRow(pit, row);
1886 par.rows().push_back(row);
1887 dim.wid = std::max(dim.wid, row.width());
1888 dim.des += row.height();
1890 } while (z < par.size());
1892 // Make sure that if a par ends in newline, there is one more row
1894 // FIXME this is a dirty trick. Now the _same_ position in the
1895 // paragraph occurs in _two_ different rows, and has two different
1896 // display positions, leading to weird behaviour when moving up/down.
1897 if (z > 0 && par.isNewline(z - 1)) {
1900 setRowWidth(pit, row);
1901 setHeightOfRow(pit, row);
1902 par.rows().push_back(row);
1903 dim.des += row.height();
1906 dim.asc += par.rows()[0].ascent();
1907 dim.des -= par.rows()[0].ascent();
1909 bool const same = dim == par.dim();
1912 //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1918 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1920 //BOOST_ASSERT(mi.base.textwidth);
1921 if (mi.base.textwidth)
1922 maxwidth_ = mi.base.textwidth;
1923 //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1924 // << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1925 // save the caller's font locally:
1926 font_ = mi.base.font;
1930 for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1932 Paragraph & par = paragraphs()[pit];
1934 if (w < par.width())
1939 dim.asc = pars_[0].ascent();
1940 dim.des = h - dim.asc;
1946 // only used for inset right now. should also be used for main text
1947 void LyXText::draw(PainterInfo & pi, int x, int y) const
1949 paintTextInset(*this, pi, x, y);
1954 // only used for inset right now. should also be used for main text
1955 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1957 LCursor & cur = pi.base.bv->cursor();
1958 if (!cur.selection())
1960 if (!ptr_cmp(cur.text(), this))
1963 lyxerr << "draw selection at " << x << endl;
1965 DocIterator beg = cur.selectionBegin();
1966 DocIterator end = cur.selectionEnd();
1968 // the selection doesn't touch the visible screen
1969 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1970 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1973 Paragraph const & par1 = pars_[beg.pit()];
1974 Paragraph const & par2 = pars_[end.pit()];
1976 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1977 Row const & row2 = par2.getRow(end.pos(), end.boundary());
1980 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1985 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1986 int const startx = cursorX(beg.top(), begin.boundary());
1987 x1 = isRTL(par1) ? startx : 0;
1988 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
1992 if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
1993 y2 = pi.base.bv->workHeight();
1997 y2 = bv_funcs::getPos(end).y_ + row2.descent();
1998 int const endx = cursorX(end.top(), end.boundary());
1999 X1 = isRTL(par2) ? 0 : endx;
2000 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
2003 lyxerr << " y1: " << y1 << " y2: " << y2
2004 << " xo: " << xo_ << " wid: " << dim_.wid
2007 // paint big rectangle in one go
2008 pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
2010 // reset background at begin of first selected line
2011 pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
2012 LColor::background);
2014 // reset background at end of last selected line
2015 pi.pain.fillRectangle(x + X1, y2 - row2.height(),
2016 X2 - X1, row2.height(), LColor::background);
2021 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
2023 LCursor & cur = pi.base.bv->cursor();
2024 if (!cur.selection())
2026 if (!ptr_cmp(cur.text(), this))
2029 lyxerr[Debug::DEBUG]
2030 << BOOST_CURRENT_FUNCTION
2031 << "draw selection at " << x
2034 DocIterator beg = cur.selectionBegin();
2035 DocIterator end = cur.selectionEnd();
2037 BufferView * bv = pi.base.bv;
2039 // the selection doesn't touch the visible screen
2040 if (bv_funcs::status(bv, beg) == bv_funcs::CUR_BELOW
2041 || bv_funcs::status(bv, end) == bv_funcs::CUR_ABOVE)
2044 Paragraph const & par1 = pars_[beg.pit()];
2045 Paragraph const & par2 = pars_[end.pit()];
2047 bool const above = (bv_funcs::status(bv, beg)
2048 == bv_funcs::CUR_ABOVE);
2049 bool const below = (bv_funcs::status(bv, end)
2050 == bv_funcs::CUR_BELOW);
2058 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
2059 y1 = bv_funcs::getPos(*bv, beg, beg.boundary()).y_ - row1.ascent();
2060 y2 = y1 + row1.height();
2061 int const startx = cursorX(beg.top(), beg.boundary());
2062 x1 = !isRTL(par1) ? startx : 0;
2063 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
2068 Y1 = bv->workHeight();
2069 Y2 = bv->workHeight();
2073 Row const & row2 = par2.getRow(end.pos(), end.boundary());
2074 Y1 = bv_funcs::getPos(*bv, end, end.boundary()).y_ - row2.ascent();
2075 Y2 = Y1 + row2.height();
2076 int const endx = cursorX(end.top(), end.boundary());
2077 X1 = !isRTL(par2) ? 0 : endx;
2078 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
2081 if (!above && !below && &par1.getRow(beg.pos(), beg.boundary())
2082 == &par2.getRow(end.pos(), end.boundary()))
2084 // paint only one rectangle
2085 int const b( !isRTL(par1) ? x + x1 : x + X1 );
2086 int const w( !isRTL(par1) ? X2 - x1 : x2 - X1 );
2087 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
2091 lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
2092 << "X1:" << X1 << " x2: " << X2 << " wid: " << dim_.wid
2095 // paint upper rectangle
2096 pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
2098 // paint bottom rectangle
2099 pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
2101 // paint center rectangle
2102 pi.pain.fillRectangle(x, y2, dim_.wid,
2103 Y1 - y2, LColor::selection);
2107 bool LyXText::isLastRow(pit_type pit, Row const & row) const
2109 return row.endpos() >= pars_[pit].size()
2110 && pit + 1 == pit_type(paragraphs().size());
2114 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
2116 return row.pos() == 0 && pit == 0;
2120 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
2121 word_location const loc)
2123 Paragraph const & from_par = pars_[from.pit()];
2125 case WHOLE_WORD_STRICT:
2126 if (from.pos() == 0 || from.pos() == from_par.size()
2127 || !from_par.isLetter(from.pos())
2128 || !from_par.isLetter(from.pos() - 1)) {
2132 // no break here, we go to the next
2135 // If we are already at the beginning of a word, do nothing
2136 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
2138 // no break here, we go to the next
2141 // always move the cursor to the beginning of previous word
2142 while (from.pos() && from_par.isLetter(from.pos() - 1))
2146 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
2150 // no need to move the 'from' cursor
2154 Paragraph & to_par = pars_[to.pit()];
2155 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
2160 void LyXText::write(Buffer const & buf, std::ostream & os) const
2162 ParagraphList::const_iterator pit = paragraphs().begin();
2163 ParagraphList::const_iterator end = paragraphs().end();
2165 for (; pit != end; ++pit)
2166 pit->write(buf, os, buf.params(), dth);
2170 bool LyXText::read(Buffer const & buf, LyXLex & lex, ErrorList & errorList)
2172 depth_type depth = 0;
2174 while (lex.isOK()) {
2176 string const token = lex.getString();
2181 if (token == "\\end_inset")
2184 if (token == "\\end_body")
2187 if (token == "\\begin_body")
2190 if (token == "\\end_document")
2193 if (token == "\\begin_layout") {
2194 lex.pushToken(token);
2197 par.params().depth(depth);
2198 par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
2199 pars_.push_back(par);
2201 // FIXME: goddamn InsetTabular makes us pass a Buffer
2203 lyx::readParagraph(buf, pars_.back(), lex, errorList);
2205 } else if (token == "\\begin_deeper") {
2207 } else if (token == "\\end_deeper") {
2209 lex.printError("\\end_deeper: " "depth is already null");
2214 lyxerr << "Handling unknown body token: `"
2215 << token << '\'' << endl;
2222 int LyXText::ascent() const
2228 int LyXText::descent() const
2234 int LyXText::cursorX(CursorSlice const & sl, bool boundary) const
2236 pit_type const pit = sl.pit();
2237 Paragraph const & par = pars_[pit];
2238 if (par.rows().empty())
2241 pos_type ppos = sl.pos();
2242 // Correct position in front of big insets
2243 bool const boundary_correction = ppos != 0 && boundary;
2244 if (boundary_correction)
2247 Row const & row = par.getRow(sl.pos(), boundary);
2249 pos_type cursor_vpos = 0;
2251 RowMetrics const m = computeRowMetrics(pit, row);
2254 pos_type const row_pos = row.pos();
2255 pos_type const end = row.endpos();
2258 cursor_vpos = row_pos;
2259 else if (ppos >= end)
2260 cursor_vpos = isRTL(par) ? row_pos : end;
2261 else if (ppos > row_pos && ppos >= end)
2262 // Place cursor after char at (logical) position pos - 1
2263 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
2264 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
2266 // Place cursor before char at (logical) position ppos
2267 cursor_vpos = (bidi.level(ppos) % 2 == 0)
2268 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
2270 pos_type body_pos = par.beginOfBody();
2272 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2275 // Use font span to speed things up, see below
2278 FontMetrics const & labelfm = theFontMetrics(getLabelFont(par));
2280 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2281 pos_type pos = bidi.vis2log(vpos);
2282 if (body_pos > 0 && pos == body_pos - 1) {
2284 docstring const lsep = from_utf8(par.layout()->labelsep);
2285 x += m.label_hfill + labelfm.width(lsep);
2286 if (par.isLineSeparator(body_pos - 1))
2287 x -= singleWidth(par, body_pos - 1);
2290 // Use font span to speed things up, see above
2291 if (pos < font_span.first || pos > font_span.last) {
2292 font_span = par.fontSpan(pos);
2293 font = getFont(par, pos);
2296 x += singleWidth(par, pos, par.getChar(pos), font);
2298 if (par.hfillExpansion(row, pos))
2299 x += (pos >= body_pos) ? m.hfill : m.label_hfill;
2300 else if (par.isSeparator(pos) && pos >= body_pos)
2304 // see correction above
2305 if (boundary_correction)
2306 if (getFont(par, ppos).isVisibleRightToLeft())
2307 x -= singleWidth(par, ppos);
2309 x += singleWidth(par, ppos);
2311 // Make sure inside an inset we always count from the left
2312 // edge (bidi!) -- MV
2313 if (sl.pos() < par.size()) {
2314 font = getFont(par, sl.pos());
2315 if (!boundary && font.isVisibleRightToLeft()
2316 && par.isInset(sl.pos()))
2317 x -= par.getInset(sl.pos())->width();
2323 int LyXText::cursorY(CursorSlice const & sl, bool boundary) const
2325 //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
2326 Paragraph const & par = getPar(sl.pit());
2327 if (par.rows().empty())
2331 h -= pars_[0].rows()[0].ascent();
2332 for (pit_type pit = 0; pit < sl.pit(); ++pit)
2333 h += pars_[pit].height();
2335 if (pos && boundary)
2337 size_t const rend = par.pos2row(pos);
2338 for (size_t rit = 0; rit != rend; ++rit)
2339 h += par.rows()[rit].height();
2340 h += par.rows()[rend].ascent();
2345 // Returns the current font and depth as a message.
2346 string LyXText::currentState(LCursor & cur)
2348 BOOST_ASSERT(this == cur.text());
2349 Buffer & buf = cur.buffer();
2350 Paragraph const & par = cur.paragraph();
2351 std::ostringstream os;
2353 if (buf.params().trackChanges)
2356 Change change = par.lookupChange(cur.pos());
2358 if (change.type != Change::UNCHANGED) {
2359 Author const & a = buf.params().authors().get(change.author);
2360 os << to_utf8(_("Change: ")) << a.name();
2361 if (!a.email().empty())
2362 os << " (" << a.email() << ")";
2363 os << to_utf8(_(" at ")) << ctime(&change.changetime);
2367 // I think we should only show changes from the default
2369 // No, from the document font (MV)
2370 LyXFont font = real_current_font;
2371 font.reduce(buf.params().getFont());
2373 // avoid to_utf8(_(...)) re-entrance problem
2374 string const s = font.stateText(&buf.params());
2375 os << to_utf8(bformat(_("Font: %1$s"), from_utf8(s)));
2377 // os << to_utf8(bformat(_("Font: %1$s"), font.stateText(&buf.params)));
2379 // The paragraph depth
2380 int depth = cur.paragraph().getDepth();
2382 os << to_utf8(bformat(_(", Depth: %1$d"), depth));
2384 // The paragraph spacing, but only if different from
2386 Spacing const & spacing = par.params().spacing();
2387 if (!spacing.isDefault()) {
2388 os << to_utf8(_(", Spacing: "));
2389 switch (spacing.getSpace()) {
2390 case Spacing::Single:
2391 os << to_utf8(_("Single"));
2393 case Spacing::Onehalf:
2394 os << to_utf8(_("OneHalf"));
2396 case Spacing::Double:
2397 os << to_utf8(_("Double"));
2399 case Spacing::Other:
2400 os << to_utf8(_("Other (")) << spacing.getValueAsString() << ')';
2402 case Spacing::Default:
2403 // should never happen, do nothing
2408 #ifdef DEVEL_VERSION
2409 os << to_utf8(_(", Inset: ")) << &cur.inset();
2410 os << to_utf8(_(", Paragraph: ")) << cur.pit();
2411 os << to_utf8(_(", Id: ")) << par.id();
2412 os << to_utf8(_(", Position: ")) << cur.pos();
2413 os << to_utf8(_(", Boundary: ")) << cur.boundary();
2414 // Row & row = cur.textRow();
2415 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2421 string LyXText::getPossibleLabel(LCursor & cur) const
2423 pit_type pit = cur.pit();
2425 LyXLayout_ptr layout = pars_[pit].layout();
2427 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2428 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2429 if (layout2->latextype != LATEX_PARAGRAPH) {
2435 string name = layout->latexname();
2437 // for captions, we want the abbreviation of the float type
2438 if (layout->labeltype == LABEL_SENSITIVE) {
2439 // Search for the first float or wrap inset in the iterator
2440 for (int i = cur.depth(); --i >= 0; ) {
2441 InsetBase * const in = &cur[i].inset();
2442 if (in->lyxCode() == InsetBase::FLOAT_CODE
2443 || in->lyxCode() == InsetBase::WRAP_CODE) {
2444 name = to_utf8(in->getInsetName());
2450 string text = name.substr(0, 3);
2451 if (name == "theorem")
2452 text = "thm"; // Create a correct prefix for prettyref
2455 if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2459 string par_text = to_utf8(pars_[pit].asString(cur.buffer(), false));
2460 for (int i = 0; i < lyxrc.label_init_length; ++i) {
2461 if (par_text.empty())
2464 par_text = split(par_text, head, ' ');
2465 // Is it legal to use spaces in labels ?
2475 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2479 // Paragraph const & par = pars_[pit];
2480 // Row const & r = par.rows()[row];
2481 // int pos = r.pos();
2482 // for (; currx < x && pos < r.endpos(); ++pos) {
2484 // currx += singleWidth(par, pos);
2486 // if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2492 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2494 BOOST_ASSERT(row < int(pars_[pit].rows().size()));
2496 Row const & r = pars_[pit].rows()[row];
2497 return r.pos() + getColumnNearX(pit, r, x, bound);
2501 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2503 // Paragraph const & par = pars_[pit];
2504 // Row const & r = par.rows()[row];
2510 // x,y are screen coordinates
2511 // sets cursor only within this LyXText
2512 bool LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2514 BOOST_ASSERT(this == cur.text());
2515 pit_type pit = getPitNearY(y);
2516 int yy = cur.bv().coordCache().get(this, pit).y_ - pars_[pit].ascent();
2517 lyxerr[Debug::DEBUG]
2518 << BOOST_CURRENT_FUNCTION
2522 << " yy: " << yy << endl;
2524 Paragraph const & par = pars_[pit];
2526 BOOST_ASSERT(par.rows().size());
2527 for (; r < int(par.rows().size()) - 1; ++r) {
2528 Row const & row = par.rows()[r];
2529 if (int(yy + row.height()) > y)
2534 Row const & row = par.rows()[r];
2536 lyxerr[Debug::DEBUG]
2537 << BOOST_CURRENT_FUNCTION
2539 << " from pos: " << row.pos()
2544 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2546 lyxerr[Debug::DEBUG]
2547 << BOOST_CURRENT_FUNCTION
2548 << ": setting cursor pit: " << pit
2552 return setCursor(cur, pit, pos, true, bound);