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