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