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