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