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