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