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