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