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