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