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