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