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