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