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