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