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