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