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