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