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 "buffer_funcs.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
28 #include "CutAndPaste.h"
29 #include "InsetList.h"
33 #include "MetricsInfo.h"
34 #include "ParagraphParameters.h"
35 #include "RowPainter.h"
37 #include "TextClass.h"
40 #include "insets/InsetText.h"
42 #include "mathed/InsetMathMacroTemplate.h"
44 #include "frontends/FontMetrics.h"
45 #include "frontends/Painter.h"
46 #include "frontends/NullPainter.h"
48 #include "support/convert.h"
49 #include "support/debug.h"
50 #include "support/lassert.h"
51 #include "support/lyxlib.h"
61 using frontend::FontMetrics;
65 // the somewhat arbitrary leading added between rows. This is 20% of
66 // the characters height, inluding the possible leading of the font.
67 // 20% is a standard value used by LaTeX and word processors.
68 double const extra_leading = 0.2;
70 int numberOfLabelHfills(Paragraph const & par, Row const & row)
72 pos_type last = row.endpos() - 1;
73 pos_type first = row.pos();
75 // hfill *DO* count at the beginning of paragraphs!
77 while (first < last && par.isHfill(first))
81 last = min(last, par.beginOfBody());
83 for (pos_type p = first; p < last; ++p) {
90 // FIXME: this needs to be rewritten, probably by merging it into some
91 // code that, besides counting, sets the active status of the space
92 // inset in the row element.
93 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
94 pos_type const body_pos)
97 Row::const_iterator cit = row.begin();
98 Row::const_iterator const end = row.end();
99 for ( ; cit != end ; ++cit)
100 if (cit->pos >= body_pos
101 && cit->inset && pm.hfillExpansion(row, cit->pos))
109 /////////////////////////////////////////////////////////////////////
113 /////////////////////////////////////////////////////////////////////
116 TextMetrics::TextMetrics(BufferView * bv, Text * text)
117 : bv_(bv), text_(text)
120 max_width_ = bv_->workWidth();
121 dim_.wid = max_width_;
127 bool TextMetrics::contains(pit_type pit) const
129 return par_metrics_.find(pit) != par_metrics_.end();
133 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
135 ParMetricsCache::const_iterator it = par_metrics_.begin();
136 return make_pair(it->first, &it->second);
140 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
142 LBUFERR(!par_metrics_.empty());
143 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
144 return make_pair(it->first, &it->second);
148 bool TextMetrics::isLastRow(Row const & row) const
150 ParagraphList const & pars = text_->paragraphs();
151 return row.endpos() >= pars[row.pit()].size()
152 && row.pit() + 1 == pit_type(pars.size());
156 bool TextMetrics::isFirstRow(Row const & row) const
158 return row.pos() == 0 && row.pit() == 0;
162 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
164 for (auto & pm_pair : par_metrics_)
165 if (pm_pair.first == pit)
166 for (Row & row : pm_pair.second.rows())
167 if (row.pos() == pos)
172 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
174 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
175 if (pmc_it == par_metrics_.end()) {
176 pmc_it = par_metrics_.insert(
177 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
179 if (pmc_it->second.rows().empty() && redo)
181 return pmc_it->second;
185 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
187 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
191 void TextMetrics::newParMetricsDown()
193 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
194 pit_type const pit = last.first + 1;
195 if (pit == int(text_->paragraphs().size()))
198 // do it and update its position.
200 par_metrics_[pit].setPosition(last.second.position()
201 + last.second.descent() + par_metrics_[pit].ascent());
206 void TextMetrics::newParMetricsUp()
208 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
209 if (first.first == 0)
212 pit_type const pit = first.first - 1;
213 // do it and update its position.
215 par_metrics_[pit].setPosition(first.second.position()
216 - first.second.ascent() - par_metrics_[pit].descent());
221 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width,
222 bool const expand_on_multipars)
224 LBUFERR(mi.base.textwidth > 0);
225 max_width_ = mi.base.textwidth;
226 // backup old dimension.
227 Dimension const old_dim = dim_;
230 dim_.wid = min_width;
231 pit_type const npar = text_->paragraphs().size();
232 if (npar > 1 && expand_on_multipars)
233 // If there is more than one row, expand the text to
234 // the full allowable width.
235 dim_.wid = max_width_;
237 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
238 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
240 bool changed = false;
242 for (pit_type pit = 0; pit != npar; ++pit) {
243 // create rows, but do not set alignment yet
244 changed |= redoParagraph(pit, false);
245 ParagraphMetrics const & pm = par_metrics_[pit];
247 if (dim_.wid < pm.width())
248 dim_.wid = pm.width();
251 // Now set alignment for all rows (the width might not have been known before).
252 for (pit_type pit = 0; pit != npar; ++pit) {
253 ParagraphMetrics & pm = par_metrics_[pit];
254 for (Row & row : pm.rows())
255 setRowAlignment(row, dim_.wid);
258 dim_.asc = par_metrics_[0].ascent();
259 dim_.des = h - dim_.asc;
260 //lyxerr << "dim_.wid " << dim_.wid << endl;
261 //lyxerr << "dim_.asc " << dim_.asc << endl;
262 //lyxerr << "dim_.des " << dim_.des << endl;
264 changed |= dim_ != old_dim;
270 void TextMetrics::updatePosCache(pit_type pit) const
272 frontend::NullPainter np;
273 PainterInfo pi(bv_, np);
274 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
278 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
280 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
284 int TextMetrics::rightMargin(pit_type const pit) const
286 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
290 void TextMetrics::applyOuterFont(Font & font) const
292 FontInfo lf(font_.fontInfo());
293 lf.reduce(bv_->buffer().params().getFont().fontInfo());
294 font.fontInfo().realize(lf);
298 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
300 LASSERT(pos >= 0, { static Font f; return f; });
302 ParagraphList const & pars = text_->paragraphs();
303 Paragraph const & par = pars[pit];
304 Layout const & layout = par.layout();
305 Buffer const & buffer = bv_->buffer();
307 BufferParams const & params = buffer.params();
308 pos_type const body_pos = par.beginOfBody();
310 // We specialize the 95% common case:
311 if (!par.getDepth()) {
312 Font f = par.getFontSettings(params, pos);
313 if (!text_->isMainText())
315 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
317 FontInfo const & lf = lab ? layout.labelfont : layout.font;
318 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
320 // In case the default family has been customized
321 if (lf.family() == INHERIT_FAMILY)
322 rlf.setFamily(params.getFont().fontInfo().family());
323 f.fontInfo().realize(rlf);
327 // The uncommon case need not be optimized as much
328 FontInfo const & layoutfont = pos < body_pos ?
329 layout.labelfont : layout.font;
331 Font font = par.getFontSettings(params, pos);
332 font.fontInfo().realize(layoutfont);
334 if (!text_->isMainText())
335 applyOuterFont(font);
337 // Realize against environment font information
338 // NOTE: the cast to pit_type should be removed when pit_type
339 // changes to a unsigned integer.
340 if (pit < pit_type(pars.size()))
341 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
343 // Realize with the fonts of lesser depth.
344 font.fontInfo().realize(params.getFont().fontInfo());
350 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
356 if (boundary && sl.pos() > 0)
359 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
363 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
365 // no RTL boundary at paragraph start
369 Font const & left_font = displayFont(pit, pos - 1);
371 return isRTLBoundary(pit, pos, left_font);
375 // isRTLBoundary returns false on a real end-of-line boundary,
376 // because otherwise the two boundary types get mixed up.
377 // This is the whole purpose of this being in TextMetrics.
378 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
379 Font const & font) const
381 if (// no RTL boundary at paragraph start
383 // if the metrics have not been calculated, then we are not
384 // on screen and can safely ignore issues about boundaries.
388 ParagraphMetrics & pm = par_metrics_[pit];
389 // no RTL boundary in empty paragraph
390 if (pm.rows().empty())
393 pos_type endpos = pm.getRow(pos - 1, false).endpos();
394 pos_type startpos = pm.getRow(pos, false).pos();
395 // no RTL boundary at line start:
396 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
398 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
401 Paragraph const & par = text_->getPar(pit);
402 // no RTL boundary at line break:
403 // abc|\n -> move right -> abc\n (and not: abc\n|
405 if (startpos == pos && endpos == pos && endpos != par.size()
406 && (par.isNewline(pos - 1)
407 || par.isEnvSeparator(pos - 1)
408 || par.isLineSeparator(pos - 1)
409 || par.isSeparator(pos - 1)))
412 bool left = font.isVisibleRightToLeft();
414 if (pos == par.size())
415 right = par.isRTL(bv_->buffer().params());
417 right = displayFont(pit, pos).isVisibleRightToLeft();
419 return left != right;
423 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
425 Paragraph & par = text_->getPar(pit);
426 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
427 // redoParagraph() recursively inside parMetrics.
428 Dimension old_dim = parMetrics(pit, false).dim();
429 ParagraphMetrics & pm = par_metrics_[pit];
432 Buffer & buffer = bv_->buffer();
433 bool changed = false;
435 // Check whether there are InsetBibItems that need fixing
436 // FIXME: This check ought to be done somewhere else. It is the reason
437 // why text_ is not const. But then, where else to do it?
438 // Well, how can you end up with either (a) a biblio environment that
439 // has no InsetBibitem, (b) a biblio environment with more than one
440 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
441 // environment? I think the answer is: when paragraphs are merged;
442 // when layout is set; when material is pasted.
443 if (par.brokenBiblio()) {
444 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
445 // In some cases, we do not know how to record undo
446 if (&cur.inset() == &text_->inset())
447 cur.recordUndo(pit, pit);
449 int const moveCursor = par.fixBiblio(buffer);
451 // Is it necessary to update the cursor?
452 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
455 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
460 // Optimisation: this is used in the next two loops
461 // so better to calculate that once here.
462 int const right_margin = rightMargin(pm);
464 // iterator pointing to paragraph to resolve macros
465 DocIterator parPos = text_->macrocontextPosition();
469 LYXERR(Debug::INFO, "MacroContext not initialised!"
470 << " Going through the buffer again and hope"
471 << " the context is better then.");
472 // FIXME audit updateBuffer calls
473 // This should not be here, but it is not clear yet where else it
475 bv_->buffer().updateBuffer();
476 parPos = text_->macrocontextPosition();
477 LBUFERR(!parPos.empty());
482 par.setBeginOfBody();
483 Font const bufferfont = buffer.params().getFont();
484 CoordCache::Insets & insetCache = bv_->coordCache().insets();
485 for (auto const & e : par.insetList()) {
486 // FIXME Doesn't this HAVE to be non-empty?
487 // position already initialized?
488 if (!parPos.empty()) {
489 parPos.pos() = e.pos;
491 // A macro template would normally not be visible
492 // by itself. But the tex macro semantics allow
493 // recursion, so we artifically take the context
494 // after the macro template to simulate this.
495 if (e.inset->lyxCode() == MATHMACRO_CODE)
499 // If there is an end of paragraph marker, its size should be
500 // substracted to the available width. The logic here is
501 // almost the same as in breakRow, remember keep them in sync.
503 if (lyxrc.paragraph_markers && e.pos + 1 == par.size()
504 && size_type(pit + 1) < text_->paragraphs().size()) {
505 Font f(text_->layoutFont(pit));
506 // ¶ U+00B6 PILCROW SIGN
507 eop = theFontMetrics(f).width(char_type(0x00B6));
510 // do the metric calculation
512 int const w = max_width_ - leftMargin(pit, e.pos)
513 - right_margin - eop;
514 Font const & font = e.inset->inheritFont() ?
515 displayFont(pit, e.pos) : bufferfont;
516 MacroContext mc(&buffer, parPos);
517 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
518 e.inset->metrics(mi, dim);
519 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
520 insetCache.add(e.inset, dim);
526 size_t row_index = 0;
527 bool need_new_row = false;
528 // maximum pixel width of a row
530 if (row_index == pm.rows().size())
531 pm.rows().push_back(Row());
532 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 // FIXME: It might be better to move this in another method
563 // specially tailored for the main text.
564 // Top and bottom margin of the document (only at top-level)
565 if (text_->isMainText()) {
566 // original value was 20px, which is 0.2in at 100dpi
567 int const margin = bv_->zoomedPixels(20);
569 pm.rows().front().dim().asc += margin;
570 /* coverity thinks that we should update pm.dim().asc
571 * below, but all the rows heights are actually counted as
572 * part of the paragraph metric descent see loop above).
574 // coverity[copy_paste_error]
575 pm.dim().des += margin;
577 ParagraphList const & pars = text_->paragraphs();
578 if (pit + 1 == pit_type(pars.size())) {
579 pm.rows().back().dim().des += margin;
580 pm.dim().des += margin;
584 // The space above and below the paragraph.
585 int const top = parTopSpacing(pit);
586 pm.rows().front().dim().asc += top;
587 int const bottom = parBottomSpacing(pit);
588 pm.rows().back().dim().des += bottom;
589 pm.dim().des += top + bottom;
591 pm.dim().asc += pm.rows()[0].ascent();
592 pm.dim().des -= pm.rows()[0].ascent();
594 changed |= old_dim.height() != pm.dim().height();
600 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
602 LyXAlignment align = par.getAlign();
604 // handle alignment inside tabular cells
605 Inset const & owner = text_->inset();
606 bool forced_block = false;
607 switch (owner.contentAlignment()) {
608 case LYX_ALIGN_BLOCK:
609 // In general block align is the default state, but here it is
610 // an explicit choice. Therefore it should not be overridden
614 case LYX_ALIGN_CENTER:
616 case LYX_ALIGN_RIGHT:
617 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
618 align = owner.contentAlignment();
621 // unchanged (use align)
625 // Display-style insets should always be on a centered row
626 if (Inset const * inset = par.getInset(row.pos())) {
627 switch (inset->display()) {
628 case Inset::AlignLeft:
629 align = LYX_ALIGN_BLOCK;
631 case Inset::AlignCenter:
632 align = LYX_ALIGN_CENTER;
635 // unchanged (use align)
637 case Inset::AlignRight:
638 align = LYX_ALIGN_RIGHT;
643 if (align == LYX_ALIGN_BLOCK) {
644 // If this row has been broken abruptly by a display inset, or
645 // it is the end of the paragraph, or the user requested we
646 // not justify stuff, then don't stretch.
647 // A forced block alignment can only be overridden the 'no
648 // justification on screen' setting.
649 if ((row.flushed() && !forced_block)
650 || !bv_->buffer().params().justification)
651 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
658 void TextMetrics::setRowAlignment(Row & row, int width) const
663 Paragraph const & par = text_->getPar(row.pit());
665 int const w = width - row.right_margin - row.width();
666 // FIXME: put back this assertion when the crash on new doc is solved.
667 //LASSERT(w >= 0, /**/);
669 // is there a manual margin with a manual label
670 Layout const & layout = par.layout();
673 if (layout.margintype == MARGIN_MANUAL
674 && layout.labeltype == LABEL_MANUAL) {
675 /// We might have real hfills in the label part
676 nlh = numberOfLabelHfills(par, row);
678 // A manual label par (e.g. List) has an auto-hfill
679 // between the label text and the body of the
681 // But we don't want to do this auto hfill if the par
686 if (nlh && !par.getLabelWidthString().empty())
687 row.label_hfill = labelFill(row) / double(nlh);
690 // are there any hfills in the row?
691 ParagraphMetrics & pm = par_metrics_[row.pit()];
692 int nh = numberOfHfills(row, pm, par.beginOfBody());
696 // We don't have to look at the alignment if the row is already
697 // larger then the permitted width as then we force the
698 // LEFT_ALIGN'edness!
699 if (int(row.width()) >= max_width_)
703 // Common case : there is no hfill, and the alignment will be
705 switch (getAlign(par, row)) {
706 case LYX_ALIGN_BLOCK:
707 // Expand expanding characters by a total of w
708 if (!row.setExtraWidth(w) && row.isRTL()) {
709 // Justification failed and the text is RTL: align to the right
710 row.left_margin += w;
715 // a displayed inset that is flushed
716 if (Inset const * inset = par.getInset(row.pos())) {
717 row.left_margin += inset->indent(*bv_);
718 row.dim().wid += inset->indent(*bv_);
721 case LYX_ALIGN_RIGHT:
722 if (Inset const * inset = par.getInset(row.pos())) {
723 int const new_w = max(w - inset->indent(*bv_), 0);
724 row.left_margin += new_w;
725 row.dim().wid += new_w;
727 row.left_margin += w;
731 case LYX_ALIGN_CENTER:
732 row.dim().wid += w / 2;
733 row.left_margin += w / 2;
736 case LYX_ALIGN_LAYOUT:
737 case LYX_ALIGN_SPECIAL:
738 case LYX_ALIGN_DECIMAL:
744 // Case nh > 0. There are hfill separators.
748 // Set size of hfill insets
749 pos_type const endpos = row.endpos();
750 pos_type body_pos = par.beginOfBody();
752 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
755 CoordCache::Insets & insetCache = bv_->coordCache().insets();
756 for (Row::Element & e : row) {
757 if (row.label_hfill && e.endpos == body_pos
758 && e.type == Row::SPACE)
759 e.dim.wid -= int(row.label_hfill * (nlh - 1));
760 if (e.inset && pm.hfillExpansion(row, e.pos)) {
761 if (e.pos >= body_pos) {
765 e.dim.wid += hfill_rem;
767 e.dim.wid += int(row.label_hfill);
768 // Cache the inset dimension.
769 insetCache.add(e.inset, e.dim);
775 int TextMetrics::labelFill(Row const & row) const
777 Paragraph const & par = text_->getPar(row.pit());
778 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
781 // iterate over elements before main body (except the last one,
782 // which is extra space).
783 for (Row::Element const & e : row) {
784 if (e.endpos >= par.beginOfBody())
789 docstring const & label = par.params().labelWidthString();
793 FontMetrics const & fm
794 = theFontMetrics(text_->labelFont(par));
796 return max(0, fm.width(label) - w);
801 // Not used, see TextMetrics::breakRow
802 // this needs special handling - only newlines count as a break point
803 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
805 pos_type const end = par.size();
808 if (par.isNewline(i))
816 int TextMetrics::labelEnd(pit_type const pit) const
818 // labelEnd is only needed if the layout fills a flushleft label.
819 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
821 // return the beginning of the body
822 return leftMargin(pit);
828 * Calling Text::getFont is slow. While rebreaking we scan a
829 * paragraph from left to right calling getFont for every char. This
830 * simple class address this problem by hidding an optimization trick
831 * (not mine btw -AB): the font is reused in the whole font span. The
832 * class handles transparently the "hidden" (not part of the fontlist)
833 * label font (as getFont does).
839 FontIterator(TextMetrics const & tm,
840 Paragraph const & par, pit_type pit, pos_type pos)
841 : tm_(tm), par_(par), pit_(pit), pos_(pos),
842 font_(tm.displayFont(pit, pos)),
843 endspan_(par.fontSpan(pos).last),
844 bodypos_(par.beginOfBody())
848 Font const & operator*() const { return font_; }
851 FontIterator & operator++()
854 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
855 font_ = tm_.displayFont(pit_, pos_);
856 endspan_ = par_.fontSpan(pos_).last;
862 Font * operator->() { return &font_; }
866 TextMetrics const & tm_;
868 Paragraph const & par_;
883 /** This is the function where the hard work is done. The code here is
884 * very sensitive to small changes :) Note that part of the
885 * intelligence is also in Row::shortenIfNeeded.
887 bool TextMetrics::breakRow(Row & row, int const right_margin) const
889 Paragraph const & par = text_->getPar(row.pit());
890 pos_type const end = par.size();
891 pos_type const pos = row.pos();
892 pos_type const body_pos = par.beginOfBody();
893 bool const is_rtl = text_->isRTL(row.pit());
894 bool need_new_row = false;
897 row.left_margin = leftMargin(row.pit(), pos);
898 row.right_margin = right_margin;
900 swap(row.left_margin, row.right_margin);
901 // Remember that the row width takes into account the left_margin
902 // but not the right_margin.
903 row.dim().wid = row.left_margin;
904 // the width available for the row.
905 int const width = max_width_ - row.right_margin;
908 //FIXME: As long as leftMargin() is not correctly implemented for
909 // MARGIN_RIGHT_ADDRESS_BOX, we should also not do this here.
910 // Otherwise, long rows will be painted off the screen.
911 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX)
912 return addressBreakPoint(pos, par);
915 // check for possible inline completion
916 DocIterator const & ic_it = bv_->inlineCompletionPos();
917 pos_type ic_pos = -1;
918 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == row.pit())
919 ic_pos = ic_it.pos();
921 // Now we iterate through until we reach the right margin
922 // or the end of the par, then build a representation of the row.
924 FontIterator fi = FontIterator(*this, par, row.pit(), pos);
925 while (i < end && (i == pos || row.width() <= width)) {
926 char_type c = par.getChar(i);
927 // The most special cases are handled first.
928 if (par.isInset(i)) {
929 Inset const * ins = par.getInset(i);
930 Dimension dim = bv_->coordCache().insets().dim(ins);
931 row.add(i, ins, dim, *fi, par.lookupChange(i));
932 } else if (c == ' ' && i + 1 == body_pos) {
933 // There is a space at i, but it should not be
934 // added as a separator, because it is just
935 // before body_pos. Instead, insert some spacing to
937 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
938 // this is needed to make sure that the row width is correct
940 int const add = max(fm.width(par.layout().labelsep),
941 labelEnd(row.pit()) - row.width());
942 row.addSpace(i, add, *fi, par.lookupChange(i));
943 } else if (c == '\t')
944 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
945 *fi, par.lookupChange(i));
946 else if (c == 0x2028 || c == 0x2029) {
948 * U+2028 LINE SEPARATOR
949 * U+2029 PARAGRAPH SEPARATOR
951 * These are special unicode characters that break
952 * lines/pragraphs. Not handling them lead to trouble wrt
953 * Qt QTextLayout formatting. We add a visible character
954 * on screen so that the user can see that something is
958 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
959 // ¶ U+00B6 PILCROW SIGN
960 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
961 row.add(i, screen_char, *fi, par.lookupChange(i));
963 row.add(i, c, *fi, par.lookupChange(i));
965 // add inline completion width
966 // draw logically behind the previous character
967 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
968 docstring const comp = bv_->inlineCompletion();
969 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
973 f.fontInfo().setColor(Color_inlinecompletion);
974 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
976 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
977 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
980 // Handle some situations that abruptly terminate the row
982 // - Before a display inset
983 // - After a display inset
984 Inset const * inset = 0;
985 if (par.isNewline(i) || par.isEnvSeparator(i)
986 || (i + 1 < end && (inset = par.getInset(i + 1))
988 || (!row.empty() && row.back().inset
989 && row.back().inset->display())) {
991 // We will force a row creation after either
993 // - a display inset followed by a end label.
996 || (inset && inset->display() && i + 1 == end
997 && text_->getEndLabel(row.pit()) != END_LABEL_NO_LABEL);
1008 // End of paragraph marker. The logic here is almost the
1009 // same as in redoParagraph, remember keep them in sync.
1010 ParagraphList const & pars = text_->paragraphs();
1011 Change const & change = par.lookupChange(i);
1012 if ((lyxrc.paragraph_markers || change.changed())
1014 && i == end && size_type(row.pit() + 1) < pars.size()) {
1015 // add a virtual element for the end-of-paragraph
1016 // marker; it is shown on screen, but does not exist
1017 // in the paragraph.
1018 Font f(text_->layoutFont(row.pit()));
1019 f.fontInfo().setColor(Color_paragraphmarker);
1020 BufferParams const & bparams
1021 = text_->inset().buffer().params();
1022 f.setLanguage(par.getParLanguage(bparams));
1023 // ¶ U+00B6 PILCROW SIGN
1024 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, change);
1027 // Is there a end-of-paragaph change?
1028 if (i == end && par.lookupChange(end).changed() && !need_new_row)
1029 row.needsChangeBar(true);
1031 // if the row is too large, try to cut at last separator. In case
1032 // of success, reset indication that the row was broken abruptly.
1033 int const next_width = max_width_ - leftMargin(row.pit(), row.endpos())
1034 - rightMargin(row.pit());
1036 if (row.shortenIfNeeded(body_pos, width, next_width))
1038 row.right_boundary(!row.empty() && row.endpos() < end
1039 && row.back().endpos == row.endpos());
1040 // Last row in paragraph is flushed
1041 if (row.endpos() == end)
1044 // make sure that the RTL elements are in reverse ordering
1045 row.reverseRTL(is_rtl);
1046 //LYXERR0("breakrow: row is " << row);
1048 return need_new_row;
1051 int TextMetrics::parTopSpacing(pit_type const pit) const
1053 Paragraph const & par = text_->getPar(pit);
1054 Layout const & layout = par.layout();
1057 ParagraphList const & pars = text_->paragraphs();
1058 double const dh = defaultRowHeight();
1060 BufferParams const & bparams = bv_->buffer().params();
1061 Inset const & inset = text_->inset();
1062 // some parskips VERY EASY IMPLEMENTATION
1063 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1064 && !inset.getLayout().parbreakIsNewline()
1065 && !par.layout().parbreak_is_newline
1067 && ((layout.isParagraph() && par.getDepth() == 0)
1068 || (pars[pit - 1].layout().isParagraph()
1069 && pars[pit - 1].getDepth() == 0))) {
1070 asc += bparams.getDefSkip().inPixels(*bv_);
1073 if (par.params().startOfAppendix())
1076 // special code for the top label
1077 if (layout.labelIsAbove()
1078 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1079 && !par.labelString().empty()) {
1080 FontInfo labelfont = text_->labelFont(par);
1081 FontMetrics const & lfm = theFontMetrics(labelfont);
1082 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1083 * text_->spacing(par)
1084 + (layout.topsep + layout.labelbottomsep) * dh);
1087 // Add the layout spaces, for example before and after
1088 // a section, or between the items of a itemize or enumerate
1091 pit_type prev = text_->depthHook(pit, par.getDepth());
1092 Paragraph const & prevpar = pars[prev];
1093 double layoutasc = 0;
1095 && prevpar.layout() == layout
1096 && prevpar.getDepth() == par.getDepth()
1097 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1098 layoutasc = layout.itemsep * dh;
1099 } else if (pit != 0 && layout.topsep > 0)
1100 layoutasc = layout.topsep * dh;
1102 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1104 prev = text_->outerHook(pit);
1105 if (prev != pit_type(pars.size())) {
1106 asc += int(pars[prev].layout().parsep * dh);
1107 } else if (pit != 0) {
1108 Paragraph const & prevpar2 = pars[pit - 1];
1109 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1110 asc += int(layout.parsep * dh);
1117 int TextMetrics::parBottomSpacing(pit_type const pit) const
1119 double layoutdesc = 0;
1120 ParagraphList const & pars = text_->paragraphs();
1121 double const dh = defaultRowHeight();
1123 // add the layout spaces, for example before and after
1124 // a section, or between the items of a itemize or enumerate
1126 pit_type nextpit = pit + 1;
1127 if (nextpit != pit_type(pars.size())) {
1128 pit_type cpit = pit;
1130 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1131 double usual = pars[cpit].layout().bottomsep * dh;
1133 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1134 if (pars[cpit].layout() != pars[nextpit].layout()
1135 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1136 unusual = pars[cpit].layout().bottomsep * dh;
1137 layoutdesc = max(unusual, usual);
1138 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1139 if (pars[cpit].layout() != pars[nextpit].layout()
1140 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1141 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1145 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1149 void TextMetrics::setRowHeight(Row & row) const
1151 Paragraph const & par = text_->getPar(row.pit());
1152 Layout const & layout = par.layout();
1153 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1155 // Initial value for ascent (useful if row is empty).
1156 Font const font = displayFont(row.pit(), row.pos());
1157 FontMetrics const & fm = theFontMetrics(font);
1158 int maxasc = fm.maxAscent() + fm.leading();
1159 int maxdes = fm.maxDescent();
1161 // Find the ascent/descent of the row contents
1162 for (Row::Element const & e : row) {
1163 maxasc = max(maxasc, e.dim.ascent());
1164 maxdes = max(maxdes, e.dim.descent());
1167 // Add some leading (split between before and after)
1168 int const leading = support::iround(extra_leading * (maxasc + maxdes));
1169 row.dim().asc = int((maxasc + leading - leading / 2) * spacing_val);
1170 row.dim().des = int((maxdes + leading / 2) * spacing_val);
1174 // x is an absolute screen coord
1175 // returns the column near the specified x-coordinate of the row
1176 // x is set to the real beginning of this column
1177 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1178 bool & boundary) const
1180 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1181 /// For the main Text, it is possible that this pit is not
1182 /// yet in the CoordCache when moving cursor up.
1183 /// x Paragraph coordinate is always 0 for main text anyway.
1184 int const xo = origin_.x_;
1187 // Adapt to cursor row scroll offset if applicable.
1188 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1191 pos_type pos = row.pos();
1194 x = row.left_margin;
1195 else if (x <= row.left_margin) {
1196 pos = row.front().left_pos();
1197 x = row.left_margin;
1198 } else if (x >= row.width()) {
1199 pos = row.back().right_pos();
1202 double w = row.left_margin;
1203 Row::const_iterator cit = row.begin();
1204 Row::const_iterator cend = row.end();
1205 for ( ; cit != cend; ++cit) {
1206 if (w <= x && w + cit->full_width() > x) {
1207 int x_offset = int(x - w);
1208 pos = cit->x2pos(x_offset);
1209 x = int(x_offset + w);
1212 w += cit->full_width();
1214 if (cit == row.end()) {
1215 pos = row.back().right_pos();
1218 /** This tests for the case where the cursor is placed
1219 * just before a font direction change. See comment on
1220 * the boundary_ member in DocIterator.h to understand
1221 * how boundary helps here.
1223 else if (pos == cit->endpos
1224 && ((!cit->isRTL() && cit + 1 != row.end()
1225 && (cit + 1)->isRTL())
1226 || (cit->isRTL() && cit != row.begin()
1227 && !(cit - 1)->isRTL())))
1231 /** This tests for the case where the cursor is set at the end
1232 * of a row which has been broken due something else than a
1233 * separator (a display inset or a forced breaking of the
1234 * row). We know that there is a separator when the end of the
1235 * row is larger than the end of its last element.
1237 if (!row.empty() && pos == row.back().endpos
1238 && row.back().endpos == row.endpos()) {
1239 Inset const * inset = row.back().inset;
1240 if (inset && (inset->lyxCode() == NEWLINE_CODE
1241 || inset->lyxCode() == SEPARATOR_CODE))
1242 pos = row.back().pos;
1244 boundary = row.right_boundary();
1248 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1254 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1256 // We play safe and use parMetrics(pit) to make sure the
1257 // ParagraphMetrics will be redone and OK to use if needed.
1258 // Otherwise we would use an empty ParagraphMetrics in
1259 // upDownInText() while in selection mode.
1260 ParagraphMetrics const & pm = parMetrics(pit);
1262 LBUFERR(row < int(pm.rows().size()));
1264 Row const & r = pm.rows()[row];
1265 return getPosNearX(r, x, bound);
1269 // y is screen coordinate
1270 pit_type TextMetrics::getPitNearY(int y)
1272 LASSERT(!text_->paragraphs().empty(), return -1);
1273 LASSERT(!par_metrics_.empty(), return -1);
1274 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1276 // look for highest numbered paragraph with y coordinate less than given y
1279 ParMetricsCache::const_iterator it = par_metrics_.begin();
1280 ParMetricsCache::const_iterator et = par_metrics_.end();
1281 ParMetricsCache::const_iterator last = et;
1284 ParagraphMetrics const & pm = it->second;
1286 if (y < it->second.position() - int(pm.ascent())) {
1287 // We are looking for a position that is before the first paragraph in
1288 // the cache (which is in priciple off-screen, that is before the
1291 // We are already at the first paragraph in the inset.
1293 // OK, this is the paragraph we are looking for.
1294 pit = it->first - 1;
1299 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1301 if (y >= last->second.position() + int(pm_last.descent())) {
1302 // We are looking for a position that is after the last paragraph in
1303 // the cache (which is in priciple off-screen), that is before the
1305 pit = last->first + 1;
1306 if (pit == int(text_->paragraphs().size()))
1307 // We are already at the last paragraph in the inset.
1309 // OK, this is the paragraph we are looking for.
1310 newParMetricsDown();
1314 for (; it != et; ++it) {
1315 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1316 << " y: " << it->second.position());
1318 ParagraphMetrics const & pm2 = par_metrics_[it->first];
1320 if (it->first >= pit && int(it->second.position()) - int(pm2.ascent()) <= y) {
1322 yy = it->second.position();
1326 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1332 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1333 bool assert_in_view, bool up)
1335 ParagraphMetrics const & pm = par_metrics_[pit];
1337 int yy = pm.position() - pm.ascent();
1338 LBUFERR(!pm.rows().empty());
1339 RowList::const_iterator rit = pm.rows().begin();
1340 RowList::const_iterator rlast = pm.rows().end();
1342 for (; rit != rlast; yy += rit->height(), ++rit)
1343 if (yy + rit->height() > y)
1346 if (assert_in_view) {
1347 if (!up && yy + rit->height() > y) {
1348 if (rit != pm.rows().begin()) {
1351 } else if (pit != 0) {
1354 ParagraphMetrics const & pm2 = par_metrics_[pit];
1355 rit = pm2.rows().end();
1359 } else if (up && yy != y) {
1361 y = yy + rit->height();
1363 } else if (pit < int(text_->paragraphs().size()) - 1) {
1365 newParMetricsDown();
1366 ParagraphMetrics const & pm2 = par_metrics_[pit];
1367 rit = pm2.rows().begin();
1376 // x,y are absolute screen coordinates
1377 // sets cursor recursively descending into nested editable insets
1378 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1379 bool assert_in_view, bool up)
1381 if (lyxerr.debugging(Debug::WORKAREA)) {
1382 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1383 cur.bv().coordCache().dump();
1385 pit_type pit = getPitNearY(y);
1386 LASSERT(pit != -1, return 0);
1387 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1390 // Do we cover an inset?
1391 InsetList::Element * e = checkInsetHit(pit, x, y);
1394 // No inset, set position in the text
1395 bool bound = false; // is modified by getPosNearX
1396 cur.pos() = getPosNearX(row, x, bound);
1397 cur.boundary(bound);
1398 cur.setCurrentFont();
1403 Inset * inset = e->inset;
1404 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1406 // Set position in front of inset
1408 cur.boundary(false);
1411 // Try to descend recursively inside the inset.
1412 Inset * edited = inset->editXY(cur, x, y);
1413 // FIXME: it is not clear that the test on position is needed
1414 // Remove it if/when semantics of editXY is clarified
1415 if (cur.text() == text_ && cur.pos() == e->pos) {
1416 // non-editable inset, set cursor after the inset if x is
1417 // nearer to that position (bug 9628)
1418 bool bound = false; // is modified by getPosNearX
1419 cur.pos() = getPosNearX(row, x, bound);
1420 cur.boundary(bound);
1421 cur.setCurrentFont();
1425 if (cur.top().text() == text_)
1426 cur.setCurrentFont();
1431 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1433 LASSERT(text_ == cur.text(), return);
1434 pit_type const pit = getPitNearY(y);
1435 LASSERT(pit != -1, return);
1437 ParagraphMetrics const & pm = par_metrics_[pit];
1439 int yy = pm.position() - pm.ascent();
1440 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1441 " pit: " << pit << " yy: " << yy);
1444 LBUFERR(pm.rows().size());
1445 for (; r < int(pm.rows().size()) - 1; ++r) {
1446 Row const & row = pm.rows()[r];
1447 if (int(yy + row.height()) > y)
1452 Row const & row = pm.rows()[r];
1454 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1458 pos_type const pos = getPosNearX(row, xx, bound);
1460 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1462 text_->setCursor(cur, pit, pos, true, bound);
1463 // remember new position.
1468 //takes screen x,y coordinates
1469 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1471 Paragraph const & par = text_->paragraphs()[pit];
1472 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1474 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1476 for (InsetList::Element const & e : par.insetList()) {
1477 LYXERR(Debug::DEBUG, "examining inset " << e.inset);
1479 if (insetCache.covers(e.inset, x, y)) {
1480 LYXERR(Debug::DEBUG, "Hit inset: " << e.inset);
1481 return const_cast<InsetList::Element *>(&e);
1485 LYXERR(Debug::DEBUG, "No inset hit. ");
1490 //takes screen x,y coordinates
1491 Inset * TextMetrics::checkInsetHit(int x, int y)
1493 pit_type const pit = getPitNearY(y);
1494 LASSERT(pit != -1, return 0);
1495 InsetList::Element * e = checkInsetHit(pit, x, y);
1504 int TextMetrics::cursorX(CursorSlice const & sl,
1505 bool boundary) const
1507 LASSERT(sl.text() == text_, return 0);
1509 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1510 if (pm.rows().empty())
1512 Row const & row = pm.getRow(sl.pos(), boundary);
1513 pos_type const pos = sl.pos();
1516 row.findElement(pos, boundary, x);
1522 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1524 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1525 ParagraphMetrics const & pm = parMetrics(sl.pit());
1526 if (pm.rows().empty())
1530 h -= parMetrics(0).rows()[0].ascent();
1531 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1532 h += parMetrics(pit).height();
1535 if (pos && boundary)
1537 size_t const rend = pm.pos2row(pos);
1538 for (size_t rit = 0; rit != rend; ++rit)
1539 h += pm.rows()[rit].height();
1540 h += pm.rows()[rend].ascent();
1545 // the cursor set functions have a special mechanism. When they
1546 // realize you left an empty paragraph, they will delete it.
1548 bool TextMetrics::cursorHome(Cursor & cur)
1550 LASSERT(text_ == cur.text(), return false);
1551 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1552 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1553 return text_->setCursor(cur, cur.pit(), row.pos());
1557 bool TextMetrics::cursorEnd(Cursor & cur)
1559 LASSERT(text_ == cur.text(), return false);
1560 // if not on the last row of the par, put the cursor before
1561 // the final space exept if I have a spanning inset or one string
1562 // is so long that we force a break.
1563 pos_type end = cur.textRow().endpos();
1565 // empty text, end-1 is no valid position
1567 bool boundary = false;
1568 if (end != cur.lastpos()) {
1569 if (!cur.paragraph().isLineSeparator(end-1)
1570 && !cur.paragraph().isNewline(end-1)
1571 && !cur.paragraph().isEnvSeparator(end-1))
1575 } else if (cur.paragraph().isEnvSeparator(end-1))
1577 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1581 void TextMetrics::deleteLineForward(Cursor & cur)
1583 LASSERT(text_ == cur.text(), return);
1584 if (cur.lastpos() == 0) {
1585 // Paragraph is empty, so we just go forward
1586 text_->cursorForward(cur);
1589 cur.selection(true); // to avoid deletion
1592 // What is this test for ??? (JMarc)
1593 if (!cur.selection())
1594 text_->deleteWordForward(cur);
1596 cap::cutSelection(cur, false);
1597 cur.checkBufferStructure();
1602 int TextMetrics::leftMargin(pit_type pit) const
1604 return leftMargin(pit, text_->paragraphs()[pit].size());
1608 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1610 ParagraphList const & pars = text_->paragraphs();
1612 LASSERT(pit >= 0, return 0);
1613 LASSERT(pit < int(pars.size()), return 0);
1614 Paragraph const & par = pars[pit];
1615 LASSERT(pos >= 0, return 0);
1616 LASSERT(pos <= par.size(), return 0);
1617 Buffer const & buffer = bv_->buffer();
1618 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1619 DocumentClass const & tclass = buffer.params().documentClass();
1620 Layout const & layout = par.layout();
1621 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1623 docstring parindent = layout.parindent;
1627 if (text_->isMainText()) {
1628 l_margin += bv_->leftMargin();
1629 l_margin += bfm.signedWidth(tclass.leftmargin());
1632 int depth = par.getDepth();
1634 // find the next level paragraph
1635 pit_type newpar = text_->outerHook(pit);
1636 if (newpar != pit_type(pars.size())) {
1637 if (pars[newpar].layout().isEnvironment()) {
1638 int nestmargin = depth * nestMargin();
1639 if (text_->isMainText())
1640 nestmargin += changebarMargin();
1641 l_margin = max(leftMargin(newpar), nestmargin);
1642 // Remove the parindent that has been added
1643 // if the paragraph was empty.
1644 if (pars[newpar].empty() &&
1645 buffer.params().paragraph_separation ==
1646 BufferParams::ParagraphIndentSeparation) {
1647 docstring pi = pars[newpar].layout().parindent;
1648 l_margin -= bfm.signedWidth(pi);
1651 if (tclass.isDefaultLayout(par.layout())
1652 || tclass.isPlainLayout(par.layout())) {
1653 if (pars[newpar].params().noindent())
1656 parindent = pars[newpar].layout().parindent;
1661 // This happens after sections or environments in standard classes.
1662 // We have to check the previous layout at same depth.
1663 if (buffer.params().paragraph_separation ==
1664 BufferParams::ParagraphSkipSeparation)
1666 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1667 pit_type prev = text_->depthHook(pit, par.getDepth());
1668 if (par.layout() == pars[prev].layout()) {
1670 && pars[pit - 1].layout().nextnoindent)
1672 } else if (pars[prev].layout().nextnoindent)
1676 FontInfo const labelfont = text_->labelFont(par);
1677 FontMetrics const & lfm = theFontMetrics(labelfont);
1679 switch (layout.margintype) {
1680 case MARGIN_DYNAMIC:
1681 if (!layout.leftmargin.empty()) {
1682 l_margin += bfm.signedWidth(layout.leftmargin);
1684 if (!par.labelString().empty()) {
1685 l_margin += lfm.signedWidth(layout.labelindent);
1686 l_margin += lfm.width(par.labelString());
1687 l_margin += lfm.width(layout.labelsep);
1691 case MARGIN_MANUAL: {
1692 l_margin += lfm.signedWidth(layout.labelindent);
1693 // The width of an empty par, even with manual label, should be 0
1694 if (!par.empty() && pos >= par.beginOfBody()) {
1695 if (!par.getLabelWidthString().empty()) {
1696 docstring labstr = par.getLabelWidthString();
1697 l_margin += lfm.width(labstr);
1698 l_margin += lfm.width(layout.labelsep);
1704 case MARGIN_STATIC: {
1705 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1706 / (par.getDepth() + 4);
1710 case MARGIN_FIRST_DYNAMIC:
1711 if (layout.labeltype == LABEL_MANUAL) {
1712 // if we are at position 0, we are never in the body
1713 if (pos > 0 && pos >= par.beginOfBody())
1714 l_margin += lfm.signedWidth(layout.leftmargin);
1716 l_margin += lfm.signedWidth(layout.labelindent);
1718 // Special case to fix problems with
1720 || (layout.labeltype == LABEL_STATIC
1721 && layout.latextype == LATEX_ENVIRONMENT
1722 && !text_->isFirstInSequence(pit))) {
1723 l_margin += lfm.signedWidth(layout.leftmargin);
1724 } else if (!layout.labelIsAbove()) {
1725 l_margin += lfm.signedWidth(layout.labelindent);
1726 l_margin += lfm.width(layout.labelsep);
1727 l_margin += lfm.width(par.labelString());
1731 case MARGIN_RIGHT_ADDRESS_BOX: {
1733 // The left margin depends on the widest row in this paragraph.
1734 // This code is wrong because it depends on the rows, but at the
1735 // same time this function is used in redoParagraph to construct
1737 ParagraphMetrics const & pm = par_metrics_[pit];
1738 int minfill = max_width_;
1739 for (row : pm.rows())
1740 if (row.fill() < minfill)
1741 minfill = row.fill();
1742 l_margin += bfm.signedWidth(layout.leftmargin);
1743 l_margin += minfill;
1745 // also wrong, but much shorter.
1746 l_margin += max_width_ / 2;
1751 if (!par.params().leftIndent().zero())
1752 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1754 LyXAlignment align = par.getAlign();
1756 // set the correct parindent
1758 && (layout.labeltype == LABEL_NO_LABEL
1759 || layout.labeltype == LABEL_ABOVE
1760 || layout.labeltype == LABEL_CENTERED
1761 || (layout.labeltype == LABEL_STATIC
1762 && layout.latextype == LATEX_ENVIRONMENT
1763 && !text_->isFirstInSequence(pit)))
1764 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1765 && !par.params().noindent()
1766 // in some insets, paragraphs are never indented
1767 && !text_->inset().neverIndent()
1768 // display style insets are always centered, omit indentation
1771 && par.getInset(pos)->display())
1772 && (!(tclass.isDefaultLayout(par.layout())
1773 || tclass.isPlainLayout(par.layout()))
1774 || buffer.params().paragraph_separation
1775 == BufferParams::ParagraphIndentSeparation)) {
1776 /* use the parindent of the layout when the default
1777 * indentation is used otherwise use the indentation set in
1778 * the document settings
1780 if (buffer.params().getParIndent().empty())
1781 l_margin += bfm.signedWidth(parindent);
1783 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1790 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1792 if (par_metrics_.empty())
1798 y -= par_metrics_.begin()->second.ascent();
1799 for (auto & pm_pair : par_metrics_) {
1800 pit_type const pit = pm_pair.first;
1801 ParagraphMetrics & pm = pm_pair.second;
1803 // Save the paragraph position in the cache.
1805 drawParagraph(pi, pit, x, y);
1811 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1813 ParagraphMetrics const & pm = par_metrics_[pit];
1814 if (pm.rows().empty())
1816 size_t const nrows = pm.rows().size();
1818 // Use fast lane in nodraw stage.
1819 if (pi.pain.isNull()) {
1820 for (size_t i = 0; i != nrows; ++i) {
1822 Row const & row = pm.rows()[i];
1823 // Adapt to cursor row scroll offset if applicable.
1824 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1828 RowPainter rp(pi, *text_, row, row_x, y);
1830 rp.paintOnlyInsets();
1836 int const ww = bv_->workHeight();
1837 Cursor const & cur = bv_->cursor();
1838 DocIterator sel_beg = cur.selectionBegin();
1839 DocIterator sel_end = cur.selectionEnd();
1840 bool selection = cur.selection()
1841 // This is our text.
1842 && cur.text() == text_
1843 // if the anchor is outside, this is not our selection
1844 && cur.normalAnchor().text() == text_
1845 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1847 // We store the begin and end pos of the selection relative to this par
1848 DocIterator sel_beg_par = cur.selectionBegin();
1849 DocIterator sel_end_par = cur.selectionEnd();
1851 // We care only about visible selection.
1853 if (pit != sel_beg.pit()) {
1854 sel_beg_par.pit() = pit;
1855 sel_beg_par.pos() = 0;
1857 if (pit != sel_end.pit()) {
1858 sel_end_par.pit() = pit;
1859 sel_end_par.pos() = sel_end_par.lastpos();
1863 for (size_t i = 0; i != nrows; ++i) {
1865 Row const & row = pm.rows()[i];
1866 // Adapt to cursor row scroll offset if applicable.
1867 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1871 // It is not needed to draw on screen if we are not inside.
1872 bool const inside = (y + row.descent() >= 0
1873 && y - row.ascent() < ww);
1875 // Inset positions have already been set in nodraw stage.
1881 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
1883 row.clearSelectionAndMargins();
1885 // The row knows nothing about the paragraph, so we have to check
1886 // whether this row is the first or last and update the margins.
1887 if (row.selection()) {
1888 if (row.sel_beg == 0)
1889 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
1890 if (row.sel_end == sel_end_par.lastpos())
1891 row.change(row.end_margin_sel, sel_end.pit() > pit);
1894 // Take this opportunity to spellcheck the row contents.
1895 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
1896 text_->getPar(pit).spellCheck();
1899 RowPainter rp(pi, *text_, row, row_x, y);
1901 // Don't paint the row if a full repaint has not been requested
1902 // and if it has not changed.
1903 if (!pi.full_repaint && !row.changed()) {
1904 // Paint only the insets if the text itself is
1906 rp.paintOnlyInsets();
1912 // Clear background of this row if paragraph background was not
1913 // already cleared because of a full repaint.
1914 if (!pi.full_repaint && row.changed()) {
1915 LYXERR(Debug::PAINTING, "Clear rect@("
1916 << max(row_x, 0) << ", " << y - row.ascent() << ")="
1917 << width() << " x " << row.height());
1918 // FIXME: this is a hack. We know that at least this
1919 // amount of pixels can be cleared on right and left.
1920 // Doing so gets rid of caret ghosts when the cursor is at
1921 // the begining/end of row. However, it will not work if
1922 // the caret has a ridiculous width like 6. (see ticket
1924 pi.pain.fillRectangle(max(row_x, 0) - Inset::TEXT_TO_INSET_OFFSET,
1926 width() + 2 * Inset::TEXT_TO_INSET_OFFSET,
1927 row.height(), pi.background_color);
1930 // Instrumentation for testing row cache (see also
1932 if (lyxerr.debugging(Debug::PAINTING)
1933 && (row.selection() || pi.full_repaint || row.changed())) {
1934 string const foreword = text_->isMainText() ? "main text redraw "
1935 : "inset text redraw: ";
1936 LYXERR0(foreword << "pit=" << pit << " row=" << i
1937 << (row.selection() ? " row_selection": "")
1938 << (pi.full_repaint ? " full_repaint" : "")
1939 << (row.changed() ? " row.changed" : ""));
1942 // Backup full_repaint status and force full repaint
1943 // for inner insets as the Row has been cleared out.
1944 bool tmp = pi.full_repaint;
1945 pi.full_repaint = true;
1947 rp.paintSelection();
1950 if (row.needsChangeBar())
1951 rp.paintChangeBar();
1957 rp.paintTooLargeMarks(row_x + row.left_x() < 0,
1958 row_x + row.right_x() > bv_->workWidth());
1962 // This debug code shows on screen which rows are repainted.
1963 // FIXME: since the updates related to caret blinking restrict
1964 // the painter to a small rectangle, the numbers are not
1965 // updated when this happens. Change the code in
1966 // GuiWorkArea::Private::show/hideCaret if this is important.
1967 static int count = 0;
1969 FontInfo fi(sane_font);
1970 fi.setSize(FONT_SIZE_TINY);
1971 fi.setColor(Color_red);
1972 pi.pain.text(row_x, y, convert<docstring>(count), fi);
1975 // Restore full_repaint status.
1976 pi.full_repaint = tmp;
1981 //LYXERR(Debug::PAINTING, ".");
1985 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
1986 Dimension & dim) const
1988 Cursor const & bvcur = cur.bv().cursor();
1990 // get word in front of cursor
1991 docstring word = text_->previousWord(bvcur.top());
1992 DocIterator wordStart = bvcur;
1993 wordStart.pos() -= word.length();
1995 // calculate dimensions of the word
1997 row.pit(bvcur.pit());
1998 row.pos(wordStart.pos());
1999 row.endpos(bvcur.pos());
2003 // get position on screen of the word start and end
2004 //FIXME: Is it necessary to explicitly set this to false?
2005 wordStart.boundary(false);
2006 Point lxy = cur.bv().getPos(wordStart);
2007 Point rxy = cur.bv().getPos(bvcur);
2008 dim.wid = abs(rxy.x_ - lxy.x_);
2010 // calculate position of word
2012 x = min(rxy.x_, lxy.x_);
2014 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2015 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2018 int defaultRowHeight()
2020 FontMetrics const & fm = theFontMetrics(sane_font);
2021 return support::iround(fm.maxHeight() * (1 + extra_leading) + fm.leading());