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