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