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