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