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