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