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