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