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