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