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