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