]> git.lyx.org Git - lyx.git/blob - src/TextMetrics.cpp
Introduce new helpers ParagraphMetrics::top/bottom
[lyx.git] / src / TextMetrics.cpp
1 /**
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.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Jürgen Vigna
13  * \author Abdelrazak Younes
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "TextMetrics.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CoordCache.h"
26 #include "Cursor.h"
27 #include "CutAndPaste.h"
28 #include "Layout.h"
29 #include "LyXRC.h"
30 #include "MetricsInfo.h"
31 #include "ParagraphParameters.h"
32 #include "RowPainter.h"
33 #include "Session.h"
34 #include "Text.h"
35 #include "TextClass.h"
36 #include "VSpace.h"
37
38 #include "insets/InsetSeparator.h"
39 #include "insets/InsetText.h"
40
41 #include "mathed/MacroTable.h"
42
43 #include "frontends/FontMetrics.h"
44 #include "frontends/NullPainter.h"
45
46 #include "support/debug.h"
47 #include "support/lassert.h"
48 #include "support/Changer.h"
49
50 #include <stdlib.h>
51 #include <cmath>
52
53 using namespace std;
54
55
56 namespace lyx {
57
58 using frontend::FontMetrics;
59
60 namespace {
61
62
63 int numberOfLabelHfills(Paragraph const & par, Row const & row)
64 {
65         pos_type last = row.endpos() - 1;
66         pos_type first = row.pos();
67
68         // hfill *DO* count at the beginning of paragraphs!
69         if (first) {
70                 while (first < last && par.isHfill(first))
71                         ++first;
72         }
73
74         last = min(last, par.beginOfBody());
75         int n = 0;
76         for (pos_type p = first; p < last; ++p) {
77                 if (par.isHfill(p))
78                         ++n;
79         }
80         return n;
81 }
82
83 // FIXME: this needs to be rewritten, probably by merging it into some
84 // code that, besides counting, sets the active status of the space
85 // inset in the row element.
86 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
87                    pos_type const body_pos)
88 {
89         int n = 0;
90         Row::const_iterator cit = row.begin();
91         Row::const_iterator const end = row.end();
92         for ( ; cit != end ; ++cit)
93                 if (cit->pos >= body_pos
94                     && cit->inset && pm.hfillExpansion(row, cit->pos))
95                         ++n;
96         return n;
97 }
98
99
100 } // namespace
101
102 /////////////////////////////////////////////////////////////////////
103 //
104 // TextMetrics
105 //
106 /////////////////////////////////////////////////////////////////////
107
108
109 TextMetrics::TextMetrics(BufferView * bv, Text * text)
110         : bv_(bv), text_(text), dim_(bv_->workWidth(), 10, 10),
111           max_width_(dim_.wid), tight_(false)
112 {}
113
114
115 bool TextMetrics::contains(pit_type pit) const
116 {
117         return par_metrics_.find(pit) != par_metrics_.end();
118 }
119
120
121 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
122 {
123         ParMetricsCache::const_iterator it = par_metrics_.begin();
124         return make_pair(it->first, &it->second);
125 }
126
127
128 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
129 {
130         LBUFERR(!par_metrics_.empty());
131         ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
132         return make_pair(it->first, &it->second);
133 }
134
135
136 bool TextMetrics::isLastRow(Row const & row) const
137 {
138         ParagraphList const & pars = text_->paragraphs();
139         return row.endpos() >= pars[row.pit()].size()
140                 && row.pit() + 1 == pit_type(pars.size());
141 }
142
143
144 bool TextMetrics::isFirstRow(Row const & row) const
145 {
146         return row.pos() == 0 && row.pit() == 0;
147 }
148
149
150 void TextMetrics::setRowChanged(pit_type pit, pos_type pos)
151 {
152         for (auto & pm_pair : par_metrics_)
153                 if (pm_pair.first == pit)
154                         for (Row & row : pm_pair.second.rows())
155                                 if (row.pos() == pos)
156                                         row.changed(true);
157 }
158
159
160 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
161 {
162         ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
163         if (pmc_it == par_metrics_.end()) {
164                 pmc_it = par_metrics_.insert(
165                         make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
166         }
167         if (pmc_it->second.rows().empty() && redo)
168                 redoParagraph(pit);
169         return pmc_it->second;
170 }
171
172
173 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
174 {
175         return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
176 }
177
178
179 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit)
180 {
181         return parMetrics(pit, true);
182 }
183
184
185 void TextMetrics::newParMetricsDown()
186 {
187         pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
188         pit_type const pit = last.first + 1;
189         if (pit == int(text_->paragraphs().size()))
190                 return;
191
192         // do it and update its position.
193         redoParagraph(pit);
194         par_metrics_[pit].setPosition(last.second.bottom() + par_metrics_[pit].ascent());
195         updatePosCache(pit);
196 }
197
198
199 void TextMetrics::newParMetricsUp()
200 {
201         pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
202         if (first.first == 0)
203                 return;
204
205         pit_type const pit = first.first - 1;
206         // do it and update its position.
207         redoParagraph(pit);
208         par_metrics_[pit].setPosition(first.second.top() - par_metrics_[pit].descent());
209         updatePosCache(pit);
210 }
211
212
213 bool TextMetrics::metrics(MetricsInfo const & mi, Dimension & dim, int min_width)
214 {
215         LBUFERR(mi.base.textwidth > 0);
216         max_width_ = mi.base.textwidth;
217         tight_ = mi.tight_insets;
218         // backup old dimension.
219         Dimension const old_dim = dim_;
220         // reset dimension.
221         dim_ = Dimension();
222         dim_.wid = min_width;
223         pit_type const npar = text_->paragraphs().size();
224         if (npar > 1 && !tight_)
225                 // If there is more than one row, expand the text to
226                 // the full allowable width.
227                 dim_.wid = max_width_;
228
229         //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
230         //      << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
231
232         bool changed = false;
233         int h = 0;
234         for (pit_type pit = 0; pit != npar; ++pit) {
235                 // create rows, but do not set alignment yet
236                 changed |= redoParagraph(pit, false);
237                 ParagraphMetrics const & pm = par_metrics_[pit];
238                 h += pm.height();
239                 if (dim_.wid < pm.width())
240                         dim_.wid = pm.width();
241         }
242
243         // Now set alignment for all rows (the width might not have been known before).
244         for (pit_type pit = 0; pit != npar; ++pit) {
245                 ParagraphMetrics & pm = par_metrics_[pit];
246                 for (Row & row : pm.rows())
247                         setRowAlignment(row, dim_.wid);
248         }
249
250         dim_.asc = par_metrics_[0].ascent();
251         dim_.des = h - dim_.asc;
252         //lyxerr << "dim_.wid " << dim_.wid << endl;
253         //lyxerr << "dim_.asc " << dim_.asc << endl;
254         //lyxerr << "dim_.des " << dim_.des << endl;
255
256         changed |= dim_ != old_dim;
257         dim = dim_;
258         return changed;
259 }
260
261
262 void TextMetrics::updatePosCache(pit_type pit) const
263 {
264         frontend::NullPainter np;
265         PainterInfo pi(bv_, np);
266         drawParagraph(pi, pit, origin_.x_, par_metrics_[pit].position());
267 }
268
269
270 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
271 {
272         return text_->isMainText() ? pm.rightMargin(*bv_) : 0;
273 }
274
275
276 int TextMetrics::rightMargin(pit_type const pit) const
277 {
278         return text_->isMainText() ? par_metrics_[pit].rightMargin(*bv_) : 0;
279 }
280
281
282 void TextMetrics::applyOuterFont(Font & font) const
283 {
284         FontInfo lf(font_.fontInfo());
285         lf.reduce(bv_->buffer().params().getFont().fontInfo());
286         font.fontInfo().realize(lf);
287 }
288
289
290 // This is an arbitrary magic value
291 static const pos_type force_label = -12345;
292
293 // if pos == force_label, this function will return the label font instead.
294 // This undocumented and only for use by labelDisplayFont()
295 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
296 {
297         LASSERT(pos >= 0 || pos == force_label, { static Font f; return f; });
298
299         ParagraphList const & pars = text_->paragraphs();
300         Paragraph const & par = pars[pit];
301         Layout const & layout = par.layout();
302         Buffer const & buffer = bv_->buffer();
303         // FIXME: broken?
304         BufferParams const & bparams = buffer.params();
305         bool const label = pos < par.beginOfBody() || pos == force_label;
306
307         Font f = (pos == force_label) ? Font(inherit_font, bparams.language)
308                                       : par.getFontSettings(bparams, pos);
309         FontInfo const & lf = label ? layout.labelfont : layout.font;
310
311         // We specialize the 95% common case:
312         if (!par.getDepth()) {
313                 if (!text_->isMainText())
314                         applyOuterFont(f);
315
316                 FontInfo rlf = label ? layout.reslabelfont : layout.resfont;
317
318                 // In case the default family has been customized
319                 if (lf.family() == INHERIT_FAMILY)
320                         rlf.setFamily(bparams.getFont().fontInfo().family());
321                 f.fontInfo().realize(rlf);
322                 return f;
323         }
324
325         // The uncommon case need not be optimized as much.
326         // FIXME : the two code paths seem different in function.
327         f.fontInfo().realize(lf);
328
329         if (!text_->isMainText())
330                 applyOuterFont(f);
331
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                 f.fontInfo().realize(text_->outerFont(pit).fontInfo());
337
338         // Realize with the fonts of lesser depth.
339         f.fontInfo().realize(bparams.getFont().fontInfo());
340
341         return f;
342 }
343
344
345 Font TextMetrics::labelDisplayFont(pit_type pit) const
346 {
347         return displayFont(pit, force_label);
348 }
349
350
351 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
352 {
353         if (!sl.text())
354                 return false;
355
356         int correction = 0;
357         if (boundary && sl.pos() > 0)
358                 correction = -1;
359
360         return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
361 }
362
363
364 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
365 {
366         // no RTL boundary at paragraph start
367         if (pos == 0)
368                 return false;
369
370         Font const & left_font = displayFont(pit, pos - 1);
371
372         return isRTLBoundary(pit, pos, left_font);
373 }
374
375
376 // isRTLBoundary returns false on a real end-of-line boundary,
377 // because otherwise the two boundary types get mixed up.
378 // This is the whole purpose of this being in TextMetrics.
379 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
380                 Font const & font) const
381 {
382         if (// no RTL boundary at paragraph start
383             pos == 0
384             // if the metrics have not been calculated, then we are not
385             // on screen and can safely ignore issues about boundaries.
386             || !contains(pit))
387                 return false;
388
389         ParagraphMetrics const & pm = par_metrics_[pit];
390         // no RTL boundary in empty paragraph
391         if (pm.rows().empty())
392                 return false;
393
394         pos_type const endpos = pm.getRow(pos - 1, false).endpos();
395         pos_type const startpos = pm.getRow(pos, false).pos();
396         // no RTL boundary at line start:
397         // abc\n   -> toggle to RTL ->    abc\n     (and not:    abc\n|
398         // |                              |                               )
399         if (pos == startpos && pos == endpos) // start of cur row, end of prev row
400                 return false;
401
402         Paragraph const & par = text_->getPar(pit);
403         // no RTL boundary at line break:
404         // abc|\n    -> move right ->   abc\n       (and not:    abc\n|
405         // FED                          FED|                     FED     )
406         if (startpos == pos && endpos == pos && endpos != par.size()
407                 && (par.isNewline(pos - 1)
408                         || par.isEnvSeparator(pos - 1)
409                         || par.isLineSeparator(pos - 1)
410                         || par.isSeparator(pos - 1)))
411                 return false;
412
413         bool const left = font.isVisibleRightToLeft();
414         bool right;
415         if (pos == par.size())
416                 right = par.isRTL(bv_->buffer().params());
417         else
418                 right = displayFont(pit, pos).isVisibleRightToLeft();
419
420         return left != right;
421 }
422
423
424 bool TextMetrics::redoParagraph(pit_type const pit, bool const align_rows)
425 {
426         Paragraph & par = text_->getPar(pit);
427         // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
428         // redoParagraph() recursively inside parMetrics.
429         Dimension old_dim = parMetrics(pit, false).dim();
430         ParagraphMetrics & pm = par_metrics_[pit];
431         pm.reset(par);
432
433         Buffer & buffer = bv_->buffer();
434         bool changed = false;
435
436         // Check whether there are InsetBibItems that need fixing
437         // FIXME: This check ought to be done somewhere else. It is the reason
438         // why text_ is not const. But then, where else to do it?
439         // Well, how can you end up with either (a) a biblio environment that
440         // has no InsetBibitem, (b) a biblio environment with more than one
441         // InsetBibitem or (c) a paragraph that has a bib item but is no biblio
442         // environment? I think the answer is: when paragraphs are merged;
443         // when layout is set; when material is pasted.
444         if (par.brokenBiblio()) {
445                 Cursor & cur = bv_->cursor();
446                 // In some cases, we do not know how to record undo
447                 if (&cur.inset() == &text_->inset())
448                         cur.recordUndo(pit, pit);
449
450                 int const moveCursor = par.fixBiblio(buffer);
451
452                 // Is it necessary to update the cursor?
453                 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
454                         if (moveCursor > 0)
455                                 cur.posForward();
456                         else if (moveCursor < 0 && cur.pos() >= -moveCursor)
457                                 cur.posBackward();
458                 }
459         }
460
461         // Optimisation: this is used in the next two loops
462         // so better to calculate that once here.
463         int const right_margin = rightMargin(pm);
464
465         // iterator pointing to paragraph to resolve macros
466         DocIterator parPos = text_->macrocontextPosition();
467         if (!parPos.empty())
468                 parPos.pit() = pit;
469         else {
470                 LYXERR(Debug::INFO, "MacroContext not initialised!"
471                         << " Going through the buffer again and hope"
472                         << " the context is better then.");
473                 // FIXME audit updateBuffer calls
474                 // This should not be here, but it is not clear yet where else it
475                 // should be.
476                 bv_->buffer().updateBuffer();
477                 parPos = text_->macrocontextPosition();
478                 LBUFERR(!parPos.empty());
479                 parPos.pit() = pit;
480         }
481
482         // redo insets
483         par.setBeginOfBody();
484         Font const bufferfont = buffer.params().getFont();
485         CoordCache::Insets & insetCache = bv_->coordCache().insets();
486         map <Inset const *, int> extrawidths;
487         for (auto const & e : par.insetList()) {
488                 // FIXME Doesn't this HAVE to be non-empty?
489                 // position already initialized?
490                 if (!parPos.empty()) {
491                         parPos.pos() = e.pos;
492
493                         // A macro template would normally not be visible
494                         // by itself. But the tex macro semantics allow
495                         // recursion, so we artifically take the context
496                         // after the macro template to simulate this.
497                         if (e.inset->lyxCode() == MATHMACRO_CODE)
498                                 parPos.pos()++;
499                 }
500
501                 // If there is an end of paragraph marker, its size should be
502                 // substracted to the available width. The logic here is
503                 // almost the same as in tokenizeParagraph, remember keep them in sync.
504                 int eop = 0;
505                 if (e.pos + 1 == par.size()
506                       && (lyxrc.paragraph_markers || par.lookupChange(par.size()).changed())
507                       && size_type(pit + 1) < text_->paragraphs().size()) {
508                         Font f(text_->layoutFont(pit));
509                         // ¶ U+00B6 PILCROW SIGN
510                         eop = theFontMetrics(f).width(char_type(0x00B6));
511                 }
512
513                 // do the metric calculation
514                 Dimension dim;
515                 int const w = max_width_ - leftMargin(pit, e.pos)
516                         - right_margin - eop;
517                 Font const & font = e.inset->inheritFont() ?
518                         displayFont(pit, e.pos) : bufferfont;
519                 MacroContext mc(&buffer, parPos);
520                 MetricsInfo mi(bv_, font.fontInfo(), w, mc, e.pos == 0, tight_);
521                 mi.base.outer_font = displayFont(pit, e.pos).fontInfo();
522                 e.inset->metrics(mi, dim);
523                 /* FIXME: This is a hack. This allows InsetMathHull to state
524                  * that it needs some elbow room beyond its width, in order to
525                  * fit the numbering and/or the left margin (with left
526                  * alignment), which are outside of the inset itself.
527                  *
528                  * To this end, InsetMathHull::metrics() sets a value in
529                  * MetricsInfo::extrawidth and this value is added later to
530                  * the width of the row that contains the inset (when this row
531                  * is tight or shorter than the max allowed width).
532                  *
533                  * See ticket #12320 for details.
534                 */
535                 extrawidths[e.inset] = mi.extrawidth;
536
537                 if (!insetCache.has(e.inset) || insetCache.dim(e.inset) != dim) {
538                         insetCache.add(e.inset, dim);
539                         changed = true;
540                 }
541         }
542
543         // Transform the paragraph into a single row containing all the elements.
544         Row const bigrow = tokenizeParagraph(pit);
545         // Split the row in several rows fitting in available width
546         pm.rows() = breakParagraph(bigrow);
547
548         // Add the needed extra width to the rows that contain the insets that request it
549         for (Row & row : pm.rows())
550                 for (Row::Element & e : row)
551                         if (e.type == Row::INSET && (row.width() < max_width_ || tight_))
552                                 row.dim().wid += extrawidths[e.inset];
553
554         /* If there is more than one row, expand the text to the full
555          * allowable width. This setting here is needed for the
556          * setRowAlignment() below. We do nothing when tight insets are
557          * requested.
558          */
559         if (pm.rows().size() > 1 && !tight_ && dim_.wid < max_width_)
560                         dim_.wid = max_width_;
561
562         // Compute height and alignment of the rows.
563         for (Row & row : pm.rows()) {
564                 setRowHeight(row);
565                 if (align_rows)
566                         setRowAlignment(row, max(dim_.wid, row.width()));
567
568                 pm.dim().wid = max(pm.dim().wid, row.width() + row.right_margin);
569                 pm.dim().des += row.height();
570         }
571
572         // This type of margin can only be handled at the global paragraph level
573         if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX) {
574                 int offset = 0;
575                 if (par.isRTL(buffer.params())) {
576                         // globally align the paragraph to the left.
577                         int minleft = max_width_;
578                         for (Row const & row : pm.rows())
579                                 minleft = min(minleft, row.left_margin);
580                         offset = right_margin - minleft;
581                 } else {
582                         // globally align the paragraph to the right.
583                         int maxwid = 0;
584                         for (Row const & row : pm.rows())
585                                 maxwid = max(maxwid, row.width());
586                         offset = max_width_ - right_margin - maxwid;
587                 }
588
589                 for (Row & row : pm.rows()) {
590                         row.left_margin += offset;
591                         row.dim().wid += offset;
592                 }
593         }
594
595         // The space above and below the paragraph.
596         int top = parTopSpacing(pit);
597         int bottom = parBottomSpacing(pit);
598
599         // Top and bottom margin of the document (only at top-level)
600         // FIXME: It might be better to move this in another method
601         // specially tailored for the main text.
602         if (text_->isMainText()) {
603                 if (pit == 0)
604                         top += bv_->topMargin();
605                 if (pit + 1 == pit_type(text_->paragraphs().size())) {
606                         bottom += bv_->bottomMargin();
607                 }
608         }
609
610         // Add the top/bottom space to rows and paragraph metrics
611         pm.rows().front().dim().asc += top;
612         pm.rows().back().dim().des += bottom;
613         pm.dim().des += top + bottom;
614
615         // Move the pm ascent to be the same as the first row ascent
616         pm.dim().asc += pm.rows().front().ascent();
617         pm.dim().des -= pm.rows().front().ascent();
618
619         changed |= old_dim.height() != pm.dim().height();
620
621         return changed;
622 }
623
624
625 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
626 {
627         LyXAlignment align = par.getAlign(bv_->buffer().params());
628
629         // handle alignment inside tabular cells
630         Inset const & owner = text_->inset();
631         bool forced_block = false;
632         switch (owner.contentAlignment()) {
633         case LYX_ALIGN_BLOCK:
634                 // In general block align is the default state, but here it is
635                 // an explicit choice. Therefore it should not be overridden
636                 // later.
637                 forced_block = true;
638                 // fall through
639         case LYX_ALIGN_CENTER:
640         case LYX_ALIGN_LEFT:
641         case LYX_ALIGN_RIGHT:
642                 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
643                         align = owner.contentAlignment();
644                 break;
645         default:
646                 // unchanged (use align)
647                 break;
648         }
649
650         // Display-style insets should always be on a centered row
651         if (Inset const * inset = par.getInset(row.pos())) {
652                 if (inset->rowFlags() & Display) {
653                         if (inset->rowFlags() & AlignLeft)
654                                 align = LYX_ALIGN_LEFT;
655                         else if (inset->rowFlags() & AlignRight)
656                                 align = LYX_ALIGN_RIGHT;
657                         else
658                                 align = LYX_ALIGN_CENTER;
659                 }
660         }
661
662         if (align == LYX_ALIGN_BLOCK) {
663                 // If this row has been broken abruptly by a display inset, or
664                 // it is the end of the paragraph, or the user requested we
665                 // not justify stuff, then don't stretch.
666                 // A forced block alignment can only be overridden the 'no
667                 // justification on screen' setting.
668                 if ((row.flushed() && !forced_block)
669                     || !bv_->buffer().params().justification)
670                         align = row.isRTL() ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
671         }
672
673         return align;
674 }
675
676
677 void TextMetrics::setRowAlignment(Row & row, int width) const
678 {
679         row.label_hfill = 0;
680         row.separator = 0;
681
682         Paragraph const & par = text_->getPar(row.pit());
683
684         int const w = width - row.right_margin - row.width();
685         // FIXME: put back this assertion when the crash on new doc is solved.
686         //LASSERT(w >= 0, /**/);
687
688         // is there a manual margin with a manual label
689         Layout const & layout = par.layout();
690
691         int nlh = 0;
692         if (layout.margintype == MARGIN_MANUAL
693             && layout.labeltype == LABEL_MANUAL) {
694                 /// We might have real hfills in the label part
695                 nlh = numberOfLabelHfills(par, row);
696
697                 // A manual label par (e.g. List) has an auto-hfill
698                 // between the label text and the body of the
699                 // paragraph too.
700                 // But we don't want to do this auto hfill if the par
701                 // is empty.
702                 if (!par.empty())
703                         ++nlh;
704
705                 if (nlh && !par.getLabelWidthString().empty())
706                         row.label_hfill = labelFill(row) / double(nlh);
707         }
708
709         // are there any hfills in the row?
710         ParagraphMetrics const & pm = par_metrics_[row.pit()];
711         int nh = numberOfHfills(row, pm, par.beginOfBody());
712         int hfill = 0;
713         int hfill_rem = 0;
714
715         // We don't have to look at the alignment if the row is already
716         // larger then the permitted width as then we force the
717         // LEFT_ALIGN'edness!
718         if (row.width() >= max_width_)
719                 return;
720
721         if (nh == 0) {
722                 // Common case : there is no hfill, and the alignment will be
723                 // meaningful
724                 switch (getAlign(par, row)) {
725                 case LYX_ALIGN_BLOCK:
726                         // Expand expanding characters by a total of w
727                         if (!row.setExtraWidth(w) && row.isRTL()) {
728                                 // Justification failed and the text is RTL: align to the right
729                                 row.left_margin += w;
730                                 row.dim().wid += w;
731                         }
732                         break;
733                 case LYX_ALIGN_LEFT:
734                         // a displayed inset that is flushed
735                         if (Inset const * inset = par.getInset(row.pos())) {
736                                 row.left_margin += inset->indent(*bv_);
737                                 row.dim().wid += inset->indent(*bv_);
738                         }
739                         break;
740                 case LYX_ALIGN_RIGHT:
741                         if (Inset const * inset = par.getInset(row.pos())) {
742                                 int const new_w = max(w - inset->indent(*bv_), 0);
743                                 row.left_margin += new_w;
744                                 row.dim().wid += new_w;
745                         } else {
746                                 row.left_margin += w;
747                                 row.dim().wid += w;
748                         }
749                         break;
750                 case LYX_ALIGN_CENTER:
751                         row.dim().wid += w / 2;
752                         row.left_margin += w / 2;
753                         break;
754                 case LYX_ALIGN_NONE:
755                 case LYX_ALIGN_LAYOUT:
756                 case LYX_ALIGN_SPECIAL:
757                 case LYX_ALIGN_DECIMAL:
758                         break;
759                 }
760                 return;
761         }
762
763         // Case nh > 0. There are hfill separators.
764         hfill = w / nh;
765         hfill_rem = w % nh;
766         row.dim().wid += w;
767         // Set size of hfill insets
768         pos_type const endpos = row.endpos();
769         pos_type body_pos = par.beginOfBody();
770         if (body_pos > 0
771             && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
772                 body_pos = 0;
773
774         CoordCache::Insets & insetCache = bv_->coordCache().insets();
775         for (Row::Element & e : row) {
776                 if (row.label_hfill && e.endpos == body_pos
777                     && e.type == Row::SPACE)
778                         e.dim.wid -= int(row.label_hfill * (nlh - 1));
779                 if (e.inset && pm.hfillExpansion(row, e.pos)) {
780                         if (e.pos >= body_pos) {
781                                 e.dim.wid += hfill;
782                                 --nh;
783                                 if (nh == 0)
784                                         e.dim.wid += hfill_rem;
785                         } else
786                                 e.dim.wid += int(row.label_hfill);
787                         // Cache the inset dimension.
788                         insetCache.add(e.inset, e.dim);
789                 }
790         }
791 }
792
793
794 int TextMetrics::labelFill(Row const & row) const
795 {
796         Paragraph const & par = text_->getPar(row.pit());
797         LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
798
799         int w = 0;
800         // iterate over elements before main body (except the last one,
801         // which is extra space).
802         for (Row::Element const & e : row) {
803                 if (e.endpos >= par.beginOfBody())
804                         break;
805                 w += e.dim.wid;
806         }
807
808         docstring const & label = par.params().labelWidthString();
809         if (label.empty())
810                 return 0;
811
812         FontMetrics const & fm
813                 = theFontMetrics(text_->labelFont(par));
814
815         return max(0, fm.width(label) - w);
816 }
817
818
819 namespace {
820
821 /**
822  * Calling Text::getFont is slow. While rebreaking we scan a
823  * paragraph from left to right calling getFont for every char.  This
824  * simple class address this problem by hidding an optimization trick
825  * (not mine btw -AB): the font is reused in the whole font span.  The
826  * class handles transparently the "hidden" (not part of the fontlist)
827  * label font (as getFont does).
828  **/
829 class FontIterator
830 {
831 public:
832         ///
833         FontIterator(TextMetrics const & tm,
834                 Paragraph const & par, pit_type pit, pos_type pos)
835                 : tm_(tm), par_(par), pit_(pit), pos_(pos),
836                 font_(tm.displayFont(pit, pos)),
837                 endspan_(par.fontSpan(pos).last),
838                 bodypos_(par.beginOfBody())
839         {}
840
841         ///
842         Font const & operator*() const { return font_; }
843
844         ///
845         FontIterator & operator++()
846         {
847                 ++pos_;
848                 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
849                         font_ = tm_.displayFont(pit_, pos_);
850                         endspan_ = par_.fontSpan(pos_).last;
851                 }
852                 return *this;
853         }
854
855         ///
856         Font * operator->() { return &font_; }
857
858 private:
859         ///
860         TextMetrics const & tm_;
861         ///
862         Paragraph const & par_;
863         ///
864         pit_type pit_;
865         ///
866         pos_type pos_;
867         ///
868         Font font_;
869         ///
870         pos_type endspan_;
871         ///
872         pos_type bodypos_;
873 };
874
875 } // namespace
876
877
878 Row TextMetrics::tokenizeParagraph(pit_type const pit) const
879 {
880         Row row;
881         row.pit(pit);
882         Paragraph const & par = text_->getPar(pit);
883         Buffer const & buf = text_->inset().buffer();
884         BookmarksSection::BookmarkPosList bpl =
885                 theSession().bookmarks().bookmarksInPar(buf.fileName(), par.id());
886
887         pos_type const end = par.size();
888         pos_type const body_pos = par.beginOfBody();
889
890         // check for possible inline completion
891         DocIterator const & ic_it = bv_->inlineCompletionPos();
892         pos_type ic_pos = -1;
893         if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == pit)
894                 ic_pos = ic_it.pos();
895
896         // Now we iterate through until we reach the right margin
897         // or the end of the par, then build a representation of the row.
898         pos_type i = 0;
899         FontIterator fi = FontIterator(*this, par, pit, 0);
900         // The real stopping condition is a few lines below.
901         while (true) {
902                 // Firstly, check whether there is a bookmark here.
903                 if (lyxrc.bookmarks_visibility == LyXRC::BMK_INLINE)
904                         for (auto const & bp_p : bpl)
905                                 if (bp_p.second == i) {
906                                         Font f = *fi;
907                                         f.fontInfo().setColor(Color_bookmark);
908                                         // ❶ U+2776 DINGBAT NEGATIVE CIRCLED DIGIT ONE
909                                         char_type const ch = 0x2775 + bp_p.first;
910                                         row.addVirtual(i, docstring(1, ch), f, Change());
911                                 }
912
913                 // The stopping condition is here so that the display of a
914                 // bookmark can take place at paragraph start too.
915                 if (i >= end)
916                         break;
917
918                 char_type c = par.getChar(i);
919                 // The most special cases are handled first.
920                 if (par.isInset(i)) {
921                         Inset const * ins = par.getInset(i);
922                         Dimension dim = bv_->coordCache().insets().dim(ins);
923                         row.add(i, ins, dim, *fi, par.lookupChange(i));
924                 } else if (c == ' ' && i + 1 == body_pos) {
925                         // This space is an \item separator. Represent it with a
926                         // special space element, which dimension will be computed
927                         // in breakRow.
928                         FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
929                         int const wid = fm.width(par.layout().labelsep);
930                         row.addMarginSpace(i, wid, *fi, par.lookupChange(i));
931                 } else if (c == '\t')
932                         row.addSpace(i, theFontMetrics(*fi).width(from_ascii("    ")),
933                                      *fi, par.lookupChange(i));
934                 else if (c == 0x2028 || c == 0x2029) {
935                         /**
936                          * U+2028 LINE SEPARATOR
937                          * U+2029 PARAGRAPH SEPARATOR
938
939                          * These are special unicode characters that break
940                          * lines/pragraphs. Not handling them leads to trouble wrt
941                          * Qt QTextLayout formatting. We add a visible character
942                          * on screen so that the user can see that something is
943                          * happening.
944                         */
945                         row.finalizeLast();
946                         // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
947                         // ¶ U+00B6 PILCROW SIGN
948                         char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
949                         row.add(i, screen_char, *fi, par.lookupChange(i));
950                 } else
951                         // row elements before body are unbreakable
952                         row.add(i, c, *fi, par.lookupChange(i));
953
954                 // add inline completion width
955                 // draw logically behind the previous character
956                 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
957                         docstring const comp = bv_->inlineCompletion();
958                         size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
959                         Font f = *fi;
960
961                         if (uniqueTo > 0) {
962                                 f.fontInfo().setColor(Color_inlinecompletion);
963                                 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
964                         }
965                         f.fontInfo().setColor(Color_nonunique_inlinecompletion);
966                         row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
967                 }
968
969                 ++i;
970                 ++fi;
971         }
972         row.finalizeLast();
973         row.endpos(end);
974
975         // End of paragraph marker, either if LyXRc requires it, or there
976         // is an end of paragraph change. The logic here is almost the
977         // same as in redoParagraph, remember keep them in sync.
978         ParagraphList const & pars = text_->paragraphs();
979         Change const & endchange = par.lookupChange(end);
980         if (endchange.changed())
981                 row.needsChangeBar(true);
982         if ((lyxrc.paragraph_markers || endchange.changed())
983             && size_type(pit + 1) < pars.size()) {
984                 // add a virtual element for the end-of-paragraph
985                 // marker; it is shown on screen, but does not exist
986                 // in the paragraph.
987                 Font f(text_->layoutFont(pit));
988                 f.fontInfo().setColor(Color_paragraphmarker);
989                 f.setLanguage(par.getParLanguage(buf.params()));
990                 // ¶ U+00B6 PILCROW SIGN
991                 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, endchange);
992         }
993
994         return row;
995 }
996
997
998 namespace {
999
1000 /** Helper template flexible_const_iterator<T>
1001  * A way to iterate over a const container, but insert fake elements in it.
1002  * In the case of a row, we will have to break some elements, which
1003  * create new ones. This class allows to abstract this.
1004  * Only the required parts are implemented for now.
1005  */
1006 template<class T>
1007 class flexible_const_iterator {
1008         typedef typename T::value_type value_type;
1009 public:
1010
1011         //
1012         flexible_const_iterator & operator++() {
1013                 if (pile_.empty())
1014                         ++cit_;
1015                 else
1016                         pile_.pop_back();
1017                 return *this;
1018         }
1019
1020         value_type operator*() const { return pile_.empty() ? *cit_ : pile_.back(); }
1021
1022         value_type const * operator->() const { return pile_.empty() ? &*cit_ : &pile_.back(); }
1023
1024         void put(value_type const & e) { pile_.push_back(e); }
1025
1026         // Put a sequence of elements on the pile (in reverse order!)
1027         void put(vector<value_type> const & elts) {
1028                 pile_.insert(pile_.end(), elts.rbegin(), elts.rend());
1029         }
1030
1031 // This should be private, but declaring the friend functions is too much work
1032 //private:
1033         typename T::const_iterator cit_;
1034         // A vector that is used as like a pile to store the elements to
1035         // consider before incrementing the underlying iterator.
1036         vector<value_type> pile_;
1037 };
1038
1039
1040 template<class T>
1041 flexible_const_iterator<T> flexible_begin(T const & t)
1042 {
1043         return { t.begin(), vector<typename T::value_type>() };
1044 }
1045
1046
1047 template<class T>
1048 flexible_const_iterator<T> flexible_end(T const & t)
1049 {
1050         return { t.end(), vector<typename T::value_type>() };
1051 }
1052
1053
1054 // Equality is only possible if respective piles are empty
1055 template<class T>
1056 bool operator==(flexible_const_iterator<T> const & t1,
1057                 flexible_const_iterator<T> const & t2)
1058 {
1059         return t1.cit_ == t2.cit_ && t1.pile_.empty() && t2.pile_.empty();
1060 }
1061
1062
1063 Row newRow(TextMetrics const & tm, pit_type pit, pos_type pos, bool is_rtl)
1064 {
1065         Row nrow;
1066         nrow.pit(pit);
1067         nrow.pos(pos);
1068         nrow.left_margin = tm.leftMargin(pit, pos);
1069         nrow.right_margin = tm.rightMargin(pit);
1070         nrow.setRTL(is_rtl);
1071         if (is_rtl)
1072                 swap(nrow.left_margin, nrow.right_margin);
1073         // Remember that the row width takes into account the left_margin
1074         // but not the right_margin.
1075         nrow.dim().wid = nrow.left_margin;
1076         return nrow;
1077 }
1078
1079
1080 void cleanupRow(Row & row, bool at_end)
1081 {
1082         if (row.empty()) {
1083                 row.endpos(row.pos());
1084                 return;
1085         }
1086
1087         row.endpos(row.back().endpos);
1088         // remove trailing spaces on row break
1089         if (!at_end && !row.flushed())
1090                 row.back().rtrim();
1091         // boundary exists when there was no space at the end of row
1092         row.end_boundary(!at_end && row.back().endpos == row.endpos());
1093         // make sure that the RTL elements are in reverse ordering
1094         row.reverseRTL();
1095 }
1096
1097
1098 // Implement the priorities described in RowFlags.h.
1099 bool needsRowBreak(int f1, int f2)
1100 {
1101         if (f1 & AlwaysBreakAfter /*|| f2 & AlwaysBreakBefore*/)
1102                 return true;
1103         if (f1 & NoBreakAfter || f2 & NoBreakBefore)
1104                 return false;
1105         if (f1 & BreakAfter || f2 & BreakBefore)
1106                 return true;
1107         return false;
1108 }
1109
1110
1111 }
1112
1113
1114 RowList TextMetrics::breakParagraph(Row const & bigrow) const
1115 {
1116         RowList rows;
1117         bool const is_rtl = text_->isRTL(bigrow.pit());
1118         bool const end_label = text_->getEndLabel(bigrow.pit()) != END_LABEL_NO_LABEL;
1119         int const next_width = max_width_ - leftMargin(bigrow.pit(), bigrow.endpos())
1120                 - rightMargin(bigrow.pit());
1121
1122         int width = 0;
1123         flexible_const_iterator<Row> fcit = flexible_begin(bigrow);
1124         flexible_const_iterator<Row> const end = flexible_end(bigrow);
1125         while (true) {
1126                 bool const row_empty = rows.empty() || rows.back().empty();
1127                 // The row flags of previous element, if there is one.
1128                 // Otherwise we use NoBreakAfter to avoid an empty row before
1129                 // e.g. a displayed equation.
1130                 int const f1 = row_empty ? NoBreakAfter : rows.back().back().row_flags;
1131                 // The row flags of next element, if there is one.
1132                 // Otherwise we use NoBreakBefore (see above), unless the
1133                 // paragraph has an end label (for which an empty row is OK).
1134                 int const f2 = (fcit == end) ? (end_label ? Inline : NoBreakBefore)
1135                                              : fcit->row_flags;
1136                 if (rows.empty() || needsRowBreak(f1, f2)) {
1137                         if (!rows.empty()) {
1138                                 // Flush row as requested by row flags
1139                                 rows.back().flushed((f1 & Flush) || (f2 & FlushBefore));
1140                                 cleanupRow(rows.back(), false);
1141                         }
1142                         pos_type pos = rows.empty() ? 0 : rows.back().endpos();
1143                         rows.push_back(newRow(*this, bigrow.pit(), pos, is_rtl));
1144                         // the width available for the row.
1145                         width = max_width_ - rows.back().right_margin;
1146                 }
1147
1148                 // The stopping condition is here because we may need a new
1149                 // empty row at the end.
1150                 if (fcit == end)
1151                         break;
1152
1153                 // Next element to consider is either the top of the temporary
1154                 // pile, or the place when we were in main row
1155                 Row::Element elt = *fcit;
1156                 Row::Elements tail;
1157                 elt.splitAt(width - rows.back().width(), next_width, Row::FIT, tail);
1158                 Row & rb = rows.back();
1159                 if (elt.type == Row::MARGINSPACE)
1160                         elt.dim.wid = max(elt.dim.wid, leftMargin(bigrow.pit()) - rb.width());
1161                 rb.push_back(elt);
1162                 rb.finalizeLast();
1163                 if (rb.width() > width) {
1164                         // Keep the tail for later; this ought to be rare, but play safe.
1165                         if (!tail.empty())
1166                                 fcit.put(tail);
1167                         // if the row is too large, try to cut at last separator.
1168                         tail = rb.shortenIfNeeded(width, next_width);
1169                 }
1170
1171                 // Go to next element
1172                 ++fcit;
1173
1174                 // Handle later the elements returned by splitAt or shortenIfNeeded.
1175                 fcit.put(tail);
1176         }
1177
1178         if (!rows.empty()) {
1179                 // Last row in paragraph is flushed
1180                 rows.back().flushed(true);
1181                 cleanupRow(rows.back(), true);
1182                 // Is there an end-of-paragraph change?
1183                 if (bigrow.needsChangeBar())
1184                         rows.back().needsChangeBar(true);
1185         }
1186
1187         return rows;
1188 }
1189
1190
1191 int TextMetrics::parTopSpacing(pit_type const pit) const
1192 {
1193         Paragraph const & par = text_->getPar(pit);
1194         Layout const & layout = par.layout();
1195
1196         int asc = 0;
1197         ParagraphList const & pars = text_->paragraphs();
1198         double const dh = defaultRowHeight();
1199
1200         BufferParams const & bparams = bv_->buffer().params();
1201         Inset const & inset = text_->inset();
1202         // some parskips VERY EASY IMPLEMENTATION
1203         if (bparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1204                 && !inset.getLayout().parbreakIsNewline()
1205                 && !par.layout().parbreak_is_newline
1206                 && pit > 0
1207                 && ((layout.isParagraph() && par.getDepth() == 0)
1208                     || (pars[pit - 1].layout().isParagraph()
1209                         && pars[pit - 1].getDepth() == 0))) {
1210                 asc += bparams.getDefSkip().inPixels(*bv_);
1211         }
1212
1213         if (par.params().startOfAppendix())
1214                 asc += int(3 * dh);
1215
1216         // special code for the top label
1217         if (layout.labelIsAbove()
1218             && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1219             && !par.labelString().empty()) {
1220                 FontInfo labelfont = text_->labelFont(par);
1221                 FontMetrics const & lfm = theFontMetrics(labelfont);
1222                 asc += int(lfm.maxHeight() * layout.spacing.getValue()
1223                                            * text_->spacing(par)
1224                            + (layout.topsep + layout.labelbottomsep) * dh);
1225         }
1226
1227         // Add the layout spaces, for example before and after
1228         // a section, or between the items of a itemize or enumerate
1229         // environment.
1230
1231         pit_type prev = text_->depthHook(pit, par.getDepth());
1232         Paragraph const & prevpar = pars[prev];
1233         double layoutasc = 0;
1234         if (prev != pit
1235             && prevpar.layout() == layout
1236             && prevpar.getDepth() == par.getDepth()
1237             && prevpar.getLabelWidthString() == par.getLabelWidthString()) {
1238                 layoutasc = layout.itemsep * dh;
1239         } else if (pit != 0 && layout.topsep > 0)
1240                 // combine the separation between different layouts (with same depth)
1241                 layoutasc = max(0.0,
1242                         prevpar.getDepth() != par.getDepth() ? layout.topsep
1243                         : layout.topsep - prevpar.layout().bottomsep) * dh;
1244
1245         asc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1246
1247         prev = text_->outerHook(pit);
1248         if (prev != pit_type(pars.size())) {
1249                 asc += int(pars[prev].layout().parsep * dh);
1250         } else if (pit != 0) {
1251                 Paragraph const & prevpar2 = pars[pit - 1];
1252                 if (prevpar2.getDepth() != 0 || prevpar2.layout() == layout)
1253                         asc += int(layout.parsep * dh);
1254         }
1255
1256         return asc;
1257 }
1258
1259
1260 int TextMetrics::parBottomSpacing(pit_type const pit) const
1261 {
1262         double layoutdesc = 0;
1263         ParagraphList const & pars = text_->paragraphs();
1264         double const dh = defaultRowHeight();
1265
1266         // add the layout spaces, for example before and after
1267         // a section, or between the items of a itemize or enumerate
1268         // environment
1269         pit_type nextpit = pit + 1;
1270         if (nextpit != pit_type(pars.size())) {
1271                 pit_type cpit = pit;
1272
1273                 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1274                         double usual = pars[cpit].layout().bottomsep * dh;
1275                         double unusual = 0;
1276                         cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1277                         if (pars[cpit].layout() != pars[nextpit].layout()
1278                                 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1279                                 unusual = pars[cpit].layout().bottomsep * dh;
1280                         layoutdesc = max(unusual, usual);
1281                 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1282                         if (pars[cpit].layout() != pars[nextpit].layout()
1283                                 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1284                                 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1285                 }
1286         }
1287
1288         return int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1289 }
1290
1291
1292 void TextMetrics::setRowHeight(Row & row) const
1293 {
1294         Paragraph const & par = text_->getPar(row.pit());
1295         Layout const & layout = par.layout();
1296         // leading space (line spacing) factor based on current paragraph
1297         double spacing_val = layout.spacing.getValue() * text_->spacing(par);
1298
1299         // if this is the first row but not the first paragraph, take into
1300         // account the spacing of the previous paragraph.
1301         if (row.pos() == 0 && row.pit() > 0) {
1302                 // for the first row in the paragraph,
1303                 // use previous paragraphs line spacing if it is larger
1304                 Paragraph const & previousPar = text_->getPar(row.pit() - 1);
1305                 Layout const & previousLayout = previousPar.layout();
1306                 // leading space factor based on previous paragraph
1307                 double const previous_spacing_val
1308                         = previousLayout.spacing.getValue() * text_->spacing(previousPar);
1309                 if (previous_spacing_val > spacing_val)
1310                         spacing_val = previous_spacing_val;
1311         }
1312
1313         // Initial value for ascent (useful if row is empty).
1314         Font const font = displayFont(row.pit(), row.pos());
1315         FontMetrics const & fm = theFontMetrics(font);
1316         int maxasc = int(fm.maxAscent()
1317                 // add leading space
1318                 + fm.maxHeight() * (spacing_val - 1));
1319         int maxdes = int(fm.maxDescent());
1320
1321         // Take label string into account (useful if labelfont is large)
1322         if (row.pos() == 0 && layout.labelIsInline()) {
1323                 FontInfo const labelfont = text_->labelFont(par);
1324                 FontMetrics const & lfm = theFontMetrics(labelfont);
1325                 maxasc = max(maxasc, int(lfm.maxAscent()
1326                         // add leading space
1327                         + lfm.maxHeight() * (spacing_val - 1)));
1328                 maxdes = max(maxdes, int(lfm.maxDescent()));
1329         }
1330
1331         // Find the ascent/descent of the row contents
1332         for (Row::Element const & e : row) {
1333                 if (e.inset) {
1334                         maxasc = max(maxasc, e.dim.ascent());
1335                         maxdes = max(maxdes, e.dim.descent());
1336                 } else {
1337                         FontMetrics const & fm2 = theFontMetrics(e.font);
1338                         maxasc = max(maxasc, int(fm2.maxAscent()
1339                                 // add leading space
1340                                 + fm2.maxHeight() * (spacing_val - 1)));
1341                         maxdes = max(maxdes, int(fm2.maxDescent()));
1342                 }
1343         }
1344
1345         // This is nicer with box insets
1346         ++maxasc;
1347         ++maxdes;
1348
1349         row.dim().asc = maxasc;
1350         row.dim().des = maxdes;
1351
1352         // This is useful for selections
1353         row.contents_dim() = row.dim();
1354 }
1355
1356
1357 // x is an absolute screen coord
1358 // returns the column near the specified x-coordinate of the row
1359 // x is set to the real beginning of this column
1360 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1361                                   bool & boundary) const
1362 {
1363         //LYXERR0("getPosNearX(" << x << ") row=" << row);
1364         /// For the main Text, it is possible that this pit is not
1365         /// yet in the CoordCache when moving cursor up.
1366         /// x Paragraph coordinate is always 0 for main text anyway.
1367         int const xo = origin_.x_;
1368         x -= xo;
1369
1370         // Adapt to cursor row scroll offset if applicable.
1371         int const offset = bv_->horizScrollOffset(text_, row.pit(), row.pos());
1372         x += offset;
1373
1374         pos_type pos = row.pos();
1375         boundary = false;
1376         if (row.empty())
1377                 x = row.left_margin;
1378         else if (x <= row.left_margin) {
1379                 pos = row.front().left_pos();
1380                 x = row.left_margin;
1381         } else if (x >= row.width()) {
1382                 pos = row.back().right_pos();
1383                 x = row.width();
1384         } else {
1385                 double w = row.left_margin;
1386                 Row::const_iterator cit = row.begin();
1387                 Row::const_iterator cend = row.end();
1388                 for ( ; cit != cend; ++cit) {
1389                         if (w <= x &&  w + cit->full_width() > x) {
1390                                 int x_offset = int(x - w);
1391                                 pos = cit->x2pos(x_offset);
1392                                 x = int(x_offset + w);
1393                                 break;
1394                         }
1395                         w += cit->full_width();
1396                 }
1397                 if (cit == row.end()) {
1398                         pos = row.back().right_pos();
1399                         x = row.width();
1400                 }
1401                 /** This tests for the case where the cursor is placed
1402                  * just before a font direction change. See comment on
1403                  * the boundary_ member in DocIterator.h to understand
1404                  * how boundary helps here.
1405                  */
1406                 else if (pos == cit->endpos
1407                          && ((!cit->isRTL() && cit + 1 != row.end()
1408                               && (cit + 1)->isRTL())
1409                              || (cit->isRTL() && cit != row.begin()
1410                                  && !(cit - 1)->isRTL())))
1411                         boundary = true;
1412         }
1413
1414         /** This tests for the case where the cursor is set at the end
1415          * of a row which has been broken due something else than a
1416          * separator (a display inset or a forced breaking of the
1417          * row). We know that there is a separator when the end of the
1418          * row is larger than the end of its last element.
1419          */
1420         if (!row.empty() && pos == row.back().endpos
1421             && row.back().endpos == row.endpos()) {
1422                 Inset const * inset = row.back().inset;
1423                 if (inset && (inset->lyxCode() == NEWLINE_CODE
1424                               || inset->lyxCode() == SEPARATOR_CODE))
1425                         pos = row.back().pos;
1426                 else
1427                         boundary = row.end_boundary();
1428         }
1429
1430         x += xo - offset;
1431         //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1432
1433         return pos;
1434 }
1435
1436
1437 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1438 {
1439         // We play safe and use parMetrics(pit) to make sure the
1440         // ParagraphMetrics will be redone and OK to use if needed.
1441         // Otherwise we would use an empty ParagraphMetrics in
1442         // upDownInText() while in selection mode.
1443         ParagraphMetrics const & pm = parMetrics(pit);
1444
1445         LBUFERR(row < int(pm.rows().size()));
1446         bool bound = false;
1447         Row const & r = pm.rows()[row];
1448         return getPosNearX(r, x, bound);
1449 }
1450
1451
1452 // y is screen coordinate
1453 pit_type TextMetrics::getPitNearY(int y)
1454 {
1455         LASSERT(!text_->paragraphs().empty(), return -1);
1456         LASSERT(!par_metrics_.empty(), return -1);
1457         LYXERR(Debug::PAINTING, "y: " << y << " cache size: " << par_metrics_.size());
1458
1459         // look for highest numbered paragraph with y coordinate less than given y
1460         pit_type pit = -1;
1461         int yy = -1;
1462         ParMetricsCache::const_iterator it = par_metrics_.begin();
1463         ParMetricsCache::const_iterator et = par_metrics_.end();
1464         ParMetricsCache::const_iterator last = et;
1465         --last;
1466
1467         if (y < it->second.top()) {
1468                 // We are looking for a position that is before the first paragraph in
1469                 // the cache (which is in priciple off-screen, that is before the
1470                 // visible part.
1471                 if (it->first == 0)
1472                         // We are already at the first paragraph in the inset.
1473                         return 0;
1474                 // OK, this is the paragraph we are looking for.
1475                 pit = it->first - 1;
1476                 newParMetricsUp();
1477                 return pit;
1478         }
1479
1480         if (y >= par_metrics_[last->first].bottom()) {
1481                 // We are looking for a position that is after the last paragraph in
1482                 // the cache (which is in priciple off-screen), that is before the
1483                 // visible part.
1484                 pit = last->first + 1;
1485                 if (pit == int(text_->paragraphs().size()))
1486                         //  We are already at the last paragraph in the inset.
1487                         return last->first;
1488                 // OK, this is the paragraph we are looking for.
1489                 newParMetricsDown();
1490                 return pit;
1491         }
1492
1493         for (; it != et; ++it) {
1494                 LYXERR(Debug::PAINTING, "examining: pit: " << it->first
1495                         << " y: " << it->second.position());
1496
1497                 if (it->first >= pit && it->second.top() <= y) {
1498                         pit = it->first;
1499                         yy = it->second.position();
1500                 }
1501         }
1502
1503         LYXERR(Debug::PAINTING, "found best y: " << yy << " for pit: " << pit);
1504
1505         return pit;
1506 }
1507
1508
1509 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1510         bool assert_in_view, bool up)
1511 {
1512         ParagraphMetrics const & pm = par_metrics_[pit];
1513
1514         int yy = pm.top();
1515         LBUFERR(!pm.rows().empty());
1516         RowList::const_iterator rit = pm.rows().begin();
1517         RowList::const_iterator rlast = pm.rows().end();
1518         --rlast;
1519         for (; rit != rlast; yy += rit->height(), ++rit)
1520                 if (yy + rit->height() > y)
1521                         break;
1522
1523         if (assert_in_view) {
1524                 if (!up && yy + rit->height() > y) {
1525                         if (rit != pm.rows().begin()) {
1526                                 y = yy;
1527                                 --rit;
1528                         } else if (pit != 0) {
1529                                 --pit;
1530                                 newParMetricsUp();
1531                                 ParagraphMetrics const & pm2 = par_metrics_[pit];
1532                                 rit = pm2.rows().end();
1533                                 --rit;
1534                                 y = yy;
1535                         }
1536                 } else if (up && yy != y) {
1537                         if (rit != rlast) {
1538                                 y = yy + rit->height();
1539                                 ++rit;
1540                         } else if (pit < int(text_->paragraphs().size()) - 1) {
1541                                 ++pit;
1542                                 newParMetricsDown();
1543                                 ParagraphMetrics const & pm2 = par_metrics_[pit];
1544                                 rit = pm2.rows().begin();
1545                                 y = pm2.position();
1546                         }
1547                 }
1548         }
1549         return *rit;
1550 }
1551
1552
1553 // x,y are absolute screen coordinates
1554 // sets cursor recursively descending into nested editable insets
1555 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1556         bool assert_in_view, bool up)
1557 {
1558         if (lyxerr.debugging(Debug::WORKAREA)) {
1559                 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1560                 cur.bv().coordCache().dump();
1561         }
1562         pit_type pit = getPitNearY(y);
1563         LASSERT(pit != -1, return 0);
1564         Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1565         cur.pit() = pit;
1566
1567         // Do we cover an inset?
1568         InsetList::Element * e = checkInsetHit(pit, x, y);
1569
1570         if (!e) {
1571                 // No inset, set position in the text
1572                 bool bound = false; // is modified by getPosNearX
1573                 cur.pos() = getPosNearX(row, x, bound);
1574                 cur.boundary(bound);
1575                 cur.setCurrentFont();
1576                 cur.setTargetX(x);
1577                 return 0;
1578         }
1579
1580         Inset * inset = e->inset;
1581         //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1582
1583         // Set position in front of inset
1584         cur.pos() = e->pos;
1585         cur.boundary(false);
1586         cur.setTargetX(x);
1587
1588         // Try to descend recursively inside the inset.
1589         Inset * edited = inset->editXY(cur, x, y);
1590         // FIXME: it is not clear that the test on position is needed
1591         // Remove it if/when semantics of editXY is clarified
1592         if (cur.text() == text_ && cur.pos() == e->pos) {
1593                 // non-editable inset, set cursor after the inset if x is
1594                 // nearer to that position (bug 9628)
1595                 bool bound = false; // is modified by getPosNearX
1596                 cur.pos() = getPosNearX(row, x, bound);
1597                 cur.boundary(bound);
1598                 cur.setCurrentFont();
1599                 cur.setTargetX(x);
1600         }
1601
1602         if (cur.top().text() == text_)
1603                 cur.setCurrentFont();
1604         return edited;
1605 }
1606
1607
1608 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1609 {
1610         LASSERT(text_ == cur.text(), return);
1611         pit_type const pit = getPitNearY(y);
1612         LASSERT(pit != -1, return);
1613
1614         ParagraphMetrics const & pm = par_metrics_[pit];
1615
1616         int yy = pm.position() - pm.rows().front().ascent();
1617         LYXERR(Debug::PAINTING, "x: " << x << " y: " << y <<
1618                 " pit: " << pit << " yy: " << yy);
1619
1620         int r = 0;
1621         LBUFERR(pm.rows().size());
1622         for (; r < int(pm.rows().size()) - 1; ++r) {
1623                 Row const & row = pm.rows()[r];
1624                 if (yy + row.height() > y)
1625                         break;
1626                 yy += row.height();
1627         }
1628
1629         Row const & row = pm.rows()[r];
1630
1631         LYXERR(Debug::PAINTING, "row " << r << " from pos: " << row.pos());
1632
1633         bool bound = false;
1634         int xx = x;
1635         pos_type const pos = getPosNearX(row, xx, bound);
1636
1637         LYXERR(Debug::PAINTING, "setting cursor pit: " << pit << " pos: " << pos);
1638
1639         text_->setCursor(cur, pit, pos, true, bound);
1640         // remember new position.
1641         cur.setTargetX();
1642 }
1643
1644
1645 //takes screen x,y coordinates
1646 InsetList::Element * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1647 {
1648         Paragraph const & par = text_->paragraphs()[pit];
1649         CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1650
1651         LYXERR(Debug::PAINTING, "x: " << x << " y: " << y << "  pit: " << pit);
1652
1653         for (InsetList::Element const & e : par.insetList()) {
1654                 LYXERR(Debug::PAINTING, "examining inset " << e.inset);
1655
1656                 if (insetCache.covers(e.inset, x, y)) {
1657                         LYXERR(Debug::PAINTING, "Hit inset: " << e.inset);
1658                         return const_cast<InsetList::Element *>(&e);
1659                 }
1660         }
1661
1662         LYXERR(Debug::PAINTING, "No inset hit. ");
1663         return nullptr;
1664 }
1665
1666
1667 //takes screen x,y coordinates
1668 Inset * TextMetrics::checkInsetHit(int x, int y)
1669 {
1670         pit_type const pit = getPitNearY(y);
1671         LASSERT(pit != -1, return 0);
1672         InsetList::Element * e = checkInsetHit(pit, x, y);
1673
1674         if (!e)
1675                 return 0;
1676
1677         return e->inset;
1678 }
1679
1680
1681 int TextMetrics::cursorX(CursorSlice const & sl,
1682                 bool boundary) const
1683 {
1684         LASSERT(sl.text() == text_, return 0);
1685
1686         ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1687         if (pm.rows().empty())
1688                 return 0;
1689         Row const & row = pm.getRow(sl.pos(), boundary);
1690         pos_type const pos = sl.pos();
1691
1692         double x = 0;
1693         row.findElement(pos, boundary, x);
1694         return int(x);
1695
1696 }
1697
1698
1699 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1700 {
1701         //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1702         ParagraphMetrics const & pm = parMetrics(sl.pit());
1703         if (pm.rows().empty())
1704                 return 0;
1705
1706         int h = 0;
1707         h -= parMetrics(0).rows()[0].ascent();
1708         for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1709                 h += parMetrics(pit).height();
1710         }
1711         int pos = sl.pos();
1712         if (pos && boundary)
1713                 --pos;
1714         size_t const rend = pm.pos2row(pos);
1715         for (size_t rit = 0; rit != rend; ++rit)
1716                 h += pm.rows()[rit].height();
1717         h += pm.rows()[rend].ascent();
1718         return h;
1719 }
1720
1721
1722 // the cursor set functions have a special mechanism. When they
1723 // realize you left an empty paragraph, they will delete it.
1724
1725 bool TextMetrics::cursorHome(Cursor & cur)
1726 {
1727         LASSERT(text_ == cur.text(), return false);
1728         ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1729         Row const & row = pm.getRow(cur.pos(),cur.boundary());
1730         return text_->setCursor(cur, cur.pit(), row.pos());
1731 }
1732
1733
1734 bool TextMetrics::cursorEnd(Cursor & cur)
1735 {
1736         LASSERT(text_ == cur.text(), return false);
1737         // if not on the last row of the par, put the cursor before
1738         // the final space exept if I have a spanning inset or one string
1739         // is so long that we force a break.
1740         pos_type end = cur.textRow().endpos();
1741         if (end == 0)
1742                 // empty text, end-1 is no valid position
1743                 return false;
1744         bool boundary = false;
1745         if (end != cur.lastpos()) {
1746                 if (!cur.paragraph().isLineSeparator(end-1)
1747                     && !cur.paragraph().isNewline(end-1)
1748                     && !cur.paragraph().isEnvSeparator(end-1))
1749                         boundary = true;
1750                 else
1751                         --end;
1752         } else if (cur.paragraph().isEnvSeparator(end-1))
1753                 --end;
1754         return text_->setCursor(cur, cur.pit(), end, true, boundary);
1755 }
1756
1757
1758 void TextMetrics::deleteLineForward(Cursor & cur)
1759 {
1760         LASSERT(text_ == cur.text(), return);
1761         if (cur.lastpos() == 0) {
1762                 // Paragraph is empty, so we just go forward
1763                 text_->cursorForward(cur);
1764         } else {
1765                 cur.resetAnchor();
1766                 cur.selection(true); // to avoid deletion
1767                 cursorEnd(cur);
1768                 cur.setSelection();
1769                 // What is this test for ??? (JMarc)
1770                 if (!cur.selection())
1771                         text_->deleteWordForward(cur);
1772                 else
1773                         cap::cutSelection(cur, false);
1774                 cur.checkBufferStructure();
1775         }
1776 }
1777
1778
1779 int TextMetrics::leftMargin(pit_type pit) const
1780 {
1781         // FIXME: what is the semantics? It depends on whether the
1782         // paragraph is empty!
1783         return leftMargin(pit, text_->paragraphs()[pit].size());
1784 }
1785
1786
1787 int TextMetrics::leftMargin(pit_type const pit, pos_type const pos) const
1788 {
1789         ParagraphList const & pars = text_->paragraphs();
1790
1791         LASSERT(pit >= 0, return 0);
1792         LASSERT(pit < int(pars.size()), return 0);
1793         Paragraph const & par = pars[pit];
1794         LASSERT(pos >= 0, return 0);
1795         // We do not really care whether pos > par.size(), since we do not
1796         // access the data. It can be actually useful, when querying the
1797         // margin without indentation (see leftMargin(pit_type).
1798
1799         Buffer const & buffer = bv_->buffer();
1800         //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1801         DocumentClass const & tclass = buffer.params().documentClass();
1802         Layout const & layout = par.layout();
1803         FontMetrics const & bfm = theFontMetrics(buffer.params().getFont());
1804
1805         docstring parindent = layout.parindent;
1806
1807         int l_margin = 0;
1808
1809         if (text_->isMainText()) {
1810                 l_margin += bv_->leftMargin();
1811                 l_margin += bfm.signedWidth(tclass.leftmargin());
1812         }
1813
1814         int depth = par.getDepth();
1815         if (depth != 0) {
1816                 // find the next level paragraph
1817                 pit_type newpar = text_->outerHook(pit);
1818                 if (newpar != pit_type(pars.size())) {
1819                         if (pars[newpar].layout().isEnvironment()) {
1820                                 int nestmargin = depth * nestMargin();
1821                                 if (text_->isMainText())
1822                                         nestmargin += changebarMargin();
1823                                 l_margin = max(leftMargin(newpar), nestmargin);
1824                                 // Remove the parindent that has been added
1825                                 // if the paragraph was empty.
1826                                 if (pars[newpar].empty() &&
1827                                     buffer.params().paragraph_separation ==
1828                                     BufferParams::ParagraphIndentSeparation) {
1829                                         docstring pi = pars[newpar].layout().parindent;
1830                                         l_margin -= bfm.signedWidth(pi);
1831                                 }
1832                         }
1833                         if (tclass.isDefaultLayout(par.layout())
1834                             || tclass.isPlainLayout(par.layout())) {
1835                                 if (pars[newpar].params().noindent())
1836                                         parindent.erase();
1837                                 else
1838                                         parindent = pars[newpar].layout().parindent;
1839                         }
1840                 }
1841         }
1842
1843         // Check for reasons to remove indentation.
1844         // First, at document level.
1845         if (buffer.params().paragraph_separation ==
1846                         BufferParams::ParagraphSkipSeparation)
1847                 parindent.erase();
1848         // This happens after sections or environments in standard classes.
1849         // We have to check the previous layout at same depth.
1850         else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1851                 pit_type prev = text_->depthHook(pit, par.getDepth());
1852                 if (par.layout() == pars[prev].layout()) {
1853                         if (prev != pit - 1
1854                             && pars[pit - 1].layout().nextnoindent)
1855                                 parindent.erase();
1856                 } else if (pars[prev].layout().nextnoindent)
1857                         parindent.erase();
1858         }
1859         // The previous paragraph may have ended with a separator inset.
1860         if (pit > 0) {
1861                 Paragraph const & ppar = pars[pit - 1];
1862                 if (ppar.size() > 0) {
1863                         auto * in = dynamic_cast<InsetSeparator const *>(ppar.getInset(ppar.size() - 1));
1864                         if (in != nullptr && in->nextnoindent())
1865                                 parindent.erase();
1866                 }
1867         }
1868
1869         FontInfo const labelfont = text_->labelFont(par);
1870         FontMetrics const & lfm = theFontMetrics(labelfont);
1871
1872         switch (layout.margintype) {
1873         case MARGIN_DYNAMIC:
1874                 if (!layout.leftmargin.empty()) {
1875                         l_margin += bfm.signedWidth(layout.leftmargin);
1876                 }
1877                 if (!par.labelString().empty()) {
1878                         l_margin += lfm.signedWidth(layout.labelindent);
1879                         l_margin += lfm.width(par.labelString());
1880                         l_margin += lfm.width(layout.labelsep);
1881                 }
1882                 break;
1883
1884         case MARGIN_MANUAL: {
1885                 l_margin += lfm.signedWidth(layout.labelindent);
1886                 // The width of an empty par, even with manual label, should be 0
1887                 if (!par.empty() && pos >= par.beginOfBody()) {
1888                         if (!par.getLabelWidthString().empty()) {
1889                                 docstring labstr = par.getLabelWidthString();
1890                                 l_margin += lfm.width(labstr);
1891                                 l_margin += lfm.width(layout.labelsep);
1892                         }
1893                 }
1894                 break;
1895         }
1896
1897         case MARGIN_STATIC: {
1898                 l_margin += bfm.signedWidth(layout.leftmargin) * 4
1899                              / (par.getDepth() + 4);
1900                 break;
1901         }
1902
1903         case MARGIN_FIRST_DYNAMIC:
1904                 if (layout.labeltype == LABEL_MANUAL) {
1905                         // if we are at position 0, we are never in the body
1906                         if (pos > 0 && pos >= par.beginOfBody())
1907                                 l_margin += lfm.signedWidth(layout.leftmargin);
1908                         else
1909                                 l_margin += lfm.signedWidth(layout.labelindent);
1910                 } else if (pos != 0
1911                            // Special case to fix problems with
1912                            // theorems (JMarc)
1913                            || (layout.labeltype == LABEL_STATIC
1914                                && layout.latextype == LATEX_ENVIRONMENT
1915                                && !text_->isFirstInSequence(pit))) {
1916                         l_margin += lfm.signedWidth(layout.leftmargin);
1917                 } else if (!layout.labelIsAbove()) {
1918                         l_margin += lfm.signedWidth(layout.labelindent);
1919                         l_margin += lfm.width(layout.labelsep);
1920                         l_margin += lfm.width(par.labelString());
1921                 }
1922                 break;
1923
1924         case MARGIN_RIGHT_ADDRESS_BOX:
1925                 // This is handled globally in redoParagraph().
1926                 break;
1927         }
1928
1929         if (!par.params().leftIndent().zero())
1930                 l_margin += par.params().leftIndent().inPixels(max_width_, lfm.em());
1931
1932         LyXAlignment align = par.getAlign(bv_->buffer().params());
1933
1934         // set the correct parindent
1935         if (pos == 0
1936             && (layout.labeltype == LABEL_NO_LABEL
1937                 || layout.labeltype == LABEL_ABOVE
1938                 || layout.labeltype == LABEL_CENTERED
1939                 || (layout.labeltype == LABEL_STATIC
1940                     && layout.latextype == LATEX_ENVIRONMENT
1941                     && !text_->isFirstInSequence(pit)))
1942             && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1943             && !par.params().noindent()
1944             // in some insets, paragraphs are never indented
1945             && !text_->inset().neverIndent()
1946             // display style insets do not need indentation
1947             && !(!par.empty()
1948                  && par.isInset(0)
1949                  && par.getInset(0)->rowFlags() & Display)
1950             && (!(tclass.isDefaultLayout(par.layout())
1951                 || tclass.isPlainLayout(par.layout()))
1952                 || buffer.params().paragraph_separation
1953                                 == BufferParams::ParagraphIndentSeparation)) {
1954                 /* use the parindent of the layout when the default
1955                  * indentation is used otherwise use the indentation set in
1956                  * the document settings
1957                  */
1958                 if (buffer.params().getParIndent().empty())
1959                         l_margin += bfm.signedWidth(parindent);
1960                 else
1961                         l_margin += buffer.params().getParIndent().inPixels(max_width_, bfm.em());
1962         }
1963
1964         return l_margin;
1965 }
1966
1967
1968 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1969 {
1970         if (par_metrics_.empty())
1971                 return;
1972
1973         origin_.x_ = x;
1974         origin_.y_ = y;
1975
1976         y -= par_metrics_.begin()->second.ascent();
1977         for (auto & pm_pair : par_metrics_) {
1978                 pit_type const pit = pm_pair.first;
1979                 ParagraphMetrics & pm = pm_pair.second;
1980                 y += pm.ascent();
1981                 // Save the paragraph position in the cache.
1982                 pm.setPosition(y);
1983                 drawParagraph(pi, pit, x, y);
1984                 y += pm.descent();
1985         }
1986 }
1987
1988
1989 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1990 {
1991         ParagraphMetrics const & pm = par_metrics_[pit];
1992         if (pm.rows().empty())
1993                 return;
1994         size_t const nrows = pm.rows().size();
1995         int const wh = bv_->workHeight();
1996         // Remember left and right margin for drawing math numbers
1997         Changer changeleft = changeVar(pi.leftx, x + leftMargin(pit));
1998         Changer changeright = changeVar(pi.rightx, x + width() - rightMargin(pit));
1999
2000         // Use fast lane in nodraw stage.
2001         if (pi.pain.isNull()) {
2002                 for (size_t i = 0; i != nrows; ++i) {
2003
2004                         Row const & row = pm.rows()[i];
2005                         // Adapt to cursor row scroll offset if applicable.
2006                         int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
2007                         if (i)
2008                                 y += row.ascent();
2009
2010                         // It is not needed to draw on screen if we are not inside
2011                         bool const inside = (y + row.descent() >= 0 && y - row.ascent() < wh);
2012                         if (inside) {
2013                                 RowPainter rp(pi, *text_, row, row_x, y);
2014                                 rp.paintOnlyInsets();
2015                         }
2016                         y += row.descent();
2017                 }
2018                 return;
2019         }
2020
2021         Cursor const & cur = bv_->cursor();
2022         DocIterator sel_beg = cur.selectionBegin();
2023         DocIterator sel_end = cur.selectionEnd();
2024         bool selection = cur.selection()
2025                 // This is our text.
2026                 && cur.text() == text_
2027                 // if the anchor is outside, this is not our selection
2028                 && cur.normalAnchor().text() == text_
2029                 && pit >= sel_beg.pit() && pit <= sel_end.pit();
2030
2031         // We store the begin and end pos of the selection relative to this par
2032         DocIterator sel_beg_par = cur.selectionBegin();
2033         DocIterator sel_end_par = cur.selectionEnd();
2034
2035         // We care only about visible selection.
2036         if (selection) {
2037                 if (pit != sel_beg.pit()) {
2038                         sel_beg_par.pit() = pit;
2039                         sel_beg_par.pos() = 0;
2040                 }
2041                 if (pit != sel_end.pit()) {
2042                         sel_end_par.pit() = pit;
2043                         sel_end_par.pos() = sel_end_par.lastpos();
2044                 }
2045         }
2046
2047         if (text_->isRTL(pit))
2048                 swap(pi.leftx, pi.rightx);
2049
2050         BookmarksSection::BookmarkPosList bpl =
2051                 theSession().bookmarks().bookmarksInPar(bv_->buffer().fileName(), pm.id());
2052
2053         for (size_t i = 0; i != nrows; ++i) {
2054
2055                 Row const & row = pm.rows()[i];
2056                 // Adapt to cursor row scroll offset if applicable.
2057                 int row_x = x - bv_->horizScrollOffset(text_, pit, row.pos());
2058                 if (i)
2059                         y += row.ascent();
2060
2061                 // It is not needed to draw on screen if we are not inside.
2062                 bool const inside = (y + row.descent() >= 0
2063                         && y - row.ascent() < wh);
2064                 if (!inside) {
2065                         // Inset positions have already been set in nodraw stage.
2066                         y += row.descent();
2067                         continue;
2068                 }
2069
2070                 if (selection)
2071                         row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2072                 else
2073                         row.clearSelectionAndMargins();
2074
2075                 // The row knows nothing about the paragraph, so we have to check
2076                 // whether this row is the first or last and update the margins.
2077                 if (row.selection()) {
2078                         if (row.sel_beg == 0)
2079                                 row.change(row.begin_margin_sel, sel_beg.pit() < pit);
2080                         if (row.sel_end == sel_end_par.lastpos())
2081                                 row.change(row.end_margin_sel, sel_end.pit() > pit);
2082                 }
2083
2084                 // Take this opportunity to spellcheck the row contents.
2085                 if (row.changed() && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
2086                         text_->getPar(pit).spellCheck();
2087                 }
2088
2089                 RowPainter rp(pi, *text_, row, row_x, y);
2090
2091                 // Don't paint the row if a full repaint has not been requested
2092                 // and if it has not changed.
2093                 if (!pi.full_repaint && !row.changed()) {
2094                         // Paint only the insets if the text itself is
2095                         // unchanged.
2096                         rp.paintOnlyInsets();
2097                         rp.paintTooLargeMarks(
2098                                 row_x + row.left_x() < bv_->leftMargin(),
2099                                 row_x + row.right_x() > bv_->workWidth() - bv_->rightMargin());
2100                         row.changed(false);
2101                         y += row.descent();
2102                         continue;
2103                 }
2104
2105                 // Clear background of this row if paragraph background was not
2106                 // already cleared because of a full repaint.
2107                 if (!pi.full_repaint && row.changed()) {
2108                         LYXERR(Debug::PAINTING, "Clear rect@("
2109                                << x << ", " << y - row.ascent() << ")="
2110                                << width() << " x " << row.height());
2111                         pi.pain.fillRectangle(x, y - row.ascent(),
2112                                               width(), row.height(), pi.background_color);
2113                 }
2114
2115                 // Instrumentation for testing row cache (see also
2116                 // 12 lines lower):
2117                 if (lyxerr.debugging(Debug::PAINTING)
2118                     && (row.selection() || pi.full_repaint || row.changed())) {
2119                         string const foreword = text_->isMainText() ? "main text redraw "
2120                                 : "inset text redraw: ";
2121                         LYXERR0(foreword << "pit=" << pit << " row=" << i
2122                                 << (row.selection() ? " row_selection": "")
2123                                 << (pi.full_repaint ? " full_repaint" : "")
2124                                 << (row.changed() ? " row.changed" : ""));
2125                 }
2126
2127                 // Backup full_repaint status and force full repaint
2128                 // for inner insets as the Row has been cleared out.
2129                 bool tmp = pi.full_repaint;
2130                 pi.full_repaint = true;
2131
2132                 rp.paintSelection();
2133                 rp.paintAppendix();
2134                 rp.paintDepthBar();
2135                 if (row.needsChangeBar())
2136                         rp.paintChangeBar();
2137                 if (i == 0)
2138                         rp.paintFirst();
2139                 if (i == nrows - 1)
2140                         rp.paintLast();
2141                 rp.paintText();
2142                 rp.paintTooLargeMarks(
2143                         row_x + row.left_x() < bv_->leftMargin(),
2144                         row_x + row.right_x() > bv_->workWidth() - bv_->rightMargin());
2145                 // indicate bookmarks presence in margin
2146                 if (lyxrc.bookmarks_visibility == LyXRC::BMK_MARGIN)
2147                         for (auto const & bp_p : bpl)
2148                                 if (bp_p.second >= row.pos() && bp_p.second < row.endpos())
2149                                         rp.paintBookmark(bp_p.first);
2150
2151                 y += row.descent();
2152
2153 #if 0
2154                 // This debug code shows on screen which rows are repainted.
2155                 // FIXME: since the updates related to caret blinking restrict
2156                 // the painter to a small rectangle, the numbers are not
2157                 // updated when this happens. Change the code in
2158                 // GuiWorkArea::Private::show/hideCaret if this is important.
2159                 static int count = 0;
2160                 ++count;
2161                 FontInfo fi(sane_font);
2162                 fi.setSize(TINY_SIZE);
2163                 fi.setColor(Color_red);
2164                 pi.pain.text(row_x, y, convert<docstring>(count), fi);
2165 #endif
2166
2167                 // Restore full_repaint status.
2168                 pi.full_repaint = tmp;
2169
2170                 row.changed(false);
2171         }
2172
2173         //LYXERR(Debug::PAINTING, ".");
2174 }
2175
2176
2177 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2178         Dimension & dim) const
2179 {
2180         DocIterator from = cur.bv().cursor();
2181         DocIterator to = from;
2182         text_->getWord(from.top(), to.top(), PREVIOUS_WORD);
2183
2184         // The vertical dimension of the word
2185         Font const font = displayFont(cur.pit(), from.pos());
2186         FontMetrics const & fm = theFontMetrics(font);
2187         // the +1's below are related to the extra pixels added in setRowHeight
2188         dim.asc = fm.maxAscent() + 1;
2189         dim.des = fm.maxDescent() + 1;
2190
2191         // get position on screen of the word start and end
2192         //FIXME: Is it necessary to explicitly set this to false?
2193         from.boundary(false);
2194         Point lxy = cur.bv().getPos(from);
2195         Point rxy = cur.bv().getPos(to);
2196         dim.wid = abs(rxy.x_ - lxy.x_);
2197
2198         // calculate position of word
2199         y = lxy.y_;
2200         x = min(rxy.x_, lxy.x_);
2201
2202         //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2203         //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2204 }
2205
2206 int defaultRowHeight()
2207 {
2208         return int(theFontMetrics(sane_font).maxHeight() *  1.2);
2209 }
2210
2211 } // namespace lyx