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