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