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