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