]> git.lyx.org Git - lyx.git/blob - src/TextMetrics.cpp
Remerge po files
[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         ParagraphList const & pars = text_->paragraphs();
1057         Inset const & inset = text_->inset();
1058
1059         // is it a top line?
1060         if (first == 0 && topBottomSpace) {
1061                 BufferParams const & bufparams = buffer.params();
1062                 // some parskips VERY EASY IMPLEMENTATION
1063                 if (bufparams.paragraph_separation
1064                     == BufferParams::ParagraphSkipSeparation
1065                         && inset.lyxCode() != ERT_CODE
1066                         && inset.lyxCode() != LISTINGS_CODE
1067                         && pit > 0
1068                         && ((layout.isParagraph() && par.getDepth() == 0)
1069                             || (pars[pit - 1].layout().isParagraph()
1070                                 && pars[pit - 1].getDepth() == 0)))
1071                 {
1072                                 maxasc += bufparams.getDefSkip().inPixels(*bv_);
1073                 }
1074
1075                 if (par.params().startOfAppendix())
1076                         maxasc += int(3 * dh);
1077
1078                 // This is special code for the chapter, since the label of this
1079                 // layout is printed in an extra row
1080                 if (layout.counter == "chapter"
1081                     && !par.params().labelString().empty()) {
1082                         labeladdon = int(labelfont_metrics.maxHeight()
1083                                      * layout.spacing.getValue()
1084                                      * text_->spacing(par));
1085                 }
1086
1087                 // special code for the top label
1088                 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1089                      || layout.labeltype == LABEL_BIBLIO
1090                      || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1091                     && text_->isFirstInSequence(pit)
1092                     && !par.labelString().empty())
1093                 {
1094                         labeladdon = int(
1095                                   labelfont_metrics.maxHeight()
1096                                         * layout.spacing.getValue()
1097                                         * text_->spacing(par)
1098                                 + (layout.topsep + layout.labelbottomsep) * dh);
1099                 }
1100
1101                 // Add the layout spaces, for example before and after
1102                 // a section, or between the items of a itemize or enumerate
1103                 // environment.
1104
1105                 pit_type prev = text_->depthHook(pit, par.getDepth());
1106                 Paragraph const & prevpar = pars[prev];
1107                 if (prev != pit
1108                     && prevpar.layout() == layout
1109                     && prevpar.getDepth() == par.getDepth()
1110                     && prevpar.getLabelWidthString()
1111                                         == par.getLabelWidthString()) {
1112                         layoutasc = layout.itemsep * dh;
1113                 } else if (pit != 0 || first != 0) {
1114                         if (layout.topsep > 0)
1115                                 layoutasc = layout.topsep * dh;
1116                 }
1117
1118                 prev = text_->outerHook(pit);
1119                 if (prev != pit_type(pars.size())) {
1120                         maxasc += int(pars[prev].layout().parsep * dh);
1121                 } else if (pit != 0) {
1122                         Paragraph const & prevpar = pars[pit - 1];
1123                         if (prevpar.getDepth() != 0 ||
1124                                         prevpar.layout() == layout) {
1125                                 maxasc += int(layout.parsep * dh);
1126                         }
1127                 }
1128         }
1129
1130         // is it a bottom line?
1131         if (end >= par.size() && topBottomSpace) {
1132                 // add the layout spaces, for example before and after
1133                 // a section, or between the items of a itemize or enumerate
1134                 // environment
1135                 pit_type nextpit = pit + 1;
1136                 if (nextpit != pit_type(pars.size())) {
1137                         pit_type cpit = pit;
1138                         double usual = 0;
1139                         double unusual = 0;
1140
1141                         if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1142                                 usual = pars[cpit].layout().bottomsep * dh;
1143                                 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1144                                 if (pars[cpit].layout() != pars[nextpit].layout()
1145                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1146                                 {
1147                                         unusual = pars[cpit].layout().bottomsep * dh;
1148                                 }
1149                                 layoutdesc = max(unusual, usual);
1150                         } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1151                                 if (pars[cpit].layout() != pars[nextpit].layout()
1152                                         || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1153                                         layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1154                         }
1155                 }
1156         }
1157
1158         // incalculate the layout spaces
1159         maxasc  += int(layoutasc  * 2 / (2 + pars[pit].getDepth()));
1160         maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1161
1162         // FIXME: the correct way is to do the following is to move the
1163         // following code in another method specially tailored for the
1164         // main Text. The following test is thus bogus.
1165         // Top and bottom margin of the document (only at top-level)
1166         if (main_text_ && topBottomSpace) {
1167                 if (pit == 0 && first == 0)
1168                         maxasc += 20;
1169                 if (pit + 1 == pit_type(pars.size()) &&
1170                     end == par.size() &&
1171                                 !(end > 0 && par.isNewline(end - 1)))
1172                         maxdesc += 20;
1173         }
1174
1175         return Dimension(0, maxasc + labeladdon, maxdesc);
1176 }
1177
1178
1179 // x is an absolute screen coord
1180 // returns the column near the specified x-coordinate of the row
1181 // x is set to the real beginning of this column
1182 pos_type TextMetrics::getColumnNearX(pit_type const pit,
1183                 Row const & row, int & x, bool & boundary) const
1184 {
1185         Buffer const & buffer = bv_->buffer();
1186
1187         /// For the main Text, it is possible that this pit is not
1188         /// yet in the CoordCache when moving cursor up.
1189         /// x Paragraph coordinate is always 0 for main text anyway.
1190         int const xo = origin_.x_;
1191         x -= xo;
1192         Paragraph const & par = text_->getPar(pit);
1193         Bidi bidi;
1194         bidi.computeTables(par, buffer, row);
1195
1196         pos_type vc = row.pos();
1197         pos_type end = row.endpos();
1198         pos_type c = 0;
1199         Layout const & layout = par.layout();
1200
1201         bool left_side = false;
1202
1203         pos_type body_pos = par.beginOfBody();
1204
1205         double tmpx = row.x;
1206         double last_tmpx = tmpx;
1207
1208         if (body_pos > 0 &&
1209             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1210                 body_pos = 0;
1211
1212         // check for empty row
1213         if (vc == end) {
1214                 x = int(tmpx) + xo;
1215                 return 0;
1216         }
1217
1218         // This (rtl_support test) is not needed, but gives
1219         // some speedup if rtl_support == false
1220         bool const lastrow = lyxrc.rtl_support && row.endpos() == par.size();
1221
1222         // If lastrow is false, we don't need to compute
1223         // the value of rtl.
1224         bool const rtl = lastrow ? text_->isRTL(par) : false;
1225
1226         // if the first character is a separator, and we are in RTL
1227         // text, this character will not be painted on screen
1228         // and thus we should not count it and skip to the next.
1229         if (rtl && par.isSeparator(bidi.vis2log(vc)))
1230                 ++vc;
1231
1232         while (vc < end && tmpx <= x) {
1233                 c = bidi.vis2log(vc);
1234                 last_tmpx = tmpx;
1235                 if (body_pos > 0 && c == body_pos - 1) {
1236                         FontMetrics const & fm = theFontMetrics(
1237                                 text_->labelFont(par));
1238                         tmpx += row.label_hfill + fm.width(layout.labelsep);
1239                         if (par.isLineSeparator(body_pos - 1))
1240                                 tmpx -= singleWidth(pit, body_pos - 1);
1241                 }
1242
1243                 tmpx += singleWidth(pit, c);
1244                 if (par.isSeparator(c) && c >= body_pos)
1245                                 tmpx += row.separator;
1246                 ++vc;
1247         }
1248
1249         if ((tmpx + last_tmpx) / 2 > x) {
1250                 tmpx = last_tmpx;
1251                 left_side = true;
1252         }
1253
1254         LASSERT(vc <= end, /**/);  // This shouldn't happen.
1255
1256         boundary = false;
1257
1258         if (lastrow &&
1259             ((rtl  &&  left_side && vc == row.pos() && x < tmpx - 5) ||
1260              (!rtl && !left_side && vc == end  && x > tmpx + 5))) {
1261                 if (!par.isNewline(end - 1))
1262                         c = end;
1263         } else if (vc == row.pos()) {
1264                 c = bidi.vis2log(vc);
1265                 if (bidi.level(c) % 2 == 1)
1266                         ++c;
1267         } else {
1268                 c = bidi.vis2log(vc - 1);
1269                 bool const rtl = (bidi.level(c) % 2 == 1);
1270                 if (left_side == rtl) {
1271                         ++c;
1272                         boundary = isRTLBoundary(pit, c);
1273                 }
1274         }
1275
1276 // I believe this code is not needed anymore (Jug 20050717)
1277 #if 0
1278         // The following code is necessary because the cursor position past
1279         // the last char in a row is logically equivalent to that before
1280         // the first char in the next row. That's why insets causing row
1281         // divisions -- Newline and display-style insets -- must be treated
1282         // specially, so cursor up/down doesn't get stuck in an air gap -- MV
1283         // Newline inset, air gap below:
1284         if (row.pos() < end && c >= end && par.isNewline(end - 1)) {
1285                 if (bidi.level(end -1) % 2 == 0)
1286                         tmpx -= singleWidth(pit, end - 1);
1287                 else
1288                         tmpx += singleWidth(pit, end - 1);
1289                 c = end - 1;
1290         }
1291
1292         // Air gap above display inset:
1293         if (row.pos() < end && c >= end && end < par.size()
1294             && par.isInset(end) && par.getInset(end)->display()) {
1295                 c = end - 1;
1296         }
1297         // Air gap below display inset:
1298         if (row.pos() < end && c >= end && par.isInset(end - 1)
1299             && par.getInset(end - 1)->display()) {
1300                 c = end - 1;
1301         }
1302 #endif
1303
1304         x = int(tmpx) + xo;
1305         pos_type const col = c - row.pos();
1306
1307         if (!c || end == par.size())
1308                 return col;
1309
1310         if (c==end && !par.isLineSeparator(c-1) && !par.isNewline(c-1)) {
1311                 boundary = true;
1312                 return col;
1313         }
1314
1315         return min(col, end - 1 - row.pos());
1316 }
1317
1318
1319 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1320 {
1321         // We play safe and use parMetrics(pit) to make sure the
1322         // ParagraphMetrics will be redone and OK to use if needed.
1323         // Otherwise we would use an empty ParagraphMetrics in
1324         // upDownInText() while in selection mode.
1325         ParagraphMetrics const & pm = parMetrics(pit);
1326
1327         LASSERT(row < int(pm.rows().size()), /**/);
1328         bool bound = false;
1329         Row const & r = pm.rows()[row];
1330         return r.pos() + getColumnNearX(pit, r, x, bound);
1331 }
1332
1333
1334 void TextMetrics::newParMetricsDown()
1335 {
1336         pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1337         pit_type const pit = last.first + 1;
1338         if (pit == int(text_->paragraphs().size()))
1339                 return;
1340
1341         // do it and update its position.
1342         redoParagraph(pit);
1343         par_metrics_[pit].setPosition(last.second.position()
1344                 + last.second.descent() + par_metrics_[pit].ascent());
1345 }
1346
1347
1348 void TextMetrics::newParMetricsUp()
1349 {
1350         pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1351         if (first.first == 0)
1352                 return;
1353
1354         pit_type const pit = first.first - 1;
1355         // do it and update its position.
1356         redoParagraph(pit);
1357         par_metrics_[pit].setPosition(first.second.position()
1358                 - first.second.ascent() - par_metrics_[pit].descent());
1359 }
1360
1361 // y is screen coordinate
1362 pit_type TextMetrics::getPitNearY(int y)
1363 {
1364         LASSERT(!text_->paragraphs().empty(), return -1);
1365         LASSERT(!par_metrics_.empty(), return -1);
1366         LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1367
1368         // look for highest numbered paragraph with y coordinate less than given y
1369         pit_type pit = -1;
1370         int yy = -1;
1371         ParMetricsCache::const_iterator it = par_metrics_.begin();
1372         ParMetricsCache::const_iterator et = par_metrics_.end();
1373         ParMetricsCache::const_iterator last = et; last--;
1374
1375         ParagraphMetrics const & pm = it->second;
1376
1377         if (y < it->second.position() - int(pm.ascent())) {
1378                 // We are looking for a position that is before the first paragraph in
1379                 // the cache (which is in priciple off-screen, that is before the
1380                 // visible part.
1381                 if (it->first == 0)
1382                         // We are already at the first paragraph in the inset.
1383                         return 0;
1384                 // OK, this is the paragraph we are looking for.
1385                 pit = it->first - 1;
1386                 newParMetricsUp();
1387                 return pit;
1388         }
1389
1390         ParagraphMetrics const & pm_last = par_metrics_[last->first];
1391
1392         if (y >= last->second.position() + int(pm_last.descent())) {
1393                 // We are looking for a position that is after the last paragraph in
1394                 // the cache (which is in priciple off-screen), that is before the
1395                 // visible part.
1396                 pit = last->first + 1;
1397                 if (pit == int(text_->paragraphs().size()))
1398                         //  We are already at the last paragraph in the inset.
1399                         return last->first;
1400                 // OK, this is the paragraph we are looking for.
1401                 newParMetricsDown();
1402                 return pit;
1403         }
1404
1405         for (; it != et; ++it) {
1406                 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1407                         << " y: " << it->second.position());
1408
1409                 ParagraphMetrics const & pm = par_metrics_[it->first];
1410
1411                 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1412                         pit = it->first;
1413                         yy = it->second.position();
1414                 }
1415         }
1416
1417         LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1418
1419         return pit;
1420 }
1421
1422
1423 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1424         bool assert_in_view, bool up)
1425 {
1426         ParagraphMetrics const & pm = par_metrics_[pit];
1427
1428         int yy = pm.position() - pm.ascent();
1429         LASSERT(!pm.rows().empty(), /**/);
1430         RowList::const_iterator rit = pm.rows().begin();
1431         RowList::const_iterator rlast = pm.rows().end();
1432         --rlast;
1433         for (; rit != rlast; yy += rit->height(), ++rit)
1434                 if (yy + rit->height() > y)
1435                         break;
1436
1437         if (assert_in_view) {
1438                 if (!up && yy + rit->height() > y) {
1439                         if (rit != pm.rows().begin()) {
1440                                 y = yy;
1441                                 --rit;
1442                         } else if (pit != 0) {
1443                                 --pit;
1444                                 newParMetricsUp();
1445                                 ParagraphMetrics const & pm2 = par_metrics_[pit];
1446                                 rit = pm2.rows().end();
1447                                 --rit;
1448                                 y = yy;
1449                         }
1450                 } else if (up && yy != y) {
1451                         if (rit != rlast) {
1452                                 y = yy + rit->height();
1453                                 ++rit;
1454                         } else if (pit < int(text_->paragraphs().size()) - 1) {
1455                                 ++pit;
1456                                 newParMetricsDown();
1457                                 ParagraphMetrics const & pm2 = par_metrics_[pit];
1458                                 rit = pm2.rows().begin();
1459                                 y = pm2.position();
1460                         }
1461                 }
1462         }
1463         return *rit;
1464 }
1465
1466
1467 // x,y are absolute screen coordinates
1468 // sets cursor recursively descending into nested editable insets
1469 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1470         bool assert_in_view, bool up)
1471 {
1472         if (lyxerr.debugging(Debug::WORKAREA)) {
1473                 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1474                 cur.bv().coordCache().dump();
1475         }
1476         pit_type pit = getPitNearY(y);
1477         LASSERT(pit != -1, return 0);
1478         
1479         int yy = y; // is modified by getPitAndRowNearY
1480         Row const & row = getPitAndRowNearY(yy, pit, assert_in_view, up);
1481
1482         bool bound = false; // is modified by getColumnNearX
1483         int xx = x; // is modified by getColumnNearX
1484         pos_type const pos = row.pos()
1485                 + getColumnNearX(pit, row, xx, bound);
1486         cur.pit() = pit;
1487         cur.pos() = pos;
1488         cur.boundary(bound);
1489         cur.setTargetX(x);
1490
1491         // try to descend into nested insets
1492         Inset * inset = checkInsetHit(x, yy);
1493         //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1494         if (!inset) {
1495                 // Either we deconst editXY or better we move current_font
1496                 // and real_current_font to Cursor
1497                 // FIXME: what is needed now that current_font and real_current_font
1498                 // are transferred?
1499                 cur.setCurrentFont();
1500                 return 0;
1501         }
1502
1503         ParagraphList const & pars = text_->paragraphs();
1504         Inset const * inset_before = pos ? pars[pit].getInset(pos - 1) : 0;
1505
1506         // This should be just before or just behind the
1507         // cursor position set above.
1508         LASSERT(inset == inset_before 
1509                 || inset == pars[pit].getInset(pos), /**/);
1510
1511         // Make sure the cursor points to the position before
1512         // this inset.
1513         if (inset == inset_before) {
1514                 --cur.pos();
1515                 cur.boundary(false);
1516         }
1517
1518         // Try to descend recursively inside the inset.
1519         inset = inset->editXY(cur, x, yy);
1520
1521         if (cur.top().text() == text_)
1522                 cur.setCurrentFont();
1523         return inset;
1524 }
1525
1526
1527 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1528 {
1529         LASSERT(text_ == cur.text(), /**/);
1530         pit_type pit = getPitNearY(y);
1531         LASSERT(pit != -1, return);
1532
1533         ParagraphMetrics const & pm = par_metrics_[pit];
1534
1535         int yy = pm.position() - pm.ascent();
1536         LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1537                 " pit: " << pit << " yy: " << yy);
1538
1539         int r = 0;
1540         LASSERT(pm.rows().size(), /**/);
1541         for (; r < int(pm.rows().size()) - 1; ++r) {
1542                 Row const & row = pm.rows()[r];
1543                 if (int(yy + row.height()) > y)
1544                         break;
1545                 yy += row.height();
1546         }
1547
1548         Row const & row = pm.rows()[r];
1549
1550         LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1551
1552         bool bound = false;
1553         int xx = x;
1554         pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
1555
1556         LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1557
1558         text_->setCursor(cur, pit, pos, true, bound);
1559         // remember new position.
1560         cur.setTargetX();
1561 }
1562
1563
1564 //takes screen x,y coordinates
1565 Inset * TextMetrics::checkInsetHit(int x, int y)
1566 {
1567         pit_type pit = getPitNearY(y);
1568         LASSERT(pit != -1, return 0);
1569
1570         Paragraph const & par = text_->paragraphs()[pit];
1571         ParagraphMetrics const & pm = par_metrics_[pit];
1572
1573         LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << "  pit: " << pit);
1574
1575         InsetList::const_iterator iit = par.insetList().begin();
1576         InsetList::const_iterator iend = par.insetList().end();
1577         for (; iit != iend; ++iit) {
1578                 Inset * inset = iit->inset;
1579
1580                 LYXERR(Debug::DEBUG, "examining inset " << inset);
1581
1582                 if (!bv_->coordCache().getInsets().has(inset)) {
1583                         LYXERR(Debug::DEBUG, "inset has no cached position");
1584                         return 0;
1585                 }
1586
1587                 Dimension const & dim = pm.insetDimension(inset);
1588                 Point p = bv_->coordCache().getInsets().xy(inset);
1589
1590                 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1591                         << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1592
1593                 if (x >= p.x_
1594                         && x <= p.x_ + dim.wid
1595                         && y >= p.y_ - dim.asc
1596                         && y <= p.y_ + dim.des) {
1597                         LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1598                         return inset;
1599                 }
1600         }
1601
1602         LYXERR(Debug::DEBUG, "No inset hit. ");
1603         return 0;
1604 }
1605
1606
1607 int TextMetrics::cursorX(CursorSlice const & sl,
1608                 bool boundary) const
1609 {
1610         LASSERT(sl.text() == text_, /**/);
1611         pit_type const pit = sl.pit();
1612         Paragraph const & par = text_->paragraphs()[pit];
1613         ParagraphMetrics const & pm = par_metrics_[pit];
1614         if (pm.rows().empty())
1615                 return 0;
1616
1617         pos_type ppos = sl.pos();
1618         // Correct position in front of big insets
1619         bool const boundary_correction = ppos != 0 && boundary;
1620         if (boundary_correction)
1621                 --ppos;
1622
1623         Row const & row = pm.getRow(sl.pos(), boundary);
1624
1625         pos_type cursor_vpos = 0;
1626
1627         Buffer const & buffer = bv_->buffer();
1628         double x = row.x;
1629         Bidi bidi;
1630         bidi.computeTables(par, buffer, row);
1631
1632         pos_type const row_pos  = row.pos();
1633         pos_type const end      = row.endpos();
1634         // Spaces at logical line breaks in bidi text must be skipped during
1635         // cursor positioning. However, they may appear visually in the middle
1636         // of a row; they must be skipped, wherever they are...
1637         // * logically "abc_[HEBREW_\nHEBREW]"
1638         // * visually "abc_[_WERBEH\nWERBEH]"
1639         pos_type skipped_sep_vpos = -1;
1640
1641         if (end <= row_pos)
1642                 cursor_vpos = row_pos;
1643         else if (ppos >= end)
1644                 cursor_vpos = text_->isRTL(par) ? row_pos : end;
1645         else if (ppos > row_pos && ppos >= end)
1646                 //FIXME: this code is never reached!
1647                 //       (see http://www.lyx.org/trac/changeset/8251)
1648                 // Place cursor after char at (logical) position pos - 1
1649                 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1650                         ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1651         else
1652                 // Place cursor before char at (logical) position ppos
1653                 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1654                         ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1655
1656         pos_type body_pos = par.beginOfBody();
1657         if (body_pos > 0 &&
1658             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1659                 body_pos = 0;
1660
1661         // check for possible inline completion in this row
1662         DocIterator const & inlineCompletionPos = bv_->inlineCompletionPos();
1663         pos_type inlineCompletionVPos = -1;
1664         if (inlineCompletionPos.inTexted()
1665             && inlineCompletionPos.text() == text_
1666             && inlineCompletionPos.pit() == pit
1667             && inlineCompletionPos.pos() - 1 >= row_pos
1668             && inlineCompletionPos.pos() - 1 < end) {
1669                 // draw logically behind the previous character
1670                 inlineCompletionVPos = bidi.log2vis(inlineCompletionPos.pos() - 1);
1671         }
1672
1673         // Use font span to speed things up, see below
1674         FontSpan font_span;
1675         Font font;
1676
1677         // If the last logical character is a separator, skip it, unless
1678         // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1679         if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1680                 skipped_sep_vpos = bidi.log2vis(end - 1);
1681
1682         if (lyxrc.paragraph_markers && text_->isRTL(par)) {
1683                 ParagraphList const & pars_ = text_->paragraphs();
1684                 if (size_type(pit + 1) < pars_.size()) {
1685                         FontInfo f;
1686                         docstring const s = docstring(1, char_type(0x00B6));
1687                         x += theFontMetrics(f).width(s);
1688                 }
1689         }
1690
1691         // Inline completion RTL special case row_pos == cursor_pos:
1692         // "__|b" => cursor_pos is right of __
1693         if (row_pos == inlineCompletionVPos && row_pos == cursor_vpos) {
1694                 font = displayFont(pit, row_pos + 1);
1695                 docstring const & completion = bv_->inlineCompletion();
1696                 if (font.isRightToLeft() && completion.length() > 0)
1697                         x += theFontMetrics(font.fontInfo()).width(completion);
1698         }
1699
1700         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1701                 // Skip the separator which is at the logical end of the row
1702                 if (vpos == skipped_sep_vpos)
1703                         continue;
1704                 pos_type pos = bidi.vis2log(vpos);
1705                 if (body_pos > 0 && pos == body_pos - 1) {
1706                         FontMetrics const & labelfm = theFontMetrics(
1707                                 text_->labelFont(par));
1708                         x += row.label_hfill + labelfm.width(par.layout().labelsep);
1709                         if (par.isLineSeparator(body_pos - 1))
1710                                 x -= singleWidth(pit, body_pos - 1);
1711                 }
1712
1713                 // Use font span to speed things up, see above
1714                 if (pos < font_span.first || pos > font_span.last) {
1715                         font_span = par.fontSpan(pos);
1716                         font = displayFont(pit, pos);
1717                 }
1718
1719                 x += pm.singleWidth(pos, font);
1720
1721                 // Inline completion RTL case:
1722                 // "a__|b", __ of b => non-boundary a-pos is right of __
1723                 if (vpos + 1 == inlineCompletionVPos
1724                     && (vpos + 1 < cursor_vpos || !boundary_correction)) {
1725                         font = displayFont(pit, vpos + 1);
1726                         docstring const & completion = bv_->inlineCompletion();
1727                         if (font.isRightToLeft() && completion.length() > 0)
1728                                 x += theFontMetrics(font.fontInfo()).width(completion);
1729                 }
1730
1731                 //  Inline completion LTR case:
1732                 // "b|__a", __ of b => non-boundary a-pos is in front of __
1733                 if (vpos == inlineCompletionVPos
1734                     && (vpos + 1 < cursor_vpos || boundary_correction)) {
1735                         font = displayFont(pit, vpos);
1736                         docstring const & completion = bv_->inlineCompletion();
1737                         if (!font.isRightToLeft() && completion.length() > 0)
1738                                 x += theFontMetrics(font.fontInfo()).width(completion);
1739                 }
1740
1741                 if (par.isSeparator(pos) && pos >= body_pos)
1742                         x += row.separator;
1743         }
1744
1745         // see correction above
1746         if (boundary_correction) {
1747                 if (isRTL(sl, boundary))
1748                         x -= singleWidth(pit, ppos);
1749                 else
1750                         x += singleWidth(pit, ppos);
1751         }
1752
1753         return int(x);
1754 }
1755
1756
1757 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1758 {
1759         //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1760         ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1761         if (pm.rows().empty())
1762                 return 0;
1763
1764         int h = 0;
1765         h -= par_metrics_[0].rows()[0].ascent();
1766         for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1767                 h += par_metrics_[pit].height();
1768         }
1769         int pos = sl.pos();
1770         if (pos && boundary)
1771                 --pos;
1772         size_t const rend = pm.pos2row(pos);
1773         for (size_t rit = 0; rit != rend; ++rit)
1774                 h += pm.rows()[rit].height();
1775         h += pm.rows()[rend].ascent();
1776         return h;
1777 }
1778
1779
1780 // the cursor set functions have a special mechanism. When they
1781 // realize you left an empty paragraph, they will delete it.
1782
1783 bool TextMetrics::cursorHome(Cursor & cur)
1784 {
1785         LASSERT(text_ == cur.text(), /**/);
1786         ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1787         Row const & row = pm.getRow(cur.pos(),cur.boundary());
1788         return text_->setCursor(cur, cur.pit(), row.pos());
1789 }
1790
1791
1792 bool TextMetrics::cursorEnd(Cursor & cur)
1793 {
1794         LASSERT(text_ == cur.text(), /**/);
1795         // if not on the last row of the par, put the cursor before
1796         // the final space exept if I have a spanning inset or one string
1797         // is so long that we force a break.
1798         pos_type end = cur.textRow().endpos();
1799         if (end == 0)
1800                 // empty text, end-1 is no valid position
1801                 return false;
1802         bool boundary = false;
1803         if (end != cur.lastpos()) {
1804                 if (!cur.paragraph().isLineSeparator(end-1)
1805                     && !cur.paragraph().isNewline(end-1))
1806                         boundary = true;
1807                 else
1808                         --end;
1809         }
1810         return text_->setCursor(cur, cur.pit(), end, true, boundary);
1811 }
1812
1813
1814 void TextMetrics::deleteLineForward(Cursor & cur)
1815 {
1816         LASSERT(text_ == cur.text(), /**/);
1817         if (cur.lastpos() == 0) {
1818                 // Paragraph is empty, so we just go forward
1819                 text_->cursorForward(cur);
1820         } else {
1821                 cur.resetAnchor();
1822                 cur.setSelection(true); // to avoid deletion
1823                 cursorEnd(cur);
1824                 cur.setSelection();
1825                 // What is this test for ??? (JMarc)
1826                 if (!cur.selection())
1827                         text_->deleteWordForward(cur);
1828                 else
1829                         cap::cutSelection(cur, true, false);
1830                 cur.checkBufferStructure();
1831         }
1832 }
1833
1834
1835 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1836 {
1837         ParagraphList const & pars = text_->paragraphs();
1838         return row.endpos() >= pars[pit].size()
1839                 && pit + 1 == pit_type(pars.size());
1840 }
1841
1842
1843 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1844 {
1845         return row.pos() == 0 && pit == 0;
1846 }
1847
1848
1849 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1850 {
1851         LASSERT(pit >= 0, /**/);
1852         LASSERT(pit < int(text_->paragraphs().size()), /**/);
1853         return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1854 }
1855
1856
1857 int TextMetrics::leftMargin(int max_width,
1858                 pit_type const pit, pos_type const pos) const
1859 {
1860         ParagraphList const & pars = text_->paragraphs();
1861
1862         LASSERT(pit >= 0, /**/);
1863         LASSERT(pit < int(pars.size()), /**/);
1864         Paragraph const & par = pars[pit];
1865         LASSERT(pos >= 0, /**/);
1866         LASSERT(pos <= par.size(), /**/);
1867         Buffer const & buffer = bv_->buffer();
1868         //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1869         DocumentClass const & tclass = buffer.params().documentClass();
1870         Layout const & layout = par.layout();
1871
1872         docstring parindent = layout.parindent;
1873
1874         int l_margin = 0;
1875
1876         if (text_->isMainText())
1877                 l_margin += bv_->leftMargin();
1878
1879         l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1880                 tclass.leftmargin());
1881
1882         if (par.getDepth() != 0) {
1883                 // find the next level paragraph
1884                 pit_type newpar = text_->outerHook(pit);
1885                 if (newpar != pit_type(pars.size())) {
1886                         if (pars[newpar].layout().isEnvironment()) {
1887                                 l_margin = leftMargin(max_width, newpar);
1888                         }
1889                         if (tclass.isDefaultLayout(par.layout())
1890                             || tclass.isPlainLayout(par.layout())) {
1891                                 if (pars[newpar].params().noindent())
1892                                         parindent.erase();
1893                                 else
1894                                         parindent = pars[newpar].layout().parindent;
1895                         }
1896                 }
1897         }
1898
1899         // This happens after sections in standard classes. The 1.3.x
1900         // code compared depths too, but it does not seem necessary
1901         // (JMarc)
1902         if (tclass.isDefaultLayout(par.layout())
1903             && pit > 0 && pars[pit - 1].layout().nextnoindent)
1904                 parindent.erase();
1905
1906         FontInfo const labelfont = text_->labelFont(par);
1907         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1908
1909         switch (layout.margintype) {
1910         case MARGIN_DYNAMIC:
1911                 if (!layout.leftmargin.empty()) {
1912                         l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1913                                 layout.leftmargin);
1914                 }
1915                 if (!par.labelString().empty()) {
1916                         l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1917                         l_margin += labelfont_metrics.width(par.labelString());
1918                         l_margin += labelfont_metrics.width(layout.labelsep);
1919                 }
1920                 break;
1921
1922         case MARGIN_MANUAL: {
1923                 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1924                 // The width of an empty par, even with manual label, should be 0
1925                 if (!par.empty() && pos >= par.beginOfBody()) {
1926                         if (!par.getLabelWidthString().empty()) {
1927                                 docstring labstr = par.getLabelWidthString();
1928                                 l_margin += labelfont_metrics.width(labstr);
1929                                 l_margin += labelfont_metrics.width(layout.labelsep);
1930                         }
1931                 }
1932                 break;
1933         }
1934
1935         case MARGIN_STATIC: {
1936                 l_margin += theFontMetrics(buffer.params().getFont()).
1937                         signedWidth(layout.leftmargin) * 4      / (par.getDepth() + 4);
1938                 break;
1939         }
1940
1941         case MARGIN_FIRST_DYNAMIC:
1942                 if (layout.labeltype == LABEL_MANUAL) {
1943                         // if we are at position 0, we are never in the body
1944                         if (pos > 0 && pos >= par.beginOfBody())
1945                                 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1946                         else
1947                                 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1948                 } else if (pos != 0
1949                            // Special case to fix problems with
1950                            // theorems (JMarc)
1951                            || (layout.labeltype == LABEL_STATIC
1952                                && layout.latextype == LATEX_ENVIRONMENT
1953                                && !text_->isFirstInSequence(pit))) {
1954                         l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1955                 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
1956                            && layout.labeltype != LABEL_BIBLIO
1957                            && layout.labeltype !=
1958                            LABEL_CENTERED_TOP_ENVIRONMENT) {
1959                         l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1960                         l_margin += labelfont_metrics.width(layout.labelsep);
1961                         l_margin += labelfont_metrics.width(par.labelString());
1962                 }
1963                 break;
1964
1965         case MARGIN_RIGHT_ADDRESS_BOX: {
1966 #if 0
1967                 // ok, a terrible hack. The left margin depends on the widest
1968                 // row in this paragraph.
1969                 RowList::iterator rit = par.rows().begin();
1970                 RowList::iterator end = par.rows().end();
1971                 // FIXME: This is wrong.
1972                 int minfill = max_width;
1973                 for ( ; rit != end; ++rit)
1974                         if (rit->fill() < minfill)
1975                                 minfill = rit->fill();
1976                 l_margin += theFontMetrics(params.getFont()).signedWidth(layout.leftmargin);
1977                 l_margin += minfill;
1978 #endif
1979                 // also wrong, but much shorter.
1980                 l_margin += max_width / 2;
1981                 break;
1982         }
1983         }
1984
1985         if (!par.params().leftIndent().zero())
1986                 l_margin += par.params().leftIndent().inPixels(max_width);
1987
1988         LyXAlignment align;
1989
1990         if (par.params().align() == LYX_ALIGN_LAYOUT)
1991                 align = layout.align;
1992         else
1993                 align = par.params().align();
1994
1995         // set the correct parindent
1996         if (pos == 0
1997             && (layout.labeltype == LABEL_NO_LABEL
1998                || layout.labeltype == LABEL_TOP_ENVIRONMENT
1999                || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
2000                || (layout.labeltype == LABEL_STATIC
2001                    && layout.latextype == LATEX_ENVIRONMENT
2002                    && !text_->isFirstInSequence(pit)))
2003             && align == LYX_ALIGN_BLOCK
2004             && !par.params().noindent()
2005             // in some insets, paragraphs are never indented
2006             && !text_->inset().neverIndent()
2007             // display style insets are always centered, omit indentation
2008             && !(!par.empty()
2009                     && par.isInset(pos)
2010                     && par.getInset(pos)->display())
2011                         && (!(tclass.isDefaultLayout(par.layout())
2012                  || tclass.isPlainLayout(par.layout()))
2013                 || buffer.params().paragraph_separation 
2014                                 == BufferParams::ParagraphIndentSeparation)
2015             )
2016                 {
2017                         // use the parindent of the layout when the default indentation is
2018                         // used otherwise use the indentation set in the document settings
2019                         if (buffer.params().getIndentation().asLyXCommand() == "default")
2020                                 l_margin += theFontMetrics(
2021                                         buffer.params().getFont()).signedWidth(parindent);
2022                         else
2023                                 l_margin += buffer.params().getIndentation().inPixels(*bv_);
2024                 }
2025         
2026         return l_margin;
2027 }
2028
2029
2030 int TextMetrics::singleWidth(pit_type pit, pos_type pos) const
2031 {
2032         ParagraphMetrics const & pm = par_metrics_[pit];
2033
2034         return pm.singleWidth(pos, displayFont(pit, pos));
2035 }
2036
2037
2038 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
2039 {
2040         if (par_metrics_.empty())
2041                 return;
2042
2043         origin_.x_ = x;
2044         origin_.y_ = y;
2045
2046         ParMetricsCache::iterator it = par_metrics_.begin();
2047         ParMetricsCache::iterator const pm_end = par_metrics_.end();
2048         y -= it->second.ascent();
2049         for (; it != pm_end; ++it) {
2050                 ParagraphMetrics const & pmi = it->second;
2051                 y += pmi.ascent();
2052                 pit_type const pit = it->first;
2053                 // Save the paragraph position in the cache.
2054                 it->second.setPosition(y);
2055                 drawParagraph(pi, pit, x, y);
2056                 y += pmi.descent();
2057         }
2058 }
2059
2060
2061 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type pit, int x, int y) const
2062 {
2063         BufferParams const & bparams = bv_->buffer().params();
2064         ParagraphMetrics const & pm = par_metrics_[pit];
2065         if (pm.rows().empty())
2066                 return;
2067
2068         Bidi bidi;
2069         bool const original_drawing_state = pi.pain.isDrawingEnabled();
2070         int const ww = bv_->workHeight();
2071         size_t const nrows = pm.rows().size();
2072
2073         Cursor const & cur = bv_->cursor();
2074         DocIterator sel_beg = cur.selectionBegin();
2075         DocIterator sel_end = cur.selectionEnd();
2076         bool selection = cur.selection()
2077                 // This is our text.
2078                 && cur.text() == text_
2079                 // if the anchor is outside, this is not our selection
2080                 && cur.normalAnchor().text() == text_
2081                 && pit >= sel_beg.pit() && pit <= sel_end.pit();
2082
2083         // We store the begin and end pos of the selection relative to this par
2084         DocIterator sel_beg_par = cur.selectionBegin();
2085         DocIterator sel_end_par = cur.selectionEnd();
2086         
2087         // We care only about visible selection.
2088         if (selection) {
2089                 if (pit != sel_beg.pit()) {
2090                         sel_beg_par.pit() = pit;
2091                         sel_beg_par.pos() = 0;
2092                 }
2093                 if (pit != sel_end.pit()) {
2094                         sel_end_par.pit() = pit;
2095                         sel_end_par.pos() = sel_end_par.lastpos();
2096                 }
2097         }
2098
2099         for (size_t i = 0; i != nrows; ++i) {
2100
2101                 Row const & row = pm.rows()[i];
2102                 if (i)
2103                         y += row.ascent();
2104
2105                 bool const inside = (y + row.descent() >= 0
2106                         && y - row.ascent() < ww);
2107                 // It is not needed to draw on screen if we are not inside.
2108                 pi.pain.setDrawingEnabled(inside && original_drawing_state);
2109                 RowPainter rp(pi, *text_, pit, row, bidi, x, y);
2110
2111                 if (selection)
2112                         row.setSelectionAndMargins(sel_beg_par, sel_end_par);
2113                 else
2114                         row.setSelection(-1, -1);
2115                 
2116                 // The row knows nothing about the paragraph, so we have to check
2117                 // whether this row is the first or last and update the margins.
2118                 if (row.selection()) {
2119                         if (row.sel_beg == 0)
2120                                 row.begin_margin_sel = sel_beg.pit() < pit;
2121                         if (row.sel_end == sel_end_par.lastpos())
2122                                 row.end_margin_sel = sel_end.pit() > pit;
2123                 }
2124
2125                 // Row signature; has row changed since last paint?
2126                 row.setCrc(pm.computeRowSignature(row, bparams));
2127                 bool row_has_changed = row.changed();
2128
2129                 // Take this opportunity to spellcheck the row contents.
2130                 if (row_has_changed && lyxrc.spellcheck_continuously) {
2131                         WordLangTuple wl;
2132                         // dummy variable, not used.
2133                         static docstring_list suggestions;
2134                         pos_type from = row.pos();
2135                         pos_type to = row.endpos();
2136                         while (from < row.endpos()) {
2137                                 text_->getPar(pit).spellCheck(from, to, wl, suggestions, false);
2138                                 from = to + 1;
2139                         }
2140                 }
2141
2142                 // Don't paint the row if a full repaint has not been requested
2143                 // and if it has not changed.
2144                 if (!pi.full_repaint && !row_has_changed) {
2145                         // Paint only the insets if the text itself is
2146                         // unchanged.
2147                         rp.paintOnlyInsets();
2148                         y += row.descent();
2149                         continue;
2150                 }
2151
2152                 // Clear background of this row if paragraph background was not
2153                 // already cleared because of a full repaint.
2154                 if (!pi.full_repaint && row_has_changed) {
2155                         pi.pain.fillRectangle(x, y - row.ascent(),
2156                                 width(), row.height(), pi.background_color);
2157                 }
2158                 
2159                 if (row.selection())
2160                         drawRowSelection(pi, x, row, cur, pit);
2161
2162                 // Instrumentation for testing row cache (see also
2163                 // 12 lines lower):
2164                 if (lyxerr.debugging(Debug::PAINTING) && inside
2165                         && (row.selection() || pi.full_repaint || row_has_changed)) {
2166                                 string const foreword = text_->isMainText() ?
2167                                         "main text redraw " : "inset text redraw: ";
2168                         LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2169                                 << " row_selection="    << row.selection()
2170                                 << " full_repaint="     << pi.full_repaint
2171                                 << " row_has_changed="  << row_has_changed);
2172                 }
2173
2174                 // Backup full_repaint status and force full repaint
2175                 // for inner insets as the Row has been cleared out.
2176                 bool tmp = pi.full_repaint;
2177                 pi.full_repaint = true;
2178                 rp.paintAppendix();
2179                 rp.paintDepthBar();
2180                 rp.paintChangeBar();
2181                 bool const is_rtl = text_->isRTL(text_->getPar(pit));
2182                 if (i == 0 && !is_rtl)
2183                         rp.paintFirst();
2184                 if (i == nrows - 1 && is_rtl)
2185                         rp.paintLast();
2186                 rp.paintText();
2187                 if (i == nrows - 1 && !is_rtl)
2188                         rp.paintLast();
2189                 if (i == 0 && is_rtl)
2190                         rp.paintFirst();
2191                 y += row.descent();
2192                 // Restore full_repaint status.
2193                 pi.full_repaint = tmp;
2194         }
2195         // Re-enable screen drawing for future use of the painter.
2196         pi.pain.setDrawingEnabled(original_drawing_state);
2197
2198         //LYXERR(Debug::PAINTING, ".");
2199 }
2200
2201
2202 void TextMetrics::drawRowSelection(PainterInfo & pi, int x, Row const & row,
2203                 Cursor const & curs, pit_type pit) const
2204 {
2205         DocIterator beg = curs.selectionBegin();
2206         beg.pit() = pit;
2207         beg.pos() = row.sel_beg;
2208
2209         DocIterator end = curs.selectionEnd();
2210         end.pit() = pit;
2211         end.pos() = row.sel_end;
2212
2213         bool const begin_boundary = beg.pos() >= row.endpos();
2214         bool const end_boundary = row.sel_end == row.endpos();
2215
2216         DocIterator cur = beg;
2217         cur.boundary(begin_boundary);
2218         int x1 = cursorX(beg.top(), begin_boundary);
2219         int x2 = cursorX(end.top(), end_boundary);
2220         int const y1 = bv_->getPos(cur).y_ - row.ascent();
2221         int const y2 = y1 + row.height();
2222
2223         int const rm = text_->isMainText() ? bv_->rightMargin() : 0;
2224         int const lm = text_->isMainText() ? bv_->leftMargin() : 0;
2225
2226         // draw the margins
2227         if (row.begin_margin_sel) {
2228                 if (text_->isRTL(beg.paragraph())) {
2229                         pi.pain.fillRectangle(x + x1, y1,  width() - rm - x1, y2 - y1,
2230                                 Color_selection);
2231                 } else {
2232                         pi.pain.fillRectangle(x + lm, y1, x1 - lm, y2 - y1,
2233                                 Color_selection);
2234                 }
2235         }
2236
2237         if (row.end_margin_sel) {
2238                 if (text_->isRTL(beg.paragraph())) {
2239                         pi.pain.fillRectangle(x + lm, y1, x2 - lm, y2 - y1,
2240                                 Color_selection);
2241                 } else {
2242                         pi.pain.fillRectangle(x + x2, y1, width() - rm - x2, y2 - y1,
2243                                 Color_selection);
2244                 }
2245         }
2246
2247         // if we are on a boundary from the beginning, it's probably
2248         // a RTL boundary and we jump to the other side directly as this
2249         // segement is 0-size and confuses the logic below
2250         if (cur.boundary())
2251                 cur.boundary(false);
2252
2253         // go through row and draw from RTL boundary to RTL boundary
2254         while (cur < end) {
2255                 bool draw_now = false;
2256
2257                 // simplified cursorForward code below which does not
2258                 // descend into insets and which does not go into the
2259                 // next line. Compare the logic with the original cursorForward
2260
2261                 // if left of boundary -> just jump to right side, but
2262                 // for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
2263                 if (cur.boundary()) {
2264                         cur.boundary(false);
2265                 }       else if (isRTLBoundary(cur.pit(), cur.pos() + 1)) {
2266                         // in front of RTL boundary -> Stay on this side of the boundary
2267                         // because:  ab|cDDEEFFghi -> abc|DDEEFFghi
2268                         ++cur.pos();
2269                         cur.boundary(true);
2270                         draw_now = true;
2271                 } else {
2272                         // move right
2273                         ++cur.pos();
2274
2275                         // line end?
2276                         if (cur.pos() == row.endpos())
2277                                 cur.boundary(true);
2278                 }
2279
2280                 if (x1 == -1) {
2281                         // the previous segment was just drawn, now the next starts
2282                         x1 = cursorX(cur.top(), cur.boundary());
2283                 }
2284
2285                 if (!(cur < end) || draw_now) {
2286                         x2 = cursorX(cur.top(), cur.boundary());
2287                         pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
2288                                 Color_selection);
2289
2290                         // reset x1, so it is set again next round (which will be on the
2291                         // right side of a boundary or at the selection end)
2292                         x1 = -1;
2293                 }
2294         }
2295 }
2296
2297
2298 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2299         Dimension & dim) const
2300 {
2301         Cursor const & bvcur = cur.bv().cursor();
2302
2303         // get word in front of cursor
2304         docstring word = text_->previousWord(bvcur.top());
2305         DocIterator wordStart = bvcur;
2306         wordStart.pos() -= word.length();
2307
2308         // get position on screen of the word start and end
2309         //FIXME: Is it necessary to explicitly set this to false?
2310         wordStart.boundary(false);
2311         Point lxy = cur.bv().getPos(wordStart);
2312         Point rxy = cur.bv().getPos(bvcur);
2313
2314         // calculate dimensions of the word
2315         dim = rowHeight(bvcur.pit(), wordStart.pos(), bvcur.pos(), false);
2316         dim.wid = abs(rxy.x_ - lxy.x_);
2317
2318         // calculate position of word
2319         y = lxy.y_;
2320         x = min(rxy.x_, lxy.x_);
2321
2322         //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2323         //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2324 }
2325
2326 //int TextMetrics::pos2x(pit_type pit, pos_type pos) const
2327 //{
2328 //      ParagraphMetrics const & pm = par_metrics_[pit];
2329 //      Row const & r = pm.rows()[row];
2330 //      int x = 0;
2331 //      pos -= r.pos();
2332 //}
2333
2334
2335 int defaultRowHeight()
2336 {
2337         return int(theFontMetrics(sane_font).maxHeight() *  1.2);
2338 }
2339
2340 } // namespace lyx