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