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