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