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"
34 #include "TextClass.h"
37 #include "insets/InsetText.h"
39 #include "mathed/InsetMathMacroTemplate.h"
41 #include "frontends/FontMetrics.h"
42 #include "frontends/NullPainter.h"
44 #include "support/convert.h"
45 #include "support/debug.h"
46 #include "support/lassert.h"
47 #include "support/lyxlib.h"
48 #include "support/RefChanger.h"
58 using frontend::FontMetrics;
63 int numberOfLabelHfills(Paragraph const & par, Row const & row)
65 pos_type last = row.endpos() - 1;
66 pos_type first = row.pos();
68 // hfill *DO* count at the beginning of paragraphs!
70 while (first < last && par.isHfill(first))
74 last = min(last, par.beginOfBody());
76 for (pos_type p = first; p < last; ++p) {
83 // FIXME: this needs to be rewritten, probably by merging it into some
84 // code that, besides counting, sets the active status of the space
85 // inset in the row element.
86 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
87 pos_type const body_pos)
90 Row::const_iterator cit = row.begin();
91 Row::const_iterator const end = row.end();
92 for ( ; cit != end ; ++cit)
93 if (cit->pos >= body_pos
94 && cit->inset && pm.hfillExpansion(row, cit->pos))
102 /////////////////////////////////////////////////////////////////////
106 /////////////////////////////////////////////////////////////////////
109 TextMetrics::TextMetrics(BufferView * bv, Text * text)
110 : bv_(bv), text_(text)
113 max_width_ = bv_->workWidth();
114 dim_.wid = max_width_;
120 bool TextMetrics::contains(pit_type pit) const
122 return par_metrics_.find(pit) != par_metrics_.end();
126 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
128 ParMetricsCache::const_iterator it = par_metrics_.begin();
129 return make_pair(it->first, &it->second);
133 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
135 LBUFERR(!par_metrics_.empty());
136 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
137 return make_pair(it->first, &it->second);
141 bool TextMetrics::isLastRow(Row const & row) const
143 ParagraphList const & pars = text_->paragraphs();
144 return row.endpos() >= pars[row.pit()].size()
145 && row.pit() + 1 == pit_type(pars.size());
149 bool TextMetrics::isFirstRow(Row const & row) const
151 return row.pos() == 0 && row.pit() == 0;
155 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
157 for (auto & pm_pair : par_metrics_)
158 if (pm_pair.first == pit)
159 for (Row & row : pm_pair.second.rows())
160 if (row.pos() == pos)
165 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
167 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
168 if (pmc_it == par_metrics_.end()) {
169 pmc_it = par_metrics_.insert(
170 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
172 if (pmc_it->second.rows().empty() && redo)
174 return pmc_it->second;
178 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
180 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
184 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit)
186 return parMetrics(pit, true);
190 void TextMetrics::newParMetricsDown()
192 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
193 pit_type const pit = last.first + 1;
194 if (pit == int(text_->paragraphs().size()))
197 // do it and update its position.
199 par_metrics_[pit].setPosition(last.second.position()
200 + last.second.descent() + par_metrics_[pit].ascent());
205 void TextMetrics::newParMetricsUp()
207 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
208 if (first.first == 0)
211 pit_type const pit = first.first - 1;
212 // do it and update its position.
214 par_metrics_[pit].setPosition(first.second.position()
215 - first.second.ascent() - par_metrics_[pit].descent());
220 bool TextMetrics::metrics(MetricsInfo const & mi, Dimension & dim, int min_width,
221 bool const expand_on_multipars)
223 LBUFERR(mi.base.textwidth > 0);
224 max_width_ = mi.base.textwidth;
225 // backup old dimension.
226 Dimension const old_dim = dim_;
229 dim_.wid = min_width;
230 pit_type const npar = text_->paragraphs().size();
231 if (npar > 1 && expand_on_multipars)
232 // If there is more than one row, expand the text to
233 // the full allowable width.
234 dim_.wid = max_width_;
236 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
237 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
239 bool changed = false;
241 for (pit_type pit = 0; pit != npar; ++pit) {
242 // create rows, but do not set alignment yet
243 changed |= redoParagraph(pit, false);
244 ParagraphMetrics const & pm = par_metrics_[pit];
246 if (dim_.wid < pm.width())
247 dim_.wid = pm.width();
250 // Now set alignment for all rows (the width might not have been known before).
251 for (pit_type pit = 0; pit != npar; ++pit) {
252 ParagraphMetrics & pm = par_metrics_[pit];
253 for (Row & row : pm.rows())
254 setRowAlignment(row, dim_.wid);
257 dim_.asc = par_metrics_[0].ascent();
258 dim_.des = h - dim_.asc;
259 //lyxerr << "dim_.wid " << dim_.wid << endl;
260 //lyxerr << "dim_.asc " << dim_.asc << endl;
261 //lyxerr << "dim_.des " << dim_.des << endl;
263 changed |= dim_ != old_dim;
269 void TextMetrics::updatePosCache(pit_type pit) const
271 frontend::NullPainter np;
272 PainterInfo pi(bv_, np);
273 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
277 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
279 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
283 int TextMetrics::rightMargin(pit_type const pit) const
285 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
289 void TextMetrics::applyOuterFont(Font & font) const
291 FontInfo lf(font_.fontInfo());
292 lf.reduce(bv_->buffer().params().getFont().fontInfo());
293 font.fontInfo().realize(lf);
297 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
299 LASSERT(pos >= 0, { static Font f; return f; });
301 ParagraphList const & pars = text_->paragraphs();
302 Paragraph const & par = pars[pit];
303 Layout const & layout = par.layout();
304 Buffer const & buffer = bv_->buffer();
306 BufferParams const & params = buffer.params();
307 pos_type const body_pos = par.beginOfBody();
309 // We specialize the 95% common case:
310 if (!par.getDepth()) {
311 Font f = par.getFontSettings(params, pos);
312 if (!text_->isMainText())
314 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
316 FontInfo const & lf = lab ? layout.labelfont : layout.font;
317 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
319 // In case the default family has been customized
320 if (lf.family() == INHERIT_FAMILY)
321 rlf.setFamily(params.getFont().fontInfo().family());
322 f.fontInfo().realize(rlf);
326 // The uncommon case need not be optimized as much
327 FontInfo const & layoutfont = pos < body_pos ?
328 layout.labelfont : layout.font;
330 Font font = par.getFontSettings(params, pos);
331 font.fontInfo().realize(layoutfont);
333 if (!text_->isMainText())
334 applyOuterFont(font);
336 // Realize against environment font information
337 // NOTE: the cast to pit_type should be removed when pit_type
338 // changes to a unsigned integer.
339 if (pit < pit_type(pars.size()))
340 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
342 // Realize with the fonts of lesser depth.
343 font.fontInfo().realize(params.getFont().fontInfo());
349 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
355 if (boundary && sl.pos() > 0)
358 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
362 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
364 // no RTL boundary at paragraph start
368 Font const & left_font = displayFont(pit, pos - 1);
370 return isRTLBoundary(pit, pos, left_font);
374 // isRTLBoundary returns false on a real end-of-line boundary,
375 // because otherwise the two boundary types get mixed up.
376 // This is the whole purpose of this being in TextMetrics.
377 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
378 Font const & font) const
380 if (// no RTL boundary at paragraph start
382 // if the metrics have not been calculated, then we are not
383 // on screen and can safely ignore issues about boundaries.
387 ParagraphMetrics const & pm = par_metrics_[pit];
388 // no RTL boundary in empty paragraph
389 if (pm.rows().empty())
392 pos_type const endpos = pm.getRow(pos - 1, false).endpos();
393 pos_type const startpos = pm.getRow(pos, false).pos();
394 // no RTL boundary at line start:
395 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
397 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
400 Paragraph const & par = text_->getPar(pit);
401 // no RTL boundary at line break:
402 // abc|\n -> move right -> abc\n (and not: abc\n|
404 if (startpos == pos && endpos == pos && endpos != par.size()
405 && (par.isNewline(pos - 1)
406 || par.isEnvSeparator(pos - 1)
407 || par.isLineSeparator(pos - 1)
408 || par.isSeparator(pos - 1)))
411 bool const left = font.isVisibleRightToLeft();
413 if (pos == par.size())
414 right = par.isRTL(bv_->buffer().params());
416 right = displayFont(pit, pos).isVisibleRightToLeft();
418 return left != right;
422 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
424 Paragraph & par = text_->getPar(pit);
425 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
426 // redoParagraph() recursively inside parMetrics.
427 Dimension old_dim = parMetrics(pit, false).dim();
428 ParagraphMetrics & pm = par_metrics_[pit];
431 Buffer & buffer = bv_->buffer();
432 bool changed = false;
434 // Check whether there are InsetBibItems that need fixing
435 // FIXME: This check ought to be done somewhere else. It is the reason
436 // why text_ is not const. But then, where else to do it?
437 // Well, how can you end up with either (a) a biblio environment that
438 // has no InsetBibitem, (b) a biblio environment with more than one
439 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
440 // environment? I think the answer is: when paragraphs are merged;
441 // when layout is set; when material is pasted.
442 if (par.brokenBiblio()) {
443 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
444 // In some cases, we do not know how to record undo
445 if (&cur.inset() == &text_->inset())
446 cur.recordUndo(pit, pit);
448 int const moveCursor = par.fixBiblio(buffer);
450 // Is it necessary to update the cursor?
451 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
454 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
459 // Optimisation: this is used in the next two loops
460 // so better to calculate that once here.
461 int const right_margin = rightMargin(pm);
463 // iterator pointing to paragraph to resolve macros
464 DocIterator parPos = text_->macrocontextPosition();
468 LYXERR(Debug::INFO, "MacroContext not initialised!"
469 << " Going through the buffer again and hope"
470 << " the context is better then.");
471 // FIXME audit updateBuffer calls
472 // This should not be here, but it is not clear yet where else it
474 bv_->buffer().updateBuffer();
475 parPos = text_->macrocontextPosition();
476 LBUFERR(!parPos.empty());
481 par.setBeginOfBody();
482 Font const bufferfont = buffer.params().getFont();
483 CoordCache::Insets & insetCache = bv_->coordCache().insets();
484 for (auto const & e : par.insetList()) {
485 // FIXME Doesn't this HAVE to be non-empty?
486 // position already initialized?
487 if (!parPos.empty()) {
488 parPos.pos() = e.pos;
490 // A macro template would normally not be visible
491 // by itself. But the tex macro semantics allow
492 // recursion, so we artifically take the context
493 // after the macro template to simulate this.
494 if (e.inset->lyxCode() == MATHMACRO_CODE)
498 // If there is an end of paragraph marker, its size should be
499 // substracted to the available width. The logic here is
500 // almost the same as in breakRow, remember keep them in sync.
502 if (lyxrc.paragraph_markers && e.pos + 1 == par.size()
503 && size_type(pit + 1) < text_->paragraphs().size()) {
504 Font f(text_->layoutFont(pit));
505 // ¶ U+00B6 PILCROW SIGN
506 eop = theFontMetrics(f).width(char_type(0x00B6));
509 // do the metric calculation
511 int const w = max_width_ - leftMargin(pit, e.pos)
512 - right_margin - eop;
513 Font const & font = e.inset->inheritFont() ?
514 displayFont(pit, e.pos) : bufferfont;
515 MacroContext mc(&buffer, parPos);
516 MetricsInfo mi(bv_, font.fontInfo(), w, mc, e.pos == 0);
517 e.inset->metrics(mi, dim);
518 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
519 insetCache.add(e.inset, dim);
525 size_t row_index = 0;
526 bool need_new_row = false;
527 // maximum pixel width of a row
529 if (row_index == pm.rows().size())
530 pm.rows().push_back(Row());
532 pm.rows()[row_index] = Row();
533 Row & row = pm.rows()[row_index];
536 need_new_row = breakRow(row, right_margin);
539 if ((row_index || row.endpos() < par.size() || row.right_boundary())
540 && par.inInset().lyxCode() != CELL_CODE) {
541 /* If there is more than one row or the row has been
542 * broken by a display inset or a newline, expand the text
543 * to the full allowable width. This setting here is
544 * needed for the setRowAlignment() below.
545 * We do nothing when inside a table cell.
547 if (dim_.wid < max_width_)
548 dim_.wid = max_width_;
551 setRowAlignment(row, max(dim_.wid, row.width()));
552 first = row.endpos();
555 pm.dim().wid = max(pm.dim().wid, row.width());
556 pm.dim().des += row.height();
557 } while (first < par.size() || need_new_row);
559 if (row_index < pm.rows().size())
560 pm.rows().resize(row_index);
562 // The space above and below the paragraph.
563 int const top = parTopSpacing(pit);
564 pm.rows().front().dim().asc += top;
565 int const bottom = parBottomSpacing(pit);
566 pm.rows().back().dim().des += bottom;
567 pm.dim().des += top + bottom;
569 pm.dim().asc += pm.rows()[0].ascent();
570 pm.dim().des -= pm.rows()[0].ascent();
572 // Top and bottom margin of the document (only at top-level)
573 // FIXME: It might be better to move this in another method
574 // specially tailored for the main text.
575 if (text_->isMainText()) {
577 pm.dim().asc += bv_->topMargin();
578 ParagraphList const & pars = text_->paragraphs();
579 if (pit + 1 == pit_type(pars.size())) {
580 pm.dim().des += bv_->bottomMargin();
584 changed |= old_dim.height() != pm.dim().height();
590 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
592 LyXAlignment align = par.getAlign(bv_->buffer().params());
594 // handle alignment inside tabular cells
595 Inset const & owner = text_->inset();
596 bool forced_block = false;
597 switch (owner.contentAlignment()) {
598 case LYX_ALIGN_BLOCK:
599 // In general block align is the default state, but here it is
600 // an explicit choice. Therefore it should not be overridden
604 case LYX_ALIGN_CENTER:
606 case LYX_ALIGN_RIGHT:
607 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
608 align = owner.contentAlignment();
611 // unchanged (use align)
615 // Display-style insets should always be on a centered row
616 if (Inset const * inset = par.getInset(row.pos())) {
617 if (inset->rowFlags() & Inset::Display) {
618 if (inset->rowFlags() & Inset::AlignLeft)
619 align = LYX_ALIGN_BLOCK;
620 else if (inset->rowFlags() & Inset::AlignRight)
621 align = LYX_ALIGN_RIGHT;
623 align = LYX_ALIGN_CENTER;
627 if (align == LYX_ALIGN_BLOCK) {
628 // If this row has been broken abruptly by a display inset, or
629 // it is the end of the paragraph, or the user requested we
630 // not justify stuff, then don't stretch.
631 // A forced block alignment can only be overridden the 'no
632 // justification on screen' setting.
633 if ((row.flushed() && !forced_block)
634 || !bv_->buffer().params().justification)
635 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
642 void TextMetrics::setRowAlignment(Row & row, int width) const
647 Paragraph const & par = text_->getPar(row.pit());
649 int const w = width - row.right_margin - row.width();
650 // FIXME: put back this assertion when the crash on new doc is solved.
651 //LASSERT(w >= 0, /**/);
653 // is there a manual margin with a manual label
654 Layout const & layout = par.layout();
657 if (layout.margintype == MARGIN_MANUAL
658 && layout.labeltype == LABEL_MANUAL) {
659 /// We might have real hfills in the label part
660 nlh = numberOfLabelHfills(par, row);
662 // A manual label par (e.g. List) has an auto-hfill
663 // between the label text and the body of the
665 // But we don't want to do this auto hfill if the par
670 if (nlh && !par.getLabelWidthString().empty())
671 row.label_hfill = labelFill(row) / double(nlh);
674 // are there any hfills in the row?
675 ParagraphMetrics const & pm = par_metrics_[row.pit()];
676 int nh = numberOfHfills(row, pm, par.beginOfBody());
680 // We don't have to look at the alignment if the row is already
681 // larger then the permitted width as then we force the
682 // LEFT_ALIGN'edness!
683 if (int(row.width()) >= max_width_)
687 // Common case : there is no hfill, and the alignment will be
689 switch (getAlign(par, row)) {
690 case LYX_ALIGN_BLOCK:
691 // Expand expanding characters by a total of w
692 if (!row.setExtraWidth(w) && row.isRTL()) {
693 // Justification failed and the text is RTL: align to the right
694 row.left_margin += w;
699 // a displayed inset that is flushed
700 if (Inset const * inset = par.getInset(row.pos())) {
701 row.left_margin += inset->indent(*bv_);
702 row.dim().wid += inset->indent(*bv_);
705 case LYX_ALIGN_RIGHT:
706 if (Inset const * inset = par.getInset(row.pos())) {
707 int const new_w = max(w - inset->indent(*bv_), 0);
708 row.left_margin += new_w;
709 row.dim().wid += new_w;
711 row.left_margin += w;
715 case LYX_ALIGN_CENTER:
716 row.dim().wid += w / 2;
717 row.left_margin += w / 2;
720 case LYX_ALIGN_LAYOUT:
721 case LYX_ALIGN_SPECIAL:
722 case LYX_ALIGN_DECIMAL:
728 // Case nh > 0. There are hfill separators.
732 // Set size of hfill insets
733 pos_type const endpos = row.endpos();
734 pos_type body_pos = par.beginOfBody();
736 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
739 CoordCache::Insets & insetCache = bv_->coordCache().insets();
740 for (Row::Element & e : row) {
741 if (row.label_hfill && e.endpos == body_pos
742 && e.type == Row::SPACE)
743 e.dim.wid -= int(row.label_hfill * (nlh - 1));
744 if (e.inset && pm.hfillExpansion(row, e.pos)) {
745 if (e.pos >= body_pos) {
749 e.dim.wid += hfill_rem;
751 e.dim.wid += int(row.label_hfill);
752 // Cache the inset dimension.
753 insetCache.add(e.inset, e.dim);
759 int TextMetrics::labelFill(Row const & row) const
761 Paragraph const & par = text_->getPar(row.pit());
762 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
765 // iterate over elements before main body (except the last one,
766 // which is extra space).
767 for (Row::Element const & e : row) {
768 if (e.endpos >= par.beginOfBody())
773 docstring const & label = par.params().labelWidthString();
777 FontMetrics const & fm
778 = theFontMetrics(text_->labelFont(par));
780 return max(0, fm.width(label) - w);
785 // Not used, see TextMetrics::breakRow
786 // this needs special handling - only newlines count as a break point
787 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
789 pos_type const end = par.size();
792 if (par.isNewline(i))
800 int TextMetrics::labelEnd(pit_type const pit) const
802 // labelEnd is only needed if the layout fills a flushleft label.
803 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
805 // return the beginning of the body
806 return leftMargin(pit);
812 * Calling Text::getFont is slow. While rebreaking we scan a
813 * paragraph from left to right calling getFont for every char. This
814 * simple class address this problem by hidding an optimization trick
815 * (not mine btw -AB): the font is reused in the whole font span. The
816 * class handles transparently the "hidden" (not part of the fontlist)
817 * label font (as getFont does).
823 FontIterator(TextMetrics const & tm,
824 Paragraph const & par, pit_type pit, pos_type pos)
825 : tm_(tm), par_(par), pit_(pit), pos_(pos),
826 font_(tm.displayFont(pit, pos)),
827 endspan_(par.fontSpan(pos).last),
828 bodypos_(par.beginOfBody())
832 Font const & operator*() const { return font_; }
835 FontIterator & operator++()
838 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
839 font_ = tm_.displayFont(pit_, pos_);
840 endspan_ = par_.fontSpan(pos_).last;
846 Font * operator->() { return &font_; }
850 TextMetrics const & tm_;
852 Paragraph const & par_;
867 /** This is the function where the hard work is done. The code here is
868 * very sensitive to small changes :) Note that part of the
869 * intelligence is also in Row::shortenIfNeeded.
871 bool TextMetrics::breakRow(Row & row, int const right_margin) const
873 LATTEST(row.empty());
874 Paragraph const & par = text_->getPar(row.pit());
875 pos_type const end = par.size();
876 pos_type const pos = row.pos();
877 pos_type const body_pos = par.beginOfBody();
878 bool const is_rtl = text_->isRTL(row.pit());
879 bool need_new_row = false;
881 row.left_margin = leftMargin(row.pit(), pos);
882 row.right_margin = right_margin;
884 swap(row.left_margin, row.right_margin);
885 // Remember that the row width takes into account the left_margin
886 // but not the right_margin.
887 row.dim().wid = row.left_margin;
888 // the width available for the row.
889 int const width = max_width_ - row.right_margin;
892 //FIXME: As long as leftMargin() is not correctly implemented for
893 // MARGIN_RIGHT_ADDRESS_BOX, we should also not do this here.
894 // Otherwise, long rows will be painted off the screen.
895 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX)
896 return addressBreakPoint(pos, par);
899 // check for possible inline completion
900 DocIterator const & ic_it = bv_->inlineCompletionPos();
901 pos_type ic_pos = -1;
902 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == row.pit())
903 ic_pos = ic_it.pos();
905 // Now we iterate through until we reach the right margin
906 // or the end of the par, then build a representation of the row.
908 FontIterator fi = FontIterator(*this, par, row.pit(), pos);
909 while (i < end && (i == pos || row.width() <= width)) {
910 char_type c = par.getChar(i);
911 // The most special cases are handled first.
912 if (par.isInset(i)) {
913 Inset const * ins = par.getInset(i);
914 Dimension dim = bv_->coordCache().insets().dim(ins);
915 row.add(i, ins, dim, *fi, par.lookupChange(i));
916 } else if (c == ' ' && i + 1 == body_pos) {
917 // There is a space at i, but it should not be
918 // added as a separator, because it is just
919 // before body_pos. Instead, insert some spacing to
921 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
922 // this is needed to make sure that the row width is correct
924 int const add = max(fm.width(par.layout().labelsep),
925 labelEnd(row.pit()) - row.width());
926 row.addSpace(i, add, *fi, par.lookupChange(i));
927 } else if (c == '\t')
928 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
929 *fi, par.lookupChange(i));
930 else if (c == 0x2028 || c == 0x2029) {
932 * U+2028 LINE SEPARATOR
933 * U+2029 PARAGRAPH SEPARATOR
935 * These are special unicode characters that break
936 * lines/pragraphs. Not handling them lead to trouble wrt
937 * Qt QTextLayout formatting. We add a visible character
938 * on screen so that the user can see that something is
942 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
943 // ¶ U+00B6 PILCROW SIGN
944 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
945 row.add(i, screen_char, *fi, par.lookupChange(i));
947 row.add(i, c, *fi, par.lookupChange(i));
949 // add inline completion width
950 // draw logically behind the previous character
951 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
952 docstring const comp = bv_->inlineCompletion();
953 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
957 f.fontInfo().setColor(Color_inlinecompletion);
958 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
960 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
961 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
964 // Handle some situations that abruptly terminate the row
965 // - Before an inset with BreakBefore
966 // - After an inset with BreakAfter
967 Inset const * prevInset = !row.empty() ? row.back().inset : 0;
968 Inset const * nextInset = (i + 1 < end) ? par.getInset(i + 1) : 0;
969 if ((nextInset && nextInset->rowFlags() & Inset::BreakBefore)
970 || (prevInset && prevInset->rowFlags() & Inset::BreakAfter)) {
972 // Force a row creation after this one if it is ended by
973 // an inset that either
974 // - has row flag RowAfter that enforces that;
975 // - or (1) did force the row breaking, (2) is at end of
976 // paragraph and (3) the said paragraph has an end label.
977 need_new_row = prevInset &&
978 (prevInset->rowFlags() & Inset::RowAfter
979 || (prevInset->rowFlags() & Inset::BreakAfter && i + 1 == end
980 && text_->getEndLabel(row.pit()) != END_LABEL_NO_LABEL));
991 // End of paragraph marker. The logic here is almost the
992 // same as in redoParagraph, remember keep them in sync.
993 ParagraphList const & pars = text_->paragraphs();
994 Change const & change = par.lookupChange(i);
995 if ((lyxrc.paragraph_markers || change.changed())
997 && i == end && size_type(row.pit() + 1) < pars.size()) {
998 // add a virtual element for the end-of-paragraph
999 // marker; it is shown on screen, but does not exist
1000 // in the paragraph.
1001 Font f(text_->layoutFont(row.pit()));
1002 f.fontInfo().setColor(Color_paragraphmarker);
1003 BufferParams const & bparams
1004 = text_->inset().buffer().params();
1005 f.setLanguage(par.getParLanguage(bparams));
1006 // ¶ U+00B6 PILCROW SIGN
1007 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, change);
1010 // Is there a end-of-paragaph change?
1011 if (i == end && par.lookupChange(end).changed() && !need_new_row)
1012 row.needsChangeBar(true);
1014 // if the row is too large, try to cut at last separator. In case
1015 // of success, reset indication that the row was broken abruptly.
1016 int const next_width = max_width_ - leftMargin(row.pit(), row.endpos())
1017 - rightMargin(row.pit());
1019 if (row.shortenIfNeeded(body_pos, width, next_width))
1021 row.right_boundary(!row.empty() && row.endpos() < end
1022 && row.back().endpos == row.endpos());
1023 // Last row in paragraph is flushed
1024 if (row.endpos() == end)
1027 // make sure that the RTL elements are in reverse ordering
1028 row.reverseRTL(is_rtl);
1029 //LYXERR0("breakrow: row is " << row);
1031 return need_new_row;
1034 int TextMetrics::parTopSpacing(pit_type const pit) const
1036 Paragraph const & par = text_->getPar(pit);
1037 Layout const & layout = par.layout();
1040 ParagraphList const & pars = text_->paragraphs();
1041 double const dh = defaultRowHeight();
1043 BufferParams const & bparams = bv_->buffer().params();
1044 Inset const & inset = text_->inset();
1045 // some parskips VERY EASY IMPLEMENTATION
1046 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1047 && !inset.getLayout().parbreakIsNewline()
1048 && !par.layout().parbreak_is_newline
1050 && ((layout.isParagraph() && par.getDepth() == 0)
1051 || (pars[pit - 1].layout().isParagraph()
1052 && pars[pit - 1].getDepth() == 0))) {
1053 asc += bparams.getDefSkip().inPixels(*bv_);
1056 if (par.params().startOfAppendix())
1059 // special code for the top label
1060 if (layout.labelIsAbove()
1061 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1062 && !par.labelString().empty()) {
1063 FontInfo labelfont = text_->labelFont(par);
1064 FontMetrics const & lfm = theFontMetrics(labelfont);
1065 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1066 * text_->spacing(par)
1067 + (layout.topsep + layout.labelbottomsep) * dh);
1070 // Add the layout spaces, for example before and after
1071 // a section, or between the items of a itemize or enumerate
1074 pit_type prev = text_->depthHook(pit, par.getDepth());
1075 Paragraph const & prevpar = pars[prev];
1076 double layoutasc = 0;
1078 && prevpar.layout() == layout
1079 && prevpar.getDepth() == par.getDepth()
1080 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1081 layoutasc = layout.itemsep * dh;
1082 } else if (pit != 0 && layout.topsep > 0)
1083 layoutasc = layout.topsep * dh;
1085 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1087 prev = text_->outerHook(pit);
1088 if (prev != pit_type(pars.size())) {
1089 asc += int(pars[prev].layout().parsep * dh);
1090 } else if (pit != 0) {
1091 Paragraph const & prevpar2 = pars[pit - 1];
1092 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1093 asc += int(layout.parsep * dh);
1100 int TextMetrics::parBottomSpacing(pit_type const pit) const
1102 double layoutdesc = 0;
1103 ParagraphList const & pars = text_->paragraphs();
1104 double const dh = defaultRowHeight();
1106 // add the layout spaces, for example before and after
1107 // a section, or between the items of a itemize or enumerate
1109 pit_type nextpit = pit + 1;
1110 if (nextpit != pit_type(pars.size())) {
1111 pit_type cpit = pit;
1113 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1114 double usual = pars[cpit].layout().bottomsep * dh;
1116 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1117 if (pars[cpit].layout() != pars[nextpit].layout()
1118 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1119 unusual = pars[cpit].layout().bottomsep * dh;
1120 layoutdesc = max(unusual, usual);
1121 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1122 if (pars[cpit].layout() != pars[nextpit].layout()
1123 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1124 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1128 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1132 void TextMetrics::setRowHeight(Row & row) const
1134 Paragraph const & par = text_->getPar(row.pit());
1135 Layout const & layout = par.layout();
1136 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1138 // Initial value for ascent (useful if row is empty).
1139 Font const font = displayFont(row.pit(), row.pos());
1140 FontMetrics const & fm = theFontMetrics(font);
1141 int maxasc = int(fm.maxAscent() * spacing_val);
1142 int maxdes = int(fm.maxDescent() * spacing_val);
1144 // Take label string into account (useful if labelfont is large)
1145 if (row.pos() == 0 && layout.labelIsInline()) {
1146 FontInfo const labelfont = text_->labelFont(par);
1147 FontMetrics const & lfm = theFontMetrics(labelfont);
1148 maxasc = max(maxasc, int(lfm.maxAscent() * spacing_val));
1149 maxdes = max(maxdes, int(lfm.maxDescent() * spacing_val));
1152 // Find the ascent/descent of the row contents
1153 for (Row::Element const & e : row) {
1155 maxasc = max(maxasc, e.dim.ascent());
1156 maxdes = max(maxdes, e.dim.descent());
1158 FontMetrics const & fm2 = theFontMetrics(e.font);
1159 maxasc = max(maxasc, int(fm2.maxAscent() * spacing_val));
1160 maxdes = max(maxdes, int(fm2.maxDescent() * spacing_val));
1164 // This is nicer with box insets
1168 row.dim().asc = maxasc;
1169 row.dim().des = maxdes;
1173 // x is an absolute screen coord
1174 // returns the column near the specified x-coordinate of the row
1175 // x is set to the real beginning of this column
1176 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1177 bool & boundary) const
1179 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1180 /// For the main Text, it is possible that this pit is not
1181 /// yet in the CoordCache when moving cursor up.
1182 /// x Paragraph coordinate is always 0 for main text anyway.
1183 int const xo = origin_.x_;
1186 // Adapt to cursor row scroll offset if applicable.
1187 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1190 pos_type pos = row.pos();
1193 x = row.left_margin;
1194 else if (x <= row.left_margin) {
1195 pos = row.front().left_pos();
1196 x = row.left_margin;
1197 } else if (x >= row.width()) {
1198 pos = row.back().right_pos();
1201 double w = row.left_margin;
1202 Row::const_iterator cit = row.begin();
1203 Row::const_iterator cend = row.end();
1204 for ( ; cit != cend; ++cit) {
1205 if (w <= x && w + cit->full_width() > x) {
1206 int x_offset = int(x - w);
1207 pos = cit->x2pos(x_offset);
1208 x = int(x_offset + w);
1211 w += cit->full_width();
1213 if (cit == row.end()) {
1214 pos = row.back().right_pos();
1217 /** This tests for the case where the cursor is placed
1218 * just before a font direction change. See comment on
1219 * the boundary_ member in DocIterator.h to understand
1220 * how boundary helps here.
1222 else if (pos == cit->endpos
1223 && ((!cit->isRTL() && cit + 1 != row.end()
1224 && (cit + 1)->isRTL())
1225 || (cit->isRTL() && cit != row.begin()
1226 && !(cit - 1)->isRTL())))
1230 /** This tests for the case where the cursor is set at the end
1231 * of a row which has been broken due something else than a
1232 * separator (a display inset or a forced breaking of the
1233 * row). We know that there is a separator when the end of the
1234 * row is larger than the end of its last element.
1236 if (!row.empty() && pos == row.back().endpos
1237 && row.back().endpos == row.endpos()) {
1238 Inset const * inset = row.back().inset;
1239 if (inset && (inset->lyxCode() == NEWLINE_CODE
1240 || inset->lyxCode() == SEPARATOR_CODE))
1241 pos = row.back().pos;
1243 boundary = row.right_boundary();
1247 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1253 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1255 // We play safe and use parMetrics(pit) to make sure the
1256 // ParagraphMetrics will be redone and OK to use if needed.
1257 // Otherwise we would use an empty ParagraphMetrics in
1258 // upDownInText() while in selection mode.
1259 ParagraphMetrics const & pm = parMetrics(pit);
1261 LBUFERR(row < int(pm.rows().size()));
1263 Row const & r = pm.rows()[row];
1264 return getPosNearX(r, x, bound);
1268 // y is screen coordinate
1269 pit_type TextMetrics::getPitNearY(int y)
1271 LASSERT(!text_->paragraphs().empty(), return -1);
1272 LASSERT(!par_metrics_.empty(), return -1);
1273 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1275 // look for highest numbered paragraph with y coordinate less than given y
1278 ParMetricsCache::const_iterator it = par_metrics_.begin();
1279 ParMetricsCache::const_iterator et = par_metrics_.end();
1280 ParMetricsCache::const_iterator last = et;
1283 ParagraphMetrics const & pm = it->second;
1285 if (y < it->second.position() - int(pm.ascent())) {
1286 // We are looking for a position that is before the first paragraph in
1287 // the cache (which is in priciple off-screen, that is before the
1290 // We are already at the first paragraph in the inset.
1292 // OK, this is the paragraph we are looking for.
1293 pit = it->first - 1;
1298 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1300 if (y >= last->second.position() + int(pm_last.descent())) {
1301 // We are looking for a position that is after the last paragraph in
1302 // the cache (which is in priciple off-screen), that is before the
1304 pit = last->first + 1;
1305 if (pit == int(text_->paragraphs().size()))
1306 // We are already at the last paragraph in the inset.
1308 // OK, this is the paragraph we are looking for.
1309 newParMetricsDown();
1313 for (; it != et; ++it) {
1314 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1315 << " y: " << it->second.position());
1317 ParagraphMetrics const & pm2 = par_metrics_[it->first];
1319 if (it->first >= pit && int(it->second.position()) - int(pm2.ascent()) <= y) {
1321 yy = it->second.position();
1325 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1331 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1332 bool assert_in_view, bool up)
1334 ParagraphMetrics const & pm = par_metrics_[pit];
1336 int yy = pm.position() - pm.rows().front().ascent();
1337 LBUFERR(!pm.rows().empty());
1338 RowList::const_iterator rit = pm.rows().begin();
1339 RowList::const_iterator rlast = pm.rows().end();
1341 for (; rit != rlast; yy += rit->height(), ++rit)
1342 if (yy + rit->height() > y)
1345 if (assert_in_view) {
1346 if (!up && yy + rit->height() > y) {
1347 if (rit != pm.rows().begin()) {
1350 } else if (pit != 0) {
1353 ParagraphMetrics const & pm2 = par_metrics_[pit];
1354 rit = pm2.rows().end();
1358 } else if (up && yy != y) {
1360 y = yy + rit->height();
1362 } else if (pit < int(text_->paragraphs().size()) - 1) {
1364 newParMetricsDown();
1365 ParagraphMetrics const & pm2 = par_metrics_[pit];
1366 rit = pm2.rows().begin();
1375 // x,y are absolute screen coordinates
1376 // sets cursor recursively descending into nested editable insets
1377 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1378 bool assert_in_view, bool up)
1380 if (lyxerr.debugging(Debug::WORKAREA)) {
1381 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1382 cur.bv().coordCache().dump();
1384 pit_type pit = getPitNearY(y);
1385 LASSERT(pit != -1, return 0);
1386 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1389 // Do we cover an inset?
1390 InsetList::Element * e = checkInsetHit(pit, x, y);
1393 // No inset, set position in the text
1394 bool bound = false; // is modified by getPosNearX
1395 cur.pos() = getPosNearX(row, x, bound);
1396 cur.boundary(bound);
1397 cur.setCurrentFont();
1402 Inset * inset = e->inset;
1403 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1405 // Set position in front of inset
1407 cur.boundary(false);
1410 // Try to descend recursively inside the inset.
1411 Inset * edited = inset->editXY(cur, x, y);
1412 // FIXME: it is not clear that the test on position is needed
1413 // Remove it if/when semantics of editXY is clarified
1414 if (cur.text() == text_ && cur.pos() == e->pos) {
1415 // non-editable inset, set cursor after the inset if x is
1416 // nearer to that position (bug 9628)
1417 bool bound = false; // is modified by getPosNearX
1418 cur.pos() = getPosNearX(row, x, bound);
1419 cur.boundary(bound);
1420 cur.setCurrentFont();
1424 if (cur.top().text() == text_)
1425 cur.setCurrentFont();
1430 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1432 LASSERT(text_ == cur.text(), return);
1433 pit_type const pit = getPitNearY(y);
1434 LASSERT(pit != -1, return);
1436 ParagraphMetrics const & pm = par_metrics_[pit];
1438 int yy = pm.position() - pm.rows().front().ascent();
1439 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1440 " pit: " << pit << " yy: " << yy);
1443 LBUFERR(pm.rows().size());
1444 for (; r < int(pm.rows().size()) - 1; ++r) {
1445 Row const & row = pm.rows()[r];
1446 if (int(yy + row.height()) > y)
1451 Row const & row = pm.rows()[r];
1453 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1457 pos_type const pos = getPosNearX(row, xx, bound);
1459 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1461 text_->setCursor(cur, pit, pos, true, bound);
1462 // remember new position.
1467 //takes screen x,y coordinates
1468 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1470 Paragraph const & par = text_->paragraphs()[pit];
1471 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1473 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1475 for (InsetList::Element const & e : par.insetList()) {
1476 LYXERR(Debug::DEBUG, "examining inset " << e.inset);
1478 if (insetCache.covers(e.inset, x, y)) {
1479 LYXERR(Debug::DEBUG, "Hit inset: " << e.inset);
1480 return const_cast<InsetList::Element *>(&e);
1484 LYXERR(Debug::DEBUG, "No inset hit. ");
1489 //takes screen x,y coordinates
1490 Inset * TextMetrics::checkInsetHit(int x, int y)
1492 pit_type const pit = getPitNearY(y);
1493 LASSERT(pit != -1, return 0);
1494 InsetList::Element * e = checkInsetHit(pit, x, y);
1503 int TextMetrics::cursorX(CursorSlice const & sl,
1504 bool boundary) const
1506 LASSERT(sl.text() == text_, return 0);
1508 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1509 if (pm.rows().empty())
1511 Row const & row = pm.getRow(sl.pos(), boundary);
1512 pos_type const pos = sl.pos();
1515 row.findElement(pos, boundary, x);
1521 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1523 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1524 ParagraphMetrics const & pm = parMetrics(sl.pit());
1525 if (pm.rows().empty())
1529 h -= parMetrics(0).rows()[0].ascent();
1530 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1531 h += parMetrics(pit).height();
1534 if (pos && boundary)
1536 size_t const rend = pm.pos2row(pos);
1537 for (size_t rit = 0; rit != rend; ++rit)
1538 h += pm.rows()[rit].height();
1539 h += pm.rows()[rend].ascent();
1544 // the cursor set functions have a special mechanism. When they
1545 // realize you left an empty paragraph, they will delete it.
1547 bool TextMetrics::cursorHome(Cursor & cur)
1549 LASSERT(text_ == cur.text(), return false);
1550 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1551 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1552 return text_->setCursor(cur, cur.pit(), row.pos());
1556 bool TextMetrics::cursorEnd(Cursor & cur)
1558 LASSERT(text_ == cur.text(), return false);
1559 // if not on the last row of the par, put the cursor before
1560 // the final space exept if I have a spanning inset or one string
1561 // is so long that we force a break.
1562 pos_type end = cur.textRow().endpos();
1564 // empty text, end-1 is no valid position
1566 bool boundary = false;
1567 if (end != cur.lastpos()) {
1568 if (!cur.paragraph().isLineSeparator(end-1)
1569 && !cur.paragraph().isNewline(end-1)
1570 && !cur.paragraph().isEnvSeparator(end-1))
1574 } else if (cur.paragraph().isEnvSeparator(end-1))
1576 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1580 void TextMetrics::deleteLineForward(Cursor & cur)
1582 LASSERT(text_ == cur.text(), return);
1583 if (cur.lastpos() == 0) {
1584 // Paragraph is empty, so we just go forward
1585 text_->cursorForward(cur);
1588 cur.selection(true); // to avoid deletion
1591 // What is this test for ??? (JMarc)
1592 if (!cur.selection())
1593 text_->deleteWordForward(cur);
1595 cap::cutSelection(cur, false);
1596 cur.checkBufferStructure();
1601 int TextMetrics::leftMargin(pit_type pit) const
1603 return leftMargin(pit, text_->paragraphs()[pit].size());
1607 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1609 ParagraphList const & pars = text_->paragraphs();
1611 LASSERT(pit >= 0, return 0);
1612 LASSERT(pit < int(pars.size()), return 0);
1613 Paragraph const & par = pars[pit];
1614 LASSERT(pos >= 0, return 0);
1615 LASSERT(pos <= par.size(), return 0);
1616 Buffer const & buffer = bv_->buffer();
1617 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1618 DocumentClass const & tclass = buffer.params().documentClass();
1619 Layout const & layout = par.layout();
1620 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1622 docstring parindent = layout.parindent;
1626 if (text_->isMainText()) {
1627 l_margin += bv_->leftMargin();
1628 l_margin += bfm.signedWidth(tclass.leftmargin());
1631 int depth = par.getDepth();
1633 // find the next level paragraph
1634 pit_type newpar = text_->outerHook(pit);
1635 if (newpar != pit_type(pars.size())) {
1636 if (pars[newpar].layout().isEnvironment()) {
1637 int nestmargin = depth * nestMargin();
1638 if (text_->isMainText())
1639 nestmargin += changebarMargin();
1640 l_margin = max(leftMargin(newpar), nestmargin);
1641 // Remove the parindent that has been added
1642 // if the paragraph was empty.
1643 if (pars[newpar].empty() &&
1644 buffer.params().paragraph_separation ==
1645 BufferParams::ParagraphIndentSeparation) {
1646 docstring pi = pars[newpar].layout().parindent;
1647 l_margin -= bfm.signedWidth(pi);
1650 if (tclass.isDefaultLayout(par.layout())
1651 || tclass.isPlainLayout(par.layout())) {
1652 if (pars[newpar].params().noindent())
1655 parindent = pars[newpar].layout().parindent;
1660 // This happens after sections or environments in standard classes.
1661 // We have to check the previous layout at same depth.
1662 if (buffer.params().paragraph_separation ==
1663 BufferParams::ParagraphSkipSeparation)
1665 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1666 pit_type prev = text_->depthHook(pit, par.getDepth());
1667 if (par.layout() == pars[prev].layout()) {
1669 && pars[pit - 1].layout().nextnoindent)
1671 } else if (pars[prev].layout().nextnoindent)
1675 FontInfo const labelfont = text_->labelFont(par);
1676 FontMetrics const & lfm = theFontMetrics(labelfont);
1678 switch (layout.margintype) {
1679 case MARGIN_DYNAMIC:
1680 if (!layout.leftmargin.empty()) {
1681 l_margin += bfm.signedWidth(layout.leftmargin);
1683 if (!par.labelString().empty()) {
1684 l_margin += lfm.signedWidth(layout.labelindent);
1685 l_margin += lfm.width(par.labelString());
1686 l_margin += lfm.width(layout.labelsep);
1690 case MARGIN_MANUAL: {
1691 l_margin += lfm.signedWidth(layout.labelindent);
1692 // The width of an empty par, even with manual label, should be 0
1693 if (!par.empty() && pos >= par.beginOfBody()) {
1694 if (!par.getLabelWidthString().empty()) {
1695 docstring labstr = par.getLabelWidthString();
1696 l_margin += lfm.width(labstr);
1697 l_margin += lfm.width(layout.labelsep);
1703 case MARGIN_STATIC: {
1704 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1705 / (par.getDepth() + 4);
1709 case MARGIN_FIRST_DYNAMIC:
1710 if (layout.labeltype == LABEL_MANUAL) {
1711 // if we are at position 0, we are never in the body
1712 if (pos > 0 && pos >= par.beginOfBody())
1713 l_margin += lfm.signedWidth(layout.leftmargin);
1715 l_margin += lfm.signedWidth(layout.labelindent);
1717 // Special case to fix problems with
1719 || (layout.labeltype == LABEL_STATIC
1720 && layout.latextype == LATEX_ENVIRONMENT
1721 && !text_->isFirstInSequence(pit))) {
1722 l_margin += lfm.signedWidth(layout.leftmargin);
1723 } else if (!layout.labelIsAbove()) {
1724 l_margin += lfm.signedWidth(layout.labelindent);
1725 l_margin += lfm.width(layout.labelsep);
1726 l_margin += lfm.width(par.labelString());
1730 case MARGIN_RIGHT_ADDRESS_BOX: {
1732 // The left margin depends on the widest row in this paragraph.
1733 // This code is wrong because it depends on the rows, but at the
1734 // same time this function is used in redoParagraph to construct
1736 ParagraphMetrics const & pm = par_metrics_[pit];
1737 int minfill = max_width_;
1738 for (row : pm.rows())
1739 if (row.fill() < minfill)
1740 minfill = row.fill();
1741 l_margin += bfm.signedWidth(layout.leftmargin);
1742 l_margin += minfill;
1744 // also wrong, but much shorter.
1745 l_margin += max_width_ / 2;
1750 if (!par.params().leftIndent().zero())
1751 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1753 LyXAlignment align = par.getAlign(bv_->buffer().params());
1755 // set the correct parindent
1757 && (layout.labeltype == LABEL_NO_LABEL
1758 || layout.labeltype == LABEL_ABOVE
1759 || layout.labeltype == LABEL_CENTERED
1760 || (layout.labeltype == LABEL_STATIC
1761 && layout.latextype == LATEX_ENVIRONMENT
1762 && !text_->isFirstInSequence(pit)))
1763 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1764 && !par.params().noindent()
1765 // in some insets, paragraphs are never indented
1766 && !text_->inset().neverIndent()
1767 // display style insets do not need indentation
1770 && par.getInset(pos)->rowFlags() & Inset::Display)
1771 && (!(tclass.isDefaultLayout(par.layout())
1772 || tclass.isPlainLayout(par.layout()))
1773 || buffer.params().paragraph_separation
1774 == BufferParams::ParagraphIndentSeparation)) {
1775 /* use the parindent of the layout when the default
1776 * indentation is used otherwise use the indentation set in
1777 * the document settings
1779 if (buffer.params().getParIndent().empty())
1780 l_margin += bfm.signedWidth(parindent);
1782 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1789 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1791 if (par_metrics_.empty())
1797 y -= par_metrics_.begin()->second.ascent();
1798 for (auto & pm_pair : par_metrics_) {
1799 pit_type const pit = pm_pair.first;
1800 ParagraphMetrics & pm = pm_pair.second;
1802 // Save the paragraph position in the cache.
1804 drawParagraph(pi, pit, x, y);
1810 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1812 ParagraphMetrics const & pm = par_metrics_[pit];
1813 if (pm.rows().empty())
1815 size_t const nrows = pm.rows().size();
1816 // Remember left and right margin for drawing math numbers
1817 Changer changeleft = make_change(pi.leftx, x + leftMargin(pit));
1818 Changer changeright = make_change(pi.rightx, x + width() - rightMargin(pit));
1820 // Use fast lane in nodraw stage.
1821 if (pi.pain.isNull()) {
1822 for (size_t i = 0; i != nrows; ++i) {
1824 Row const & row = pm.rows()[i];
1825 // Adapt to cursor row scroll offset if applicable.
1826 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1830 RowPainter rp(pi, *text_, row, row_x, y);
1832 rp.paintOnlyInsets();
1838 int const ww = bv_->workHeight();
1839 Cursor const & cur = bv_->cursor();
1840 DocIterator sel_beg = cur.selectionBegin();
1841 DocIterator sel_end = cur.selectionEnd();
1842 bool selection = cur.selection()
1843 // This is our text.
1844 && cur.text() == text_
1845 // if the anchor is outside, this is not our selection
1846 && cur.normalAnchor().text() == text_
1847 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1849 // We store the begin and end pos of the selection relative to this par
1850 DocIterator sel_beg_par = cur.selectionBegin();
1851 DocIterator sel_end_par = cur.selectionEnd();
1853 // We care only about visible selection.
1855 if (pit != sel_beg.pit()) {
1856 sel_beg_par.pit() = pit;
1857 sel_beg_par.pos() = 0;
1859 if (pit != sel_end.pit()) {
1860 sel_end_par.pit() = pit;
1861 sel_end_par.pos() = sel_end_par.lastpos();
1865 if (text_->isRTL(pit))
1866 swap(pi.leftx, pi.rightx);
1868 for (size_t i = 0; i != nrows; ++i) {
1870 Row const & row = pm.rows()[i];
1871 // Adapt to cursor row scroll offset if applicable.
1872 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1876 // It is not needed to draw on screen if we are not inside.
1877 bool const inside = (y + row.descent() >= 0
1878 && y - row.ascent() < ww);
1880 // Inset positions have already been set in nodraw stage.
1886 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
1888 row.clearSelectionAndMargins();
1890 // The row knows nothing about the paragraph, so we have to check
1891 // whether this row is the first or last and update the margins.
1892 if (row.selection()) {
1893 if (row.sel_beg == 0)
1894 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
1895 if (row.sel_end == sel_end_par.lastpos())
1896 row.change(row.end_margin_sel, sel_end.pit() > pit);
1899 // Take this opportunity to spellcheck the row contents.
1900 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
1901 text_->getPar(pit).spellCheck();
1904 RowPainter rp(pi, *text_, row, row_x, y);
1906 // Don't paint the row if a full repaint has not been requested
1907 // and if it has not changed.
1908 if (!pi.full_repaint && !row.changed()) {
1909 // Paint only the insets if the text itself is
1911 rp.paintOnlyInsets();
1917 // Clear background of this row if paragraph background was not
1918 // already cleared because of a full repaint.
1919 if (!pi.full_repaint && row.changed()) {
1920 LYXERR(Debug::PAINTING, "Clear rect@("
1921 << max(row_x, 0) << ", " << y - row.ascent() << ")="
1922 << width() << " x " << row.height());
1923 // FIXME: this is a hack. We clear an amount equal to
1924 // cursor width. This will not work if the caret has a
1925 // ridiculous width like 6. (see ticket #10797)
1926 // This is the same formula as in GuiWorkArea.
1927 int const caret_width = lyxrc.cursor_width
1928 ? lyxrc.cursor_width
1929 : 1 + int((lyxrc.currentZoom + 50) / 200.0);
1930 pi.pain.fillRectangle(max(row_x, 0), y - row.ascent(),
1931 width() + caret_width,
1932 row.height(), pi.background_color);
1935 // Instrumentation for testing row cache (see also
1937 if (lyxerr.debugging(Debug::PAINTING)
1938 && (row.selection() || pi.full_repaint || row.changed())) {
1939 string const foreword = text_->isMainText() ? "main text redraw "
1940 : "inset text redraw: ";
1941 LYXERR0(foreword << "pit=" << pit << " row=" << i
1942 << (row.selection() ? " row_selection": "")
1943 << (pi.full_repaint ? " full_repaint" : "")
1944 << (row.changed() ? " row.changed" : ""));
1947 // Backup full_repaint status and force full repaint
1948 // for inner insets as the Row has been cleared out.
1949 bool tmp = pi.full_repaint;
1950 pi.full_repaint = true;
1952 rp.paintSelection();
1955 if (row.needsChangeBar())
1956 rp.paintChangeBar();
1962 rp.paintTooLargeMarks(row_x + row.left_x() < 0,
1963 row_x + row.right_x() > bv_->workWidth());
1967 // This debug code shows on screen which rows are repainted.
1968 // FIXME: since the updates related to caret blinking restrict
1969 // the painter to a small rectangle, the numbers are not
1970 // updated when this happens. Change the code in
1971 // GuiWorkArea::Private::show/hideCaret if this is important.
1972 static int count = 0;
1974 FontInfo fi(sane_font);
1975 fi.setSize(TINY_SIZE);
1976 fi.setColor(Color_red);
1977 pi.pain.text(row_x, y, convert<docstring>(count), fi);
1980 // Restore full_repaint status.
1981 pi.full_repaint = tmp;
1986 //LYXERR(Debug::PAINTING, ".");
1990 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
1991 Dimension & dim) const
1993 DocIterator from = cur.bv().cursor();
1994 DocIterator to = from;
1995 text_->getWord(from.top(), to.top(), PREVIOUS_WORD);
1997 // The vertical dimension of the word
1998 Font const font = displayFont(cur.pit(), from.pos());
1999 FontMetrics const & fm = theFontMetrics(font);
2000 // the +1's below are related to the extra pixels added in setRowHeight
2001 dim.asc = fm.maxAscent() + 1;
2002 dim.des = fm.maxDescent() + 1;
2004 // get position on screen of the word start and end
2005 //FIXME: Is it necessary to explicitly set this to false?
2006 from.boundary(false);
2007 Point lxy = cur.bv().getPos(from);
2008 Point rxy = cur.bv().getPos(to);
2009 dim.wid = abs(rxy.x_ - lxy.x_);
2011 // calculate position of word
2013 x = min(rxy.x_, lxy.x_);
2015 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2016 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2019 int defaultRowHeight()
2021 return int(theFontMetrics(sane_font).maxHeight() * 1.2);