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