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/InsetText.h"
40 #include "mathed/MacroTable.h"
42 #include "frontends/FontMetrics.h"
43 #include "frontends/NullPainter.h"
45 #include "support/debug.h"
46 #include "support/lassert.h"
47 #include "support/Changer.h"
57 using frontend::FontMetrics;
62 int numberOfLabelHfills(Paragraph const & par, Row const & row)
64 pos_type last = row.endpos() - 1;
65 pos_type first = row.pos();
67 // hfill *DO* count at the beginning of paragraphs!
69 while (first < last && par.isHfill(first))
73 last = min(last, par.beginOfBody());
75 for (pos_type p = first; p < last; ++p) {
82 // FIXME: this needs to be rewritten, probably by merging it into some
83 // code that, besides counting, sets the active status of the space
84 // inset in the row element.
85 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
86 pos_type const body_pos)
89 Row::const_iterator cit = row.begin();
90 Row::const_iterator const end = row.end();
91 for ( ; cit != end ; ++cit)
92 if (cit->pos >= body_pos
93 && cit->inset && pm.hfillExpansion(row, cit->pos))
101 /////////////////////////////////////////////////////////////////////
105 /////////////////////////////////////////////////////////////////////
108 TextMetrics::TextMetrics(BufferView * bv, Text * text)
109 : bv_(bv), text_(text), dim_(bv_->workWidth(), 10, 10),
110 max_width_(dim_.wid), tight_(false)
114 bool TextMetrics::contains(pit_type pit) const
116 return par_metrics_.find(pit) != par_metrics_.end();
120 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
122 ParMetricsCache::const_iterator it = par_metrics_.begin();
123 return make_pair(it->first, &it->second);
127 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
129 LBUFERR(!par_metrics_.empty());
130 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
131 return make_pair(it->first, &it->second);
135 bool TextMetrics::isLastRow(Row const & row) const
137 ParagraphList const & pars = text_->paragraphs();
138 return row.endpos() >= pars[row.pit()].size()
139 && row.pit() + 1 == pit_type(pars.size());
143 bool TextMetrics::isFirstRow(Row const & row) const
145 return row.pos() == 0 && row.pit() == 0;
149 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
151 for (auto & pm_pair : par_metrics_)
152 if (pm_pair.first == pit)
153 for (Row & row : pm_pair.second.rows())
154 if (row.pos() == pos)
159 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
161 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
162 if (pmc_it == par_metrics_.end()) {
163 pmc_it = par_metrics_.insert(
164 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
166 if (pmc_it->second.rows().empty() && redo)
168 return pmc_it->second;
172 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
174 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
178 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit)
180 return parMetrics(pit, true);
184 void TextMetrics::newParMetricsDown()
186 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
187 pit_type const pit = last.first + 1;
188 if (pit == int(text_->paragraphs().size()))
191 // do it and update its position.
193 par_metrics_[pit].setPosition(last.second.position()
194 + last.second.descent() + par_metrics_[pit].ascent());
199 void TextMetrics::newParMetricsUp()
201 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
202 if (first.first == 0)
205 pit_type const pit = first.first - 1;
206 // do it and update its position.
208 par_metrics_[pit].setPosition(first.second.position()
209 - first.second.ascent() - par_metrics_[pit].descent());
214 bool TextMetrics::metrics(MetricsInfo const & mi, Dimension & dim, int min_width)
216 LBUFERR(mi.base.textwidth > 0);
217 max_width_ = mi.base.textwidth;
218 tight_ = mi.tight_insets;
219 // backup old dimension.
220 Dimension const old_dim = dim_;
223 dim_.wid = min_width;
224 pit_type const npar = text_->paragraphs().size();
225 if (npar > 1 && !tight_)
226 // If there is more than one row, expand the text to
227 // the full allowable width.
228 dim_.wid = max_width_;
230 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
231 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
233 bool changed = false;
235 for (pit_type pit = 0; pit != npar; ++pit) {
236 // create rows, but do not set alignment yet
237 changed |= redoParagraph(pit, false);
238 ParagraphMetrics const & pm = par_metrics_[pit];
240 if (dim_.wid < pm.width())
241 dim_.wid = pm.width();
244 // Now set alignment for all rows (the width might not have been known before).
245 for (pit_type pit = 0; pit != npar; ++pit) {
246 ParagraphMetrics & pm = par_metrics_[pit];
247 for (Row & row : pm.rows())
248 setRowAlignment(row, dim_.wid);
251 dim_.asc = par_metrics_[0].ascent();
252 dim_.des = h - dim_.asc;
253 //lyxerr << "dim_.wid " << dim_.wid << endl;
254 //lyxerr << "dim_.asc " << dim_.asc << endl;
255 //lyxerr << "dim_.des " << dim_.des << endl;
257 changed |= dim_ != old_dim;
263 void TextMetrics::updatePosCache(pit_type pit) const
265 frontend::NullPainter np;
266 PainterInfo pi(bv_, np);
267 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
271 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
273 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
277 int TextMetrics::rightMargin(pit_type const pit) const
279 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
283 void TextMetrics::applyOuterFont(Font & font) const
285 FontInfo lf(font_.fontInfo());
286 lf.reduce(bv_->buffer().params().getFont().fontInfo());
287 font.fontInfo().realize(lf);
291 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
293 LASSERT(pos >= 0, { static Font f; return f; });
295 ParagraphList const & pars = text_->paragraphs();
296 Paragraph const & par = pars[pit];
297 Layout const & layout = par.layout();
298 Buffer const & buffer = bv_->buffer();
300 BufferParams const & params = buffer.params();
301 pos_type const body_pos = par.beginOfBody();
303 // We specialize the 95% common case:
304 if (!par.getDepth()) {
305 Font f = par.getFontSettings(params, pos);
306 if (!text_->isMainText())
308 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
310 FontInfo const & lf = lab ? layout.labelfont : layout.font;
311 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
313 // In case the default family has been customized
314 if (lf.family() == INHERIT_FAMILY)
315 rlf.setFamily(params.getFont().fontInfo().family());
316 f.fontInfo().realize(rlf);
320 // The uncommon case need not be optimized as much
321 FontInfo const & layoutfont = pos < body_pos ?
322 layout.labelfont : layout.font;
324 Font font = par.getFontSettings(params, pos);
325 font.fontInfo().realize(layoutfont);
327 if (!text_->isMainText())
328 applyOuterFont(font);
330 // Realize against environment font information
331 // NOTE: the cast to pit_type should be removed when pit_type
332 // changes to a unsigned integer.
333 if (pit < pit_type(pars.size()))
334 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
336 // Realize with the fonts of lesser depth.
337 font.fontInfo().realize(params.getFont().fontInfo());
343 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
349 if (boundary && sl.pos() > 0)
352 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
356 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
358 // no RTL boundary at paragraph start
362 Font const & left_font = displayFont(pit, pos - 1);
364 return isRTLBoundary(pit, pos, left_font);
368 // isRTLBoundary returns false on a real end-of-line boundary,
369 // because otherwise the two boundary types get mixed up.
370 // This is the whole purpose of this being in TextMetrics.
371 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
372 Font const & font) const
374 if (// no RTL boundary at paragraph start
376 // if the metrics have not been calculated, then we are not
377 // on screen and can safely ignore issues about boundaries.
381 ParagraphMetrics const & pm = par_metrics_[pit];
382 // no RTL boundary in empty paragraph
383 if (pm.rows().empty())
386 pos_type const endpos = pm.getRow(pos - 1, false).endpos();
387 pos_type const startpos = pm.getRow(pos, false).pos();
388 // no RTL boundary at line start:
389 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
391 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
394 Paragraph const & par = text_->getPar(pit);
395 // no RTL boundary at line break:
396 // abc|\n -> move right -> abc\n (and not: abc\n|
398 if (startpos == pos && endpos == pos && endpos != par.size()
399 && (par.isNewline(pos - 1)
400 || par.isEnvSeparator(pos - 1)
401 || par.isLineSeparator(pos - 1)
402 || par.isSeparator(pos - 1)))
405 bool const left = font.isVisibleRightToLeft();
407 if (pos == par.size())
408 right = par.isRTL(bv_->buffer().params());
410 right = displayFont(pit, pos).isVisibleRightToLeft();
412 return left != right;
416 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
418 Paragraph & par = text_->getPar(pit);
419 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
420 // redoParagraph() recursively inside parMetrics.
421 Dimension old_dim = parMetrics(pit, false).dim();
422 ParagraphMetrics & pm = par_metrics_[pit];
425 Buffer & buffer = bv_->buffer();
426 bool changed = false;
428 // Check whether there are InsetBibItems that need fixing
429 // FIXME: This check ought to be done somewhere else. It is the reason
430 // why text_ is not const. But then, where else to do it?
431 // Well, how can you end up with either (a) a biblio environment that
432 // has no InsetBibitem, (b) a biblio environment with more than one
433 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
434 // environment? I think the answer is: when paragraphs are merged;
435 // when layout is set; when material is pasted.
436 if (par.brokenBiblio()) {
437 Cursor & cur = bv_->cursor();
438 // In some cases, we do not know how to record undo
439 if (&cur.inset() == &text_->inset())
440 cur.recordUndo(pit, pit);
442 int const moveCursor = par.fixBiblio(buffer);
444 // Is it necessary to update the cursor?
445 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
448 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
453 // Optimisation: this is used in the next two loops
454 // so better to calculate that once here.
455 int const right_margin = rightMargin(pm);
457 // iterator pointing to paragraph to resolve macros
458 DocIterator parPos = text_->macrocontextPosition();
462 LYXERR(Debug::INFO, "MacroContext not initialised!"
463 << " Going through the buffer again and hope"
464 << " the context is better then.");
465 // FIXME audit updateBuffer calls
466 // This should not be here, but it is not clear yet where else it
468 bv_->buffer().updateBuffer();
469 parPos = text_->macrocontextPosition();
470 LBUFERR(!parPos.empty());
475 par.setBeginOfBody();
476 Font const bufferfont = buffer.params().getFont();
477 CoordCache::Insets & insetCache = bv_->coordCache().insets();
478 for (auto const & e : par.insetList()) {
479 // FIXME Doesn't this HAVE to be non-empty?
480 // position already initialized?
481 if (!parPos.empty()) {
482 parPos.pos() = e.pos;
484 // A macro template would normally not be visible
485 // by itself. But the tex macro semantics allow
486 // recursion, so we artifically take the context
487 // after the macro template to simulate this.
488 if (e.inset->lyxCode() == MATHMACRO_CODE)
492 // If there is an end of paragraph marker, its size should be
493 // substracted to the available width. The logic here is
494 // almost the same as in tokenizeParagraph, remember keep them in sync.
496 if (e.pos + 1 == par.size()
497 && (lyxrc.paragraph_markers || par.lookupChange(par.size()).changed())
498 && size_type(pit + 1) < text_->paragraphs().size()) {
499 Font f(text_->layoutFont(pit));
500 // ¶ U+00B6 PILCROW SIGN
501 eop = theFontMetrics(f).width(char_type(0x00B6));
504 // do the metric calculation
506 int const w = max_width_ - leftMargin(pit, e.pos)
507 - right_margin - eop;
508 Font const & font = e.inset->inheritFont() ?
509 displayFont(pit, e.pos) : bufferfont;
510 MacroContext mc(&buffer, parPos);
511 MetricsInfo mi(bv_, font.fontInfo(), w, mc, e.pos == 0, tight_);
512 e.inset->metrics(mi, dim);
513 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
514 insetCache.add(e.inset, dim);
519 // Transform the paragraph into a single row containing all the elements.
520 Row const bigrow = tokenizeParagraph(pit);
521 // Split the row in several rows fitting in available width
522 pm.rows() = breakParagraph(bigrow);
524 /* If there is more than one row, expand the text to the full
525 * allowable width. This setting here is needed for the
526 * setRowAlignment() below. We do nothing when tight insets are
529 if (pm.rows().size() > 1 && !tight_ && dim_.wid < max_width_)
530 dim_.wid = max_width_;
532 // Compute height and alignment of the rows.
533 for (Row & row : pm.rows()) {
536 setRowAlignment(row, max(dim_.wid, row.width()));
538 pm.dim().wid = max(pm.dim().wid, row.width() + row.right_margin);
539 pm.dim().des += row.height();
542 // This type of margin can only be handled at the global paragraph level
543 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX) {
545 if (par.isRTL(buffer.params())) {
546 // globally align the paragraph to the left.
547 int minleft = max_width_;
548 for (Row const & row : pm.rows())
549 minleft = min(minleft, row.left_margin);
550 offset = right_margin - minleft;
552 // globally align the paragraph to the right.
554 for (Row const & row : pm.rows())
555 maxwid = max(maxwid, row.width());
556 offset = max_width_ - right_margin - maxwid;
559 for (Row & row : pm.rows()) {
560 row.left_margin += offset;
561 row.dim().wid += offset;
565 // The space above and below the paragraph.
566 int top = parTopSpacing(pit);
567 int bottom = parBottomSpacing(pit);
569 // Top and bottom margin of the document (only at top-level)
570 // FIXME: It might be better to move this in another method
571 // specially tailored for the main text.
572 if (text_->isMainText()) {
574 top += bv_->topMargin();
575 if (pit + 1 == pit_type(text_->paragraphs().size())) {
576 bottom += bv_->bottomMargin();
580 // Add the top/bottom space to rows and paragraph metrics
581 pm.rows().front().dim().asc += top;
582 pm.rows().back().dim().des += bottom;
583 pm.dim().des += top + bottom;
585 // Move the pm ascent to be the same as the first row ascent
586 pm.dim().asc += pm.rows().front().ascent();
587 pm.dim().des -= pm.rows().front().ascent();
589 changed |= old_dim.height() != pm.dim().height();
595 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
597 LyXAlignment align = par.getAlign(bv_->buffer().params());
599 // handle alignment inside tabular cells
600 Inset const & owner = text_->inset();
601 bool forced_block = false;
602 switch (owner.contentAlignment()) {
603 case LYX_ALIGN_BLOCK:
604 // In general block align is the default state, but here it is
605 // an explicit choice. Therefore it should not be overridden
609 case LYX_ALIGN_CENTER:
611 case LYX_ALIGN_RIGHT:
612 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
613 align = owner.contentAlignment();
616 // unchanged (use align)
620 // Display-style insets should always be on a centered row
621 if (Inset const * inset = par.getInset(row.pos())) {
622 if (inset->rowFlags() & Display) {
623 if (inset->rowFlags() & AlignLeft)
624 align = LYX_ALIGN_BLOCK;
625 else if (inset->rowFlags() & AlignRight)
626 align = LYX_ALIGN_RIGHT;
628 align = LYX_ALIGN_CENTER;
632 if (align == LYX_ALIGN_BLOCK) {
633 // If this row has been broken abruptly by a display inset, or
634 // it is the end of the paragraph, or the user requested we
635 // not justify stuff, then don't stretch.
636 // A forced block alignment can only be overridden the 'no
637 // justification on screen' setting.
638 if ((row.flushed() && !forced_block)
639 || !bv_->buffer().params().justification)
640 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
647 void TextMetrics::setRowAlignment(Row & row, int width) const
652 Paragraph const & par = text_->getPar(row.pit());
654 int const w = width - row.right_margin - row.width();
655 // FIXME: put back this assertion when the crash on new doc is solved.
656 //LASSERT(w >= 0, /**/);
658 // is there a manual margin with a manual label
659 Layout const & layout = par.layout();
662 if (layout.margintype == MARGIN_MANUAL
663 && layout.labeltype == LABEL_MANUAL) {
664 /// We might have real hfills in the label part
665 nlh = numberOfLabelHfills(par, row);
667 // A manual label par (e.g. List) has an auto-hfill
668 // between the label text and the body of the
670 // But we don't want to do this auto hfill if the par
675 if (nlh && !par.getLabelWidthString().empty())
676 row.label_hfill = labelFill(row) / double(nlh);
679 // are there any hfills in the row?
680 ParagraphMetrics const & pm = par_metrics_[row.pit()];
681 int nh = numberOfHfills(row, pm, par.beginOfBody());
685 // We don't have to look at the alignment if the row is already
686 // larger then the permitted width as then we force the
687 // LEFT_ALIGN'edness!
688 if (row.width() >= max_width_)
692 // Common case : there is no hfill, and the alignment will be
694 switch (getAlign(par, row)) {
695 case LYX_ALIGN_BLOCK:
696 // Expand expanding characters by a total of w
697 if (!row.setExtraWidth(w) && row.isRTL()) {
698 // Justification failed and the text is RTL: align to the right
699 row.left_margin += w;
704 // a displayed inset that is flushed
705 if (Inset const * inset = par.getInset(row.pos())) {
706 row.left_margin += inset->indent(*bv_);
707 row.dim().wid += inset->indent(*bv_);
710 case LYX_ALIGN_RIGHT:
711 if (Inset const * inset = par.getInset(row.pos())) {
712 int const new_w = max(w - inset->indent(*bv_), 0);
713 row.left_margin += new_w;
714 row.dim().wid += new_w;
716 row.left_margin += w;
720 case LYX_ALIGN_CENTER:
721 row.dim().wid += w / 2;
722 row.left_margin += w / 2;
725 case LYX_ALIGN_LAYOUT:
726 case LYX_ALIGN_SPECIAL:
727 case LYX_ALIGN_DECIMAL:
733 // Case nh > 0. There are hfill separators.
737 // Set size of hfill insets
738 pos_type const endpos = row.endpos();
739 pos_type body_pos = par.beginOfBody();
741 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
744 CoordCache::Insets & insetCache = bv_->coordCache().insets();
745 for (Row::Element & e : row) {
746 if (row.label_hfill && e.endpos == body_pos
747 && e.type == Row::SPACE)
748 e.dim.wid -= int(row.label_hfill * (nlh - 1));
749 if (e.inset && pm.hfillExpansion(row, e.pos)) {
750 if (e.pos >= body_pos) {
754 e.dim.wid += hfill_rem;
756 e.dim.wid += int(row.label_hfill);
757 // Cache the inset dimension.
758 insetCache.add(e.inset, e.dim);
764 int TextMetrics::labelFill(Row const & row) const
766 Paragraph const & par = text_->getPar(row.pit());
767 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
770 // iterate over elements before main body (except the last one,
771 // which is extra space).
772 for (Row::Element const & e : row) {
773 if (e.endpos >= par.beginOfBody())
778 docstring const & label = par.params().labelWidthString();
782 FontMetrics const & fm
783 = theFontMetrics(text_->labelFont(par));
785 return max(0, fm.width(label) - w);
792 * Calling Text::getFont is slow. While rebreaking we scan a
793 * paragraph from left to right calling getFont for every char. This
794 * simple class address this problem by hidding an optimization trick
795 * (not mine btw -AB): the font is reused in the whole font span. The
796 * class handles transparently the "hidden" (not part of the fontlist)
797 * label font (as getFont does).
803 FontIterator(TextMetrics const & tm,
804 Paragraph const & par, pit_type pit, pos_type pos)
805 : tm_(tm), par_(par), pit_(pit), pos_(pos),
806 font_(tm.displayFont(pit, pos)),
807 endspan_(par.fontSpan(pos).last),
808 bodypos_(par.beginOfBody())
812 Font const & operator*() const { return font_; }
815 FontIterator & operator++()
818 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
819 font_ = tm_.displayFont(pit_, pos_);
820 endspan_ = par_.fontSpan(pos_).last;
826 Font * operator->() { return &font_; }
830 TextMetrics const & tm_;
832 Paragraph const & par_;
848 Row TextMetrics::tokenizeParagraph(pit_type const pit) const
852 Paragraph const & par = text_->getPar(pit);
853 Buffer const & buf = text_->inset().buffer();
854 BookmarksSection::BookmarkPosList bpl =
855 theSession().bookmarks().bookmarksInPar(buf.fileName(), par.id());
857 pos_type const end = par.size();
858 pos_type const body_pos = par.beginOfBody();
860 // check for possible inline completion
861 DocIterator const & ic_it = bv_->inlineCompletionPos();
862 pos_type ic_pos = -1;
863 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == pit)
864 ic_pos = ic_it.pos();
866 // Now we iterate through until we reach the right margin
867 // or the end of the par, then build a representation of the row.
869 FontIterator fi = FontIterator(*this, par, pit, 0);
870 // The real stopping condition is a few lines below.
872 // Firstly, check whether there is a bookmark here.
873 if (lyxrc.bookmarks_visibility == LyXRC::BMK_INLINE)
874 for (auto const & bp_p : bpl)
875 if (bp_p.second == i) {
877 f.fontInfo().setColor(Color_bookmark);
878 // ❶ U+2776 DINGBAT NEGATIVE CIRCLED DIGIT ONE
879 char_type const ch = 0x2775 + bp_p.first;
880 row.addVirtual(i, docstring(1, ch), f, Change());
883 // The stopping condition is here so that the display of a
884 // bookmark can take place at paragraph start too.
888 char_type c = par.getChar(i);
889 // The most special cases are handled first.
890 if (par.isInset(i)) {
891 Inset const * ins = par.getInset(i);
892 Dimension dim = bv_->coordCache().insets().dim(ins);
893 row.add(i, ins, dim, *fi, par.lookupChange(i));
894 } else if (c == ' ' && i + 1 == body_pos) {
895 // This space is an \item separator. Represent it with a
896 // special space element, which dimension will be computed
898 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
899 int const wid = fm.width(par.layout().labelsep);
900 row.addMarginSpace(i, wid, *fi, par.lookupChange(i));
901 } else if (c == '\t')
902 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
903 *fi, par.lookupChange(i));
904 else if (c == 0x2028 || c == 0x2029) {
906 * U+2028 LINE SEPARATOR
907 * U+2029 PARAGRAPH SEPARATOR
909 * These are special unicode characters that break
910 * lines/pragraphs. Not handling them leads to trouble wrt
911 * Qt QTextLayout formatting. We add a visible character
912 * on screen so that the user can see that something is
916 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
917 // ¶ U+00B6 PILCROW SIGN
918 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
919 row.add(i, screen_char, *fi, par.lookupChange(i));
921 // row elements before body are unbreakable
922 row.add(i, c, *fi, par.lookupChange(i));
924 // add inline completion width
925 // draw logically behind the previous character
926 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
927 docstring const comp = bv_->inlineCompletion();
928 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
932 f.fontInfo().setColor(Color_inlinecompletion);
933 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
935 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
936 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
945 // End of paragraph marker, either if LyXRc requires it, or there
946 // is an end of paragraph change. The logic here is almost the
947 // same as in redoParagraph, remember keep them in sync.
948 ParagraphList const & pars = text_->paragraphs();
949 Change const & endchange = par.lookupChange(end);
950 if (endchange.changed())
951 row.needsChangeBar(true);
952 if ((lyxrc.paragraph_markers || endchange.changed())
953 && size_type(pit + 1) < pars.size()) {
954 // add a virtual element for the end-of-paragraph
955 // marker; it is shown on screen, but does not exist
957 Font f(text_->layoutFont(pit));
958 f.fontInfo().setColor(Color_paragraphmarker);
959 f.setLanguage(par.getParLanguage(buf.params()));
960 // ¶ U+00B6 PILCROW SIGN
961 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, endchange);
970 /** Helper template flexible_const_iterator<T>
971 * A way to iterate over a const container, but insert fake elements in it.
972 * In the case of a row, we will have to break some elements, which
973 * create new ones. This class allows to abstract this.
974 * Only the required parts are implemented for now.
977 class flexible_const_iterator {
978 typedef typename T::value_type value_type;
982 flexible_const_iterator operator++() {
990 value_type operator*() const { return pile_.empty() ? *cit_ : pile_.back(); }
992 value_type const * operator->() const { return pile_.empty() ? &*cit_ : &pile_.back(); }
994 void put(value_type const & e) { pile_.push_back(e); }
996 // Put a sequence of elements on the pile (in reverse order!)
997 void put(vector<value_type> const & elts) {
998 pile_.insert(pile_.end(), elts.rbegin(), elts.rend());
1001 // This should be private, but declaring the friend functions is too much work
1003 typename T::const_iterator cit_;
1004 // A vector that is used as like a pile to store the elements to
1005 // consider before incrementing the underlying iterator.
1006 vector<value_type> pile_;
1011 flexible_const_iterator<T> flexible_begin(T const & t)
1013 return { t.begin(), vector<typename T::value_type>() };
1018 flexible_const_iterator<T> flexible_end(T const & t)
1020 return { t.end(), vector<typename T::value_type>() };
1024 // Equality is only possible if respective piles are empty
1026 bool operator==(flexible_const_iterator<T> const & t1,
1027 flexible_const_iterator<T> const & t2)
1029 return t1.cit_ == t2.cit_ && t1.pile_.empty() && t2.pile_.empty();
1033 Row newRow(TextMetrics const & tm, pit_type pit, pos_type pos, bool is_rtl)
1038 nrow.left_margin = tm.leftMargin(pit, pos);
1039 nrow.right_margin = tm.rightMargin(pit);
1040 nrow.setRTL(is_rtl);
1042 swap(nrow.left_margin, nrow.right_margin);
1043 // Remember that the row width takes into account the left_margin
1044 // but not the right_margin.
1045 nrow.dim().wid = nrow.left_margin;
1050 void cleanupRow(Row & row, bool at_end)
1053 row.endpos(row.pos());
1057 row.endpos(row.back().endpos);
1058 // remove trailing spaces on row break
1059 if (!at_end && !row.flushed())
1061 // boundary exists when there was no space at the end of row
1062 row.end_boundary(!at_end && row.back().endpos == row.endpos());
1063 // make sure that the RTL elements are in reverse ordering
1068 // Implement the priorities described in RowFlags.h.
1069 bool needsRowBreak(int f1, int f2)
1071 if (f1 & AlwaysBreakAfter /*|| f2 & AlwaysBreakBefore*/)
1073 if (f1 & NoBreakAfter || f2 & NoBreakBefore)
1075 if (f1 & BreakAfter || f2 & BreakBefore)
1084 RowList TextMetrics::breakParagraph(Row const & bigrow) const
1087 bool const is_rtl = text_->isRTL(bigrow.pit());
1088 bool const end_label = text_->getEndLabel(bigrow.pit()) != END_LABEL_NO_LABEL;
1089 int const next_width = max_width_ - leftMargin(bigrow.pit(), bigrow.endpos())
1090 - rightMargin(bigrow.pit());
1093 flexible_const_iterator<Row> fcit = flexible_begin(bigrow);
1094 flexible_const_iterator<Row> const end = flexible_end(bigrow);
1096 bool const row_empty = rows.empty() || rows.back().empty();
1097 // The row flags of previous element, if there is one.
1098 // Otherwise we use NoBreakAfter to avoid an empty row before
1099 // e.g. a displayed equation.
1100 int const f1 = row_empty ? NoBreakAfter : rows.back().back().row_flags;
1101 // The row flags of next element, if there is one.
1102 // Otherwise we use NoBreakBefore (see above), unless the
1103 // paragraph has an end label (for which an empty row is OK).
1104 int const f2 = (fcit == end) ? (end_label ? Inline : NoBreakBefore)
1106 if (rows.empty() || needsRowBreak(f1, f2)) {
1107 if (!rows.empty()) {
1108 // Flush row as requested by row flags
1109 rows.back().flushed((f1 & Flush) || (f2 & FlushBefore));
1110 cleanupRow(rows.back(), false);
1112 pos_type pos = rows.empty() ? 0 : rows.back().endpos();
1113 rows.push_back(newRow(*this, bigrow.pit(), pos, is_rtl));
1114 // the width available for the row.
1115 width = max_width_ - rows.back().right_margin;
1118 // The stopping condition is here because we may need a new
1119 // empty row at the end.
1123 // Next element to consider is either the top of the temporary
1124 // pile, or the place when we were in main row
1125 Row::Element elt = *fcit;
1127 elt.splitAt(width - rows.back().width(), next_width, false, tail);
1128 Row & rb = rows.back();
1129 if (elt.type == Row::MARGINSPACE)
1130 elt.dim.wid = max(elt.dim.wid, leftMargin(bigrow.pit()) - rb.width());
1133 if (rb.width() > width) {
1134 LATTEST(tail.empty());
1135 // if the row is too large, try to cut at last separator.
1136 tail = rb.shortenIfNeeded(width, next_width);
1139 // Go to next element
1142 // Handle later the elements returned by splitAt or shortenIfNeeded.
1146 if (!rows.empty()) {
1147 // Last row in paragraph is flushed
1148 rows.back().flushed(true);
1149 cleanupRow(rows.back(), true);
1156 int TextMetrics::parTopSpacing(pit_type const pit) const
1158 Paragraph const & par = text_->getPar(pit);
1159 Layout const & layout = par.layout();
1162 ParagraphList const & pars = text_->paragraphs();
1163 double const dh = defaultRowHeight();
1165 BufferParams const & bparams = bv_->buffer().params();
1166 Inset const & inset = text_->inset();
1167 // some parskips VERY EASY IMPLEMENTATION
1168 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1169 && !inset.getLayout().parbreakIsNewline()
1170 && !par.layout().parbreak_is_newline
1172 && ((layout.isParagraph() && par.getDepth() == 0)
1173 || (pars[pit - 1].layout().isParagraph()
1174 && pars[pit - 1].getDepth() == 0))) {
1175 asc += bparams.getDefSkip().inPixels(*bv_);
1178 if (par.params().startOfAppendix())
1181 // special code for the top label
1182 if (layout.labelIsAbove()
1183 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1184 && !par.labelString().empty()) {
1185 FontInfo labelfont = text_->labelFont(par);
1186 FontMetrics const & lfm = theFontMetrics(labelfont);
1187 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1188 * text_->spacing(par)
1189 + (layout.topsep + layout.labelbottomsep) * dh);
1192 // Add the layout spaces, for example before and after
1193 // a section, or between the items of a itemize or enumerate
1196 pit_type prev = text_->depthHook(pit, par.getDepth());
1197 Paragraph const & prevpar = pars[prev];
1198 double layoutasc = 0;
1200 && prevpar.layout() == layout
1201 && prevpar.getDepth() == par.getDepth()
1202 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1203 layoutasc = layout.itemsep * dh;
1204 } else if (pit != 0 && layout.topsep > 0)
1205 // combine the separation between different layouts (with same depth)
1206 layoutasc = max(0.0,
1207 prevpar.getDepth() != par.getDepth() ? layout.topsep
1208 : layout.topsep - prevpar.layout().bottomsep) * dh;
1210 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1212 prev = text_->outerHook(pit);
1213 if (prev != pit_type(pars.size())) {
1214 asc += int(pars[prev].layout().parsep * dh);
1215 } else if (pit != 0) {
1216 Paragraph const & prevpar2 = pars[pit - 1];
1217 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1218 asc += int(layout.parsep * dh);
1225 int TextMetrics::parBottomSpacing(pit_type const pit) const
1227 double layoutdesc = 0;
1228 ParagraphList const & pars = text_->paragraphs();
1229 double const dh = defaultRowHeight();
1231 // add the layout spaces, for example before and after
1232 // a section, or between the items of a itemize or enumerate
1234 pit_type nextpit = pit + 1;
1235 if (nextpit != pit_type(pars.size())) {
1236 pit_type cpit = pit;
1238 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1239 double usual = pars[cpit].layout().bottomsep * dh;
1241 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1242 if (pars[cpit].layout() != pars[nextpit].layout()
1243 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1244 unusual = pars[cpit].layout().bottomsep * dh;
1245 layoutdesc = max(unusual, usual);
1246 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1247 if (pars[cpit].layout() != pars[nextpit].layout()
1248 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1249 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1253 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1257 void TextMetrics::setRowHeight(Row & row) const
1259 Paragraph const & par = text_->getPar(row.pit());
1260 Layout const & layout = par.layout();
1261 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1263 // Initial value for ascent (useful if row is empty).
1264 Font const font = displayFont(row.pit(), row.pos());
1265 FontMetrics const & fm = theFontMetrics(font);
1266 int maxasc = int(fm.maxAscent() * spacing_val);
1267 int maxdes = int(fm.maxDescent() * spacing_val);
1269 // Take label string into account (useful if labelfont is large)
1270 if (row.pos() == 0 && layout.labelIsInline()) {
1271 FontInfo const labelfont = text_->labelFont(par);
1272 FontMetrics const & lfm = theFontMetrics(labelfont);
1273 maxasc = max(maxasc, int(lfm.maxAscent() * spacing_val));
1274 maxdes = max(maxdes, int(lfm.maxDescent() * spacing_val));
1277 // Find the ascent/descent of the row contents
1278 for (Row::Element const & e : row) {
1280 maxasc = max(maxasc, e.dim.ascent());
1281 maxdes = max(maxdes, e.dim.descent());
1283 FontMetrics const & fm2 = theFontMetrics(e.font);
1284 maxasc = max(maxasc, int(fm2.maxAscent() * spacing_val));
1285 maxdes = max(maxdes, int(fm2.maxDescent() * spacing_val));
1289 // This is nicer with box insets
1293 row.dim().asc = maxasc;
1294 row.dim().des = maxdes;
1296 // This is useful for selections
1297 row.contents_dim() = row.dim();
1301 // x is an absolute screen coord
1302 // returns the column near the specified x-coordinate of the row
1303 // x is set to the real beginning of this column
1304 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1305 bool & boundary) const
1307 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1308 /// For the main Text, it is possible that this pit is not
1309 /// yet in the CoordCache when moving cursor up.
1310 /// x Paragraph coordinate is always 0 for main text anyway.
1311 int const xo = origin_.x_;
1314 // Adapt to cursor row scroll offset if applicable.
1315 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1318 pos_type pos = row.pos();
1321 x = row.left_margin;
1322 else if (x <= row.left_margin) {
1323 pos = row.front().left_pos();
1324 x = row.left_margin;
1325 } else if (x >= row.width()) {
1326 pos = row.back().right_pos();
1329 double w = row.left_margin;
1330 Row::const_iterator cit = row.begin();
1331 Row::const_iterator cend = row.end();
1332 for ( ; cit != cend; ++cit) {
1333 if (w <= x && w + cit->full_width() > x) {
1334 int x_offset = int(x - w);
1335 pos = cit->x2pos(x_offset);
1336 x = int(x_offset + w);
1339 w += cit->full_width();
1341 if (cit == row.end()) {
1342 pos = row.back().right_pos();
1345 /** This tests for the case where the cursor is placed
1346 * just before a font direction change. See comment on
1347 * the boundary_ member in DocIterator.h to understand
1348 * how boundary helps here.
1350 else if (pos == cit->endpos
1351 && ((!cit->isRTL() && cit + 1 != row.end()
1352 && (cit + 1)->isRTL())
1353 || (cit->isRTL() && cit != row.begin()
1354 && !(cit - 1)->isRTL())))
1358 /** This tests for the case where the cursor is set at the end
1359 * of a row which has been broken due something else than a
1360 * separator (a display inset or a forced breaking of the
1361 * row). We know that there is a separator when the end of the
1362 * row is larger than the end of its last element.
1364 if (!row.empty() && pos == row.back().endpos
1365 && row.back().endpos == row.endpos()) {
1366 Inset const * inset = row.back().inset;
1367 if (inset && (inset->lyxCode() == NEWLINE_CODE
1368 || inset->lyxCode() == SEPARATOR_CODE))
1369 pos = row.back().pos;
1371 boundary = row.end_boundary();
1375 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1381 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1383 // We play safe and use parMetrics(pit) to make sure the
1384 // ParagraphMetrics will be redone and OK to use if needed.
1385 // Otherwise we would use an empty ParagraphMetrics in
1386 // upDownInText() while in selection mode.
1387 ParagraphMetrics const & pm = parMetrics(pit);
1389 LBUFERR(row < int(pm.rows().size()));
1391 Row const & r = pm.rows()[row];
1392 return getPosNearX(r, x, bound);
1396 // y is screen coordinate
1397 pit_type TextMetrics::getPitNearY(int y)
1399 LASSERT(!text_->paragraphs().empty(), return -1);
1400 LASSERT(!par_metrics_.empty(), return -1);
1401 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1403 // look for highest numbered paragraph with y coordinate less than given y
1406 ParMetricsCache::const_iterator it = par_metrics_.begin();
1407 ParMetricsCache::const_iterator et = par_metrics_.end();
1408 ParMetricsCache::const_iterator last = et;
1411 ParagraphMetrics const & pm = it->second;
1413 if (y < it->second.position() - pm.ascent()) {
1414 // We are looking for a position that is before the first paragraph in
1415 // the cache (which is in priciple off-screen, that is before the
1418 // We are already at the first paragraph in the inset.
1420 // OK, this is the paragraph we are looking for.
1421 pit = it->first - 1;
1426 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1428 if (y >= last->second.position() + pm_last.descent()) {
1429 // We are looking for a position that is after the last paragraph in
1430 // the cache (which is in priciple off-screen), that is before the
1432 pit = last->first + 1;
1433 if (pit == int(text_->paragraphs().size()))
1434 // We are already at the last paragraph in the inset.
1436 // OK, this is the paragraph we are looking for.
1437 newParMetricsDown();
1441 for (; it != et; ++it) {
1442 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1443 << " y: " << it->second.position());
1445 ParagraphMetrics const & pm2 = par_metrics_[it->first];
1447 if (it->first >= pit && it->second.position() - pm2.ascent() <= y) {
1449 yy = it->second.position();
1453 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1459 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1460 bool assert_in_view, bool up)
1462 ParagraphMetrics const & pm = par_metrics_[pit];
1464 int yy = pm.position() - pm.ascent();
1465 LBUFERR(!pm.rows().empty());
1466 RowList::const_iterator rit = pm.rows().begin();
1467 RowList::const_iterator rlast = pm.rows().end();
1469 for (; rit != rlast; yy += rit->height(), ++rit)
1470 if (yy + rit->height() > y)
1473 if (assert_in_view) {
1474 if (!up && yy + rit->height() > y) {
1475 if (rit != pm.rows().begin()) {
1478 } else if (pit != 0) {
1481 ParagraphMetrics const & pm2 = par_metrics_[pit];
1482 rit = pm2.rows().end();
1486 } else if (up && yy != y) {
1488 y = yy + rit->height();
1490 } else if (pit < int(text_->paragraphs().size()) - 1) {
1492 newParMetricsDown();
1493 ParagraphMetrics const & pm2 = par_metrics_[pit];
1494 rit = pm2.rows().begin();
1503 // x,y are absolute screen coordinates
1504 // sets cursor recursively descending into nested editable insets
1505 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1506 bool assert_in_view, bool up)
1508 if (lyxerr.debugging(Debug::WORKAREA)) {
1509 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1510 cur.bv().coordCache().dump();
1512 pit_type pit = getPitNearY(y);
1513 LASSERT(pit != -1, return 0);
1514 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1517 // Do we cover an inset?
1518 InsetList::Element * e = checkInsetHit(pit, x, y);
1521 // No inset, set position in the text
1522 bool bound = false; // is modified by getPosNearX
1523 cur.pos() = getPosNearX(row, x, bound);
1524 cur.boundary(bound);
1525 cur.setCurrentFont();
1530 Inset * inset = e->inset;
1531 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1533 // Set position in front of inset
1535 cur.boundary(false);
1538 // Try to descend recursively inside the inset.
1539 Inset * edited = inset->editXY(cur, x, y);
1540 // FIXME: it is not clear that the test on position is needed
1541 // Remove it if/when semantics of editXY is clarified
1542 if (cur.text() == text_ && cur.pos() == e->pos) {
1543 // non-editable inset, set cursor after the inset if x is
1544 // nearer to that position (bug 9628)
1545 bool bound = false; // is modified by getPosNearX
1546 cur.pos() = getPosNearX(row, x, bound);
1547 cur.boundary(bound);
1548 cur.setCurrentFont();
1552 if (cur.top().text() == text_)
1553 cur.setCurrentFont();
1558 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1560 LASSERT(text_ == cur.text(), return);
1561 pit_type const pit = getPitNearY(y);
1562 LASSERT(pit != -1, return);
1564 ParagraphMetrics const & pm = par_metrics_[pit];
1566 int yy = pm.position() - pm.rows().front().ascent();
1567 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1568 " pit: " << pit << " yy: " << yy);
1571 LBUFERR(pm.rows().size());
1572 for (; r < int(pm.rows().size()) - 1; ++r) {
1573 Row const & row = pm.rows()[r];
1574 if (yy + row.height() > y)
1579 Row const & row = pm.rows()[r];
1581 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1585 pos_type const pos = getPosNearX(row, xx, bound);
1587 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1589 text_->setCursor(cur, pit, pos, true, bound);
1590 // remember new position.
1595 //takes screen x,y coordinates
1596 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1598 Paragraph const & par = text_->paragraphs()[pit];
1599 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1601 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1603 for (InsetList::Element const & e : par.insetList()) {
1604 LYXERR(Debug::DEBUG, "examining inset " << e.inset);
1606 if (insetCache.covers(e.inset, x, y)) {
1607 LYXERR(Debug::DEBUG, "Hit inset: " << e.inset);
1608 return const_cast<InsetList::Element *>(&e);
1612 LYXERR(Debug::DEBUG, "No inset hit. ");
1617 //takes screen x,y coordinates
1618 Inset * TextMetrics::checkInsetHit(int x, int y)
1620 pit_type const pit = getPitNearY(y);
1621 LASSERT(pit != -1, return 0);
1622 InsetList::Element * e = checkInsetHit(pit, x, y);
1631 int TextMetrics::cursorX(CursorSlice const & sl,
1632 bool boundary) const
1634 LASSERT(sl.text() == text_, return 0);
1636 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1637 if (pm.rows().empty())
1639 Row const & row = pm.getRow(sl.pos(), boundary);
1640 pos_type const pos = sl.pos();
1643 row.findElement(pos, boundary, x);
1649 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1651 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1652 ParagraphMetrics const & pm = parMetrics(sl.pit());
1653 if (pm.rows().empty())
1657 h -= parMetrics(0).rows()[0].ascent();
1658 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1659 h += parMetrics(pit).height();
1662 if (pos && boundary)
1664 size_t const rend = pm.pos2row(pos);
1665 for (size_t rit = 0; rit != rend; ++rit)
1666 h += pm.rows()[rit].height();
1667 h += pm.rows()[rend].ascent();
1672 // the cursor set functions have a special mechanism. When they
1673 // realize you left an empty paragraph, they will delete it.
1675 bool TextMetrics::cursorHome(Cursor & cur)
1677 LASSERT(text_ == cur.text(), return false);
1678 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1679 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1680 return text_->setCursor(cur, cur.pit(), row.pos());
1684 bool TextMetrics::cursorEnd(Cursor & cur)
1686 LASSERT(text_ == cur.text(), return false);
1687 // if not on the last row of the par, put the cursor before
1688 // the final space exept if I have a spanning inset or one string
1689 // is so long that we force a break.
1690 pos_type end = cur.textRow().endpos();
1692 // empty text, end-1 is no valid position
1694 bool boundary = false;
1695 if (end != cur.lastpos()) {
1696 if (!cur.paragraph().isLineSeparator(end-1)
1697 && !cur.paragraph().isNewline(end-1)
1698 && !cur.paragraph().isEnvSeparator(end-1))
1702 } else if (cur.paragraph().isEnvSeparator(end-1))
1704 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1708 void TextMetrics::deleteLineForward(Cursor & cur)
1710 LASSERT(text_ == cur.text(), return);
1711 if (cur.lastpos() == 0) {
1712 // Paragraph is empty, so we just go forward
1713 text_->cursorForward(cur);
1716 cur.selection(true); // to avoid deletion
1719 // What is this test for ??? (JMarc)
1720 if (!cur.selection())
1721 text_->deleteWordForward(cur);
1723 cap::cutSelection(cur, false);
1724 cur.checkBufferStructure();
1729 int TextMetrics::leftMargin(pit_type pit) const
1731 // FIXME: what is the semantics? It depends on whether the
1732 // paragraph is empty!
1733 return leftMargin(pit, text_->paragraphs()[pit].size());
1737 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1739 ParagraphList const & pars = text_->paragraphs();
1741 LASSERT(pit >= 0, return 0);
1742 LASSERT(pit < int(pars.size()), return 0);
1743 Paragraph const & par = pars[pit];
1744 LASSERT(pos >= 0, return 0);
1745 // We do not really care whether pos > par.size(), since we do not
1746 // access the data. It can be actually useful, when querying the
1747 // margin without indentation (see leftMargin(pit_type).
1749 Buffer const & buffer = bv_->buffer();
1750 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1751 DocumentClass const & tclass = buffer.params().documentClass();
1752 Layout const & layout = par.layout();
1753 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1755 docstring parindent = layout.parindent;
1759 if (text_->isMainText()) {
1760 l_margin += bv_->leftMargin();
1761 l_margin += bfm.signedWidth(tclass.leftmargin());
1764 int depth = par.getDepth();
1766 // find the next level paragraph
1767 pit_type newpar = text_->outerHook(pit);
1768 if (newpar != pit_type(pars.size())) {
1769 if (pars[newpar].layout().isEnvironment()) {
1770 int nestmargin = depth * nestMargin();
1771 if (text_->isMainText())
1772 nestmargin += changebarMargin();
1773 l_margin = max(leftMargin(newpar), nestmargin);
1774 // Remove the parindent that has been added
1775 // if the paragraph was empty.
1776 if (pars[newpar].empty() &&
1777 buffer.params().paragraph_separation ==
1778 BufferParams::ParagraphIndentSeparation) {
1779 docstring pi = pars[newpar].layout().parindent;
1780 l_margin -= bfm.signedWidth(pi);
1783 if (tclass.isDefaultLayout(par.layout())
1784 || tclass.isPlainLayout(par.layout())) {
1785 if (pars[newpar].params().noindent())
1788 parindent = pars[newpar].layout().parindent;
1793 // This happens after sections or environments in standard classes.
1794 // We have to check the previous layout at same depth.
1795 if (buffer.params().paragraph_separation ==
1796 BufferParams::ParagraphSkipSeparation)
1798 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1799 pit_type prev = text_->depthHook(pit, par.getDepth());
1800 if (par.layout() == pars[prev].layout()) {
1802 && pars[pit - 1].layout().nextnoindent)
1804 } else if (pars[prev].layout().nextnoindent)
1808 FontInfo const labelfont = text_->labelFont(par);
1809 FontMetrics const & lfm = theFontMetrics(labelfont);
1811 switch (layout.margintype) {
1812 case MARGIN_DYNAMIC:
1813 if (!layout.leftmargin.empty()) {
1814 l_margin += bfm.signedWidth(layout.leftmargin);
1816 if (!par.labelString().empty()) {
1817 l_margin += lfm.signedWidth(layout.labelindent);
1818 l_margin += lfm.width(par.labelString());
1819 l_margin += lfm.width(layout.labelsep);
1823 case MARGIN_MANUAL: {
1824 l_margin += lfm.signedWidth(layout.labelindent);
1825 // The width of an empty par, even with manual label, should be 0
1826 if (!par.empty() && pos >= par.beginOfBody()) {
1827 if (!par.getLabelWidthString().empty()) {
1828 docstring labstr = par.getLabelWidthString();
1829 l_margin += lfm.width(labstr);
1830 l_margin += lfm.width(layout.labelsep);
1836 case MARGIN_STATIC: {
1837 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1838 / (par.getDepth() + 4);
1842 case MARGIN_FIRST_DYNAMIC:
1843 if (layout.labeltype == LABEL_MANUAL) {
1844 // if we are at position 0, we are never in the body
1845 if (pos > 0 && pos >= par.beginOfBody())
1846 l_margin += lfm.signedWidth(layout.leftmargin);
1848 l_margin += lfm.signedWidth(layout.labelindent);
1850 // Special case to fix problems with
1852 || (layout.labeltype == LABEL_STATIC
1853 && layout.latextype == LATEX_ENVIRONMENT
1854 && !text_->isFirstInSequence(pit))) {
1855 l_margin += lfm.signedWidth(layout.leftmargin);
1856 } else if (!layout.labelIsAbove()) {
1857 l_margin += lfm.signedWidth(layout.labelindent);
1858 l_margin += lfm.width(layout.labelsep);
1859 l_margin += lfm.width(par.labelString());
1863 case MARGIN_RIGHT_ADDRESS_BOX:
1864 // This is handled globally in redoParagraph().
1868 if (!par.params().leftIndent().zero())
1869 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1871 LyXAlignment align = par.getAlign(bv_->buffer().params());
1873 // set the correct parindent
1875 && (layout.labeltype == LABEL_NO_LABEL
1876 || layout.labeltype == LABEL_ABOVE
1877 || layout.labeltype == LABEL_CENTERED
1878 || (layout.labeltype == LABEL_STATIC
1879 && layout.latextype == LATEX_ENVIRONMENT
1880 && !text_->isFirstInSequence(pit)))
1881 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1882 && !par.params().noindent()
1883 // in some insets, paragraphs are never indented
1884 && !text_->inset().neverIndent()
1885 // display style insets do not need indentation
1888 && par.getInset(0)->rowFlags() & Display)
1889 && (!(tclass.isDefaultLayout(par.layout())
1890 || tclass.isPlainLayout(par.layout()))
1891 || buffer.params().paragraph_separation
1892 == BufferParams::ParagraphIndentSeparation)) {
1893 /* use the parindent of the layout when the default
1894 * indentation is used otherwise use the indentation set in
1895 * the document settings
1897 if (buffer.params().getParIndent().empty())
1898 l_margin += bfm.signedWidth(parindent);
1900 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1907 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1909 if (par_metrics_.empty())
1915 y -= par_metrics_.begin()->second.ascent();
1916 for (auto & pm_pair : par_metrics_) {
1917 pit_type const pit = pm_pair.first;
1918 ParagraphMetrics & pm = pm_pair.second;
1920 // Save the paragraph position in the cache.
1922 drawParagraph(pi, pit, x, y);
1928 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1930 ParagraphMetrics const & pm = par_metrics_[pit];
1931 if (pm.rows().empty())
1933 size_t const nrows = pm.rows().size();
1934 // Remember left and right margin for drawing math numbers
1935 Changer changeleft = changeVar(pi.leftx, x + leftMargin(pit));
1936 Changer changeright = changeVar(pi.rightx, x + width() - rightMargin(pit));
1938 // Use fast lane in nodraw stage.
1939 if (pi.pain.isNull()) {
1940 for (size_t i = 0; i != nrows; ++i) {
1942 Row const & row = pm.rows()[i];
1943 // Adapt to cursor row scroll offset if applicable.
1944 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1948 RowPainter rp(pi, *text_, row, row_x, y);
1950 rp.paintOnlyInsets();
1956 int const ww = bv_->workHeight();
1957 Cursor const & cur = bv_->cursor();
1958 DocIterator sel_beg = cur.selectionBegin();
1959 DocIterator sel_end = cur.selectionEnd();
1960 bool selection = cur.selection()
1961 // This is our text.
1962 && cur.text() == text_
1963 // if the anchor is outside, this is not our selection
1964 && cur.normalAnchor().text() == text_
1965 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1967 // We store the begin and end pos of the selection relative to this par
1968 DocIterator sel_beg_par = cur.selectionBegin();
1969 DocIterator sel_end_par = cur.selectionEnd();
1971 // We care only about visible selection.
1973 if (pit != sel_beg.pit()) {
1974 sel_beg_par.pit() = pit;
1975 sel_beg_par.pos() = 0;
1977 if (pit != sel_end.pit()) {
1978 sel_end_par.pit() = pit;
1979 sel_end_par.pos() = sel_end_par.lastpos();
1983 if (text_->isRTL(pit))
1984 swap(pi.leftx, pi.rightx);
1986 BookmarksSection::BookmarkPosList bpl =
1987 theSession().bookmarks().bookmarksInPar(bv_->buffer().fileName(), pm.par().id());
1989 for (size_t i = 0; i != nrows; ++i) {
1991 Row const & row = pm.rows()[i];
1992 // Adapt to cursor row scroll offset if applicable.
1993 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1997 // It is not needed to draw on screen if we are not inside.
1998 bool const inside = (y + row.descent() >= 0
1999 && y - row.ascent() < ww);
2001 // Inset positions have already been set in nodraw stage.
2007 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2009 row.clearSelectionAndMargins();
2011 // The row knows nothing about the paragraph, so we have to check
2012 // whether this row is the first or last and update the margins.
2013 if (row.selection()) {
2014 if (row.sel_beg == 0)
2015 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
2016 if (row.sel_end == sel_end_par.lastpos())
2017 row.change(row.end_margin_sel, sel_end.pit() > pit);
2020 // Take this opportunity to spellcheck the row contents.
2021 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
2022 text_->getPar(pit).spellCheck();
2025 RowPainter rp(pi, *text_, row, row_x, y);
2027 // Don't paint the row if a full repaint has not been requested
2028 // and if it has not changed.
2029 if (!pi.full_repaint && !row.changed()) {
2030 // Paint only the insets if the text itself is
2032 rp.paintOnlyInsets();
2033 rp.paintTooLargeMarks(
2034 row_x + row.left_x() < bv_->leftMargin(),
2035 row_x + row.right_x() > bv_->workWidth() - bv_->rightMargin());
2041 // Clear background of this row if paragraph background was not
2042 // already cleared because of a full repaint.
2043 if (!pi.full_repaint && row.changed()) {
2044 LYXERR(Debug::PAINTING, "Clear rect@("
2045 << x << ", " << y - row.ascent() << ")="
2046 << width() << " x " << row.height());
2047 pi.pain.fillRectangle(x, y - row.ascent(),
2048 width(), row.height(), pi.background_color);
2051 // Instrumentation for testing row cache (see also
2053 if (lyxerr.debugging(Debug::PAINTING)
2054 && (row.selection() || pi.full_repaint || row.changed())) {
2055 string const foreword = text_->isMainText() ? "main text redraw "
2056 : "inset text redraw: ";
2057 LYXERR0(foreword << "pit=" << pit << " row=" << i
2058 << (row.selection() ? " row_selection": "")
2059 << (pi.full_repaint ? " full_repaint" : "")
2060 << (row.changed() ? " row.changed" : ""));
2063 // Backup full_repaint status and force full repaint
2064 // for inner insets as the Row has been cleared out.
2065 bool tmp = pi.full_repaint;
2066 pi.full_repaint = true;
2068 rp.paintSelection();
2071 if (row.needsChangeBar())
2072 rp.paintChangeBar();
2078 rp.paintTooLargeMarks(
2079 row_x + row.left_x() < bv_->leftMargin(),
2080 row_x + row.right_x() > bv_->workWidth() - bv_->rightMargin());
2081 // indicate bookmarks presence in margin
2082 if (lyxrc.bookmarks_visibility == LyXRC::BMK_MARGIN)
2083 for (auto const & bp_p : bpl)
2084 if (bp_p.second >= row.pos() && bp_p.second < row.endpos())
2085 rp.paintBookmark(bp_p.first);
2090 // This debug code shows on screen which rows are repainted.
2091 // FIXME: since the updates related to caret blinking restrict
2092 // the painter to a small rectangle, the numbers are not
2093 // updated when this happens. Change the code in
2094 // GuiWorkArea::Private::show/hideCaret if this is important.
2095 static int count = 0;
2097 FontInfo fi(sane_font);
2098 fi.setSize(TINY_SIZE);
2099 fi.setColor(Color_red);
2100 pi.pain.text(row_x, y, convert<docstring>(count), fi);
2103 // Restore full_repaint status.
2104 pi.full_repaint = tmp;
2109 //LYXERR(Debug::PAINTING, ".");
2113 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2114 Dimension & dim) const
2116 DocIterator from = cur.bv().cursor();
2117 DocIterator to = from;
2118 text_->getWord(from.top(), to.top(), PREVIOUS_WORD);
2120 // The vertical dimension of the word
2121 Font const font = displayFont(cur.pit(), from.pos());
2122 FontMetrics const & fm = theFontMetrics(font);
2123 // the +1's below are related to the extra pixels added in setRowHeight
2124 dim.asc = fm.maxAscent() + 1;
2125 dim.des = fm.maxDescent() + 1;
2127 // get position on screen of the word start and end
2128 //FIXME: Is it necessary to explicitly set this to false?
2129 from.boundary(false);
2130 Point lxy = cur.bv().getPos(from);
2131 Point rxy = cur.bv().getPos(to);
2132 dim.wid = abs(rxy.x_ - lxy.x_);
2134 // calculate position of word
2136 x = min(rxy.x_, lxy.x_);
2138 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2139 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2142 int defaultRowHeight()
2144 return int(theFontMetrics(sane_font).maxHeight() * 1.2);