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