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