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