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