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