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