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