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"
60 using frontend::FontMetrics;
65 int numberOfLabelHfills(Paragraph const & par, Row const & row)
67 pos_type last = row.endpos() - 1;
68 pos_type first = row.pos();
70 // hfill *DO* count at the beginning of paragraphs!
72 while (first < last && par.isHfill(first))
76 last = min(last, par.beginOfBody());
78 for (pos_type p = first; p < last; ++p) {
85 // FIXME: this needs to be rewritten, probably by merging it into some
86 // code that, besides counting, sets the active status of the space
87 // inset in the row element.
88 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
89 pos_type const body_pos)
92 Row::const_iterator cit = row.begin();
93 Row::const_iterator const end = row.end();
94 for ( ; cit != end ; ++cit)
95 if (cit->pos >= body_pos
96 && cit->inset && pm.hfillExpansion(row, cit->pos))
104 /////////////////////////////////////////////////////////////////////
108 /////////////////////////////////////////////////////////////////////
111 TextMetrics::TextMetrics(BufferView * bv, Text * text)
112 : bv_(bv), text_(text)
115 max_width_ = bv_->workWidth();
116 dim_.wid = max_width_;
122 bool TextMetrics::contains(pit_type pit) const
124 return par_metrics_.find(pit) != par_metrics_.end();
128 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
130 ParMetricsCache::const_iterator it = par_metrics_.begin();
131 return make_pair(it->first, &it->second);
135 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
137 LBUFERR(!par_metrics_.empty());
138 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
139 return make_pair(it->first, &it->second);
143 bool TextMetrics::isLastRow(Row const & row) const
145 ParagraphList const & pars = text_->paragraphs();
146 return row.endpos() >= pars[row.pit()].size()
147 && row.pit() + 1 == pit_type(pars.size());
151 bool TextMetrics::isFirstRow(Row const & row) const
153 return row.pos() == 0 && row.pit() == 0;
157 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
159 for (auto & pm_pair : par_metrics_)
160 if (pm_pair.first == pit)
161 for (Row & row : pm_pair.second.rows())
162 if (row.pos() == pos)
167 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
169 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
170 if (pmc_it == par_metrics_.end()) {
171 pmc_it = par_metrics_.insert(
172 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
174 if (pmc_it->second.rows().empty() && redo)
176 return pmc_it->second;
180 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
182 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
186 void TextMetrics::newParMetricsDown()
188 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
189 pit_type const pit = last.first + 1;
190 if (pit == int(text_->paragraphs().size()))
193 // do it and update its position.
195 par_metrics_[pit].setPosition(last.second.position()
196 + last.second.descent() + par_metrics_[pit].ascent());
201 void TextMetrics::newParMetricsUp()
203 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
204 if (first.first == 0)
207 pit_type const pit = first.first - 1;
208 // do it and update its position.
210 par_metrics_[pit].setPosition(first.second.position()
211 - first.second.ascent() - par_metrics_[pit].descent());
216 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width,
217 bool const expand_on_multipars)
219 LBUFERR(mi.base.textwidth > 0);
220 max_width_ = mi.base.textwidth;
221 // backup old dimension.
222 Dimension const old_dim = dim_;
225 dim_.wid = min_width;
226 pit_type const npar = text_->paragraphs().size();
227 if (npar > 1 && expand_on_multipars)
228 // If there is more than one row, expand the text to
229 // the full allowable width.
230 dim_.wid = max_width_;
232 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
233 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
235 bool changed = false;
237 for (pit_type pit = 0; pit != npar; ++pit) {
238 // create rows, but do not set alignment yet
239 changed |= redoParagraph(pit, false);
240 ParagraphMetrics const & pm = par_metrics_[pit];
242 if (dim_.wid < pm.width())
243 dim_.wid = pm.width();
246 // Now set alignment for all rows (the width might not have been known before).
247 for (pit_type pit = 0; pit != npar; ++pit) {
248 ParagraphMetrics & pm = par_metrics_[pit];
249 for (Row & row : pm.rows())
250 setRowAlignment(row, dim_.wid);
253 dim_.asc = par_metrics_[0].ascent();
254 dim_.des = h - dim_.asc;
255 //lyxerr << "dim_.wid " << dim_.wid << endl;
256 //lyxerr << "dim_.asc " << dim_.asc << endl;
257 //lyxerr << "dim_.des " << dim_.des << endl;
259 changed |= dim_ != old_dim;
265 void TextMetrics::updatePosCache(pit_type pit) const
267 frontend::NullPainter np;
268 PainterInfo pi(bv_, np);
269 drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
273 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
275 return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
279 int TextMetrics::rightMargin(pit_type const pit) const
281 return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
285 void TextMetrics::applyOuterFont(Font & font) const
287 FontInfo lf(font_.fontInfo());
288 lf.reduce(bv_->buffer().params().getFont().fontInfo());
289 font.fontInfo().realize(lf);
293 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
295 LASSERT(pos >= 0, { static Font f; return f; });
297 ParagraphList const & pars = text_->paragraphs();
298 Paragraph const & par = pars[pit];
299 Layout const & layout = par.layout();
300 Buffer const & buffer = bv_->buffer();
302 BufferParams const & params = buffer.params();
303 pos_type const body_pos = par.beginOfBody();
305 // We specialize the 95% common case:
306 if (!par.getDepth()) {
307 Font f = par.getFontSettings(params, pos);
308 if (!text_->isMainText())
310 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
312 FontInfo const & lf = lab ? layout.labelfont : layout.font;
313 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
315 // In case the default family has been customized
316 if (lf.family() == INHERIT_FAMILY)
317 rlf.setFamily(params.getFont().fontInfo().family());
318 f.fontInfo().realize(rlf);
322 // The uncommon case need not be optimized as much
323 FontInfo const & layoutfont = pos < body_pos ?
324 layout.labelfont : layout.font;
326 Font font = par.getFontSettings(params, pos);
327 font.fontInfo().realize(layoutfont);
329 if (!text_->isMainText())
330 applyOuterFont(font);
332 // Realize against environment font information
333 // NOTE: the cast to pit_type should be removed when pit_type
334 // changes to a unsigned integer.
335 if (pit < pit_type(pars.size()))
336 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
338 // Realize with the fonts of lesser depth.
339 font.fontInfo().realize(params.getFont().fontInfo());
345 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
351 if (boundary && sl.pos() > 0)
354 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
358 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
360 // no RTL boundary at paragraph start
364 Font const & left_font = displayFont(pit, pos - 1);
366 return isRTLBoundary(pit, pos, left_font);
370 // isRTLBoundary returns false on a real end-of-line boundary,
371 // because otherwise the two boundary types get mixed up.
372 // This is the whole purpose of this being in TextMetrics.
373 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
374 Font const & font) const
376 if (// no RTL boundary at paragraph start
378 // if the metrics have not been calculated, then we are not
379 // on screen and can safely ignore issues about boundaries.
383 ParagraphMetrics & pm = par_metrics_[pit];
384 // no RTL boundary in empty paragraph
385 if (pm.rows().empty())
388 pos_type endpos = pm.getRow(pos - 1, false).endpos();
389 pos_type startpos = pm.getRow(pos, false).pos();
390 // no RTL boundary at line start:
391 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
393 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
396 Paragraph const & par = text_->getPar(pit);
397 // no RTL boundary at line break:
398 // abc|\n -> move right -> abc\n (and not: abc\n|
400 if (startpos == pos && endpos == pos && endpos != par.size()
401 && (par.isNewline(pos - 1)
402 || par.isEnvSeparator(pos - 1)
403 || par.isLineSeparator(pos - 1)
404 || par.isSeparator(pos - 1)))
407 bool left = font.isVisibleRightToLeft();
409 if (pos == par.size())
410 right = par.isRTL(bv_->buffer().params());
412 right = displayFont(pit, pos).isVisibleRightToLeft();
414 return left != right;
418 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
420 Paragraph & par = text_->getPar(pit);
421 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
422 // redoParagraph() recursively inside parMetrics.
423 Dimension old_dim = parMetrics(pit, false).dim();
424 ParagraphMetrics & pm = par_metrics_[pit];
427 Buffer & buffer = bv_->buffer();
428 bool changed = false;
430 // Check whether there are InsetBibItems that need fixing
431 // FIXME: This check ought to be done somewhere else. It is the reason
432 // why text_ is not const. But then, where else to do it?
433 // Well, how can you end up with either (a) a biblio environment that
434 // has no InsetBibitem, (b) a biblio environment with more than one
435 // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
436 // environment? I think the answer is: when paragraphs are merged;
437 // when layout is set; when material is pasted.
438 if (par.brokenBiblio()) {
439 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
440 // In some cases, we do not know how to record undo
441 if (&cur.inset() == &text_->inset())
442 cur.recordUndo(pit, pit);
444 int const moveCursor = par.fixBiblio(buffer);
446 // Is it necessary to update the cursor?
447 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
450 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
455 // Optimisation: this is used in the next two loops
456 // so better to calculate that once here.
457 int const right_margin = rightMargin(pm);
459 // iterator pointing to paragraph to resolve macros
460 DocIterator parPos = text_->macrocontextPosition();
464 LYXERR(Debug::INFO, "MacroContext not initialised!"
465 << " Going through the buffer again and hope"
466 << " the context is better then.");
467 // FIXME audit updateBuffer calls
468 // This should not be here, but it is not clear yet where else it
470 bv_->buffer().updateBuffer();
471 parPos = text_->macrocontextPosition();
472 LBUFERR(!parPos.empty());
477 par.setBeginOfBody();
478 Font const bufferfont = buffer.params().getFont();
479 CoordCache::Insets & insetCache = bv_->coordCache().insets();
480 for (auto const & e : par.insetList()) {
481 // FIXME Doesn't this HAVE to be non-empty?
482 // position already initialized?
483 if (!parPos.empty()) {
484 parPos.pos() = e.pos;
486 // A macro template would normally not be visible
487 // by itself. But the tex macro semantics allow
488 // recursion, so we artifically take the context
489 // after the macro template to simulate this.
490 if (e.inset->lyxCode() == MATHMACRO_CODE)
494 // If there is an end of paragraph marker, its size should be
495 // substracted to the available width. The logic here is
496 // almost the same as in breakRow, remember keep them in sync.
498 if (lyxrc.paragraph_markers && e.pos + 1 == par.size()
499 && size_type(pit + 1) < text_->paragraphs().size()) {
500 Font f(text_->layoutFont(pit));
501 // ¶ U+00B6 PILCROW SIGN
502 eop = theFontMetrics(f).width(char_type(0x00B6));
505 // do the metric calculation
507 int const w = max_width_ - leftMargin(pit, e.pos)
508 - right_margin - eop;
509 Font const & font = e.inset->inheritFont() ?
510 displayFont(pit, e.pos) : bufferfont;
511 MacroContext mc(&buffer, parPos);
512 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
513 e.inset->metrics(mi, dim);
514 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
515 insetCache.add(e.inset, dim);
521 size_t row_index = 0;
522 bool need_new_row = false;
523 // maximum pixel width of a row
525 if (row_index == pm.rows().size())
526 pm.rows().push_back(Row());
528 pm.rows()[row_index] = Row();
529 Row & row = pm.rows()[row_index];
532 need_new_row = breakRow(row, right_margin);
535 if ((row_index || row.endpos() < par.size() || row.right_boundary())
536 && par.inInset().lyxCode() != CELL_CODE) {
537 /* If there is more than one row or the row has been
538 * broken by a display inset or a newline, expand the text
539 * to the full allowable width. This setting here is
540 * needed for the setRowAlignment() below.
541 * We do nothing when inside a table cell.
543 if (dim_.wid < max_width_)
544 dim_.wid = max_width_;
547 setRowAlignment(row, max(dim_.wid, row.width()));
548 first = row.endpos();
551 pm.dim().wid = max(pm.dim().wid, row.width());
552 pm.dim().des += row.height();
553 } while (first < par.size() || need_new_row);
555 if (row_index < pm.rows().size())
556 pm.rows().resize(row_index);
558 // FIXME: It might be better to move this in another method
559 // specially tailored for the main text.
560 // Top and bottom margin of the document (only at top-level)
561 if (text_->isMainText()) {
562 // original value was 20px, which is 0.2in at 100dpi
563 int const margin = bv_->zoomedPixels(20);
565 pm.rows().front().dim().asc += margin;
566 /* coverity thinks that we should update pm.dim().asc
567 * below, but all the rows heights are actually counted as
568 * part of the paragraph metric descent see loop above).
570 // coverity[copy_paste_error]
571 pm.dim().des += margin;
573 ParagraphList const & pars = text_->paragraphs();
574 if (pit + 1 == pit_type(pars.size())) {
575 pm.rows().back().dim().des += margin;
576 pm.dim().des += margin;
580 // The space above and below the paragraph.
581 int const top = parTopSpacing(pit);
582 pm.rows().front().dim().asc += top;
583 int const bottom = parBottomSpacing(pit);
584 pm.rows().back().dim().des += bottom;
585 pm.dim().des += top + bottom;
587 pm.dim().asc += pm.rows()[0].ascent();
588 pm.dim().des -= pm.rows()[0].ascent();
590 changed |= old_dim.height() != pm.dim().height();
596 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
598 LyXAlignment align = par.getAlign();
600 // handle alignment inside tabular cells
601 Inset const & owner = text_->inset();
602 bool forced_block = false;
603 switch (owner.contentAlignment()) {
604 case LYX_ALIGN_BLOCK:
605 // In general block align is the default state, but here it is
606 // an explicit choice. Therefore it should not be overridden
610 case LYX_ALIGN_CENTER:
612 case LYX_ALIGN_RIGHT:
613 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
614 align = owner.contentAlignment();
617 // unchanged (use align)
621 // Display-style insets should always be on a centered row
622 if (Inset const * inset = par.getInset(row.pos())) {
623 switch (inset->display()) {
624 case Inset::AlignLeft:
625 align = LYX_ALIGN_BLOCK;
627 case Inset::AlignCenter:
628 align = LYX_ALIGN_CENTER;
631 // unchanged (use align)
633 case Inset::AlignRight:
634 align = LYX_ALIGN_RIGHT;
639 if (align == LYX_ALIGN_BLOCK) {
640 // If this row has been broken abruptly by a display inset, or
641 // it is the end of the paragraph, or the user requested we
642 // not justify stuff, then don't stretch.
643 // A forced block alignment can only be overridden the 'no
644 // justification on screen' setting.
645 if ((row.flushed() && !forced_block)
646 || !bv_->buffer().params().justification)
647 align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
654 void TextMetrics::setRowAlignment(Row & row, int width) const
659 Paragraph const & par = text_->getPar(row.pit());
661 int const w = width - row.right_margin - row.width();
662 // FIXME: put back this assertion when the crash on new doc is solved.
663 //LASSERT(w >= 0, /**/);
665 // is there a manual margin with a manual label
666 Layout const & layout = par.layout();
669 if (layout.margintype == MARGIN_MANUAL
670 && layout.labeltype == LABEL_MANUAL) {
671 /// We might have real hfills in the label part
672 nlh = numberOfLabelHfills(par, row);
674 // A manual label par (e.g. List) has an auto-hfill
675 // between the label text and the body of the
677 // But we don't want to do this auto hfill if the par
682 if (nlh && !par.getLabelWidthString().empty())
683 row.label_hfill = labelFill(row) / double(nlh);
686 // are there any hfills in the row?
687 ParagraphMetrics & pm = par_metrics_[row.pit()];
688 int nh = numberOfHfills(row, pm, par.beginOfBody());
692 // We don't have to look at the alignment if the row is already
693 // larger then the permitted width as then we force the
694 // LEFT_ALIGN'edness!
695 if (int(row.width()) >= max_width_)
699 // Common case : there is no hfill, and the alignment will be
701 switch (getAlign(par, row)) {
702 case LYX_ALIGN_BLOCK:
703 // Expand expanding characters by a total of w
704 if (!row.setExtraWidth(w) && row.isRTL()) {
705 // Justification failed and the text is RTL: align to the right
706 row.left_margin += w;
711 // a displayed inset that is flushed
712 if (Inset const * inset = par.getInset(row.pos())) {
713 row.left_margin += inset->indent(*bv_);
714 row.dim().wid += inset->indent(*bv_);
717 case LYX_ALIGN_RIGHT:
718 if (Inset const * inset = par.getInset(row.pos())) {
719 int const new_w = max(w - inset->indent(*bv_), 0);
720 row.left_margin += new_w;
721 row.dim().wid += new_w;
723 row.left_margin += w;
727 case LYX_ALIGN_CENTER:
728 row.dim().wid += w / 2;
729 row.left_margin += w / 2;
732 case LYX_ALIGN_LAYOUT:
733 case LYX_ALIGN_SPECIAL:
734 case LYX_ALIGN_DECIMAL:
740 // Case nh > 0. There are hfill separators.
744 // Set size of hfill insets
745 pos_type const endpos = row.endpos();
746 pos_type body_pos = par.beginOfBody();
748 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
751 CoordCache::Insets & insetCache = bv_->coordCache().insets();
752 for (Row::Element & e : row) {
753 if (row.label_hfill && e.endpos == body_pos
754 && e.type == Row::SPACE)
755 e.dim.wid -= int(row.label_hfill * (nlh - 1));
756 if (e.inset && pm.hfillExpansion(row, e.pos)) {
757 if (e.pos >= body_pos) {
761 e.dim.wid += hfill_rem;
763 e.dim.wid += int(row.label_hfill);
764 // Cache the inset dimension.
765 insetCache.add(e.inset, e.dim);
771 int TextMetrics::labelFill(Row const & row) const
773 Paragraph const & par = text_->getPar(row.pit());
774 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
777 // iterate over elements before main body (except the last one,
778 // which is extra space).
779 for (Row::Element const & e : row) {
780 if (e.endpos >= par.beginOfBody())
785 docstring const & label = par.params().labelWidthString();
789 FontMetrics const & fm
790 = theFontMetrics(text_->labelFont(par));
792 return max(0, fm.width(label) - w);
797 // Not used, see TextMetrics::breakRow
798 // this needs special handling - only newlines count as a break point
799 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
801 pos_type const end = par.size();
804 if (par.isNewline(i))
812 int TextMetrics::labelEnd(pit_type const pit) const
814 // labelEnd is only needed if the layout fills a flushleft label.
815 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
817 // return the beginning of the body
818 return leftMargin(pit);
824 * Calling Text::getFont is slow. While rebreaking we scan a
825 * paragraph from left to right calling getFont for every char. This
826 * simple class address this problem by hidding an optimization trick
827 * (not mine btw -AB): the font is reused in the whole font span. The
828 * class handles transparently the "hidden" (not part of the fontlist)
829 * label font (as getFont does).
835 FontIterator(TextMetrics const & tm,
836 Paragraph const & par, pit_type pit, pos_type pos)
837 : tm_(tm), par_(par), pit_(pit), pos_(pos),
838 font_(tm.displayFont(pit, pos)),
839 endspan_(par.fontSpan(pos).last),
840 bodypos_(par.beginOfBody())
844 Font const & operator*() const { return font_; }
847 FontIterator & operator++()
850 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
851 font_ = tm_.displayFont(pit_, pos_);
852 endspan_ = par_.fontSpan(pos_).last;
858 Font * operator->() { return &font_; }
862 TextMetrics const & tm_;
864 Paragraph const & par_;
879 /** This is the function where the hard work is done. The code here is
880 * very sensitive to small changes :) Note that part of the
881 * intelligence is also in Row::shortenIfNeeded.
883 bool TextMetrics::breakRow(Row & row, int const right_margin) const
885 LATTEST(row.empty());
886 Paragraph const & par = text_->getPar(row.pit());
887 pos_type const end = par.size();
888 pos_type const pos = row.pos();
889 pos_type const body_pos = par.beginOfBody();
890 bool const is_rtl = text_->isRTL(row.pit());
891 bool need_new_row = false;
893 row.left_margin = leftMargin(row.pit(), pos);
894 row.right_margin = right_margin;
896 swap(row.left_margin, row.right_margin);
897 // Remember that the row width takes into account the left_margin
898 // but not the right_margin.
899 row.dim().wid = row.left_margin;
900 // the width available for the row.
901 int const width = max_width_ - row.right_margin;
904 //FIXME: As long as leftMargin() is not correctly implemented for
905 // MARGIN_RIGHT_ADDRESS_BOX, we should also not do this here.
906 // Otherwise, long rows will be painted off the screen.
907 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX)
908 return addressBreakPoint(pos, par);
911 // check for possible inline completion
912 DocIterator const & ic_it = bv_->inlineCompletionPos();
913 pos_type ic_pos = -1;
914 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == row.pit())
915 ic_pos = ic_it.pos();
917 // Now we iterate through until we reach the right margin
918 // or the end of the par, then build a representation of the row.
920 FontIterator fi = FontIterator(*this, par, row.pit(), pos);
921 while (i < end && (i == pos || row.width() <= width)) {
922 char_type c = par.getChar(i);
923 // The most special cases are handled first.
924 if (par.isInset(i)) {
925 Inset const * ins = par.getInset(i);
926 Dimension dim = bv_->coordCache().insets().dim(ins);
927 row.add(i, ins, dim, *fi, par.lookupChange(i));
928 } else if (c == ' ' && i + 1 == body_pos) {
929 // There is a space at i, but it should not be
930 // added as a separator, because it is just
931 // before body_pos. Instead, insert some spacing to
933 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
934 // this is needed to make sure that the row width is correct
936 int const add = max(fm.width(par.layout().labelsep),
937 labelEnd(row.pit()) - row.width());
938 row.addSpace(i, add, *fi, par.lookupChange(i));
939 } else if (c == '\t')
940 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
941 *fi, par.lookupChange(i));
942 else if (c == 0x2028 || c == 0x2029) {
944 * U+2028 LINE SEPARATOR
945 * U+2029 PARAGRAPH SEPARATOR
947 * These are special unicode characters that break
948 * lines/pragraphs. Not handling them lead to trouble wrt
949 * Qt QTextLayout formatting. We add a visible character
950 * on screen so that the user can see that something is
954 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
955 // ¶ U+00B6 PILCROW SIGN
956 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
957 row.add(i, screen_char, *fi, par.lookupChange(i));
959 row.add(i, c, *fi, par.lookupChange(i));
961 // add inline completion width
962 // draw logically behind the previous character
963 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
964 docstring const comp = bv_->inlineCompletion();
965 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
969 f.fontInfo().setColor(Color_inlinecompletion);
970 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
972 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
973 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
976 // Handle some situations that abruptly terminate the row
978 // - Before a display inset
979 // - After a display inset
980 Inset const * inset = 0;
981 if (par.isNewline(i) || par.isEnvSeparator(i)
982 || (i + 1 < end && (inset = par.getInset(i + 1))
984 || (!row.empty() && row.back().inset
985 && row.back().inset->display())) {
987 // We will force a row creation after either
989 // - a display inset followed by a end label.
992 || (inset && inset->display() && i + 1 == end
993 && text_->getEndLabel(row.pit()) != END_LABEL_NO_LABEL);
1004 // End of paragraph marker. The logic here is almost the
1005 // same as in redoParagraph, remember keep them in sync.
1006 ParagraphList const & pars = text_->paragraphs();
1007 Change const & change = par.lookupChange(i);
1008 if ((lyxrc.paragraph_markers || change.changed())
1010 && i == end && size_type(row.pit() + 1) < pars.size()) {
1011 // add a virtual element for the end-of-paragraph
1012 // marker; it is shown on screen, but does not exist
1013 // in the paragraph.
1014 Font f(text_->layoutFont(row.pit()));
1015 f.fontInfo().setColor(Color_paragraphmarker);
1016 BufferParams const & bparams
1017 = text_->inset().buffer().params();
1018 f.setLanguage(par.getParLanguage(bparams));
1019 // ¶ U+00B6 PILCROW SIGN
1020 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, change);
1023 // Is there a end-of-paragaph change?
1024 if (i == end && par.lookupChange(end).changed() && !need_new_row)
1025 row.needsChangeBar(true);
1027 // if the row is too large, try to cut at last separator. In case
1028 // of success, reset indication that the row was broken abruptly.
1029 int const next_width = max_width_ - leftMargin(row.pit(), row.endpos())
1030 - rightMargin(row.pit());
1032 if (row.shortenIfNeeded(body_pos, width, next_width))
1034 row.right_boundary(!row.empty() && row.endpos() < end
1035 && row.back().endpos == row.endpos());
1036 // Last row in paragraph is flushed
1037 if (row.endpos() == end)
1040 // make sure that the RTL elements are in reverse ordering
1041 row.reverseRTL(is_rtl);
1042 //LYXERR0("breakrow: row is " << row);
1044 return need_new_row;
1047 int TextMetrics::parTopSpacing(pit_type const pit) const
1049 Paragraph const & par = text_->getPar(pit);
1050 Layout const & layout = par.layout();
1053 ParagraphList const & pars = text_->paragraphs();
1054 double const dh = defaultRowHeight();
1056 BufferParams const & bparams = bv_->buffer().params();
1057 Inset const & inset = text_->inset();
1058 // some parskips VERY EASY IMPLEMENTATION
1059 if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1060 && !inset.getLayout().parbreakIsNewline()
1061 && !par.layout().parbreak_is_newline
1063 && ((layout.isParagraph() && par.getDepth() == 0)
1064 || (pars[pit - 1].layout().isParagraph()
1065 && pars[pit - 1].getDepth() == 0))) {
1066 asc += bparams.getDefSkip().inPixels(*bv_);
1069 if (par.params().startOfAppendix())
1072 // special code for the top label
1073 if (layout.labelIsAbove()
1074 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1075 && !par.labelString().empty()) {
1076 FontInfo labelfont = text_->labelFont(par);
1077 FontMetrics const & lfm = theFontMetrics(labelfont);
1078 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1079 * text_->spacing(par)
1080 + (layout.topsep + layout.labelbottomsep) * dh);
1083 // Add the layout spaces, for example before and after
1084 // a section, or between the items of a itemize or enumerate
1087 pit_type prev = text_->depthHook(pit, par.getDepth());
1088 Paragraph const & prevpar = pars[prev];
1089 double layoutasc = 0;
1091 && prevpar.layout() == layout
1092 && prevpar.getDepth() == par.getDepth()
1093 && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1094 layoutasc = layout.itemsep * dh;
1095 } else if (pit != 0 && layout.topsep > 0)
1096 layoutasc = layout.topsep * dh;
1098 asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1100 prev = text_->outerHook(pit);
1101 if (prev != pit_type(pars.size())) {
1102 asc += int(pars[prev].layout().parsep * dh);
1103 } else if (pit != 0) {
1104 Paragraph const & prevpar2 = pars[pit - 1];
1105 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1106 asc += int(layout.parsep * dh);
1113 int TextMetrics::parBottomSpacing(pit_type const pit) const
1115 double layoutdesc = 0;
1116 ParagraphList const & pars = text_->paragraphs();
1117 double const dh = defaultRowHeight();
1119 // add the layout spaces, for example before and after
1120 // a section, or between the items of a itemize or enumerate
1122 pit_type nextpit = pit + 1;
1123 if (nextpit != pit_type(pars.size())) {
1124 pit_type cpit = pit;
1126 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1127 double usual = pars[cpit].layout().bottomsep * dh;
1129 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1130 if (pars[cpit].layout() != pars[nextpit].layout()
1131 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1132 unusual = pars[cpit].layout().bottomsep * dh;
1133 layoutdesc = max(unusual, usual);
1134 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1135 if (pars[cpit].layout() != pars[nextpit].layout()
1136 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1137 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1141 return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1145 void TextMetrics::setRowHeight(Row & row) const
1147 Paragraph const & par = text_->getPar(row.pit());
1148 Layout const & layout = par.layout();
1149 double const spacing_val = layout.spacing.getValue() * text_->spacing(par);
1151 // Initial value for ascent (useful if row is empty).
1152 Font const font = displayFont(row.pit(), row.pos());
1153 FontMetrics const & fm = theFontMetrics(font);
1154 int maxasc = int(fm.maxAscent() * spacing_val);
1155 int maxdes = int(fm.maxDescent() * spacing_val);
1157 // Find the ascent/descent of the row contents
1158 for (Row::Element const & e : row) {
1160 maxasc = max(maxasc, e.dim.ascent());
1161 maxdes = max(maxdes, e.dim.descent());
1163 FontMetrics const & fm2 = theFontMetrics(e.font);
1164 maxasc = max(maxasc, int(fm2.maxAscent() * spacing_val));
1165 maxdes = max(maxdes, int(fm2.maxDescent() * spacing_val));
1169 // This is nicer with box insets
1173 row.dim().asc = maxasc;
1174 row.dim().des = maxdes;
1178 // x is an absolute screen coord
1179 // returns the column near the specified x-coordinate of the row
1180 // x is set to the real beginning of this column
1181 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1182 bool & boundary) const
1184 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1185 /// For the main Text, it is possible that this pit is not
1186 /// yet in the CoordCache when moving cursor up.
1187 /// x Paragraph coordinate is always 0 for main text anyway.
1188 int const xo = origin_.x_;
1191 // Adapt to cursor row scroll offset if applicable.
1192 int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1195 pos_type pos = row.pos();
1198 x = row.left_margin;
1199 else if (x <= row.left_margin) {
1200 pos = row.front().left_pos();
1201 x = row.left_margin;
1202 } else if (x >= row.width()) {
1203 pos = row.back().right_pos();
1206 double w = row.left_margin;
1207 Row::const_iterator cit = row.begin();
1208 Row::const_iterator cend = row.end();
1209 for ( ; cit != cend; ++cit) {
1210 if (w <= x && w + cit->full_width() > x) {
1211 int x_offset = int(x - w);
1212 pos = cit->x2pos(x_offset);
1213 x = int(x_offset + w);
1216 w += cit->full_width();
1218 if (cit == row.end()) {
1219 pos = row.back().right_pos();
1222 /** This tests for the case where the cursor is placed
1223 * just before a font direction change. See comment on
1224 * the boundary_ member in DocIterator.h to understand
1225 * how boundary helps here.
1227 else if (pos == cit->endpos
1228 && ((!cit->isRTL() && cit + 1 != row.end()
1229 && (cit + 1)->isRTL())
1230 || (cit->isRTL() && cit != row.begin()
1231 && !(cit - 1)->isRTL())))
1235 /** This tests for the case where the cursor is set at the end
1236 * of a row which has been broken due something else than a
1237 * separator (a display inset or a forced breaking of the
1238 * row). We know that there is a separator when the end of the
1239 * row is larger than the end of its last element.
1241 if (!row.empty() && pos == row.back().endpos
1242 && row.back().endpos == row.endpos()) {
1243 Inset const * inset = row.back().inset;
1244 if (inset && (inset->lyxCode() == NEWLINE_CODE
1245 || inset->lyxCode() == SEPARATOR_CODE))
1246 pos = row.back().pos;
1248 boundary = row.right_boundary();
1252 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1258 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1260 // We play safe and use parMetrics(pit) to make sure the
1261 // ParagraphMetrics will be redone and OK to use if needed.
1262 // Otherwise we would use an empty ParagraphMetrics in
1263 // upDownInText() while in selection mode.
1264 ParagraphMetrics const & pm = parMetrics(pit);
1266 LBUFERR(row < int(pm.rows().size()));
1268 Row const & r = pm.rows()[row];
1269 return getPosNearX(r, x, bound);
1273 // y is screen coordinate
1274 pit_type TextMetrics::getPitNearY(int y)
1276 LASSERT(!text_->paragraphs().empty(), return -1);
1277 LASSERT(!par_metrics_.empty(), return -1);
1278 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1280 // look for highest numbered paragraph with y coordinate less than given y
1283 ParMetricsCache::const_iterator it = par_metrics_.begin();
1284 ParMetricsCache::const_iterator et = par_metrics_.end();
1285 ParMetricsCache::const_iterator last = et;
1288 ParagraphMetrics const & pm = it->second;
1290 if (y < it->second.position() - int(pm.ascent())) {
1291 // We are looking for a position that is before the first paragraph in
1292 // the cache (which is in priciple off-screen, that is before the
1295 // We are already at the first paragraph in the inset.
1297 // OK, this is the paragraph we are looking for.
1298 pit = it->first - 1;
1303 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1305 if (y >= last->second.position() + int(pm_last.descent())) {
1306 // We are looking for a position that is after the last paragraph in
1307 // the cache (which is in priciple off-screen), that is before the
1309 pit = last->first + 1;
1310 if (pit == int(text_->paragraphs().size()))
1311 // We are already at the last paragraph in the inset.
1313 // OK, this is the paragraph we are looking for.
1314 newParMetricsDown();
1318 for (; it != et; ++it) {
1319 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1320 << " y: " << it->second.position());
1322 ParagraphMetrics const & pm2 = par_metrics_[it->first];
1324 if (it->first >= pit && int(it->second.position()) - int(pm2.ascent()) <= y) {
1326 yy = it->second.position();
1330 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1336 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1337 bool assert_in_view, bool up)
1339 ParagraphMetrics const & pm = par_metrics_[pit];
1341 int yy = pm.position() - pm.ascent();
1342 LBUFERR(!pm.rows().empty());
1343 RowList::const_iterator rit = pm.rows().begin();
1344 RowList::const_iterator rlast = pm.rows().end();
1346 for (; rit != rlast; yy += rit->height(), ++rit)
1347 if (yy + rit->height() > y)
1350 if (assert_in_view) {
1351 if (!up && yy + rit->height() > y) {
1352 if (rit != pm.rows().begin()) {
1355 } else if (pit != 0) {
1358 ParagraphMetrics const & pm2 = par_metrics_[pit];
1359 rit = pm2.rows().end();
1363 } else if (up && yy != y) {
1365 y = yy + rit->height();
1367 } else if (pit < int(text_->paragraphs().size()) - 1) {
1369 newParMetricsDown();
1370 ParagraphMetrics const & pm2 = par_metrics_[pit];
1371 rit = pm2.rows().begin();
1380 // x,y are absolute screen coordinates
1381 // sets cursor recursively descending into nested editable insets
1382 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1383 bool assert_in_view, bool up)
1385 if (lyxerr.debugging(Debug::WORKAREA)) {
1386 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1387 cur.bv().coordCache().dump();
1389 pit_type pit = getPitNearY(y);
1390 LASSERT(pit != -1, return 0);
1391 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1394 // Do we cover an inset?
1395 InsetList::Element * e = checkInsetHit(pit, x, y);
1398 // No inset, set position in the text
1399 bool bound = false; // is modified by getPosNearX
1400 cur.pos() = getPosNearX(row, x, bound);
1401 cur.boundary(bound);
1402 cur.setCurrentFont();
1407 Inset * inset = e->inset;
1408 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1410 // Set position in front of inset
1412 cur.boundary(false);
1415 // Try to descend recursively inside the inset.
1416 Inset * edited = inset->editXY(cur, x, y);
1417 // FIXME: it is not clear that the test on position is needed
1418 // Remove it if/when semantics of editXY is clarified
1419 if (cur.text() == text_ && cur.pos() == e->pos) {
1420 // non-editable inset, set cursor after the inset if x is
1421 // nearer to that position (bug 9628)
1422 bool bound = false; // is modified by getPosNearX
1423 cur.pos() = getPosNearX(row, x, bound);
1424 cur.boundary(bound);
1425 cur.setCurrentFont();
1429 if (cur.top().text() == text_)
1430 cur.setCurrentFont();
1435 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1437 LASSERT(text_ == cur.text(), return);
1438 pit_type const pit = getPitNearY(y);
1439 LASSERT(pit != -1, return);
1441 ParagraphMetrics const & pm = par_metrics_[pit];
1443 int yy = pm.position() - pm.ascent();
1444 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1445 " pit: " << pit << " yy: " << yy);
1448 LBUFERR(pm.rows().size());
1449 for (; r < int(pm.rows().size()) - 1; ++r) {
1450 Row const & row = pm.rows()[r];
1451 if (int(yy + row.height()) > y)
1456 Row const & row = pm.rows()[r];
1458 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1462 pos_type const pos = getPosNearX(row, xx, bound);
1464 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1466 text_->setCursor(cur, pit, pos, true, bound);
1467 // remember new position.
1472 //takes screen x,y coordinates
1473 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1475 Paragraph const & par = text_->paragraphs()[pit];
1476 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1478 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1480 for (InsetList::Element const & e : par.insetList()) {
1481 LYXERR(Debug::DEBUG, "examining inset " << e.inset);
1483 if (insetCache.covers(e.inset, x, y)) {
1484 LYXERR(Debug::DEBUG, "Hit inset: " << e.inset);
1485 return const_cast<InsetList::Element *>(&e);
1489 LYXERR(Debug::DEBUG, "No inset hit. ");
1494 //takes screen x,y coordinates
1495 Inset * TextMetrics::checkInsetHit(int x, int y)
1497 pit_type const pit = getPitNearY(y);
1498 LASSERT(pit != -1, return 0);
1499 InsetList::Element * e = checkInsetHit(pit, x, y);
1508 int TextMetrics::cursorX(CursorSlice const & sl,
1509 bool boundary) const
1511 LASSERT(sl.text() == text_, return 0);
1513 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1514 if (pm.rows().empty())
1516 Row const & row = pm.getRow(sl.pos(), boundary);
1517 pos_type const pos = sl.pos();
1520 row.findElement(pos, boundary, x);
1526 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1528 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1529 ParagraphMetrics const & pm = parMetrics(sl.pit());
1530 if (pm.rows().empty())
1534 h -= parMetrics(0).rows()[0].ascent();
1535 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1536 h += parMetrics(pit).height();
1539 if (pos && boundary)
1541 size_t const rend = pm.pos2row(pos);
1542 for (size_t rit = 0; rit != rend; ++rit)
1543 h += pm.rows()[rit].height();
1544 h += pm.rows()[rend].ascent();
1549 // the cursor set functions have a special mechanism. When they
1550 // realize you left an empty paragraph, they will delete it.
1552 bool TextMetrics::cursorHome(Cursor & cur)
1554 LASSERT(text_ == cur.text(), return false);
1555 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1556 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1557 return text_->setCursor(cur, cur.pit(), row.pos());
1561 bool TextMetrics::cursorEnd(Cursor & cur)
1563 LASSERT(text_ == cur.text(), return false);
1564 // if not on the last row of the par, put the cursor before
1565 // the final space exept if I have a spanning inset or one string
1566 // is so long that we force a break.
1567 pos_type end = cur.textRow().endpos();
1569 // empty text, end-1 is no valid position
1571 bool boundary = false;
1572 if (end != cur.lastpos()) {
1573 if (!cur.paragraph().isLineSeparator(end-1)
1574 && !cur.paragraph().isNewline(end-1)
1575 && !cur.paragraph().isEnvSeparator(end-1))
1579 } else if (cur.paragraph().isEnvSeparator(end-1))
1581 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1585 void TextMetrics::deleteLineForward(Cursor & cur)
1587 LASSERT(text_ == cur.text(), return);
1588 if (cur.lastpos() == 0) {
1589 // Paragraph is empty, so we just go forward
1590 text_->cursorForward(cur);
1593 cur.selection(true); // to avoid deletion
1596 // What is this test for ??? (JMarc)
1597 if (!cur.selection())
1598 text_->deleteWordForward(cur);
1600 cap::cutSelection(cur, false);
1601 cur.checkBufferStructure();
1606 int TextMetrics::leftMargin(pit_type pit) const
1608 return leftMargin(pit, text_->paragraphs()[pit].size());
1612 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1614 ParagraphList const & pars = text_->paragraphs();
1616 LASSERT(pit >= 0, return 0);
1617 LASSERT(pit < int(pars.size()), return 0);
1618 Paragraph const & par = pars[pit];
1619 LASSERT(pos >= 0, return 0);
1620 LASSERT(pos <= par.size(), return 0);
1621 Buffer const & buffer = bv_->buffer();
1622 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1623 DocumentClass const & tclass = buffer.params().documentClass();
1624 Layout const & layout = par.layout();
1625 FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1627 docstring parindent = layout.parindent;
1631 if (text_->isMainText()) {
1632 l_margin += bv_->leftMargin();
1633 l_margin += bfm.signedWidth(tclass.leftmargin());
1636 int depth = par.getDepth();
1638 // find the next level paragraph
1639 pit_type newpar = text_->outerHook(pit);
1640 if (newpar != pit_type(pars.size())) {
1641 if (pars[newpar].layout().isEnvironment()) {
1642 int nestmargin = depth * nestMargin();
1643 if (text_->isMainText())
1644 nestmargin += changebarMargin();
1645 l_margin = max(leftMargin(newpar), nestmargin);
1646 // Remove the parindent that has been added
1647 // if the paragraph was empty.
1648 if (pars[newpar].empty() &&
1649 buffer.params().paragraph_separation ==
1650 BufferParams::ParagraphIndentSeparation) {
1651 docstring pi = pars[newpar].layout().parindent;
1652 l_margin -= bfm.signedWidth(pi);
1655 if (tclass.isDefaultLayout(par.layout())
1656 || tclass.isPlainLayout(par.layout())) {
1657 if (pars[newpar].params().noindent())
1660 parindent = pars[newpar].layout().parindent;
1665 // This happens after sections or environments in standard classes.
1666 // We have to check the previous layout at same depth.
1667 if (buffer.params().paragraph_separation ==
1668 BufferParams::ParagraphSkipSeparation)
1670 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1671 pit_type prev = text_->depthHook(pit, par.getDepth());
1672 if (par.layout() == pars[prev].layout()) {
1674 && pars[pit - 1].layout().nextnoindent)
1676 } else if (pars[prev].layout().nextnoindent)
1680 FontInfo const labelfont = text_->labelFont(par);
1681 FontMetrics const & lfm = theFontMetrics(labelfont);
1683 switch (layout.margintype) {
1684 case MARGIN_DYNAMIC:
1685 if (!layout.leftmargin.empty()) {
1686 l_margin += bfm.signedWidth(layout.leftmargin);
1688 if (!par.labelString().empty()) {
1689 l_margin += lfm.signedWidth(layout.labelindent);
1690 l_margin += lfm.width(par.labelString());
1691 l_margin += lfm.width(layout.labelsep);
1695 case MARGIN_MANUAL: {
1696 l_margin += lfm.signedWidth(layout.labelindent);
1697 // The width of an empty par, even with manual label, should be 0
1698 if (!par.empty() && pos >= par.beginOfBody()) {
1699 if (!par.getLabelWidthString().empty()) {
1700 docstring labstr = par.getLabelWidthString();
1701 l_margin += lfm.width(labstr);
1702 l_margin += lfm.width(layout.labelsep);
1708 case MARGIN_STATIC: {
1709 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1710 / (par.getDepth() + 4);
1714 case MARGIN_FIRST_DYNAMIC:
1715 if (layout.labeltype == LABEL_MANUAL) {
1716 // if we are at position 0, we are never in the body
1717 if (pos > 0 && pos >= par.beginOfBody())
1718 l_margin += lfm.signedWidth(layout.leftmargin);
1720 l_margin += lfm.signedWidth(layout.labelindent);
1722 // Special case to fix problems with
1724 || (layout.labeltype == LABEL_STATIC
1725 && layout.latextype == LATEX_ENVIRONMENT
1726 && !text_->isFirstInSequence(pit))) {
1727 l_margin += lfm.signedWidth(layout.leftmargin);
1728 } else if (!layout.labelIsAbove()) {
1729 l_margin += lfm.signedWidth(layout.labelindent);
1730 l_margin += lfm.width(layout.labelsep);
1731 l_margin += lfm.width(par.labelString());
1735 case MARGIN_RIGHT_ADDRESS_BOX: {
1737 // The left margin depends on the widest row in this paragraph.
1738 // This code is wrong because it depends on the rows, but at the
1739 // same time this function is used in redoParagraph to construct
1741 ParagraphMetrics const & pm = par_metrics_[pit];
1742 int minfill = max_width_;
1743 for (row : pm.rows())
1744 if (row.fill() < minfill)
1745 minfill = row.fill();
1746 l_margin += bfm.signedWidth(layout.leftmargin);
1747 l_margin += minfill;
1749 // also wrong, but much shorter.
1750 l_margin += max_width_ / 2;
1755 if (!par.params().leftIndent().zero())
1756 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1758 LyXAlignment align = par.getAlign();
1760 // set the correct parindent
1762 && (layout.labeltype == LABEL_NO_LABEL
1763 || layout.labeltype == LABEL_ABOVE
1764 || layout.labeltype == LABEL_CENTERED
1765 || (layout.labeltype == LABEL_STATIC
1766 && layout.latextype == LATEX_ENVIRONMENT
1767 && !text_->isFirstInSequence(pit)))
1768 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1769 && !par.params().noindent()
1770 // in some insets, paragraphs are never indented
1771 && !text_->inset().neverIndent()
1772 // display style insets are always centered, omit indentation
1775 && par.getInset(pos)->display())
1776 && (!(tclass.isDefaultLayout(par.layout())
1777 || tclass.isPlainLayout(par.layout()))
1778 || buffer.params().paragraph_separation
1779 == BufferParams::ParagraphIndentSeparation)) {
1780 /* use the parindent of the layout when the default
1781 * indentation is used otherwise use the indentation set in
1782 * the document settings
1784 if (buffer.params().getParIndent().empty())
1785 l_margin += bfm.signedWidth(parindent);
1787 l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1794 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1796 if (par_metrics_.empty())
1802 y -= par_metrics_.begin()->second.ascent();
1803 for (auto & pm_pair : par_metrics_) {
1804 pit_type const pit = pm_pair.first;
1805 ParagraphMetrics & pm = pm_pair.second;
1807 // Save the paragraph position in the cache.
1809 drawParagraph(pi, pit, x, y);
1815 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1817 ParagraphMetrics const & pm = par_metrics_[pit];
1818 if (pm.rows().empty())
1820 size_t const nrows = pm.rows().size();
1822 // Use fast lane in nodraw stage.
1823 if (pi.pain.isNull()) {
1824 for (size_t i = 0; i != nrows; ++i) {
1826 Row const & row = pm.rows()[i];
1827 // Adapt to cursor row scroll offset if applicable.
1828 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1832 RowPainter rp(pi, *text_, row, row_x, y);
1834 rp.paintOnlyInsets();
1840 int const ww = bv_->workHeight();
1841 Cursor const & cur = bv_->cursor();
1842 DocIterator sel_beg = cur.selectionBegin();
1843 DocIterator sel_end = cur.selectionEnd();
1844 bool selection = cur.selection()
1845 // This is our text.
1846 && cur.text() == text_
1847 // if the anchor is outside, this is not our selection
1848 && cur.normalAnchor().text() == text_
1849 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1851 // We store the begin and end pos of the selection relative to this par
1852 DocIterator sel_beg_par = cur.selectionBegin();
1853 DocIterator sel_end_par = cur.selectionEnd();
1855 // We care only about visible selection.
1857 if (pit != sel_beg.pit()) {
1858 sel_beg_par.pit() = pit;
1859 sel_beg_par.pos() = 0;
1861 if (pit != sel_end.pit()) {
1862 sel_end_par.pit() = pit;
1863 sel_end_par.pos() = sel_end_par.lastpos();
1867 for (size_t i = 0; i != nrows; ++i) {
1869 Row const & row = pm.rows()[i];
1870 // Adapt to cursor row scroll offset if applicable.
1871 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
1875 // It is not needed to draw on screen if we are not inside.
1876 bool const inside = (y + row.descent() >= 0
1877 && y - row.ascent() < ww);
1879 // Inset positions have already been set in nodraw stage.
1885 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
1887 row.clearSelectionAndMargins();
1889 // The row knows nothing about the paragraph, so we have to check
1890 // whether this row is the first or last and update the margins.
1891 if (row.selection()) {
1892 if (row.sel_beg == 0)
1893 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
1894 if (row.sel_end == sel_end_par.lastpos())
1895 row.change(row.end_margin_sel, sel_end.pit() > pit);
1898 // Take this opportunity to spellcheck the row contents.
1899 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
1900 text_->getPar(pit).spellCheck();
1903 RowPainter rp(pi, *text_, row, row_x, y);
1905 // Don't paint the row if a full repaint has not been requested
1906 // and if it has not changed.
1907 if (!pi.full_repaint && !row.changed()) {
1908 // Paint only the insets if the text itself is
1910 rp.paintOnlyInsets();
1916 // Clear background of this row if paragraph background was not
1917 // already cleared because of a full repaint.
1918 if (!pi.full_repaint && row.changed()) {
1919 LYXERR(Debug::PAINTING, "Clear rect@("
1920 << max(row_x, 0) << ", " << y - row.ascent() << ")="
1921 << width() << " x " << row.height());
1922 // FIXME: this is a hack. We know that at least this
1923 // amount of pixels can be cleared on right and left.
1924 // Doing so gets rid of caret ghosts when the cursor is at
1925 // the begining/end of row. However, it will not work if
1926 // the caret has a ridiculous width like 6. (see ticket
1928 pi.pain.fillRectangle(max(row_x, 0) - Inset::TEXT_TO_INSET_OFFSET,
1930 width() + 2 * Inset::TEXT_TO_INSET_OFFSET,
1931 row.height(), pi.background_color);
1934 // Instrumentation for testing row cache (see also
1936 if (lyxerr.debugging(Debug::PAINTING)
1937 && (row.selection() || pi.full_repaint || row.changed())) {
1938 string const foreword = text_->isMainText() ? "main text redraw "
1939 : "inset text redraw: ";
1940 LYXERR0(foreword << "pit=" << pit << " row=" << i
1941 << (row.selection() ? " row_selection": "")
1942 << (pi.full_repaint ? " full_repaint" : "")
1943 << (row.changed() ? " row.changed" : ""));
1946 // Backup full_repaint status and force full repaint
1947 // for inner insets as the Row has been cleared out.
1948 bool tmp = pi.full_repaint;
1949 pi.full_repaint = true;
1951 rp.paintSelection();
1954 if (row.needsChangeBar())
1955 rp.paintChangeBar();
1961 rp.paintTooLargeMarks(row_x + row.left_x() < 0,
1962 row_x + row.right_x() > bv_->workWidth());
1966 // This debug code shows on screen which rows are repainted.
1967 // FIXME: since the updates related to caret blinking restrict
1968 // the painter to a small rectangle, the numbers are not
1969 // updated when this happens. Change the code in
1970 // GuiWorkArea::Private::show/hideCaret if this is important.
1971 static int count = 0;
1973 FontInfo fi(sane_font);
1974 fi.setSize(FONT_SIZE_TINY);
1975 fi.setColor(Color_red);
1976 pi.pain.text(row_x, y, convert<docstring>(count), fi);
1979 // Restore full_repaint status.
1980 pi.full_repaint = tmp;
1985 //LYXERR(Debug::PAINTING, ".");
1989 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
1990 Dimension & dim) const
1992 Cursor const & bvcur = cur.bv().cursor();
1994 // get word in front of cursor
1995 docstring word = text_->previousWord(bvcur.top());
1996 DocIterator wordStart = bvcur;
1997 wordStart.pos() -= word.length();
1999 // calculate dimensions of the word
2001 row.pit(bvcur.pit());
2002 row.pos(wordStart.pos());
2003 row.endpos(bvcur.pos());
2007 // get position on screen of the word start and end
2008 //FIXME: Is it necessary to explicitly set this to false?
2009 wordStart.boundary(false);
2010 Point lxy = cur.bv().getPos(wordStart);
2011 Point rxy = cur.bv().getPos(bvcur);
2012 dim.wid = abs(rxy.x_ - lxy.x_);
2014 // calculate position of word
2016 x = min(rxy.x_, lxy.x_);
2018 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2019 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2022 int defaultRowHeight()
2024 return int(theFontMetrics(sane_font).maxHeight() * 1.2);