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