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