2 * \file src/TextMetrics.cpp
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
13 * \author Abdelrazak Younes
15 * Full author contact details are available in file CREDITS.
20 #include "TextMetrics.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CoordCache.h"
27 #include "CutAndPaste.h"
30 #include "MetricsInfo.h"
31 #include "ParagraphParameters.h"
32 #include "RowPainter.h"
35 #include "TextClass.h"
38 #include "insets/InsetSeparator.h"
39 #include "insets/InsetText.h"
41 #include "mathed/MacroTable.h"
43 #include "frontends/FontMetrics.h"
44 #include "frontends/NullPainter.h"
46 #include "support/debug.h"
47 #include "support/lassert.h"
48 #include "support/Changer.h"
58 using frontend::FontMetrics;
63 int numberOfLabelHfills(Paragraph const & par, Row const & row)
65 pos_type last = row.endpos() - 1;
66 pos_type first = row.pos();
68 // hfill *DO* count at the beginning of paragraphs!
70 while (first < last && par.isHfill(first))
74 last = min(last, par.beginOfBody());
76 for (pos_type p = first; p < last; ++p) {
83 // FIXME: this needs to be rewritten, probably by merging it into some
84 // code that, besides counting, sets the active status of the space
85 // inset in the row element.
86 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
87 pos_type const body_pos)
90 Row::const_iterator cit = row.begin();
91 Row::const_iterator const end = row.end();
92 for ( ; cit != end ; ++cit)
93 if (cit->pos >= body_pos
94 && cit->inset && pm.hfillExpansion(row, cit->pos))
102 /////////////////////////////////////////////////////////////////////
106 /////////////////////////////////////////////////////////////////////
109 TextMetrics::TextMetrics(BufferView * bv, Text * text)
110 : bv_(bv), text_(text), dim_(bv_->workWidth(), 10, 10),
111 max_width_(dim_.wid), tight_(false)
115 bool TextMetrics::contains(pit_type pit) const
117 return par_metrics_.find(pit) != par_metrics_.end();
121 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
123 ParMetricsCache::const_iterator it = par_metrics_.begin();
124 return make_pair(it->first, &it->second);
128 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
130 LBUFERR(!par_metrics_.empty());
131 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
132 return make_pair(it->first, &it->second);
136 bool TextMetrics::isLastRow(Row const & row) const
138 ParagraphList const & pars = text_->paragraphs();
139 return row.endpos() >= pars[row.pit()].size()
140 && row.pit() + 1 == pit_type(pars.size());
144 bool TextMetrics::isFirstRow(Row const & row) const
146 return row.pos() == 0 && row.pit() == 0;
150 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
152 for (auto & pm_pair : par_metrics_)
153 if (pm_pair.first == pit)
154 for (Row & row : pm_pair.second.rows())
155 if (row.pos() == pos)
160 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
162 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
163 if (pmc_it == par_metrics_.end()) {
164 pmc_it = par_metrics_.insert(
165 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
167 if (pmc_it->second.rows().empty() && redo)
169 return pmc_it->second;
173 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
175 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
179 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit)
181 return parMetrics(pit, true);
185 void TextMetrics::newParMetricsDown()
187 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
188 pit_type const pit = last.first + 1;
189 if (pit == int(text_->paragraphs().size()))
192 // do it and update its position.
194 par_metrics_[pit].setPosition(last.second.position()
195 + last.second.descent() + par_metrics_[pit].ascent());
200 void TextMetrics::newParMetricsUp()
202 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
203 if (first.first == 0)
206 pit_type const pit = first.first - 1;
207 // do it and update its position.
209 par_metrics_[pit].setPosition(first.second.position()
210 - first.second.ascent() - par_metrics_[pit].descent());
215 bool TextMetrics::metrics(MetricsInfo const & mi, Dimension & dim, int min_width)
217 LBUFERR(mi.base.textwidth > 0);
218 max_width_ = mi.base.textwidth;
219 tight_ = mi.tight_insets;
220 // backup old dimension.
221 Dimension const old_dim = dim_;
224 dim_.wid = min_width;
225 pit_type const npar = text_->paragraphs().size();
226 if (npar > 1 && !tight_)
227 // If there is more than one row, expand the text to
228 // the full allowable width.
229 dim_.wid = max_width_;
231 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
232 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
234 bool changed = false;
236 for (pit_type pit = 0; pit != npar; ++pit) {
237 // create rows, but do not set alignment yet
238 changed |= redoParagraph(pit, false);
239 ParagraphMetrics const & pm = par_metrics_[pit];
241 if (dim_.wid < pm.width())
242 dim_.wid = pm.width();
245 // Now set alignment for all rows (the width might not have been known before).
246 for (pit_type pit = 0; pit != npar; ++pit) {
247 ParagraphMetrics & pm = par_metrics_[pit];
248 for (Row & row : pm.rows())
249 setRowAlignment(row, dim_.wid);
252 dim_.asc = par_metrics_[0].ascent();
253 dim_.des = h - dim_.asc;
254 //lyxerr << "dim_.wid " << dim_.wid << endl;
255 //lyxerr << "dim_.asc " << dim_.asc << endl;
256 //lyxerr << "dim_.des " << dim_.des << endl;
258 changed |= dim_ != old_dim;
264 void TextMetrics::updatePosCache(pit_type pit) const
266 frontend::NullPainter np;
267 PainterInfo pi(bv_, np);
268 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
272 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
274 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
278 int TextMetrics::rightMargin(pit_type const pit) const
280 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
284 void TextMetrics::applyOuterFont(Font & font) const
286 FontInfo lf(font_.fontInfo());
287 lf.reduce(bv_->buffer().params().getFont().fontInfo());
288 font.fontInfo().realize(lf);
292 // This is an arbitrary magic value
293 static const pos_type force_label = -12345;
295 // if pos == force_label, this function will return the label font instead.
296 // This undocumented and only for use by labelDisplayFont()
297 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
299 LASSERT(pos >= 0 || pos == force_label, { static Font f; return f; });
301 ParagraphList const & pars = text_->paragraphs();
302 Paragraph const & par = pars[pit];
303 Layout const & layout = par.layout();
304 Buffer const & buffer = bv_->buffer();
306 BufferParams const & bparams = buffer.params();
307 bool const label = pos < par.beginOfBody() || pos == force_label;
309 Font f = (pos == force_label) ? Font(inherit_font, bparams.language)
310 : par.getFontSettings(bparams, pos);
311 FontInfo const & lf = label ? layout.labelfont : layout.font;
313 // We specialize the 95% common case:
314 if (!par.getDepth()) {
315 if (!text_->isMainText())
318 FontInfo rlf = label ? layout.reslabelfont : layout.resfont;
320 // In case the default family has been customized
321 if (lf.family() == INHERIT_FAMILY)
322 rlf.setFamily(bparams.getFont().fontInfo().family());
323 f.fontInfo().realize(rlf);
327 // The uncommon case need not be optimized as much.
328 // FIXME : the two code paths seem different in function.
329 f.fontInfo().realize(lf);
331 if (!text_->isMainText())
334 // Realize against environment font information
335 // NOTE: the cast to pit_type should be removed when pit_type
336 // changes to a unsigned integer.
337 if (pit < pit_type(pars.size()))
338 f.fontInfo().realize(text_->outerFont(pit).fontInfo());
340 // Realize with the fonts of lesser depth.
341 f.fontInfo().realize(bparams.getFont().fontInfo());
347 Font TextMetrics::labelDisplayFont(pit_type pit) const
349 return displayFont(pit, force_label);
353 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
359 if (boundary && sl.pos() > 0)
362 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
366 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
368 // no RTL boundary at paragraph start
372 Font const & left_font = displayFont(pit, pos - 1);
374 return isRTLBoundary(pit, pos, left_font);
378 // isRTLBoundary returns false on a real end-of-line boundary,
379 // because otherwise the two boundary types get mixed up.
380 // This is the whole purpose of this being in TextMetrics.
381 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
382 Font const & font) const
384 if (// no RTL boundary at paragraph start
386 // if the metrics have not been calculated, then we are not
387 // on screen and can safely ignore issues about boundaries.
391 ParagraphMetrics const & pm = par_metrics_[pit];
392 // no RTL boundary in empty paragraph
393 if (pm.rows().empty())
396 pos_type const endpos = pm.getRow(pos - 1, false).endpos();
397 pos_type const startpos = pm.getRow(pos, false).pos();
398 // no RTL boundary at line start:
399 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
401 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
404 Paragraph const & par = text_->getPar(pit);
405 // no RTL boundary at line break:
406 // abc|\n -> move right -> abc\n (and not: abc\n|
408 if (startpos == pos && endpos == pos && endpos != par.size()
409 && (par.isNewline(pos - 1)
410 || par.isEnvSeparator(pos - 1)
411 || par.isLineSeparator(pos - 1)
412 || par.isSeparator(pos - 1)))
415 bool const left = font.isVisibleRightToLeft();
417 if (pos == par.size())
418 right = par.isRTL(bv_->buffer().params());
420 right = displayFont(pit, pos).isVisibleRightToLeft();
422 return left != right;
426 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
428 Paragraph & par = text_->getPar(pit);
429 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
430 // redoParagraph() recursively inside parMetrics.
431 Dimension old_dim = parMetrics(pit, false).dim();
432 ParagraphMetrics & pm = par_metrics_[pit];
435 Buffer & buffer = bv_->buffer();
436 bool changed = false;
438 // Check whether there are InsetBibItems that need fixing
439 // FIXME: This check ought to be done somewhere else. It is the reason
440 // why text_ is not const. But then, where else to do it?
441 // Well, how can you end up with either (a) a biblio environment that
442 // has no InsetBibitem, (b) a biblio environment with more than one
443 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
444 // environment? I think the answer is: when paragraphs are merged;
445 // when layout is set; when material is pasted.
446 if (par.brokenBiblio()) {
447 Cursor & cur = bv_->cursor();
448 // In some cases, we do not know how to record undo
449 if (&cur.inset() == &text_->inset())
450 cur.recordUndo(pit, pit);
452 int const moveCursor = par.fixBiblio(buffer);
454 // Is it necessary to update the cursor?
455 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
458 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
463 // Optimisation: this is used in the next two loops
464 // so better to calculate that once here.
465 int const right_margin = rightMargin(pm);
467 // iterator pointing to paragraph to resolve macros
468 DocIterator parPos = text_->macrocontextPosition();
472 LYXERR(Debug::INFO, "MacroContext not initialised!"
473 << " Going through the buffer again and hope"
474 << " the context is better then.");
475 // FIXME audit updateBuffer calls
476 // This should not be here, but it is not clear yet where else it
478 bv_->buffer().updateBuffer();
479 parPos = text_->macrocontextPosition();
480 LBUFERR(!parPos.empty());
485 par.setBeginOfBody();
486 Font const bufferfont = buffer.params().getFont();
487 CoordCache::Insets & insetCache = bv_->coordCache().insets();
488 for (auto const & e : par.insetList()) {
489 // FIXME Doesn't this HAVE to be non-empty?
490 // position already initialized?
491 if (!parPos.empty()) {
492 parPos.pos() = e.pos;
494 // A macro template would normally not be visible
495 // by itself. But the tex macro semantics allow
496 // recursion, so we artifically take the context
497 // after the macro template to simulate this.
498 if (e.inset->lyxCode() == MATHMACRO_CODE)
502 // If there is an end of paragraph marker, its size should be
503 // substracted to the available width. The logic here is
504 // almost the same as in tokenizeParagraph, remember keep them in sync.
506 if (e.pos + 1 == par.size()
507 && (lyxrc.paragraph_markers || par.lookupChange(par.size()).changed())
508 && size_type(pit + 1) < text_->paragraphs().size()) {
509 Font f(text_->layoutFont(pit));
510 // ¶ U+00B6 PILCROW SIGN
511 eop = theFontMetrics(f).width(char_type(0x00B6));
514 // do the metric calculation
516 int const w = max_width_ - leftMargin(pit, e.pos)
517 - right_margin - eop;
518 Font const & font = e.inset->inheritFont() ?
519 displayFont(pit, e.pos) : bufferfont;
520 MacroContext mc(&buffer, parPos);
521 MetricsInfo mi(bv_, font.fontInfo(), w, mc, e.pos == 0, tight_);
522 e.inset->metrics(mi, dim);
523 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
524 insetCache.add(e.inset, dim);
529 // Transform the paragraph into a single row containing all the elements.
530 Row const bigrow = tokenizeParagraph(pit);
531 // Split the row in several rows fitting in available width
532 pm.rows() = breakParagraph(bigrow);
534 /* If there is more than one row, expand the text to the full
535 * allowable width. This setting here is needed for the
536 * setRowAlignment() below. We do nothing when tight insets are
539 if (pm.rows().size() > 1 && !tight_ && dim_.wid < max_width_)
540 dim_.wid = max_width_;
542 // Compute height and alignment of the rows.
543 for (Row & row : pm.rows()) {
546 setRowAlignment(row, max(dim_.wid, row.width()));
548 pm.dim().wid = max(pm.dim().wid, row.width() + row.right_margin);
549 pm.dim().des += row.height();
552 // This type of margin can only be handled at the global paragraph level
553 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX) {
555 if (par.isRTL(buffer.params())) {
556 // globally align the paragraph to the left.
557 int minleft = max_width_;
558 for (Row const & row : pm.rows())
559 minleft = min(minleft, row.left_margin);
560 offset = right_margin - minleft;
562 // globally align the paragraph to the right.
564 for (Row const & row : pm.rows())
565 maxwid = max(maxwid, row.width());
566 offset = max_width_ - right_margin - maxwid;
569 for (Row & row : pm.rows()) {
570 row.left_margin += offset;
571 row.dim().wid += offset;
575 // The space above and below the paragraph.
576 int top = parTopSpacing(pit);
577 int bottom = parBottomSpacing(pit);
579 // Top and bottom margin of the document (only at top-level)
580 // FIXME: It might be better to move this in another method
581 // specially tailored for the main text.
582 if (text_->isMainText()) {
584 top += bv_->topMargin();
585 if (pit + 1 == pit_type(text_->paragraphs().size())) {
586 bottom += bv_->bottomMargin();
590 // Add the top/bottom space to rows and paragraph metrics
591 pm.rows().front().dim().asc += top;
592 pm.rows().back().dim().des += bottom;
593 pm.dim().des += top + bottom;
595 // Move the pm ascent to be the same as the first row ascent
596 pm.dim().asc += pm.rows().front().ascent();
597 pm.dim().des -= pm.rows().front().ascent();
599 changed |= old_dim.height() != pm.dim().height();
605 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
607 LyXAlignment align = par.getAlign(bv_->buffer().params());
609 // handle alignment inside tabular cells
610 Inset const & owner = text_->inset();
611 bool forced_block = false;
612 switch (owner.contentAlignment()) {
613 case LYX_ALIGN_BLOCK:
614 // In general block align is the default state, but here it is
615 // an explicit choice. Therefore it should not be overridden
619 case LYX_ALIGN_CENTER:
621 case LYX_ALIGN_RIGHT:
622 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
623 align = owner.contentAlignment();
626 // unchanged (use align)
630 // Display-style insets should always be on a centered row
631 if (Inset const * inset = par.getInset(row.pos())) {
632 if (inset->rowFlags() & Display) {
633 if (inset->rowFlags() & AlignLeft)
634 align = LYX_ALIGN_LEFT;
635 else if (inset->rowFlags() & AlignRight)
636 align = LYX_ALIGN_RIGHT;
638 align = LYX_ALIGN_CENTER;
642 if (align == LYX_ALIGN_BLOCK) {
643 // If this row has been broken abruptly by a display inset, or
644 // it is the end of the paragraph, or the user requested we
645 // not justify stuff, then don't stretch.
646 // A forced block alignment can only be overridden the 'no
647 // justification on screen' setting.
648 if ((row.flushed() && !forced_block)
649 || !bv_->buffer().params().justification)
650 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
657 void TextMetrics::setRowAlignment(Row & row, int width) const
662 Paragraph const & par = text_->getPar(row.pit());
664 int const w = width - row.right_margin - row.width();
665 // FIXME: put back this assertion when the crash on new doc is solved.
666 //LASSERT(w >= 0, /**/);
668 // is there a manual margin with a manual label
669 Layout const & layout = par.layout();
672 if (layout.margintype == MARGIN_MANUAL
673 && layout.labeltype == LABEL_MANUAL) {
674 /// We might have real hfills in the label part
675 nlh = numberOfLabelHfills(par, row);
677 // A manual label par (e.g. List) has an auto-hfill
678 // between the label text and the body of the
680 // But we don't want to do this auto hfill if the par
685 if (nlh && !par.getLabelWidthString().empty())
686 row.label_hfill = labelFill(row) / double(nlh);
689 // are there any hfills in the row?
690 ParagraphMetrics const & pm = par_metrics_[row.pit()];
691 int nh = numberOfHfills(row, pm, par.beginOfBody());
695 // We don't have to look at the alignment if the row is already
696 // larger then the permitted width as then we force the
697 // LEFT_ALIGN'edness!
698 if (row.width() >= max_width_)
702 // Common case : there is no hfill, and the alignment will be
704 switch (getAlign(par, row)) {
705 case LYX_ALIGN_BLOCK:
706 // Expand expanding characters by a total of w
707 if (!row.setExtraWidth(w) && row.isRTL()) {
708 // Justification failed and the text is RTL: align to the right
709 row.left_margin += w;
714 // a displayed inset that is flushed
715 if (Inset const * inset = par.getInset(row.pos())) {
716 row.left_margin += inset->indent(*bv_);
717 row.dim().wid += inset->indent(*bv_);
720 case LYX_ALIGN_RIGHT:
721 if (Inset const * inset = par.getInset(row.pos())) {
722 int const new_w = max(w - inset->indent(*bv_), 0);
723 row.left_margin += new_w;
724 row.dim().wid += new_w;
726 row.left_margin += w;
730 case LYX_ALIGN_CENTER:
731 row.dim().wid += w / 2;
732 row.left_margin += w / 2;
735 case LYX_ALIGN_LAYOUT:
736 case LYX_ALIGN_SPECIAL:
737 case LYX_ALIGN_DECIMAL:
743 // Case nh > 0. There are hfill separators.
747 // Set size of hfill insets
748 pos_type const endpos = row.endpos();
749 pos_type body_pos = par.beginOfBody();
751 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
754 CoordCache::Insets & insetCache = bv_->coordCache().insets();
755 for (Row::Element & e : row) {
756 if (row.label_hfill && e.endpos == body_pos
757 && e.type == Row::SPACE)
758 e.dim.wid -= int(row.label_hfill * (nlh - 1));
759 if (e.inset && pm.hfillExpansion(row, e.pos)) {
760 if (e.pos >= body_pos) {
764 e.dim.wid += hfill_rem;
766 e.dim.wid += int(row.label_hfill);
767 // Cache the inset dimension.
768 insetCache.add(e.inset, e.dim);
774 int TextMetrics::labelFill(Row const & row) const
776 Paragraph const & par = text_->getPar(row.pit());
777 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
780 // iterate over elements before main body (except the last one,
781 // which is extra space).
782 for (Row::Element const & e : row) {
783 if (e.endpos >= par.beginOfBody())
788 docstring const & label = par.params().labelWidthString();
792 FontMetrics const & fm
793 = theFontMetrics(text_->labelFont(par));
795 return max(0, fm.width(label) - w);
802 * Calling Text::getFont is slow. While rebreaking we scan a
803 * paragraph from left to right calling getFont for every char. This
804 * simple class address this problem by hidding an optimization trick
805 * (not mine btw -AB): the font is reused in the whole font span. The
806 * class handles transparently the "hidden" (not part of the fontlist)
807 * label font (as getFont does).
813 FontIterator(TextMetrics const & tm,
814 Paragraph const & par, pit_type pit, pos_type pos)
815 : tm_(tm), par_(par), pit_(pit), pos_(pos),
816 font_(tm.displayFont(pit, pos)),
817 endspan_(par.fontSpan(pos).last),
818 bodypos_(par.beginOfBody())
822 Font const & operator*() const { return font_; }
825 FontIterator & operator++()
828 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
829 font_ = tm_.displayFont(pit_, pos_);
830 endspan_ = par_.fontSpan(pos_).last;
836 Font * operator->() { return &font_; }
840 TextMetrics const & tm_;
842 Paragraph const & par_;
858 Row TextMetrics::tokenizeParagraph(pit_type const pit) const
862 Paragraph const & par = text_->getPar(pit);
863 Buffer const & buf = text_->inset().buffer();
864 BookmarksSection::BookmarkPosList bpl =
865 theSession().bookmarks().bookmarksInPar(buf.fileName(), par.id());
867 pos_type const end = par.size();
868 pos_type const body_pos = par.beginOfBody();
870 // check for possible inline completion
871 DocIterator const & ic_it = bv_->inlineCompletionPos();
872 pos_type ic_pos = -1;
873 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == pit)
874 ic_pos = ic_it.pos();
876 // Now we iterate through until we reach the right margin
877 // or the end of the par, then build a representation of the row.
879 FontIterator fi = FontIterator(*this, par, pit, 0);
880 // The real stopping condition is a few lines below.
882 // Firstly, check whether there is a bookmark here.
883 if (lyxrc.bookmarks_visibility == LyXRC::BMK_INLINE)
884 for (auto const & bp_p : bpl)
885 if (bp_p.second == i) {
887 f.fontInfo().setColor(Color_bookmark);
888 // ❶ U+2776 DINGBAT NEGATIVE CIRCLED DIGIT ONE
889 char_type const ch = 0x2775 + bp_p.first;
890 row.addVirtual(i, docstring(1, ch), f, Change());
893 // The stopping condition is here so that the display of a
894 // bookmark can take place at paragraph start too.
898 char_type c = par.getChar(i);
899 // The most special cases are handled first.
900 if (par.isInset(i)) {
901 Inset const * ins = par.getInset(i);
902 Dimension dim = bv_->coordCache().insets().dim(ins);
903 row.add(i, ins, dim, *fi, par.lookupChange(i));
904 } else if (c == ' ' && i + 1 == body_pos) {
905 // This space is an \item separator. Represent it with a
906 // special space element, which dimension will be computed
908 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
909 int const wid = fm.width(par.layout().labelsep);
910 row.addMarginSpace(i, wid, *fi, par.lookupChange(i));
911 } else if (c == '\t')
912 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
913 *fi, par.lookupChange(i));
914 else if (c == 0x2028 || c == 0x2029) {
916 * U+2028 LINE SEPARATOR
917 * U+2029 PARAGRAPH SEPARATOR
919 * These are special unicode characters that break
920 * lines/pragraphs. Not handling them leads to trouble wrt
921 * Qt QTextLayout formatting. We add a visible character
922 * on screen so that the user can see that something is
926 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
927 // ¶ U+00B6 PILCROW SIGN
928 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
929 row.add(i, screen_char, *fi, par.lookupChange(i));
931 // row elements before body are unbreakable
932 row.add(i, c, *fi, par.lookupChange(i));
934 // add inline completion width
935 // draw logically behind the previous character
936 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
937 docstring const comp = bv_->inlineCompletion();
938 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
942 f.fontInfo().setColor(Color_inlinecompletion);
943 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
945 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
946 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
955 // End of paragraph marker, either if LyXRc requires it, or there
956 // is an end of paragraph change. The logic here is almost the
957 // same as in redoParagraph, remember keep them in sync.
958 ParagraphList const & pars = text_->paragraphs();
959 Change const & endchange = par.lookupChange(end);
960 if (endchange.changed())
961 row.needsChangeBar(true);
962 if ((lyxrc.paragraph_markers || endchange.changed())
963 && size_type(pit + 1) < pars.size()) {
964 // add a virtual element for the end-of-paragraph
965 // marker; it is shown on screen, but does not exist
967 Font f(text_->layoutFont(pit));
968 f.fontInfo().setColor(Color_paragraphmarker);
969 f.setLanguage(par.getParLanguage(buf.params()));
970 // ¶ U+00B6 PILCROW SIGN
971 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, endchange);
980 /** Helper template flexible_const_iterator<T>
981 * A way to iterate over a const container, but insert fake elements in it.
982 * In the case of a row, we will have to break some elements, which
983 * create new ones. This class allows to abstract this.
984 * Only the required parts are implemented for now.
987 class flexible_const_iterator {
988 typedef typename T::value_type value_type;
992 flexible_const_iterator & operator++() {
1000 value_type operator*() const { return pile_.empty() ? *cit_ : pile_.back(); }
1002 value_type const * operator->() const { return pile_.empty() ? &*cit_ : &pile_.back(); }
1004 void put(value_type const & e) { pile_.push_back(e); }
1006 // Put a sequence of elements on the pile (in reverse order!)
1007 void put(vector<value_type> const & elts) {
1008 pile_.insert(pile_.end(), elts.rbegin(), elts.rend());
1011 // This should be private, but declaring the friend functions is too much work
1013 typename T::const_iterator cit_;
1014 // A vector that is used as like a pile to store the elements to
1015 // consider before incrementing the underlying iterator.
1016 vector<value_type> pile_;
1021 flexible_const_iterator<T> flexible_begin(T const & t)
1023 return { t.begin(), vector<typename T::value_type>() };
1028 flexible_const_iterator<T> flexible_end(T const & t)
1030 return { t.end(), vector<typename T::value_type>() };
1034 // Equality is only possible if respective piles are empty
1036 bool operator==(flexible_const_iterator<T> const & t1,
1037 flexible_const_iterator<T> const & t2)
1039 return t1.cit_ == t2.cit_ && t1.pile_.empty() && t2.pile_.empty();
1043 Row newRow(TextMetrics const & tm, pit_type pit, pos_type pos, bool is_rtl)
1048 nrow.left_margin = tm.leftMargin(pit, pos);
1049 nrow.right_margin = tm.rightMargin(pit);
1050 nrow.setRTL(is_rtl);
1052 swap(nrow.left_margin, nrow.right_margin);
1053 // Remember that the row width takes into account the left_margin
1054 // but not the right_margin.
1055 nrow.dim().wid = nrow.left_margin;
1060 void cleanupRow(Row & row, bool at_end)
1063 row.endpos(row.pos());
1067 row.endpos(row.back().endpos);
1068 // remove trailing spaces on row break
1069 if (!at_end && !row.flushed())
1071 // boundary exists when there was no space at the end of row
1072 row.end_boundary(!at_end && row.back().endpos == row.endpos());
1073 // make sure that the RTL elements are in reverse ordering
1078 // Implement the priorities described in RowFlags.h.
1079 bool needsRowBreak(int f1, int f2)
1081 if (f1 & AlwaysBreakAfter /*|| f2 & AlwaysBreakBefore*/)
1083 if (f1 & NoBreakAfter || f2 & NoBreakBefore)
1085 if (f1 & BreakAfter || f2 & BreakBefore)
1094 RowList TextMetrics::breakParagraph(Row const & bigrow) const
1097 bool const is_rtl = text_->isRTL(bigrow.pit());
1098 bool const end_label = text_->getEndLabel(bigrow.pit()) != END_LABEL_NO_LABEL;
1099 int const next_width = max_width_ - leftMargin(bigrow.pit(), bigrow.endpos())
1100 - rightMargin(bigrow.pit());
1103 flexible_const_iterator<Row> fcit = flexible_begin(bigrow);
1104 flexible_const_iterator<Row> const end = flexible_end(bigrow);
1106 bool const row_empty = rows.empty() || rows.back().empty();
1107 // The row flags of previous element, if there is one.
1108 // Otherwise we use NoBreakAfter to avoid an empty row before
1109 // e.g. a displayed equation.
1110 int const f1 = row_empty ? NoBreakAfter : rows.back().back().row_flags;
1111 // The row flags of next element, if there is one.
1112 // Otherwise we use NoBreakBefore (see above), unless the
1113 // paragraph has an end label (for which an empty row is OK).
1114 int const f2 = (fcit == end) ? (end_label ? Inline : NoBreakBefore)
1116 if (rows.empty() || needsRowBreak(f1, f2)) {
1117 if (!rows.empty()) {
1118 // Flush row as requested by row flags
1119 rows.back().flushed((f1 & Flush) || (f2 & FlushBefore));
1120 cleanupRow(rows.back(), false);
1122 pos_type pos = rows.empty() ? 0 : rows.back().endpos();
1123 rows.push_back(newRow(*this, bigrow.pit(), pos, is_rtl));
1124 // the width available for the row.
1125 width = max_width_ - rows.back().right_margin;
1128 // The stopping condition is here because we may need a new
1129 // empty row at the end.
1133 // Next element to consider is either the top of the temporary
1134 // pile, or the place when we were in main row
1135 Row::Element elt = *fcit;
1137 elt.splitAt(width - rows.back().width(), next_width, false, tail);
1138 Row & rb = rows.back();
1139 if (elt.type == Row::MARGINSPACE)
1140 elt.dim.wid = max(elt.dim.wid, leftMargin(bigrow.pit()) - rb.width());
1143 if (rb.width() > width) {
1144 // Keep the tail for later; this ought to be rare, but play safe.
1147 // if the row is too large, try to cut at last separator.
1148 tail = rb.shortenIfNeeded(width, next_width);
1151 // Go to next element
1154 // Handle later the elements returned by splitAt or shortenIfNeeded.
1158 if (!rows.empty()) {
1159 // Last row in paragraph is flushed
1160 rows.back().flushed(true);
1161 cleanupRow(rows.back(), true);
1168 int TextMetrics::parTopSpacing(pit_type const pit) const
1170 Paragraph const & par = text_->getPar(pit);
1171 Layout const & layout = par.layout();
1174 ParagraphList const & pars = text_->paragraphs();
1175 double const dh = defaultRowHeight();
1177 BufferParams const & bparams = bv_->buffer().params();
1178 Inset const & inset = text_->inset();
1179 // some parskips VERY EASY IMPLEMENTATION
1180 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1181 && !inset.getLayout().parbreakIsNewline()
1182 && !par.layout().parbreak_is_newline
1184 && ((layout.isParagraph() && par.getDepth() == 0)
1185 || (pars[pit - 1].layout().isParagraph()
1186 && pars[pit - 1].getDepth() == 0))) {
1187 asc += bparams.getDefSkip().inPixels(*bv_);
1190 if (par.params().startOfAppendix())
1193 // special code for the top label
1194 if (layout.labelIsAbove()
1195 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1196 && !par.labelString().empty()) {
1197 FontInfo labelfont = text_->labelFont(par);
1198 FontMetrics const & lfm = theFontMetrics(labelfont);
1199 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1200 * text_->spacing(par)
1201 + (layout.topsep + layout.labelbottomsep) * dh);
1204 // Add the layout spaces, for example before and after
1205 // a section, or between the items of a itemize or enumerate
1208 pit_type prev = text_->depthHook(pit, par.getDepth());
1209 Paragraph const & prevpar = pars[prev];
1210 double layoutasc = 0;
1212 && prevpar.layout() == layout
1213 && prevpar.getDepth() == par.getDepth()
1214 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1215 layoutasc = layout.itemsep * dh;
1216 } else if (pit != 0 && layout.topsep > 0)
1217 // combine the separation between different layouts (with same depth)
1218 layoutasc = max(0.0,
1219 prevpar.getDepth() != par.getDepth() ? layout.topsep
1220 : layout.topsep - prevpar.layout().bottomsep) * dh;
1222 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1224 prev = text_->outerHook(pit);
1225 if (prev != pit_type(pars.size())) {
1226 asc += int(pars[prev].layout().parsep * dh);
1227 } else if (pit != 0) {
1228 Paragraph const & prevpar2 = pars[pit - 1];
1229 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1230 asc += int(layout.parsep * dh);
1237 int TextMetrics::parBottomSpacing(pit_type const pit) const
1239 double layoutdesc = 0;
1240 ParagraphList const & pars = text_->paragraphs();
1241 double const dh = defaultRowHeight();
1243 // add the layout spaces, for example before and after
1244 // a section, or between the items of a itemize or enumerate
1246 pit_type nextpit = pit + 1;
1247 if (nextpit != pit_type(pars.size())) {
1248 pit_type cpit = pit;
1250 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1251 double usual = pars[cpit].layout().bottomsep * dh;
1253 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1254 if (pars[cpit].layout() != pars[nextpit].layout()
1255 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1256 unusual = pars[cpit].layout().bottomsep * dh;
1257 layoutdesc = max(unusual, usual);
1258 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1259 if (pars[cpit].layout() != pars[nextpit].layout()
1260 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1261 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1265 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1269 void TextMetrics::setRowHeight(Row & row) const
1271 Paragraph const & par = text_->getPar(row.pit());
1272 Layout const & layout = par.layout();
1273 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1275 // Initial value for ascent (useful if row is empty).
1276 Font const font = displayFont(row.pit(), row.pos());
1277 FontMetrics const & fm = theFontMetrics(font);
1278 int maxasc = int(fm.maxAscent() * spacing_val);
1279 int maxdes = int(fm.maxDescent() * spacing_val);
1281 // Take label string into account (useful if labelfont is large)
1282 if (row.pos() == 0 && layout.labelIsInline()) {
1283 FontInfo const labelfont = text_->labelFont(par);
1284 FontMetrics const & lfm = theFontMetrics(labelfont);
1285 maxasc = max(maxasc, int(lfm.maxAscent() * spacing_val));
1286 maxdes = max(maxdes, int(lfm.maxDescent() * spacing_val));
1289 // Find the ascent/descent of the row contents
1290 for (Row::Element const & e : row) {
1292 maxasc = max(maxasc, e.dim.ascent());
1293 maxdes = max(maxdes, e.dim.descent());
1295 FontMetrics const & fm2 = theFontMetrics(e.font);
1296 maxasc = max(maxasc, int(fm2.maxAscent() * spacing_val));
1297 maxdes = max(maxdes, int(fm2.maxDescent() * spacing_val));
1301 // This is nicer with box insets
1305 row.dim().asc = maxasc;
1306 row.dim().des = maxdes;
1308 // This is useful for selections
1309 row.contents_dim() = row.dim();
1313 // x is an absolute screen coord
1314 // returns the column near the specified x-coordinate of the row
1315 // x is set to the real beginning of this column
1316 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1317 bool & boundary) const
1319 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1320 /// For the main Text, it is possible that this pit is not
1321 /// yet in the CoordCache when moving cursor up.
1322 /// x Paragraph coordinate is always 0 for main text anyway.
1323 int const xo = origin_.x_;
1326 // Adapt to cursor row scroll offset if applicable.
1327 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1330 pos_type pos = row.pos();
1333 x = row.left_margin;
1334 else if (x <= row.left_margin) {
1335 pos = row.front().left_pos();
1336 x = row.left_margin;
1337 } else if (x >= row.width()) {
1338 pos = row.back().right_pos();
1341 double w = row.left_margin;
1342 Row::const_iterator cit = row.begin();
1343 Row::const_iterator cend = row.end();
1344 for ( ; cit != cend; ++cit) {
1345 if (w <= x && w + cit->full_width() > x) {
1346 int x_offset = int(x - w);
1347 pos = cit->x2pos(x_offset);
1348 x = int(x_offset + w);
1351 w += cit->full_width();
1353 if (cit == row.end()) {
1354 pos = row.back().right_pos();
1357 /** This tests for the case where the cursor is placed
1358 * just before a font direction change. See comment on
1359 * the boundary_ member in DocIterator.h to understand
1360 * how boundary helps here.
1362 else if (pos == cit->endpos
1363 && ((!cit->isRTL() && cit + 1 != row.end()
1364 && (cit + 1)->isRTL())
1365 || (cit->isRTL() && cit != row.begin()
1366 && !(cit - 1)->isRTL())))
1370 /** This tests for the case where the cursor is set at the end
1371 * of a row which has been broken due something else than a
1372 * separator (a display inset or a forced breaking of the
1373 * row). We know that there is a separator when the end of the
1374 * row is larger than the end of its last element.
1376 if (!row.empty() && pos == row.back().endpos
1377 && row.back().endpos == row.endpos()) {
1378 Inset const * inset = row.back().inset;
1379 if (inset && (inset->lyxCode() == NEWLINE_CODE
1380 || inset->lyxCode() == SEPARATOR_CODE))
1381 pos = row.back().pos;
1383 boundary = row.end_boundary();
1387 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1393 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1395 // We play safe and use parMetrics(pit) to make sure the
1396 // ParagraphMetrics will be redone and OK to use if needed.
1397 // Otherwise we would use an empty ParagraphMetrics in
1398 // upDownInText() while in selection mode.
1399 ParagraphMetrics const & pm = parMetrics(pit);
1401 LBUFERR(row < int(pm.rows().size()));
1403 Row const & r = pm.rows()[row];
1404 return getPosNearX(r, x, bound);
1408 // y is screen coordinate
1409 pit_type TextMetrics::getPitNearY(int y)
1411 LASSERT(!text_->paragraphs().empty(), return -1);
1412 LASSERT(!par_metrics_.empty(), return -1);
1413 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1415 // look for highest numbered paragraph with y coordinate less than given y
1418 ParMetricsCache::const_iterator it = par_metrics_.begin();
1419 ParMetricsCache::const_iterator et = par_metrics_.end();
1420 ParMetricsCache::const_iterator last = et;
1423 ParagraphMetrics const & pm = it->second;
1425 if (y < it->second.position() - pm.ascent()) {
1426 // We are looking for a position that is before the first paragraph in
1427 // the cache (which is in priciple off-screen, that is before the
1430 // We are already at the first paragraph in the inset.
1432 // OK, this is the paragraph we are looking for.
1433 pit = it->first - 1;
1438 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1440 if (y >= last->second.position() + pm_last.descent()) {
1441 // We are looking for a position that is after the last paragraph in
1442 // the cache (which is in priciple off-screen), that is before the
1444 pit = last->first + 1;
1445 if (pit == int(text_->paragraphs().size()))
1446 // We are already at the last paragraph in the inset.
1448 // OK, this is the paragraph we are looking for.
1449 newParMetricsDown();
1453 for (; it != et; ++it) {
1454 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1455 << " y: " << it->second.position());
1457 ParagraphMetrics const & pm2 = par_metrics_[it->first];
1459 if (it->first >= pit && it->second.position() - pm2.ascent() <= y) {
1461 yy = it->second.position();
1465 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1471 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1472 bool assert_in_view, bool up)
1474 ParagraphMetrics const & pm = par_metrics_[pit];
1476 int yy = pm.position() - pm.ascent();
1477 LBUFERR(!pm.rows().empty());
1478 RowList::const_iterator rit = pm.rows().begin();
1479 RowList::const_iterator rlast = pm.rows().end();
1481 for (; rit != rlast; yy += rit->height(), ++rit)
1482 if (yy + rit->height() > y)
1485 if (assert_in_view) {
1486 if (!up && yy + rit->height() > y) {
1487 if (rit != pm.rows().begin()) {
1490 } else if (pit != 0) {
1493 ParagraphMetrics const & pm2 = par_metrics_[pit];
1494 rit = pm2.rows().end();
1498 } else if (up && yy != y) {
1500 y = yy + rit->height();
1502 } else if (pit < int(text_->paragraphs().size()) - 1) {
1504 newParMetricsDown();
1505 ParagraphMetrics const & pm2 = par_metrics_[pit];
1506 rit = pm2.rows().begin();
1515 // x,y are absolute screen coordinates
1516 // sets cursor recursively descending into nested editable insets
1517 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1518 bool assert_in_view, bool up)
1520 if (lyxerr.debugging(Debug::WORKAREA)) {
1521 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1522 cur.bv().coordCache().dump();
1524 pit_type pit = getPitNearY(y);
1525 LASSERT(pit != -1, return 0);
1526 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1529 // Do we cover an inset?
1530 InsetList::Element * e = checkInsetHit(pit, x, y);
1533 // No inset, set position in the text
1534 bool bound = false; // is modified by getPosNearX
1535 cur.pos() = getPosNearX(row, x, bound);
1536 cur.boundary(bound);
1537 cur.setCurrentFont();
1542 Inset * inset = e->inset;
1543 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1545 // Set position in front of inset
1547 cur.boundary(false);
1550 // Try to descend recursively inside the inset.
1551 Inset * edited = inset->editXY(cur, x, y);
1552 // FIXME: it is not clear that the test on position is needed
1553 // Remove it if/when semantics of editXY is clarified
1554 if (cur.text() == text_ && cur.pos() == e->pos) {
1555 // non-editable inset, set cursor after the inset if x is
1556 // nearer to that position (bug 9628)
1557 bool bound = false; // is modified by getPosNearX
1558 cur.pos() = getPosNearX(row, x, bound);
1559 cur.boundary(bound);
1560 cur.setCurrentFont();
1564 if (cur.top().text() == text_)
1565 cur.setCurrentFont();
1570 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1572 LASSERT(text_ == cur.text(), return);
1573 pit_type const pit = getPitNearY(y);
1574 LASSERT(pit != -1, return);
1576 ParagraphMetrics const & pm = par_metrics_[pit];
1578 int yy = pm.position() - pm.rows().front().ascent();
1579 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1580 " pit: " << pit << " yy: " << yy);
1583 LBUFERR(pm.rows().size());
1584 for (; r < int(pm.rows().size()) - 1; ++r) {
1585 Row const & row = pm.rows()[r];
1586 if (yy + row.height() > y)
1591 Row const & row = pm.rows()[r];
1593 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1597 pos_type const pos = getPosNearX(row, xx, bound);
1599 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1601 text_->setCursor(cur, pit, pos, true, bound);
1602 // remember new position.
1607 //takes screen x,y coordinates
1608 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1610 Paragraph const & par = text_->paragraphs()[pit];
1611 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1613 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1615 for (InsetList::Element const & e : par.insetList()) {
1616 LYXERR(Debug::DEBUG, "examining inset " << e.inset);
1618 if (insetCache.covers(e.inset, x, y)) {
1619 LYXERR(Debug::DEBUG, "Hit inset: " << e.inset);
1620 return const_cast<InsetList::Element *>(&e);
1624 LYXERR(Debug::DEBUG, "No inset hit. ");
1629 //takes screen x,y coordinates
1630 Inset * TextMetrics::checkInsetHit(int x, int y)
1632 pit_type const pit = getPitNearY(y);
1633 LASSERT(pit != -1, return 0);
1634 InsetList::Element * e = checkInsetHit(pit, x, y);
1643 int TextMetrics::cursorX(CursorSlice const & sl,
1644 bool boundary) const
1646 LASSERT(sl.text() == text_, return 0);
1648 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1649 if (pm.rows().empty())
1651 Row const & row = pm.getRow(sl.pos(), boundary);
1652 pos_type const pos = sl.pos();
1655 row.findElement(pos, boundary, x);
1661 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1663 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1664 ParagraphMetrics const & pm = parMetrics(sl.pit());
1665 if (pm.rows().empty())
1669 h -= parMetrics(0).rows()[0].ascent();
1670 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1671 h += parMetrics(pit).height();
1674 if (pos && boundary)
1676 size_t const rend = pm.pos2row(pos);
1677 for (size_t rit = 0; rit != rend; ++rit)
1678 h += pm.rows()[rit].height();
1679 h += pm.rows()[rend].ascent();
1684 // the cursor set functions have a special mechanism. When they
1685 // realize you left an empty paragraph, they will delete it.
1687 bool TextMetrics::cursorHome(Cursor & cur)
1689 LASSERT(text_ == cur.text(), return false);
1690 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1691 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1692 return text_->setCursor(cur, cur.pit(), row.pos());
1696 bool TextMetrics::cursorEnd(Cursor & cur)
1698 LASSERT(text_ == cur.text(), return false);
1699 // if not on the last row of the par, put the cursor before
1700 // the final space exept if I have a spanning inset or one string
1701 // is so long that we force a break.
1702 pos_type end = cur.textRow().endpos();
1704 // empty text, end-1 is no valid position
1706 bool boundary = false;
1707 if (end != cur.lastpos()) {
1708 if (!cur.paragraph().isLineSeparator(end-1)
1709 && !cur.paragraph().isNewline(end-1)
1710 && !cur.paragraph().isEnvSeparator(end-1))
1714 } else if (cur.paragraph().isEnvSeparator(end-1))
1716 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1720 void TextMetrics::deleteLineForward(Cursor & cur)
1722 LASSERT(text_ == cur.text(), return);
1723 if (cur.lastpos() == 0) {
1724 // Paragraph is empty, so we just go forward
1725 text_->cursorForward(cur);
1728 cur.selection(true); // to avoid deletion
1731 // What is this test for ??? (JMarc)
1732 if (!cur.selection())
1733 text_->deleteWordForward(cur);
1735 cap::cutSelection(cur, false);
1736 cur.checkBufferStructure();
1741 int TextMetrics::leftMargin(pit_type pit) const
1743 // FIXME: what is the semantics? It depends on whether the
1744 // paragraph is empty!
1745 return leftMargin(pit, text_->paragraphs()[pit].size());
1749 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1751 ParagraphList const & pars = text_->paragraphs();
1753 LASSERT(pit >= 0, return 0);
1754 LASSERT(pit < int(pars.size()), return 0);
1755 Paragraph const & par = pars[pit];
1756 LASSERT(pos >= 0, return 0);
1757 // We do not really care whether pos > par.size(), since we do not
1758 // access the data. It can be actually useful, when querying the
1759 // margin without indentation (see leftMargin(pit_type).
1761 Buffer const & buffer = bv_->buffer();
1762 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1763 DocumentClass const & tclass = buffer.params().documentClass();
1764 Layout const & layout = par.layout();
1765 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1767 docstring parindent = layout.parindent;
1771 if (text_->isMainText()) {
1772 l_margin += bv_->leftMargin();
1773 l_margin += bfm.signedWidth(tclass.leftmargin());
1776 int depth = par.getDepth();
1778 // find the next level paragraph
1779 pit_type newpar = text_->outerHook(pit);
1780 if (newpar != pit_type(pars.size())) {
1781 if (pars[newpar].layout().isEnvironment()) {
1782 int nestmargin = depth * nestMargin();
1783 if (text_->isMainText())
1784 nestmargin += changebarMargin();
1785 l_margin = max(leftMargin(newpar), nestmargin);
1786 // Remove the parindent that has been added
1787 // if the paragraph was empty.
1788 if (pars[newpar].empty() &&
1789 buffer.params().paragraph_separation ==
1790 BufferParams::ParagraphIndentSeparation) {
1791 docstring pi = pars[newpar].layout().parindent;
1792 l_margin -= bfm.signedWidth(pi);
1795 if (tclass.isDefaultLayout(par.layout())
1796 || tclass.isPlainLayout(par.layout())) {
1797 if (pars[newpar].params().noindent())
1800 parindent = pars[newpar].layout().parindent;
1805 // Check for reasons to remove indentation.
1806 // First, at document level.
1807 if (buffer.params().paragraph_separation ==
1808 BufferParams::ParagraphSkipSeparation)
1810 // This happens after sections or environments in standard classes.
1811 // We have to check the previous layout at same depth.
1812 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1813 pit_type prev = text_->depthHook(pit, par.getDepth());
1814 if (par.layout() == pars[prev].layout()) {
1816 && pars[pit - 1].layout().nextnoindent)
1818 } else if (pars[prev].layout().nextnoindent)
1821 // The previous paragraph may have ended with a separator inset.
1823 Paragraph const & ppar = pars[pit - 1];
1824 if (ppar.size() > 0) {
1825 auto * in = dynamic_cast<InsetSeparator const *>(ppar.getInset(ppar.size() - 1));
1826 if (in != nullptr && in->nextnoindent())
1831 FontInfo const labelfont = text_->labelFont(par);
1832 FontMetrics const & lfm = theFontMetrics(labelfont);
1834 switch (layout.margintype) {
1835 case MARGIN_DYNAMIC:
1836 if (!layout.leftmargin.empty()) {
1837 l_margin += bfm.signedWidth(layout.leftmargin);
1839 if (!par.labelString().empty()) {
1840 l_margin += lfm.signedWidth(layout.labelindent);
1841 l_margin += lfm.width(par.labelString());
1842 l_margin += lfm.width(layout.labelsep);
1846 case MARGIN_MANUAL: {
1847 l_margin += lfm.signedWidth(layout.labelindent);
1848 // The width of an empty par, even with manual label, should be 0
1849 if (!par.empty() && pos >= par.beginOfBody()) {
1850 if (!par.getLabelWidthString().empty()) {
1851 docstring labstr = par.getLabelWidthString();
1852 l_margin += lfm.width(labstr);
1853 l_margin += lfm.width(layout.labelsep);
1859 case MARGIN_STATIC: {
1860 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1861 / (par.getDepth() + 4);
1865 case MARGIN_FIRST_DYNAMIC:
1866 if (layout.labeltype == LABEL_MANUAL) {
1867 // if we are at position 0, we are never in the body
1868 if (pos > 0 && pos >= par.beginOfBody())
1869 l_margin += lfm.signedWidth(layout.leftmargin);
1871 l_margin += lfm.signedWidth(layout.labelindent);
1873 // Special case to fix problems with
1875 || (layout.labeltype == LABEL_STATIC
1876 && layout.latextype == LATEX_ENVIRONMENT
1877 && !text_->isFirstInSequence(pit))) {
1878 l_margin += lfm.signedWidth(layout.leftmargin);
1879 } else if (!layout.labelIsAbove()) {
1880 l_margin += lfm.signedWidth(layout.labelindent);
1881 l_margin += lfm.width(layout.labelsep);
1882 l_margin += lfm.width(par.labelString());
1886 case MARGIN_RIGHT_ADDRESS_BOX:
1887 // This is handled globally in redoParagraph().
1891 if (!par.params().leftIndent().zero())
1892 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1894 LyXAlignment align = par.getAlign(bv_->buffer().params());
1896 // set the correct parindent
1898 && (layout.labeltype == LABEL_NO_LABEL
1899 || layout.labeltype == LABEL_ABOVE
1900 || layout.labeltype == LABEL_CENTERED
1901 || (layout.labeltype == LABEL_STATIC
1902 && layout.latextype == LATEX_ENVIRONMENT
1903 && !text_->isFirstInSequence(pit)))
1904 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1905 && !par.params().noindent()
1906 // in some insets, paragraphs are never indented
1907 && !text_->inset().neverIndent()
1908 // display style insets do not need indentation
1911 && par.getInset(0)->rowFlags() & Display)
1912 && (!(tclass.isDefaultLayout(par.layout())
1913 || tclass.isPlainLayout(par.layout()))
1914 || buffer.params().paragraph_separation
1915 == BufferParams::ParagraphIndentSeparation)) {
1916 /* use the parindent of the layout when the default
1917 * indentation is used otherwise use the indentation set in
1918 * the document settings
1920 if (buffer.params().getParIndent().empty())
1921 l_margin += bfm.signedWidth(parindent);
1923 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1930 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1932 if (par_metrics_.empty())
1938 y -= par_metrics_.begin()->second.ascent();
1939 for (auto & pm_pair : par_metrics_) {
1940 pit_type const pit = pm_pair.first;
1941 ParagraphMetrics & pm = pm_pair.second;
1943 // Save the paragraph position in the cache.
1945 drawParagraph(pi, pit, x, y);
1951 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1953 ParagraphMetrics const & pm = par_metrics_[pit];
1954 if (pm.rows().empty())
1956 size_t const nrows = pm.rows().size();
1957 // Remember left and right margin for drawing math numbers
1958 Changer changeleft = changeVar(pi.leftx, x + leftMargin(pit));
1959 Changer changeright = changeVar(pi.rightx, x + width() - rightMargin(pit));
1961 // Use fast lane in nodraw stage.
1962 if (pi.pain.isNull()) {
1963 for (size_t i = 0; i != nrows; ++i) {
1965 Row const & row = pm.rows()[i];
1966 // Adapt to cursor row scroll offset if applicable.
1967 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1971 RowPainter rp(pi, *text_, row, row_x, y);
1973 rp.paintOnlyInsets();
1979 int const ww = bv_->workHeight();
1980 Cursor const & cur = bv_->cursor();
1981 DocIterator sel_beg = cur.selectionBegin();
1982 DocIterator sel_end = cur.selectionEnd();
1983 bool selection = cur.selection()
1984 // This is our text.
1985 && cur.text() == text_
1986 // if the anchor is outside, this is not our selection
1987 && cur.normalAnchor().text() == text_
1988 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1990 // We store the begin and end pos of the selection relative to this par
1991 DocIterator sel_beg_par = cur.selectionBegin();
1992 DocIterator sel_end_par = cur.selectionEnd();
1994 // We care only about visible selection.
1996 if (pit != sel_beg.pit()) {
1997 sel_beg_par.pit() = pit;
1998 sel_beg_par.pos() = 0;
2000 if (pit != sel_end.pit()) {
2001 sel_end_par.pit() = pit;
2002 sel_end_par.pos() = sel_end_par.lastpos();
2006 if (text_->isRTL(pit))
2007 swap(pi.leftx, pi.rightx);
2009 BookmarksSection::BookmarkPosList bpl =
2010 theSession().bookmarks().bookmarksInPar(bv_->buffer().fileName(), pm.id());
2012 for (size_t i = 0; i != nrows; ++i) {
2014 Row const & row = pm.rows()[i];
2015 // Adapt to cursor row scroll offset if applicable.
2016 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
2020 // It is not needed to draw on screen if we are not inside.
2021 bool const inside = (y + row.descent() >= 0
2022 && y - row.ascent() < ww);
2024 // Inset positions have already been set in nodraw stage.
2030 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2032 row.clearSelectionAndMargins();
2034 // The row knows nothing about the paragraph, so we have to check
2035 // whether this row is the first or last and update the margins.
2036 if (row.selection()) {
2037 if (row.sel_beg == 0)
2038 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
2039 if (row.sel_end == sel_end_par.lastpos())
2040 row.change(row.end_margin_sel, sel_end.pit() > pit);
2043 // Take this opportunity to spellcheck the row contents.
2044 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
2045 text_->getPar(pit).spellCheck();
2048 RowPainter rp(pi, *text_, row, row_x, y);
2050 // Don't paint the row if a full repaint has not been requested
2051 // and if it has not changed.
2052 if (!pi.full_repaint && !row.changed()) {
2053 // Paint only the insets if the text itself is
2055 rp.paintOnlyInsets();
2056 rp.paintTooLargeMarks(
2057 row_x + row.left_x() < bv_->leftMargin(),
2058 row_x + row.right_x() > bv_->workWidth() - bv_->rightMargin());
2064 // Clear background of this row if paragraph background was not
2065 // already cleared because of a full repaint.
2066 if (!pi.full_repaint && row.changed()) {
2067 LYXERR(Debug::PAINTING, "Clear rect@("
2068 << x << ", " << y - row.ascent() << ")="
2069 << width() << " x " << row.height());
2070 pi.pain.fillRectangle(x, y - row.ascent(),
2071 width(), row.height(), pi.background_color);
2074 // Instrumentation for testing row cache (see also
2076 if (lyxerr.debugging(Debug::PAINTING)
2077 && (row.selection() || pi.full_repaint || row.changed())) {
2078 string const foreword = text_->isMainText() ? "main text redraw "
2079 : "inset text redraw: ";
2080 LYXERR0(foreword << "pit=" << pit << " row=" << i
2081 << (row.selection() ? " row_selection": "")
2082 << (pi.full_repaint ? " full_repaint" : "")
2083 << (row.changed() ? " row.changed" : ""));
2086 // Backup full_repaint status and force full repaint
2087 // for inner insets as the Row has been cleared out.
2088 bool tmp = pi.full_repaint;
2089 pi.full_repaint = true;
2091 rp.paintSelection();
2094 if (row.needsChangeBar())
2095 rp.paintChangeBar();
2101 rp.paintTooLargeMarks(
2102 row_x + row.left_x() < bv_->leftMargin(),
2103 row_x + row.right_x() > bv_->workWidth() - bv_->rightMargin());
2104 // indicate bookmarks presence in margin
2105 if (lyxrc.bookmarks_visibility == LyXRC::BMK_MARGIN)
2106 for (auto const & bp_p : bpl)
2107 if (bp_p.second >= row.pos() && bp_p.second < row.endpos())
2108 rp.paintBookmark(bp_p.first);
2113 // This debug code shows on screen which rows are repainted.
2114 // FIXME: since the updates related to caret blinking restrict
2115 // the painter to a small rectangle, the numbers are not
2116 // updated when this happens. Change the code in
2117 // GuiWorkArea::Private::show/hideCaret if this is important.
2118 static int count = 0;
2120 FontInfo fi(sane_font);
2121 fi.setSize(TINY_SIZE);
2122 fi.setColor(Color_red);
2123 pi.pain.text(row_x, y, convert<docstring>(count), fi);
2126 // Restore full_repaint status.
2127 pi.full_repaint = tmp;
2132 //LYXERR(Debug::PAINTING, ".");
2136 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2137 Dimension & dim) const
2139 DocIterator from = cur.bv().cursor();
2140 DocIterator to = from;
2141 text_->getWord(from.top(), to.top(), PREVIOUS_WORD);
2143 // The vertical dimension of the word
2144 Font const font = displayFont(cur.pit(), from.pos());
2145 FontMetrics const & fm = theFontMetrics(font);
2146 // the +1's below are related to the extra pixels added in setRowHeight
2147 dim.asc = fm.maxAscent() + 1;
2148 dim.des = fm.maxDescent() + 1;
2150 // get position on screen of the word start and end
2151 //FIXME: Is it necessary to explicitly set this to false?
2152 from.boundary(false);
2153 Point lxy = cur.bv().getPos(from);
2154 Point rxy = cur.bv().getPos(to);
2155 dim.wid = abs(rxy.x_ - lxy.x_);
2157 // calculate position of word
2159 x = min(rxy.x_, lxy.x_);
2161 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2162 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2165 int defaultRowHeight()
2167 return int(theFontMetrics(sane_font).maxHeight() * 1.2);