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)
112 max_width_ = bv_->workWidth();
113 dim_.wid = max_width_;
119 bool TextMetrics::contains(pit_type pit) const
121 return par_metrics_.find(pit) != par_metrics_.end();
125 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
127 ParMetricsCache::const_iterator it = par_metrics_.begin();
128 return make_pair(it->first, &it->second);
132 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
134 LBUFERR(!par_metrics_.empty());
135 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
136 return make_pair(it->first, &it->second);
140 bool TextMetrics::isLastRow(Row const & row) const
142 ParagraphList const & pars = text_->paragraphs();
143 return row.endpos() >= pars[row.pit()].size()
144 && row.pit() + 1 == pit_type(pars.size());
148 bool TextMetrics::isFirstRow(Row const & row) const
150 return row.pos() == 0 && row.pit() == 0;
154 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
156 for (auto & pm_pair : par_metrics_)
157 if (pm_pair.first == pit)
158 for (Row & row : pm_pair.second.rows())
159 if (row.pos() == pos)
164 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
166 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
167 if (pmc_it == par_metrics_.end()) {
168 pmc_it = par_metrics_.insert(
169 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
171 if (pmc_it->second.rows().empty() && redo)
173 return pmc_it->second;
177 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
179 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
183 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit)
185 return parMetrics(pit, true);
189 void TextMetrics::newParMetricsDown()
191 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
192 pit_type const pit = last.first + 1;
193 if (pit == int(text_->paragraphs().size()))
196 // do it and update its position.
198 par_metrics_[pit].setPosition(last.second.position()
199 + last.second.descent() + par_metrics_[pit].ascent());
204 void TextMetrics::newParMetricsUp()
206 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
207 if (first.first == 0)
210 pit_type const pit = first.first - 1;
211 // do it and update its position.
213 par_metrics_[pit].setPosition(first.second.position()
214 - first.second.ascent() - par_metrics_[pit].descent());
219 bool TextMetrics::metrics(MetricsInfo const & mi, Dimension & dim, int min_width,
220 bool const expand_on_multipars)
222 LBUFERR(mi.base.textwidth > 0);
223 max_width_ = mi.base.textwidth;
224 // backup old dimension.
225 Dimension const old_dim = dim_;
228 dim_.wid = min_width;
229 pit_type const npar = text_->paragraphs().size();
230 if (npar > 1 && expand_on_multipars)
231 // If there is more than one row, expand the text to
232 // the full allowable width.
233 dim_.wid = max_width_;
235 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
236 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
238 bool changed = false;
240 for (pit_type pit = 0; pit != npar; ++pit) {
241 // create rows, but do not set alignment yet
242 changed |= redoParagraph(pit, false);
243 ParagraphMetrics const & pm = par_metrics_[pit];
245 if (dim_.wid < pm.width())
246 dim_.wid = pm.width();
249 // Now set alignment for all rows (the width might not have been known before).
250 for (pit_type pit = 0; pit != npar; ++pit) {
251 ParagraphMetrics & pm = par_metrics_[pit];
252 for (Row & row : pm.rows())
253 setRowAlignment(row, dim_.wid);
256 dim_.asc = par_metrics_[0].ascent();
257 dim_.des = h - dim_.asc;
258 //lyxerr << "dim_.wid " << dim_.wid << endl;
259 //lyxerr << "dim_.asc " << dim_.asc << endl;
260 //lyxerr << "dim_.des " << dim_.des << endl;
262 changed |= dim_ != old_dim;
268 void TextMetrics::updatePosCache(pit_type pit) const
270 frontend::NullPainter np;
271 PainterInfo pi(bv_, np);
272 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
276 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
278 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
282 int TextMetrics::rightMargin(pit_type const pit) const
284 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
288 void TextMetrics::applyOuterFont(Font & font) const
290 FontInfo lf(font_.fontInfo());
291 lf.reduce(bv_->buffer().params().getFont().fontInfo());
292 font.fontInfo().realize(lf);
296 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
298 LASSERT(pos >= 0, { static Font f; return f; });
300 ParagraphList const & pars = text_->paragraphs();
301 Paragraph const & par = pars[pit];
302 Layout const & layout = par.layout();
303 Buffer const & buffer = bv_->buffer();
305 BufferParams const & params = buffer.params();
306 pos_type const body_pos = par.beginOfBody();
308 // We specialize the 95% common case:
309 if (!par.getDepth()) {
310 Font f = par.getFontSettings(params, pos);
311 if (!text_->isMainText())
313 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
315 FontInfo const & lf = lab ? layout.labelfont : layout.font;
316 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
318 // In case the default family has been customized
319 if (lf.family() == INHERIT_FAMILY)
320 rlf.setFamily(params.getFont().fontInfo().family());
321 f.fontInfo().realize(rlf);
325 // The uncommon case need not be optimized as much
326 FontInfo const & layoutfont = pos < body_pos ?
327 layout.labelfont : layout.font;
329 Font font = par.getFontSettings(params, pos);
330 font.fontInfo().realize(layoutfont);
332 if (!text_->isMainText())
333 applyOuterFont(font);
335 // Realize against environment font information
336 // NOTE: the cast to pit_type should be removed when pit_type
337 // changes to a unsigned integer.
338 if (pit < pit_type(pars.size()))
339 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
341 // Realize with the fonts of lesser depth.
342 font.fontInfo().realize(params.getFont().fontInfo());
348 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
354 if (boundary && sl.pos() > 0)
357 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
361 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
363 // no RTL boundary at paragraph start
367 Font const & left_font = displayFont(pit, pos - 1);
369 return isRTLBoundary(pit, pos, left_font);
373 // isRTLBoundary returns false on a real end-of-line boundary,
374 // because otherwise the two boundary types get mixed up.
375 // This is the whole purpose of this being in TextMetrics.
376 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
377 Font const & font) const
379 if (// no RTL boundary at paragraph start
381 // if the metrics have not been calculated, then we are not
382 // on screen and can safely ignore issues about boundaries.
386 ParagraphMetrics const & pm = par_metrics_[pit];
387 // no RTL boundary in empty paragraph
388 if (pm.rows().empty())
391 pos_type const endpos = pm.getRow(pos - 1, false).endpos();
392 pos_type const startpos = pm.getRow(pos, false).pos();
393 // no RTL boundary at line start:
394 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
396 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
399 Paragraph const & par = text_->getPar(pit);
400 // no RTL boundary at line break:
401 // abc|\n -> move right -> abc\n (and not: abc\n|
403 if (startpos == pos && endpos == pos && endpos != par.size()
404 && (par.isNewline(pos - 1)
405 || par.isEnvSeparator(pos - 1)
406 || par.isLineSeparator(pos - 1)
407 || par.isSeparator(pos - 1)))
410 bool const left = font.isVisibleRightToLeft();
412 if (pos == par.size())
413 right = par.isRTL(bv_->buffer().params());
415 right = displayFont(pit, pos).isVisibleRightToLeft();
417 return left != right;
421 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
423 Paragraph & par = text_->getPar(pit);
424 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
425 // redoParagraph() recursively inside parMetrics.
426 Dimension old_dim = parMetrics(pit, false).dim();
427 ParagraphMetrics & pm = par_metrics_[pit];
430 Buffer & buffer = bv_->buffer();
431 bool changed = false;
433 // Check whether there are InsetBibItems that need fixing
434 // FIXME: This check ought to be done somewhere else. It is the reason
435 // why text_ is not const. But then, where else to do it?
436 // Well, how can you end up with either (a) a biblio environment that
437 // has no InsetBibitem, (b) a biblio environment with more than one
438 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
439 // environment? I think the answer is: when paragraphs are merged;
440 // when layout is set; when material is pasted.
441 if (par.brokenBiblio()) {
442 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
443 // In some cases, we do not know how to record undo
444 if (&cur.inset() == &text_->inset())
445 cur.recordUndo(pit, pit);
447 int const moveCursor = par.fixBiblio(buffer);
449 // Is it necessary to update the cursor?
450 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
453 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
458 // Optimisation: this is used in the next two loops
459 // so better to calculate that once here.
460 int const right_margin = rightMargin(pm);
462 // iterator pointing to paragraph to resolve macros
463 DocIterator parPos = text_->macrocontextPosition();
467 LYXERR(Debug::INFO, "MacroContext not initialised!"
468 << " Going through the buffer again and hope"
469 << " the context is better then.");
470 // FIXME audit updateBuffer calls
471 // This should not be here, but it is not clear yet where else it
473 bv_->buffer().updateBuffer();
474 parPos = text_->macrocontextPosition();
475 LBUFERR(!parPos.empty());
480 par.setBeginOfBody();
481 Font const bufferfont = buffer.params().getFont();
482 CoordCache::Insets & insetCache = bv_->coordCache().insets();
483 for (auto const & e : par.insetList()) {
484 // FIXME Doesn't this HAVE to be non-empty?
485 // position already initialized?
486 if (!parPos.empty()) {
487 parPos.pos() = e.pos;
489 // A macro template would normally not be visible
490 // by itself. But the tex macro semantics allow
491 // recursion, so we artifically take the context
492 // after the macro template to simulate this.
493 if (e.inset->lyxCode() == MATHMACRO_CODE)
497 // If there is an end of paragraph marker, its size should be
498 // substracted to the available width. The logic here is
499 // almost the same as in breakRow, remember keep them in sync.
501 if (lyxrc.paragraph_markers && e.pos + 1 == par.size()
502 && size_type(pit + 1) < text_->paragraphs().size()) {
503 Font f(text_->layoutFont(pit));
504 // ¶ U+00B6 PILCROW SIGN
505 eop = theFontMetrics(f).width(char_type(0x00B6));
508 // do the metric calculation
510 int const w = max_width_ - leftMargin(pit, e.pos)
511 - right_margin - eop;
512 Font const & font = e.inset->inheritFont() ?
513 displayFont(pit, e.pos) : bufferfont;
514 MacroContext mc(&buffer, parPos);
515 MetricsInfo mi(bv_, font.fontInfo(), w, mc, e.pos == 0);
516 e.inset->metrics(mi, dim);
517 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
518 insetCache.add(e.inset, dim);
524 size_t row_index = 0;
525 bool need_new_row = false;
526 // maximum pixel width of a row
528 if (row_index == pm.rows().size())
529 pm.rows().push_back(Row());
531 pm.rows()[row_index] = Row();
532 Row & row = pm.rows()[row_index];
535 need_new_row = breakRow(row, right_margin);
538 if ((row_index || row.endpos() < par.size() || row.right_boundary())
539 && par.inInset().lyxCode() != CELL_CODE) {
540 /* If there is more than one row or the row has been
541 * broken by a display inset or a newline, expand the text
542 * to the full allowable width. This setting here is
543 * needed for the setRowAlignment() below.
544 * We do nothing when inside a table cell.
546 if (dim_.wid < max_width_)
547 dim_.wid = max_width_;
550 setRowAlignment(row, max(dim_.wid, row.width()));
551 first = row.endpos();
554 pm.dim().wid = max(pm.dim().wid, row.width() + row.right_margin);
555 pm.dim().des += row.height();
556 } while (first < par.size() || need_new_row);
558 if (row_index < pm.rows().size())
559 pm.rows().resize(row_index);
561 // This type of margin can only be handled at the global paragraph level
562 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX) {
564 if (par.isRTL(buffer.params())) {
565 // globally align the paragraph to the left.
566 int minleft = max_width_;
567 for (Row const & row : pm.rows())
568 minleft = min(minleft, row.left_margin);
569 offset = right_margin - minleft;
571 // globally align the paragraph to the right.
573 for (Row const & row : pm.rows())
574 maxwid = max(maxwid, row.width());
575 offset = max_width_ - right_margin - maxwid;
578 for (Row & row : pm.rows()) {
579 row.left_margin += offset;
580 row.dim().wid += offset;
584 // The space above and below the paragraph.
585 int top = parTopSpacing(pit);
586 int bottom = parBottomSpacing(pit);
588 // Top and bottom margin of the document (only at top-level)
589 // FIXME: It might be better to move this in another method
590 // specially tailored for the main text.
591 if (text_->isMainText()) {
593 top += bv_->topMargin();
594 if (pit + 1 == pit_type(text_->paragraphs().size())) {
595 bottom += bv_->bottomMargin();
599 // Add the top/bottom space to rows and paragraph metrics
600 pm.rows().front().dim().asc += top;
601 pm.rows().back().dim().des += bottom;
602 pm.dim().des += top + bottom;
604 // Move the pm ascent to be the same as the first row ascent
605 pm.dim().asc += pm.rows().front().ascent();
606 pm.dim().des -= pm.rows().front().ascent();
608 changed |= old_dim.height() != pm.dim().height();
614 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
616 LyXAlignment align = par.getAlign(bv_->buffer().params());
618 // handle alignment inside tabular cells
619 Inset const & owner = text_->inset();
620 bool forced_block = false;
621 switch (owner.contentAlignment()) {
622 case LYX_ALIGN_BLOCK:
623 // In general block align is the default state, but here it is
624 // an explicit choice. Therefore it should not be overridden
628 case LYX_ALIGN_CENTER:
630 case LYX_ALIGN_RIGHT:
631 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
632 align = owner.contentAlignment();
635 // unchanged (use align)
639 // Display-style insets should always be on a centered row
640 if (Inset const * inset = par.getInset(row.pos())) {
641 if (inset->rowFlags() & Inset::Display) {
642 if (inset->rowFlags() & Inset::AlignLeft)
643 align = LYX_ALIGN_BLOCK;
644 else if (inset->rowFlags() & Inset::AlignRight)
645 align = LYX_ALIGN_RIGHT;
647 align = LYX_ALIGN_CENTER;
651 if (align == LYX_ALIGN_BLOCK) {
652 // If this row has been broken abruptly by a display inset, or
653 // it is the end of the paragraph, or the user requested we
654 // not justify stuff, then don't stretch.
655 // A forced block alignment can only be overridden the 'no
656 // justification on screen' setting.
657 if ((row.flushed() && !forced_block)
658 || !bv_->buffer().params().justification)
659 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
666 void TextMetrics::setRowAlignment(Row & row, int width) const
671 Paragraph const & par = text_->getPar(row.pit());
673 int const w = width - row.right_margin - row.width();
674 // FIXME: put back this assertion when the crash on new doc is solved.
675 //LASSERT(w >= 0, /**/);
677 // is there a manual margin with a manual label
678 Layout const & layout = par.layout();
681 if (layout.margintype == MARGIN_MANUAL
682 && layout.labeltype == LABEL_MANUAL) {
683 /// We might have real hfills in the label part
684 nlh = numberOfLabelHfills(par, row);
686 // A manual label par (e.g. List) has an auto-hfill
687 // between the label text and the body of the
689 // But we don't want to do this auto hfill if the par
694 if (nlh && !par.getLabelWidthString().empty())
695 row.label_hfill = labelFill(row) / double(nlh);
698 // are there any hfills in the row?
699 ParagraphMetrics const & pm = par_metrics_[row.pit()];
700 int nh = numberOfHfills(row, pm, par.beginOfBody());
704 // We don't have to look at the alignment if the row is already
705 // larger then the permitted width as then we force the
706 // LEFT_ALIGN'edness!
707 if (int(row.width()) >= max_width_)
711 // Common case : there is no hfill, and the alignment will be
713 switch (getAlign(par, row)) {
714 case LYX_ALIGN_BLOCK:
715 // Expand expanding characters by a total of w
716 if (!row.setExtraWidth(w) && row.isRTL()) {
717 // Justification failed and the text is RTL: align to the right
718 row.left_margin += w;
723 // a displayed inset that is flushed
724 if (Inset const * inset = par.getInset(row.pos())) {
725 row.left_margin += inset->indent(*bv_);
726 row.dim().wid += inset->indent(*bv_);
729 case LYX_ALIGN_RIGHT:
730 if (Inset const * inset = par.getInset(row.pos())) {
731 int const new_w = max(w - inset->indent(*bv_), 0);
732 row.left_margin += new_w;
733 row.dim().wid += new_w;
735 row.left_margin += w;
739 case LYX_ALIGN_CENTER:
740 row.dim().wid += w / 2;
741 row.left_margin += w / 2;
744 case LYX_ALIGN_LAYOUT:
745 case LYX_ALIGN_SPECIAL:
746 case LYX_ALIGN_DECIMAL:
752 // Case nh > 0. There are hfill separators.
756 // Set size of hfill insets
757 pos_type const endpos = row.endpos();
758 pos_type body_pos = par.beginOfBody();
760 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
763 CoordCache::Insets & insetCache = bv_->coordCache().insets();
764 for (Row::Element & e : row) {
765 if (row.label_hfill && e.endpos == body_pos
766 && e.type == Row::SPACE)
767 e.dim.wid -= int(row.label_hfill * (nlh - 1));
768 if (e.inset && pm.hfillExpansion(row, e.pos)) {
769 if (e.pos >= body_pos) {
773 e.dim.wid += hfill_rem;
775 e.dim.wid += int(row.label_hfill);
776 // Cache the inset dimension.
777 insetCache.add(e.inset, e.dim);
783 int TextMetrics::labelFill(Row const & row) const
785 Paragraph const & par = text_->getPar(row.pit());
786 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
789 // iterate over elements before main body (except the last one,
790 // which is extra space).
791 for (Row::Element const & e : row) {
792 if (e.endpos >= par.beginOfBody())
797 docstring const & label = par.params().labelWidthString();
801 FontMetrics const & fm
802 = theFontMetrics(text_->labelFont(par));
804 return max(0, fm.width(label) - w);
808 int TextMetrics::labelEnd(pit_type const pit) const
810 // labelEnd is only needed if the layout fills a flushleft label.
811 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
813 // return the beginning of the body
814 return leftMargin(pit);
820 * Calling Text::getFont is slow. While rebreaking we scan a
821 * paragraph from left to right calling getFont for every char. This
822 * simple class address this problem by hidding an optimization trick
823 * (not mine btw -AB): the font is reused in the whole font span. The
824 * class handles transparently the "hidden" (not part of the fontlist)
825 * label font (as getFont does).
831 FontIterator(TextMetrics const & tm,
832 Paragraph const & par, pit_type pit, pos_type pos)
833 : tm_(tm), par_(par), pit_(pit), pos_(pos),
834 font_(tm.displayFont(pit, pos)),
835 endspan_(par.fontSpan(pos).last),
836 bodypos_(par.beginOfBody())
840 Font const & operator*() const { return font_; }
843 FontIterator & operator++()
846 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
847 font_ = tm_.displayFont(pit_, pos_);
848 endspan_ = par_.fontSpan(pos_).last;
854 Font * operator->() { return &font_; }
858 TextMetrics const & tm_;
860 Paragraph const & par_;
875 /** This is the function where the hard work is done. The code here is
876 * very sensitive to small changes :) Note that part of the
877 * intelligence is also in Row::shortenIfNeeded.
879 bool TextMetrics::breakRow(Row & row, int const right_margin) const
881 LATTEST(row.empty());
882 Paragraph const & par = text_->getPar(row.pit());
883 Buffer const & buf = text_->inset().buffer();
884 BookmarksSection::BookmarkPosList bpl =
885 theSession().bookmarks().bookmarksInPar(buf.fileName(), par.id());
887 pos_type const end = par.size();
888 pos_type const pos = row.pos();
889 pos_type const body_pos = par.beginOfBody();
890 bool const is_rtl = text_->isRTL(row.pit());
891 bool need_new_row = false;
893 row.left_margin = leftMargin(row.pit(), pos);
894 row.right_margin = right_margin;
896 swap(row.left_margin, row.right_margin);
897 // Remember that the row width takes into account the left_margin
898 // but not the right_margin.
899 row.dim().wid = row.left_margin;
900 // the width available for the row.
901 int const width = max_width_ - row.right_margin;
903 // check for possible inline completion
904 DocIterator const & ic_it = bv_->inlineCompletionPos();
905 pos_type ic_pos = -1;
906 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == row.pit())
907 ic_pos = ic_it.pos();
909 // Now we iterate through until we reach the right margin
910 // or the end of the par, then build a representation of the row.
912 FontIterator fi = FontIterator(*this, par, row.pit(), pos);
913 // The real stopping condition is a few lines below.
915 // Firstly, check whether there is a bookmark here.
916 for (auto const & bp_p : bpl)
917 if (bp_p.second == i) {
919 f.fontInfo().setColor(Color_bookmark);
920 // ❶ U+2776 DINGBAT NEGATIVE CIRCLED DIGIT ONE
921 char_type const ch = 0x2775 + bp_p.first;
922 row.addVirtual(i, docstring(1, ch), f, Change());
925 // The stopping condition is here so that the display of a
926 // bookmark can take place at paragraph start too.
927 if (i >= end || (i != pos && row.width() > width))
930 char_type c = par.getChar(i);
931 // The most special cases are handled first.
932 if (par.isInset(i)) {
933 Inset const * ins = par.getInset(i);
934 Dimension dim = bv_->coordCache().insets().dim(ins);
935 row.add(i, ins, dim, *fi, par.lookupChange(i));
936 } else if (c == ' ' && i + 1 == body_pos) {
937 // There is a space at i, but it should not be
938 // added as a separator, because it is just
939 // before body_pos. Instead, insert some spacing to
941 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
942 // this is needed to make sure that the row width is correct
944 int const add = max(fm.width(par.layout().labelsep),
945 labelEnd(row.pit()) - row.width());
946 row.addSpace(i, add, *fi, par.lookupChange(i));
947 } else if (c == '\t')
948 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
949 *fi, par.lookupChange(i));
950 else if (c == 0x2028 || c == 0x2029) {
952 * U+2028 LINE SEPARATOR
953 * U+2029 PARAGRAPH SEPARATOR
955 * These are special unicode characters that break
956 * lines/pragraphs. Not handling them lead to trouble wrt
957 * Qt QTextLayout formatting. We add a visible character
958 * on screen so that the user can see that something is
962 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
963 // ¶ U+00B6 PILCROW SIGN
964 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
965 row.add(i, screen_char, *fi, par.lookupChange(i));
967 row.add(i, c, *fi, par.lookupChange(i));
969 // add inline completion width
970 // draw logically behind the previous character
971 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
972 docstring const comp = bv_->inlineCompletion();
973 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
977 f.fontInfo().setColor(Color_inlinecompletion);
978 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
980 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
981 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
984 // Handle some situations that abruptly terminate the row
985 // - Before an inset with BreakBefore
986 // - After an inset with BreakAfter
987 Inset const * prevInset = !row.empty() ? row.back().inset : 0;
988 Inset const * nextInset = (i + 1 < end) ? par.getInset(i + 1) : 0;
989 if ((nextInset && nextInset->rowFlags() & Inset::BreakBefore)
990 || (prevInset && prevInset->rowFlags() & Inset::BreakAfter)) {
992 // Force a row creation after this one if it is ended by
993 // an inset that either
994 // - has row flag RowAfter that enforces that;
995 // - or (1) did force the row breaking, (2) is at end of
996 // paragraph and (3) the said paragraph has an end label.
997 need_new_row = prevInset &&
998 (prevInset->rowFlags() & Inset::RowAfter
999 || (prevInset->rowFlags() & Inset::BreakAfter && i + 1 == end
1000 && text_->getEndLabel(row.pit()) != END_LABEL_NO_LABEL));
1011 // End of paragraph marker. The logic here is almost the
1012 // same as in redoParagraph, remember keep them in sync.
1013 ParagraphList const & pars = text_->paragraphs();
1014 Change const & change = par.lookupChange(i);
1015 if ((lyxrc.paragraph_markers || change.changed())
1017 && i == end && size_type(row.pit() + 1) < pars.size()) {
1018 // add a virtual element for the end-of-paragraph
1019 // marker; it is shown on screen, but does not exist
1020 // in the paragraph.
1021 Font f(text_->layoutFont(row.pit()));
1022 f.fontInfo().setColor(Color_paragraphmarker);
1023 f.setLanguage(par.getParLanguage(buf.params()));
1024 // ¶ U+00B6 PILCROW SIGN
1025 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, change);
1028 // Is there a end-of-paragaph change?
1029 if (i == end && par.lookupChange(end).changed() && !need_new_row)
1030 row.needsChangeBar(true);
1032 // if the row is too large, try to cut at last separator. In case
1033 // of success, reset indication that the row was broken abruptly.
1034 int const next_width = max_width_ - leftMargin(row.pit(), row.endpos())
1035 - rightMargin(row.pit());
1037 if (row.shortenIfNeeded(body_pos, width, next_width))
1039 row.right_boundary(!row.empty() && row.endpos() < end
1040 && row.back().endpos == row.endpos());
1041 // Last row in paragraph is flushed
1042 if (row.endpos() == end)
1045 // make sure that the RTL elements are in reverse ordering
1046 row.reverseRTL(is_rtl);
1047 //LYXERR0("breakrow: row is " << row);
1049 return need_new_row;
1052 int TextMetrics::parTopSpacing(pit_type const pit) const
1054 Paragraph const & par = text_->getPar(pit);
1055 Layout const & layout = par.layout();
1058 ParagraphList const & pars = text_->paragraphs();
1059 double const dh = defaultRowHeight();
1061 BufferParams const & bparams = bv_->buffer().params();
1062 Inset const & inset = text_->inset();
1063 // some parskips VERY EASY IMPLEMENTATION
1064 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1065 && !inset.getLayout().parbreakIsNewline()
1066 && !par.layout().parbreak_is_newline
1068 && ((layout.isParagraph() && par.getDepth() == 0)
1069 || (pars[pit - 1].layout().isParagraph()
1070 && pars[pit - 1].getDepth() == 0))) {
1071 asc += bparams.getDefSkip().inPixels(*bv_);
1074 if (par.params().startOfAppendix())
1077 // special code for the top label
1078 if (layout.labelIsAbove()
1079 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1080 && !par.labelString().empty()) {
1081 FontInfo labelfont = text_->labelFont(par);
1082 FontMetrics const & lfm = theFontMetrics(labelfont);
1083 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1084 * text_->spacing(par)
1085 + (layout.topsep + layout.labelbottomsep) * dh);
1088 // Add the layout spaces, for example before and after
1089 // a section, or between the items of a itemize or enumerate
1092 pit_type prev = text_->depthHook(pit, par.getDepth());
1093 Paragraph const & prevpar = pars[prev];
1094 double layoutasc = 0;
1096 && prevpar.layout() == layout
1097 && prevpar.getDepth() == par.getDepth()
1098 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1099 layoutasc = layout.itemsep * dh;
1100 } else if (pit != 0 && layout.topsep > 0)
1101 layoutasc = layout.topsep * dh;
1103 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1105 prev = text_->outerHook(pit);
1106 if (prev != pit_type(pars.size())) {
1107 asc += int(pars[prev].layout().parsep * dh);
1108 } else if (pit != 0) {
1109 Paragraph const & prevpar2 = pars[pit - 1];
1110 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1111 asc += int(layout.parsep * dh);
1118 int TextMetrics::parBottomSpacing(pit_type const pit) const
1120 double layoutdesc = 0;
1121 ParagraphList const & pars = text_->paragraphs();
1122 double const dh = defaultRowHeight();
1124 // add the layout spaces, for example before and after
1125 // a section, or between the items of a itemize or enumerate
1127 pit_type nextpit = pit + 1;
1128 if (nextpit != pit_type(pars.size())) {
1129 pit_type cpit = pit;
1131 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1132 double usual = pars[cpit].layout().bottomsep * dh;
1134 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1135 if (pars[cpit].layout() != pars[nextpit].layout()
1136 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1137 unusual = pars[cpit].layout().bottomsep * dh;
1138 layoutdesc = max(unusual, usual);
1139 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1140 if (pars[cpit].layout() != pars[nextpit].layout()
1141 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1142 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1146 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1150 void TextMetrics::setRowHeight(Row & row) const
1152 Paragraph const & par = text_->getPar(row.pit());
1153 Layout const & layout = par.layout();
1154 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1156 // Initial value for ascent (useful if row is empty).
1157 Font const font = displayFont(row.pit(), row.pos());
1158 FontMetrics const & fm = theFontMetrics(font);
1159 int maxasc = int(fm.maxAscent() * spacing_val);
1160 int maxdes = int(fm.maxDescent() * spacing_val);
1162 // Take label string into account (useful if labelfont is large)
1163 if (row.pos() == 0 && layout.labelIsInline()) {
1164 FontInfo const labelfont = text_->labelFont(par);
1165 FontMetrics const & lfm = theFontMetrics(labelfont);
1166 maxasc = max(maxasc, int(lfm.maxAscent() * spacing_val));
1167 maxdes = max(maxdes, int(lfm.maxDescent() * spacing_val));
1170 // Find the ascent/descent of the row contents
1171 for (Row::Element const & e : row) {
1173 maxasc = max(maxasc, e.dim.ascent());
1174 maxdes = max(maxdes, e.dim.descent());
1176 FontMetrics const & fm2 = theFontMetrics(e.font);
1177 maxasc = max(maxasc, int(fm2.maxAscent() * spacing_val));
1178 maxdes = max(maxdes, int(fm2.maxDescent() * spacing_val));
1182 // This is nicer with box insets
1186 row.dim().asc = maxasc;
1187 row.dim().des = maxdes;
1189 // This is useful for selections
1190 row.contents_dim() = row.dim();
1194 // x is an absolute screen coord
1195 // returns the column near the specified x-coordinate of the row
1196 // x is set to the real beginning of this column
1197 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1198 bool & boundary) const
1200 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1201 /// For the main Text, it is possible that this pit is not
1202 /// yet in the CoordCache when moving cursor up.
1203 /// x Paragraph coordinate is always 0 for main text anyway.
1204 int const xo = origin_.x_;
1207 // Adapt to cursor row scroll offset if applicable.
1208 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1211 pos_type pos = row.pos();
1214 x = row.left_margin;
1215 else if (x <= row.left_margin) {
1216 pos = row.front().left_pos();
1217 x = row.left_margin;
1218 } else if (x >= row.width()) {
1219 pos = row.back().right_pos();
1222 double w = row.left_margin;
1223 Row::const_iterator cit = row.begin();
1224 Row::const_iterator cend = row.end();
1225 for ( ; cit != cend; ++cit) {
1226 if (w <= x && w + cit->full_width() > x) {
1227 int x_offset = int(x - w);
1228 pos = cit->x2pos(x_offset);
1229 x = int(x_offset + w);
1232 w += cit->full_width();
1234 if (cit == row.end()) {
1235 pos = row.back().right_pos();
1238 /** This tests for the case where the cursor is placed
1239 * just before a font direction change. See comment on
1240 * the boundary_ member in DocIterator.h to understand
1241 * how boundary helps here.
1243 else if (pos == cit->endpos
1244 && ((!cit->isRTL() && cit + 1 != row.end()
1245 && (cit + 1)->isRTL())
1246 || (cit->isRTL() && cit != row.begin()
1247 && !(cit - 1)->isRTL())))
1251 /** This tests for the case where the cursor is set at the end
1252 * of a row which has been broken due something else than a
1253 * separator (a display inset or a forced breaking of the
1254 * row). We know that there is a separator when the end of the
1255 * row is larger than the end of its last element.
1257 if (!row.empty() && pos == row.back().endpos
1258 && row.back().endpos == row.endpos()) {
1259 Inset const * inset = row.back().inset;
1260 if (inset && (inset->lyxCode() == NEWLINE_CODE
1261 || inset->lyxCode() == SEPARATOR_CODE))
1262 pos = row.back().pos;
1264 boundary = row.right_boundary();
1268 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1274 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1276 // We play safe and use parMetrics(pit) to make sure the
1277 // ParagraphMetrics will be redone and OK to use if needed.
1278 // Otherwise we would use an empty ParagraphMetrics in
1279 // upDownInText() while in selection mode.
1280 ParagraphMetrics const & pm = parMetrics(pit);
1282 LBUFERR(row < int(pm.rows().size()));
1284 Row const & r = pm.rows()[row];
1285 return getPosNearX(r, x, bound);
1289 // y is screen coordinate
1290 pit_type TextMetrics::getPitNearY(int y)
1292 LASSERT(!text_->paragraphs().empty(), return -1);
1293 LASSERT(!par_metrics_.empty(), return -1);
1294 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1296 // look for highest numbered paragraph with y coordinate less than given y
1299 ParMetricsCache::const_iterator it = par_metrics_.begin();
1300 ParMetricsCache::const_iterator et = par_metrics_.end();
1301 ParMetricsCache::const_iterator last = et;
1304 ParagraphMetrics const & pm = it->second;
1306 if (y < it->second.position() - int(pm.ascent())) {
1307 // We are looking for a position that is before the first paragraph in
1308 // the cache (which is in priciple off-screen, that is before the
1311 // We are already at the first paragraph in the inset.
1313 // OK, this is the paragraph we are looking for.
1314 pit = it->first - 1;
1319 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1321 if (y >= last->second.position() + int(pm_last.descent())) {
1322 // We are looking for a position that is after the last paragraph in
1323 // the cache (which is in priciple off-screen), that is before the
1325 pit = last->first + 1;
1326 if (pit == int(text_->paragraphs().size()))
1327 // We are already at the last paragraph in the inset.
1329 // OK, this is the paragraph we are looking for.
1330 newParMetricsDown();
1334 for (; it != et; ++it) {
1335 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1336 << " y: " << it->second.position());
1338 ParagraphMetrics const & pm2 = par_metrics_[it->first];
1340 if (it->first >= pit && int(it->second.position()) - int(pm2.ascent()) <= y) {
1342 yy = it->second.position();
1346 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1352 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1353 bool assert_in_view, bool up)
1355 ParagraphMetrics const & pm = par_metrics_[pit];
1357 int yy = pm.position() - pm.ascent();
1358 LBUFERR(!pm.rows().empty());
1359 RowList::const_iterator rit = pm.rows().begin();
1360 RowList::const_iterator rlast = pm.rows().end();
1362 for (; rit != rlast; yy += rit->height(), ++rit)
1363 if (yy + rit->height() > y)
1366 if (assert_in_view) {
1367 if (!up && yy + rit->height() > y) {
1368 if (rit != pm.rows().begin()) {
1371 } else if (pit != 0) {
1374 ParagraphMetrics const & pm2 = par_metrics_[pit];
1375 rit = pm2.rows().end();
1379 } else if (up && yy != y) {
1381 y = yy + rit->height();
1383 } else if (pit < int(text_->paragraphs().size()) - 1) {
1385 newParMetricsDown();
1386 ParagraphMetrics const & pm2 = par_metrics_[pit];
1387 rit = pm2.rows().begin();
1396 // x,y are absolute screen coordinates
1397 // sets cursor recursively descending into nested editable insets
1398 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1399 bool assert_in_view, bool up)
1401 if (lyxerr.debugging(Debug::WORKAREA)) {
1402 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1403 cur.bv().coordCache().dump();
1405 pit_type pit = getPitNearY(y);
1406 LASSERT(pit != -1, return 0);
1407 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1410 // Do we cover an inset?
1411 InsetList::Element * e = checkInsetHit(pit, x, y);
1414 // No inset, set position in the text
1415 bool bound = false; // is modified by getPosNearX
1416 cur.pos() = getPosNearX(row, x, bound);
1417 cur.boundary(bound);
1418 cur.setCurrentFont();
1423 Inset * inset = e->inset;
1424 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1426 // Set position in front of inset
1428 cur.boundary(false);
1431 // Try to descend recursively inside the inset.
1432 Inset * edited = inset->editXY(cur, x, y);
1433 // FIXME: it is not clear that the test on position is needed
1434 // Remove it if/when semantics of editXY is clarified
1435 if (cur.text() == text_ && cur.pos() == e->pos) {
1436 // non-editable inset, set cursor after the inset if x is
1437 // nearer to that position (bug 9628)
1438 bool bound = false; // is modified by getPosNearX
1439 cur.pos() = getPosNearX(row, x, bound);
1440 cur.boundary(bound);
1441 cur.setCurrentFont();
1445 if (cur.top().text() == text_)
1446 cur.setCurrentFont();
1451 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1453 LASSERT(text_ == cur.text(), return);
1454 pit_type const pit = getPitNearY(y);
1455 LASSERT(pit != -1, return);
1457 ParagraphMetrics const & pm = par_metrics_[pit];
1459 int yy = pm.position() - pm.rows().front().ascent();
1460 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1461 " pit: " << pit << " yy: " << yy);
1464 LBUFERR(pm.rows().size());
1465 for (; r < int(pm.rows().size()) - 1; ++r) {
1466 Row const & row = pm.rows()[r];
1467 if (int(yy + row.height()) > y)
1472 Row const & row = pm.rows()[r];
1474 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1478 pos_type const pos = getPosNearX(row, xx, bound);
1480 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1482 text_->setCursor(cur, pit, pos, true, bound);
1483 // remember new position.
1488 //takes screen x,y coordinates
1489 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1491 Paragraph const & par = text_->paragraphs()[pit];
1492 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1494 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1496 for (InsetList::Element const & e : par.insetList()) {
1497 LYXERR(Debug::DEBUG, "examining inset " << e.inset);
1499 if (insetCache.covers(e.inset, x, y)) {
1500 LYXERR(Debug::DEBUG, "Hit inset: " << e.inset);
1501 return const_cast<InsetList::Element *>(&e);
1505 LYXERR(Debug::DEBUG, "No inset hit. ");
1510 //takes screen x,y coordinates
1511 Inset * TextMetrics::checkInsetHit(int x, int y)
1513 pit_type const pit = getPitNearY(y);
1514 LASSERT(pit != -1, return 0);
1515 InsetList::Element * e = checkInsetHit(pit, x, y);
1524 int TextMetrics::cursorX(CursorSlice const & sl,
1525 bool boundary) const
1527 LASSERT(sl.text() == text_, return 0);
1529 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1530 if (pm.rows().empty())
1532 Row const & row = pm.getRow(sl.pos(), boundary);
1533 pos_type const pos = sl.pos();
1536 row.findElement(pos, boundary, x);
1542 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1544 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1545 ParagraphMetrics const & pm = parMetrics(sl.pit());
1546 if (pm.rows().empty())
1550 h -= parMetrics(0).rows()[0].ascent();
1551 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1552 h += parMetrics(pit).height();
1555 if (pos && boundary)
1557 size_t const rend = pm.pos2row(pos);
1558 for (size_t rit = 0; rit != rend; ++rit)
1559 h += pm.rows()[rit].height();
1560 h += pm.rows()[rend].ascent();
1565 // the cursor set functions have a special mechanism. When they
1566 // realize you left an empty paragraph, they will delete it.
1568 bool TextMetrics::cursorHome(Cursor & cur)
1570 LASSERT(text_ == cur.text(), return false);
1571 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1572 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1573 return text_->setCursor(cur, cur.pit(), row.pos());
1577 bool TextMetrics::cursorEnd(Cursor & cur)
1579 LASSERT(text_ == cur.text(), return false);
1580 // if not on the last row of the par, put the cursor before
1581 // the final space exept if I have a spanning inset or one string
1582 // is so long that we force a break.
1583 pos_type end = cur.textRow().endpos();
1585 // empty text, end-1 is no valid position
1587 bool boundary = false;
1588 if (end != cur.lastpos()) {
1589 if (!cur.paragraph().isLineSeparator(end-1)
1590 && !cur.paragraph().isNewline(end-1)
1591 && !cur.paragraph().isEnvSeparator(end-1))
1595 } else if (cur.paragraph().isEnvSeparator(end-1))
1597 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1601 void TextMetrics::deleteLineForward(Cursor & cur)
1603 LASSERT(text_ == cur.text(), return);
1604 if (cur.lastpos() == 0) {
1605 // Paragraph is empty, so we just go forward
1606 text_->cursorForward(cur);
1609 cur.selection(true); // to avoid deletion
1612 // What is this test for ??? (JMarc)
1613 if (!cur.selection())
1614 text_->deleteWordForward(cur);
1616 cap::cutSelection(cur, false);
1617 cur.checkBufferStructure();
1622 int TextMetrics::leftMargin(pit_type pit) const
1624 // FIXME: what is the semantics? It depends on whether the
1625 // paragraph is empty!
1626 return leftMargin(pit, text_->paragraphs()[pit].size());
1630 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1632 ParagraphList const & pars = text_->paragraphs();
1634 LASSERT(pit >= 0, return 0);
1635 LASSERT(pit < int(pars.size()), return 0);
1636 Paragraph const & par = pars[pit];
1637 LASSERT(pos >= 0, return 0);
1638 // We do not really care whether pos > par.size(), since we do not
1639 // access the data. It can be actually useful, when querying the
1640 // margin without indentation (see leftMargin(pit_type).
1642 Buffer const & buffer = bv_->buffer();
1643 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1644 DocumentClass const & tclass = buffer.params().documentClass();
1645 Layout const & layout = par.layout();
1646 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1648 docstring parindent = layout.parindent;
1652 if (text_->isMainText()) {
1653 l_margin += bv_->leftMargin();
1654 l_margin += bfm.signedWidth(tclass.leftmargin());
1657 int depth = par.getDepth();
1659 // find the next level paragraph
1660 pit_type newpar = text_->outerHook(pit);
1661 if (newpar != pit_type(pars.size())) {
1662 if (pars[newpar].layout().isEnvironment()) {
1663 int nestmargin = depth * nestMargin();
1664 if (text_->isMainText())
1665 nestmargin += changebarMargin();
1666 l_margin = max(leftMargin(newpar), nestmargin);
1667 // Remove the parindent that has been added
1668 // if the paragraph was empty.
1669 if (pars[newpar].empty() &&
1670 buffer.params().paragraph_separation ==
1671 BufferParams::ParagraphIndentSeparation) {
1672 docstring pi = pars[newpar].layout().parindent;
1673 l_margin -= bfm.signedWidth(pi);
1676 if (tclass.isDefaultLayout(par.layout())
1677 || tclass.isPlainLayout(par.layout())) {
1678 if (pars[newpar].params().noindent())
1681 parindent = pars[newpar].layout().parindent;
1686 // This happens after sections or environments in standard classes.
1687 // We have to check the previous layout at same depth.
1688 if (buffer.params().paragraph_separation ==
1689 BufferParams::ParagraphSkipSeparation)
1691 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1692 pit_type prev = text_->depthHook(pit, par.getDepth());
1693 if (par.layout() == pars[prev].layout()) {
1695 && pars[pit - 1].layout().nextnoindent)
1697 } else if (pars[prev].layout().nextnoindent)
1701 FontInfo const labelfont = text_->labelFont(par);
1702 FontMetrics const & lfm = theFontMetrics(labelfont);
1704 switch (layout.margintype) {
1705 case MARGIN_DYNAMIC:
1706 if (!layout.leftmargin.empty()) {
1707 l_margin += bfm.signedWidth(layout.leftmargin);
1709 if (!par.labelString().empty()) {
1710 l_margin += lfm.signedWidth(layout.labelindent);
1711 l_margin += lfm.width(par.labelString());
1712 l_margin += lfm.width(layout.labelsep);
1716 case MARGIN_MANUAL: {
1717 l_margin += lfm.signedWidth(layout.labelindent);
1718 // The width of an empty par, even with manual label, should be 0
1719 if (!par.empty() && pos >= par.beginOfBody()) {
1720 if (!par.getLabelWidthString().empty()) {
1721 docstring labstr = par.getLabelWidthString();
1722 l_margin += lfm.width(labstr);
1723 l_margin += lfm.width(layout.labelsep);
1729 case MARGIN_STATIC: {
1730 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1731 / (par.getDepth() + 4);
1735 case MARGIN_FIRST_DYNAMIC:
1736 if (layout.labeltype == LABEL_MANUAL) {
1737 // if we are at position 0, we are never in the body
1738 if (pos > 0 && pos >= par.beginOfBody())
1739 l_margin += lfm.signedWidth(layout.leftmargin);
1741 l_margin += lfm.signedWidth(layout.labelindent);
1743 // Special case to fix problems with
1745 || (layout.labeltype == LABEL_STATIC
1746 && layout.latextype == LATEX_ENVIRONMENT
1747 && !text_->isFirstInSequence(pit))) {
1748 l_margin += lfm.signedWidth(layout.leftmargin);
1749 } else if (!layout.labelIsAbove()) {
1750 l_margin += lfm.signedWidth(layout.labelindent);
1751 l_margin += lfm.width(layout.labelsep);
1752 l_margin += lfm.width(par.labelString());
1756 case MARGIN_RIGHT_ADDRESS_BOX:
1757 // This is handled globally in redoParagraph().
1761 if (!par.params().leftIndent().zero())
1762 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1764 LyXAlignment align = par.getAlign(bv_->buffer().params());
1766 // set the correct parindent
1768 && (layout.labeltype == LABEL_NO_LABEL
1769 || layout.labeltype == LABEL_ABOVE
1770 || layout.labeltype == LABEL_CENTERED
1771 || (layout.labeltype == LABEL_STATIC
1772 && layout.latextype == LATEX_ENVIRONMENT
1773 && !text_->isFirstInSequence(pit)))
1774 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1775 && !par.params().noindent()
1776 // in some insets, paragraphs are never indented
1777 && !text_->inset().neverIndent()
1778 // display style insets do not need indentation
1781 && par.getInset(0)->rowFlags() & Inset::Display)
1782 && (!(tclass.isDefaultLayout(par.layout())
1783 || tclass.isPlainLayout(par.layout()))
1784 || buffer.params().paragraph_separation
1785 == BufferParams::ParagraphIndentSeparation)) {
1786 /* use the parindent of the layout when the default
1787 * indentation is used otherwise use the indentation set in
1788 * the document settings
1790 if (buffer.params().getParIndent().empty())
1791 l_margin += bfm.signedWidth(parindent);
1793 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1800 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1802 if (par_metrics_.empty())
1808 y -= par_metrics_.begin()->second.ascent();
1809 for (auto & pm_pair : par_metrics_) {
1810 pit_type const pit = pm_pair.first;
1811 ParagraphMetrics & pm = pm_pair.second;
1813 // Save the paragraph position in the cache.
1815 drawParagraph(pi, pit, x, y);
1821 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1823 ParagraphMetrics const & pm = par_metrics_[pit];
1824 if (pm.rows().empty())
1826 size_t const nrows = pm.rows().size();
1827 // Remember left and right margin for drawing math numbers
1828 Changer changeleft = changeVar(pi.leftx, x + leftMargin(pit));
1829 Changer changeright = changeVar(pi.rightx, x + width() - rightMargin(pit));
1831 // Use fast lane in nodraw stage.
1832 if (pi.pain.isNull()) {
1833 for (size_t i = 0; i != nrows; ++i) {
1835 Row const & row = pm.rows()[i];
1836 // Adapt to cursor row scroll offset if applicable.
1837 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1841 RowPainter rp(pi, *text_, row, row_x, y);
1843 rp.paintOnlyInsets();
1849 int const ww = bv_->workHeight();
1850 Cursor const & cur = bv_->cursor();
1851 DocIterator sel_beg = cur.selectionBegin();
1852 DocIterator sel_end = cur.selectionEnd();
1853 bool selection = cur.selection()
1854 // This is our text.
1855 && cur.text() == text_
1856 // if the anchor is outside, this is not our selection
1857 && cur.normalAnchor().text() == text_
1858 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1860 // We store the begin and end pos of the selection relative to this par
1861 DocIterator sel_beg_par = cur.selectionBegin();
1862 DocIterator sel_end_par = cur.selectionEnd();
1864 // We care only about visible selection.
1866 if (pit != sel_beg.pit()) {
1867 sel_beg_par.pit() = pit;
1868 sel_beg_par.pos() = 0;
1870 if (pit != sel_end.pit()) {
1871 sel_end_par.pit() = pit;
1872 sel_end_par.pos() = sel_end_par.lastpos();
1876 if (text_->isRTL(pit))
1877 swap(pi.leftx, pi.rightx);
1879 for (size_t i = 0; i != nrows; ++i) {
1881 Row const & row = pm.rows()[i];
1882 // Adapt to cursor row scroll offset if applicable.
1883 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1887 // It is not needed to draw on screen if we are not inside.
1888 bool const inside = (y + row.descent() >= 0
1889 && y - row.ascent() < ww);
1891 // Inset positions have already been set in nodraw stage.
1897 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
1899 row.clearSelectionAndMargins();
1901 // The row knows nothing about the paragraph, so we have to check
1902 // whether this row is the first or last and update the margins.
1903 if (row.selection()) {
1904 if (row.sel_beg == 0)
1905 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
1906 if (row.sel_end == sel_end_par.lastpos())
1907 row.change(row.end_margin_sel, sel_end.pit() > pit);
1910 // Take this opportunity to spellcheck the row contents.
1911 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
1912 text_->getPar(pit).spellCheck();
1915 RowPainter rp(pi, *text_, row, row_x, y);
1917 // Don't paint the row if a full repaint has not been requested
1918 // and if it has not changed.
1919 if (!pi.full_repaint && !row.changed()) {
1920 // Paint only the insets if the text itself is
1922 rp.paintOnlyInsets();
1928 // Clear background of this row if paragraph background was not
1929 // already cleared because of a full repaint.
1930 if (!pi.full_repaint && row.changed()) {
1931 LYXERR(Debug::PAINTING, "Clear rect@("
1932 << max(row_x, 0) << ", " << y - row.ascent() << ")="
1933 << width() << " x " << row.height());
1934 pi.pain.fillRectangle(row_x, y - row.ascent(),
1935 width(), row.height(), pi.background_color);
1938 // Instrumentation for testing row cache (see also
1940 if (lyxerr.debugging(Debug::PAINTING)
1941 && (row.selection() || pi.full_repaint || row.changed())) {
1942 string const foreword = text_->isMainText() ? "main text redraw "
1943 : "inset text redraw: ";
1944 LYXERR0(foreword << "pit=" << pit << " row=" << i
1945 << (row.selection() ? " row_selection": "")
1946 << (pi.full_repaint ? " full_repaint" : "")
1947 << (row.changed() ? " row.changed" : ""));
1950 // Backup full_repaint status and force full repaint
1951 // for inner insets as the Row has been cleared out.
1952 bool tmp = pi.full_repaint;
1953 pi.full_repaint = true;
1955 rp.paintSelection();
1958 if (row.needsChangeBar())
1959 rp.paintChangeBar();
1965 rp.paintTooLargeMarks(row_x + row.left_x() < 0,
1966 row_x + row.right_x() > bv_->workWidth());
1970 // This debug code shows on screen which rows are repainted.
1971 // FIXME: since the updates related to caret blinking restrict
1972 // the painter to a small rectangle, the numbers are not
1973 // updated when this happens. Change the code in
1974 // GuiWorkArea::Private::show/hideCaret if this is important.
1975 static int count = 0;
1977 FontInfo fi(sane_font);
1978 fi.setSize(TINY_SIZE);
1979 fi.setColor(Color_red);
1980 pi.pain.text(row_x, y, convert<docstring>(count), fi);
1983 // Restore full_repaint status.
1984 pi.full_repaint = tmp;
1989 //LYXERR(Debug::PAINTING, ".");
1993 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
1994 Dimension & dim) const
1996 DocIterator from = cur.bv().cursor();
1997 DocIterator to = from;
1998 text_->getWord(from.top(), to.top(), PREVIOUS_WORD);
2000 // The vertical dimension of the word
2001 Font const font = displayFont(cur.pit(), from.pos());
2002 FontMetrics const & fm = theFontMetrics(font);
2003 // the +1's below are related to the extra pixels added in setRowHeight
2004 dim.asc = fm.maxAscent() + 1;
2005 dim.des = fm.maxDescent() + 1;
2007 // get position on screen of the word start and end
2008 //FIXME: Is it necessary to explicitly set this to false?
2009 from.boundary(false);
2010 Point lxy = cur.bv().getPos(from);
2011 Point rxy = cur.bv().getPos(to);
2012 dim.wid = abs(rxy.x_ - lxy.x_);
2014 // calculate position of word
2016 x = min(rxy.x_, lxy.x_);
2018 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2019 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2022 int defaultRowHeight()
2024 return int(theFontMetrics(sane_font).maxHeight() * 1.2);