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