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