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