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