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.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Jürgen Vigna
13 * \author Abdelrazak Younes
15 * Full author contact details are available in file CREDITS.
20 #include "TextMetrics.h"
23 #include "buffer_funcs.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
28 #include "CutAndPaste.h"
30 #include "InsetList.h"
34 #include "MetricsInfo.h"
35 #include "ParagraphParameters.h"
36 #include "RowPainter.h"
38 #include "TextClass.h"
41 #include "insets/InsetText.h"
43 #include "mathed/MathMacroTemplate.h"
45 #include "frontends/FontMetrics.h"
46 #include "frontends/Painter.h"
48 #include "support/debug.h"
49 #include "support/lassert.h"
58 using frontend::FontMetrics;
63 int numberOfLabelHfills(Paragraph const & par, Row const & row)
65 pos_type last = row.endpos() - 1;
66 pos_type first = row.pos();
68 // hfill *DO* count at the beginning of paragraphs!
70 while (first < last && par.isHfill(first))
74 last = min(last, par.beginOfBody());
76 for (pos_type p = first; p < last; ++p) {
83 // FIXME: this needs to be rewritten, probably by merging it into some
84 // code that, besides counting, sets the active status of the space
85 // inset in the row element.
86 int numberOfHfills(Row const & row, ParagraphMetrics const & pm,
87 pos_type const body_pos)
90 Row::const_iterator cit = row.begin();
91 Row::const_iterator const end = row.end();
92 for ( ; cit != end ; ++cit)
93 if (cit->pos >= body_pos
94 && cit->inset && pm.hfillExpansion(row, cit->pos))
102 /////////////////////////////////////////////////////////////////////
106 /////////////////////////////////////////////////////////////////////
109 TextMetrics::TextMetrics(BufferView * bv, Text * text)
110 : bv_(bv), text_(text)
113 max_width_ = bv_->workWidth();
114 dim_.wid = max_width_;
120 bool TextMetrics::contains(pit_type pit) const
122 return par_metrics_.find(pit) != par_metrics_.end();
126 ParagraphMetrics const & TextMetrics::parMetrics(pit_type pit) const
128 return const_cast<TextMetrics *>(this)->parMetrics(pit, true);
133 pair<pit_type, ParagraphMetrics const *> TextMetrics::first() const
135 ParMetricsCache::const_iterator it = par_metrics_.begin();
136 return make_pair(it->first, &it->second);
140 pair<pit_type, ParagraphMetrics const *> TextMetrics::last() const
142 LBUFERR(!par_metrics_.empty());
143 ParMetricsCache::const_reverse_iterator it = par_metrics_.rbegin();
144 return make_pair(it->first, &it->second);
148 ParagraphMetrics & TextMetrics::parMetrics(pit_type pit, bool redo)
150 ParMetricsCache::iterator pmc_it = par_metrics_.find(pit);
151 if (pmc_it == par_metrics_.end()) {
152 pmc_it = par_metrics_.insert(
153 make_pair(pit, ParagraphMetrics(text_->getPar(pit)))).first;
155 if (pmc_it->second.rows().empty() && redo)
157 return pmc_it->second;
161 bool TextMetrics::metrics(MetricsInfo & mi, Dimension & dim, int min_width)
163 LBUFERR(mi.base.textwidth > 0);
164 max_width_ = mi.base.textwidth;
165 // backup old dimension.
166 Dimension const old_dim = dim_;
169 dim_.wid = min_width;
170 pit_type const npar = text_->paragraphs().size();
172 // If there is more than one row, expand the text to
173 // the full allowable width.
174 dim_.wid = max_width_;
176 //lyxerr << "TextMetrics::metrics: width: " << mi.base.textwidth
177 // << " maxWidth: " << max_width_ << "\nfont: " << mi.base.font << endl;
179 bool changed = false;
181 for (pit_type pit = 0; pit != npar; ++pit) {
182 changed |= redoParagraph(pit);
183 ParagraphMetrics const & pm = par_metrics_[pit];
185 if (dim_.wid < pm.width())
186 dim_.wid = pm.width();
189 dim_.asc = par_metrics_[0].ascent();
190 dim_.des = h - dim_.asc;
191 //lyxerr << "dim_.wid " << dim_.wid << endl;
192 //lyxerr << "dim_.asc " << dim_.asc << endl;
193 //lyxerr << "dim_.des " << dim_.des << endl;
195 changed |= dim_ != old_dim;
201 int TextMetrics::rightMargin(ParagraphMetrics const & pm) const
203 return main_text_? pm.rightMargin(*bv_) : 0;
207 int TextMetrics::rightMargin(pit_type const pit) const
209 return main_text_? par_metrics_[pit].rightMargin(*bv_) : 0;
213 void TextMetrics::applyOuterFont(Font & font) const
215 FontInfo lf(font_.fontInfo());
216 lf.reduce(bv_->buffer().params().getFont().fontInfo());
217 font.fontInfo().realize(lf);
221 Font TextMetrics::displayFont(pit_type pit, pos_type pos) const
223 LASSERT(pos >= 0, { static Font f; return f; });
225 ParagraphList const & pars = text_->paragraphs();
226 Paragraph const & par = pars[pit];
227 Layout const & layout = par.layout();
228 Buffer const & buffer = bv_->buffer();
230 BufferParams const & params = buffer.params();
231 pos_type const body_pos = par.beginOfBody();
233 // We specialize the 95% common case:
234 if (!par.getDepth()) {
235 Font f = par.getFontSettings(params, pos);
236 if (!text_->isMainText())
238 bool lab = layout.labeltype == LABEL_MANUAL && pos < body_pos;
240 FontInfo const & lf = lab ? layout.labelfont : layout.font;
241 FontInfo rlf = lab ? layout.reslabelfont : layout.resfont;
243 // In case the default family has been customized
244 if (lf.family() == INHERIT_FAMILY)
245 rlf.setFamily(params.getFont().fontInfo().family());
246 f.fontInfo().realize(rlf);
250 // The uncommon case need not be optimized as much
251 FontInfo const & layoutfont = pos < body_pos ?
252 layout.labelfont : layout.font;
254 Font font = par.getFontSettings(params, pos);
255 font.fontInfo().realize(layoutfont);
257 if (!text_->isMainText())
258 applyOuterFont(font);
260 // Realize against environment font information
261 // NOTE: the cast to pit_type should be removed when pit_type
262 // changes to a unsigned integer.
263 if (pit < pit_type(pars.size()))
264 font.fontInfo().realize(text_->outerFont(pit).fontInfo());
266 // Realize with the fonts of lesser depth.
267 font.fontInfo().realize(params.getFont().fontInfo());
273 bool TextMetrics::isRTL(CursorSlice const & sl, bool boundary) const
279 if (boundary && sl.pos() > 0)
282 return displayFont(sl.pit(), sl.pos() + correction).isVisibleRightToLeft();
286 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos) const
288 // no RTL boundary at paragraph start
292 Font const & left_font = displayFont(pit, pos - 1);
294 return isRTLBoundary(pit, pos, left_font);
298 // isRTLBoundary returns false on a real end-of-line boundary,
299 // because otherwise the two boundary types get mixed up.
300 // This is the whole purpose of this being in TextMetrics.
301 bool TextMetrics::isRTLBoundary(pit_type pit, pos_type pos,
302 Font const & font) const
304 if (// no RTL boundary at paragraph start
306 // if the metrics have not been calculated, then we are not
307 // on screen and can safely ignore issues about boundaries.
311 ParagraphMetrics & pm = par_metrics_[pit];
312 // no RTL boundary in empty paragraph
313 if (pm.rows().empty())
316 pos_type endpos = pm.getRow(pos - 1, false).endpos();
317 pos_type startpos = pm.getRow(pos, false).pos();
318 // no RTL boundary at line start:
319 // abc\n -> toggle to RTL -> abc\n (and not: abc\n|
321 if (pos == startpos && pos == endpos) // start of cur row, end of prev row
324 Paragraph const & par = text_->getPar(pit);
325 // no RTL boundary at line break:
326 // abc|\n -> move right -> abc\n (and not: abc\n|
328 if (startpos == pos && endpos == pos && endpos != par.size()
329 && (par.isNewline(pos - 1)
330 || par.isEnvSeparator(pos - 1)
331 || par.isLineSeparator(pos - 1)
332 || par.isSeparator(pos - 1)))
335 bool left = font.isVisibleRightToLeft();
337 if (pos == par.size())
338 right = par.isRTL(bv_->buffer().params());
340 right = displayFont(pit, pos).isVisibleRightToLeft();
342 return left != right;
346 bool TextMetrics::redoParagraph(pit_type const pit)
348 Paragraph & par = text_->getPar(pit);
349 // IMPORTANT NOTE: We pass 'false' explicitly in order to not call
350 // redoParagraph() recursively inside parMetrics.
351 Dimension old_dim = parMetrics(pit, false).dim();
352 ParagraphMetrics & pm = par_metrics_[pit];
355 Buffer & buffer = bv_->buffer();
356 main_text_ = (text_ == &buffer.text());
357 bool changed = false;
359 // Check whether there are InsetBibItems that need fixing
360 // FIXME: This check ought to be done somewhere else. It is the reason
361 // why text_ is not const. But then, where else to do it?
362 // Well, how can you end up with either (a) a biblio environment that
363 // has no InsetBibitem or (b) a biblio environment with more than one
364 // InsetBibitem? I think the answer is: when paragraphs are merged;
365 // when layout is set; when material is pasted.
366 if (par.brokenBiblio()) {
367 Cursor & cur = const_cast<Cursor &>(bv_->cursor());
368 // In some cases, we do not know how to record undo
369 if (&cur.inset() == &text_->inset())
370 cur.recordUndo(pit, pit);
372 int const moveCursor = par.fixBiblio(buffer);
374 // Is it necessary to update the cursor?
375 if (&cur.inset() == &text_->inset() && cur.pit() == pit) {
378 else if (moveCursor < 0 && cur.pos() >= -moveCursor)
383 // Optimisation: this is used in the next two loops
384 // so better to calculate that once here.
385 int const right_margin = rightMargin(pm);
387 // iterator pointing to paragraph to resolve macros
388 DocIterator parPos = text_->macrocontextPosition();
392 LYXERR(Debug::INFO, "MacroContext not initialised!"
393 << " Going through the buffer again and hope"
394 << " the context is better then.");
395 // FIXME audit updateBuffer calls
396 // This should not be here, but it is not clear yet where else it
398 bv_->buffer().updateBuffer();
399 parPos = text_->macrocontextPosition();
400 LBUFERR(!parPos.empty());
405 par.setBeginOfBody();
406 Font const bufferfont = buffer.params().getFont();
407 CoordCache::Insets & insetCache = bv_->coordCache().insets();
408 InsetList::const_iterator ii = par.insetList().begin();
409 InsetList::const_iterator iend = par.insetList().end();
410 for (; ii != iend; ++ii) {
411 // FIXME Doesn't this HAVE to be non-empty?
412 // position already initialized?
413 if (!parPos.empty()) {
414 parPos.pos() = ii->pos;
416 // A macro template would normally not be visible
417 // by itself. But the tex macro semantics allow
418 // recursion, so we artifically take the context
419 // after the macro template to simulate this.
420 if (ii->inset->lyxCode() == MATHMACRO_CODE)
424 // If there is an end of paragraph marker, its size should be
425 // substracted to the available width. The logic here is
426 // almost the same as in breakRow, remember keep them in sync.
428 if (lyxrc.paragraph_markers && ii->pos + 1 == par.size()
429 && size_type(pit + 1) < text_->paragraphs().size()) {
430 Font f(text_->layoutFont(pit));
431 // ¶ U+00B6 PILCROW SIGN
432 eop = theFontMetrics(f).width(char_type(0x00B6));
435 // do the metric calculation
437 int const w = max_width_ - leftMargin(max_width_, pit, ii->pos)
438 - right_margin - eop;
439 Font const & font = ii->inset->inheritFont() ?
440 displayFont(pit, ii->pos) : bufferfont;
441 MacroContext mc(&buffer, parPos);
442 MetricsInfo mi(bv_, font.fontInfo(), w, mc);
443 ii->inset->metrics(mi, dim);
444 if (!insetCache.has(ii->inset) || insetCache.dim(ii->inset) != dim) {
445 insetCache.add(ii->inset, dim);
451 size_t row_index = 0;
452 // maximum pixel width of a row
454 if (row_index == pm.rows().size())
455 pm.rows().push_back(Row());
456 Row & row = pm.rows()[row_index];
459 breakRow(row, right_margin, pit);
460 setRowHeight(row, pit);
461 row.setChanged(false);
462 if (row_index || row.endpos() < par.size()
463 || (row.right_boundary() && par.inInset().lyxCode() != CELL_CODE)) {
464 /* If there is more than one row or the row has been
465 * broken by a display inset or a newline, expand the text
466 * to the full allowable width. This setting here is
467 * needed for the computeRowMetrics() below. In the case
468 * of a display inset, we do nothing when inside a table
469 * cell, because the tabular code is not prepared for
470 * that, and it triggers when using a caption in a
471 * longtable (see bugs #9945 and #9757).
473 if (dim_.wid < max_width_)
474 dim_.wid = max_width_;
476 int const max_row_width = max(dim_.wid, row.width());
477 computeRowMetrics(pit, row, max_row_width);
478 first = row.endpos();
481 pm.dim().wid = max(pm.dim().wid, row.width());
482 pm.dim().des += row.height();
483 } while (first < par.size());
485 if (row_index < pm.rows().size())
486 pm.rows().resize(row_index);
488 // Make sure that if a par ends in newline, there is one more row
490 if (first > 0 && par.isNewline(first - 1)) {
491 if (row_index == pm.rows().size())
492 pm.rows().push_back(Row());
493 Row & row = pm.rows()[row_index];
496 breakRow(row, right_margin, pit);
497 setRowHeight(row, pit);
498 row.setChanged(false);
499 int const max_row_width = max(dim_.wid, row.width());
500 computeRowMetrics(pit, row, max_row_width);
501 pm.dim().des += row.height();
504 pm.dim().asc += pm.rows()[0].ascent();
505 pm.dim().des -= pm.rows()[0].ascent();
507 changed |= old_dim.height() != pm.dim().height();
513 LyXAlignment TextMetrics::getAlign(Paragraph const & par, Row const & row) const
515 Layout const & layout = par.layout();
518 if (par.params().align() == LYX_ALIGN_LAYOUT)
519 align = layout.align;
521 align = par.params().align();
523 // handle alignment inside tabular cells
524 Inset const & owner = text_->inset();
525 bool forced_block = false;
526 switch (owner.contentAlignment()) {
527 case LYX_ALIGN_BLOCK:
528 // In general block align is the default state, but here it is
529 // an explicit choice. Therefore it should not be overridden
533 case LYX_ALIGN_CENTER:
535 case LYX_ALIGN_RIGHT:
536 if (align == LYX_ALIGN_NONE || align == LYX_ALIGN_BLOCK)
537 align = owner.contentAlignment();
540 // unchanged (use align)
544 // Display-style insets should always be on a centered row
545 if (Inset const * inset = par.getInset(row.pos())) {
546 switch (inset->display()) {
547 case Inset::AlignLeft:
548 align = LYX_ALIGN_BLOCK;
550 case Inset::AlignCenter:
551 align = LYX_ALIGN_CENTER;
554 // unchanged (use align)
556 case Inset::AlignRight:
557 align = LYX_ALIGN_RIGHT;
562 if (align == LYX_ALIGN_BLOCK) {
563 // If this row has been broken abruptly by a display inset, or
564 // it is the end of the paragraph, or the user requested we
565 // not justify stuff, then don't stretch.
566 // A forced block alignment can only be overridden the 'no
567 // justification on screen' setting.
568 if ((row.flushed() && !forced_block)
569 || !bv_->buffer().params().justification)
570 align = text_->isRTL(par) ? LYX_ALIGN_RIGHT : LYX_ALIGN_LEFT;
577 void TextMetrics::computeRowMetrics(pit_type const pit,
578 Row & row, int width) const
583 Paragraph const & par = text_->getPar(pit);
585 int const w = width - row.right_margin - row.width();
586 // FIXME: put back this assertion when the crash on new doc is solved.
587 //LASSERT(w >= 0, /**/);
589 // is there a manual margin with a manual label
590 Layout const & layout = par.layout();
593 if (layout.margintype == MARGIN_MANUAL
594 && layout.labeltype == LABEL_MANUAL) {
595 /// We might have real hfills in the label part
596 nlh = numberOfLabelHfills(par, row);
598 // A manual label par (e.g. List) has an auto-hfill
599 // between the label text and the body of the
601 // But we don't want to do this auto hfill if the par
606 if (nlh && !par.getLabelWidthString().empty())
607 row.label_hfill = labelFill(pit, row) / double(nlh);
610 // are there any hfills in the row?
611 ParagraphMetrics & pm = par_metrics_[pit];
612 int nh = numberOfHfills(row, pm, par.beginOfBody());
616 // We don't have to look at the alignment if the row is already
617 // larger then the permitted width as then we force the
618 // LEFT_ALIGN'edness!
619 if (int(row.width()) >= max_width_)
623 // Common case : there is no hfill, and the alignment will be
625 switch (getAlign(par, row)) {
626 case LYX_ALIGN_BLOCK: {
627 int const ns = row.countSeparators();
628 // If we have separators, then stretch the row
630 row.setSeparatorExtraWidth(double(w) / ns);
631 row.dimension().wid += w;
632 } else if (text_->isRTL(par)) {
633 row.left_margin += w;
634 row.dimension().wid += w;
638 case LYX_ALIGN_RIGHT:
639 row.left_margin += w;
640 row.dimension().wid += w;
642 case LYX_ALIGN_CENTER:
643 row.dimension().wid += w / 2;
644 row.left_margin += w / 2;
648 case LYX_ALIGN_LAYOUT:
649 case LYX_ALIGN_SPECIAL:
650 case LYX_ALIGN_DECIMAL:
658 row.dimension().wid += w;
659 // Set size of hfill insets
660 pos_type const endpos = row.endpos();
661 pos_type body_pos = par.beginOfBody();
663 && (body_pos > endpos || !par.isLineSeparator(body_pos - 1)))
666 CoordCache::Insets & insetCache = bv_->coordCache().insets();
667 Row::iterator cit = row.begin();
668 Row::iterator const cend = row.end();
669 for ( ; cit != cend; ++cit) {
670 if (row.label_hfill && cit->endpos == body_pos
671 && cit->type == Row::SPACE)
672 cit->dim.wid -= int(row.label_hfill * (nlh - 1));
673 if (cit->inset && pm.hfillExpansion(row, cit->pos)) {
674 if (cit->pos >= body_pos) {
675 cit->dim.wid += hfill;
678 cit->dim.wid += hfill_rem;
680 cit->dim.wid += int(row.label_hfill);
681 // Cache the inset dimension.
682 insetCache.add(cit->inset, cit->dim);
688 int TextMetrics::labelFill(pit_type const pit, Row const & row) const
690 Paragraph const & par = text_->getPar(pit);
691 LBUFERR(par.beginOfBody() > 0 || par.isEnvSeparator(0));
694 Row::const_iterator cit = row.begin();
695 Row::const_iterator const end = row.end();
696 // iterate over elements before main body (except the last one,
697 // which is extra space).
698 while (cit!= end && cit->endpos < par.beginOfBody()) {
703 docstring const & label = par.params().labelWidthString();
707 FontMetrics const & fm
708 = theFontMetrics(text_->labelFont(par));
710 return max(0, fm.width(label) - w);
715 // Not used, see TextMetrics::breakRow
716 // this needs special handling - only newlines count as a break point
717 static pos_type addressBreakPoint(pos_type i, Paragraph const & par)
719 pos_type const end = par.size();
722 if (par.isNewline(i))
730 int TextMetrics::labelEnd(pit_type const pit) const
732 // labelEnd is only needed if the layout fills a flushleft label.
733 if (text_->getPar(pit).layout().margintype != MARGIN_MANUAL)
735 // return the beginning of the body
736 return leftMargin(max_width_, pit);
742 * Calling Text::getFont is slow. While rebreaking we scan a
743 * paragraph from left to right calling getFont for every char. This
744 * simple class address this problem by hidding an optimization trick
745 * (not mine btw -AB): the font is reused in the whole font span. The
746 * class handles transparently the "hidden" (not part of the fontlist)
747 * label font (as getFont does).
753 FontIterator(TextMetrics const & tm,
754 Paragraph const & par, pit_type pit, pos_type pos)
755 : tm_(tm), par_(par), pit_(pit), pos_(pos),
756 font_(tm.displayFont(pit, pos)),
757 endspan_(par.fontSpan(pos).last),
758 bodypos_(par.beginOfBody())
762 Font const & operator*() const { return font_; }
765 FontIterator & operator++()
768 if (pos_ < par_.size() && (pos_ > endspan_ || pos_ == bodypos_)) {
769 font_ = tm_.displayFont(pit_, pos_);
770 endspan_ = par_.fontSpan(pos_).last;
776 Font * operator->() { return &font_; }
780 TextMetrics const & tm_;
782 Paragraph const & par_;
797 /** This is the function where the hard work is done. The code here is
798 * very sensitive to small changes :) Note that part of the
799 * intelligence is also in Row::shortenIfNeeded.
801 void TextMetrics::breakRow(Row & row, int const right_margin, pit_type const pit) const
803 Paragraph const & par = text_->getPar(pit);
804 pos_type const end = par.size();
805 pos_type const pos = row.pos();
806 pos_type const body_pos = par.beginOfBody();
807 bool const is_rtl = text_->isRTL(par);
808 bool need_new_row = false;
811 row.left_margin = leftMargin(max_width_, pit, pos);
812 row.right_margin = right_margin;
814 swap(row.left_margin, row.right_margin);
815 // Remember that the row width takes into account the left_margin
816 // but not the right_margin.
817 row.dimension().wid = row.left_margin;
818 // the width available for the row.
819 int const width = max_width_ - row.right_margin;
822 //FIXME: As long as leftMargin() is not correctly implemented for
823 // MARGIN_RIGHT_ADDRESS_BOX, we should also not do this here.
824 // Otherwise, long rows will be painted off the screen.
825 if (par.layout().margintype == MARGIN_RIGHT_ADDRESS_BOX)
826 return addressBreakPoint(pos, par);
829 // check for possible inline completion
830 DocIterator const & ic_it = bv_->inlineCompletionPos();
831 pos_type ic_pos = -1;
832 if (ic_it.inTexted() && ic_it.text() == text_ && ic_it.pit() == pit)
833 ic_pos = ic_it.pos();
835 // Now we iterate through until we reach the right margin
836 // or the end of the par, then build a representation of the row.
838 FontIterator fi = FontIterator(*this, par, pit, pos);
840 // this can happen for an empty row after a newline
843 char_type c = par.getChar(i);
844 // The most special cases are handled first.
845 if (par.isInset(i)) {
846 Inset const * ins = par.getInset(i);
847 Dimension dim = bv_->coordCache().insets().dim(ins);
848 row.add(i, ins, dim, *fi, par.lookupChange(i));
849 } else if (c == ' ' && i + 1 == body_pos) {
850 // There is a space at i, but it should not be
851 // added as a separator, because it is just
852 // before body_pos. Instead, insert some spacing to
854 FontMetrics const & fm = theFontMetrics(text_->labelFont(par));
855 // this is needed to make sure that the row width is correct
857 int const add = max(fm.width(par.layout().labelsep),
858 labelEnd(pit) - row.width());
859 row.addSpace(i, add, *fi, par.lookupChange(i));
860 } else if (c == '\t')
861 row.addSpace(i, theFontMetrics(*fi).width(from_ascii(" ")),
862 *fi, par.lookupChange(i));
863 else if (c == 0x2028 || c == 0x2029) {
865 * U+2028 LINE SEPARATOR
866 * U+2029 PARAGRAPH SEPARATOR
868 * These are special unicode characters that break
869 * lines/pragraphs. Not handling them lead to trouble wrt
870 * Qt QTextLayout formatting. We add a visible character
871 * on screen so that the user can see that something is
875 // ⤶ U+2936 ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
876 // ¶ U+00B6 PILCROW SIGN
877 char_type const screen_char = (c == 0x2028) ? 0x2936 : 0x00B6;
878 row.add(i, screen_char, *fi, par.lookupChange(i));
880 // FIXME: please someone fix the Hebrew/Arabic parenthesis mess!
881 // see also Paragraph::getUChar.
882 if (fi->language()->lang() == "hebrew") {
888 row.add(i, c, *fi, par.lookupChange(i));
891 // add inline completion width
892 // draw logically behind the previous character
893 if (ic_pos == i + 1 && !bv_->inlineCompletion().empty()) {
894 docstring const comp = bv_->inlineCompletion();
895 size_t const uniqueTo =bv_->inlineCompletionUniqueChars();
899 f.fontInfo().setColor(Color_inlinecompletion);
900 row.addVirtual(i + 1, comp.substr(0, uniqueTo), f, Change());
902 f.fontInfo().setColor(Color_nonunique_inlinecompletion);
903 row.addVirtual(i + 1, comp.substr(uniqueTo), f, Change());
906 // Handle some situations that abruptly terminate the row
908 // - Before a display inset
909 // - After a display inset
910 Inset const * inset = 0;
911 if (par.isNewline(i) || par.isEnvSeparator(i)
912 || (i + 1 < end && (inset = par.getInset(i + 1))
914 || (!row.empty() && row.back().inset
915 && row.back().inset->display())) {
917 need_new_row = par.isNewline(i);
924 } while (i < end && row.width() <= width);
928 // End of paragraph marker. The logic here is almost the
929 // same as in redoParagraph, remember keep them in sync.
930 ParagraphList const & pars = text_->paragraphs();
931 if (lyxrc.paragraph_markers && !need_new_row
932 && i == end && size_type(pit + 1) < pars.size()) {
933 // add a virtual element for the end-of-paragraph
934 // marker; it is shown on screen, but does not exist
936 Font f(text_->layoutFont(pit));
937 f.fontInfo().setColor(Color_paragraphmarker);
938 BufferParams const & bparams
939 = text_->inset().buffer().params();
940 f.setLanguage(par.getParLanguage(bparams));
941 // ¶ U+00B6 PILCROW SIGN
942 row.addVirtual(end, docstring(1, char_type(0x00B6)), f, Change());
945 // if the row is too large, try to cut at last separator. In case
946 // of success, reset indication that the row was broken abruptly.
947 int const next_width = max_width_ - leftMargin(max_width_, pit, row.endpos())
950 if (row.shortenIfNeeded(body_pos, width, next_width))
952 row.right_boundary(!row.empty() && row.endpos() < end
953 && row.back().endpos == row.endpos());
954 // Last row in paragraph is flushed
955 if (row.endpos() == end)
958 // make sure that the RTL elements are in reverse ordering
959 row.reverseRTL(is_rtl);
960 //LYXERR0("breakrow: row is " << row);
964 void TextMetrics::setRowHeight(Row & row, pit_type const pit,
965 bool topBottomSpace) const
967 Paragraph const & par = text_->getPar(pit);
968 // get the maximum ascent and the maximum descent
969 double layoutasc = 0;
970 double layoutdesc = 0;
971 double const dh = defaultRowHeight();
973 // ok, let us initialize the maxasc and maxdesc value.
974 // Only the fontsize count. The other properties
975 // are taken from the layoutfont. Nicer on the screen :)
976 Layout const & layout = par.layout();
978 // as max get the first character of this row then it can
979 // increase but not decrease the height. Just some point to
980 // start with so we don't have to do the assignment below too
982 Buffer const & buffer = bv_->buffer();
983 Font font = displayFont(pit, row.pos());
984 FontSize const tmpsize = font.fontInfo().size();
985 font.fontInfo() = text_->layoutFont(pit);
986 FontSize const size = font.fontInfo().size();
987 font.fontInfo().setSize(tmpsize);
989 FontInfo labelfont = text_->labelFont(par);
991 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
992 FontMetrics const & fontmetrics = theFontMetrics(font);
994 // these are minimum values
995 double const spacing_val = layout.spacing.getValue()
996 * text_->spacing(par);
997 //lyxerr << "spacing_val = " << spacing_val << endl;
998 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
999 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
1001 // insets may be taller
1002 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1003 Row::const_iterator cit = row.begin();
1004 Row::const_iterator cend = row.end();
1005 for ( ; cit != cend; ++cit) {
1007 Dimension const & dim = insetCache.dim(cit->inset);
1008 maxasc = max(maxasc, dim.ascent());
1009 maxdesc = max(maxdesc, dim.descent());
1013 // Check if any custom fonts are larger (Asger)
1014 // This is not completely correct, but we can live with the small,
1015 // cosmetic error for now.
1019 par.highestFontInRange(row.pos(), row.endpos(), size);
1020 if (maxsize > font.fontInfo().size()) {
1021 // use standard paragraph font with the maximal size
1022 FontInfo maxfont = font.fontInfo();
1023 maxfont.setSize(maxsize);
1024 FontMetrics const & maxfontmetrics = theFontMetrics(maxfont);
1025 maxasc = max(maxasc, maxfontmetrics.maxAscent());
1026 maxdesc = max(maxdesc, maxfontmetrics.maxDescent());
1029 // This is nicer with box insets:
1033 ParagraphList const & pars = text_->paragraphs();
1034 Inset const & inset = text_->inset();
1036 // is it a top line?
1037 if (row.pos() == 0 && topBottomSpace) {
1038 BufferParams const & bufparams = buffer.params();
1039 // some parskips VERY EASY IMPLEMENTATION
1040 if (bufparams.paragraph_separation == BufferParams::ParagraphSkipSeparation
1041 && !inset.getLayout().parbreakIsNewline()
1042 && !par.layout().parbreak_is_newline
1044 && ((layout.isParagraph() && par.getDepth() == 0)
1045 || (pars[pit - 1].layout().isParagraph()
1046 && pars[pit - 1].getDepth() == 0))) {
1047 maxasc += bufparams.getDefSkip().inPixels(*bv_);
1050 if (par.params().startOfAppendix())
1051 maxasc += int(3 * dh);
1053 // special code for the top label
1054 if (layout.labelIsAbove()
1055 && (!layout.isParagraphGroup() || text_->isFirstInSequence(pit))
1056 && !par.labelString().empty()) {
1058 labelfont_metrics.maxHeight()
1059 * layout.spacing.getValue()
1060 * text_->spacing(par)
1061 + (layout.topsep + layout.labelbottomsep) * dh);
1064 // Add the layout spaces, for example before and after
1065 // a section, or between the items of a itemize or enumerate
1068 pit_type prev = text_->depthHook(pit, par.getDepth());
1069 Paragraph const & prevpar = pars[prev];
1071 && prevpar.layout() == layout
1072 && prevpar.getDepth() == par.getDepth()
1073 && prevpar.getLabelWidthString()
1074 == par.getLabelWidthString()) {
1075 layoutasc = layout.itemsep * dh;
1076 } else if (pit != 0 || row.pos() != 0) {
1077 if (layout.topsep > 0)
1078 layoutasc = layout.topsep * dh;
1081 prev = text_->outerHook(pit);
1082 if (prev != pit_type(pars.size())) {
1083 maxasc += int(pars[prev].layout().parsep * dh);
1084 } else if (pit != 0) {
1085 Paragraph const & prevpar = pars[pit - 1];
1086 if (prevpar.getDepth() != 0 ||
1087 prevpar.layout() == layout) {
1088 maxasc += int(layout.parsep * dh);
1093 // is it a bottom line?
1094 if (row.endpos() >= par.size() && topBottomSpace) {
1095 // add the layout spaces, for example before and after
1096 // a section, or between the items of a itemize or enumerate
1098 pit_type nextpit = pit + 1;
1099 if (nextpit != pit_type(pars.size())) {
1100 pit_type cpit = pit;
1102 if (pars[cpit].getDepth() > pars[nextpit].getDepth()) {
1103 double usual = pars[cpit].layout().bottomsep * dh;
1105 cpit = text_->depthHook(cpit, pars[nextpit].getDepth());
1106 if (pars[cpit].layout() != pars[nextpit].layout()
1107 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1108 unusual = pars[cpit].layout().bottomsep * dh;
1109 layoutdesc = max(unusual, usual);
1110 } else if (pars[cpit].getDepth() == pars[nextpit].getDepth()) {
1111 if (pars[cpit].layout() != pars[nextpit].layout()
1112 || pars[nextpit].getLabelWidthString() != pars[cpit].getLabelWidthString())
1113 layoutdesc = int(pars[cpit].layout().bottomsep * dh);
1118 // incalculate the layout spaces
1119 maxasc += int(layoutasc * 2 / (2 + pars[pit].getDepth()));
1120 maxdesc += int(layoutdesc * 2 / (2 + pars[pit].getDepth()));
1122 // FIXME: the correct way is to do the following is to move the
1123 // following code in another method specially tailored for the
1124 // main Text. The following test is thus bogus.
1125 // Top and bottom margin of the document (only at top-level)
1126 if (main_text_ && topBottomSpace) {
1127 if (pit == 0 && row.pos() == 0)
1129 if (pit + 1 == pit_type(pars.size()) &&
1130 row.endpos() == par.size() &&
1131 !(row.endpos() > 0 && par.isNewline(row.endpos() - 1)))
1135 row.dimension().asc = maxasc + labeladdon;
1136 row.dimension().des = maxdesc;
1140 // x is an absolute screen coord
1141 // returns the column near the specified x-coordinate of the row
1142 // x is set to the real beginning of this column
1143 pos_type TextMetrics::getPosNearX(Row const & row, int & x,
1144 bool & boundary) const
1146 //LYXERR0("getPosNearX(" << x << ") row=" << row);
1147 /// For the main Text, it is possible that this pit is not
1148 /// yet in the CoordCache when moving cursor up.
1149 /// x Paragraph coordinate is always 0 for main text anyway.
1150 int const xo = origin_.x_;
1154 CursorSlice rowSlice(const_cast<InsetText &>(text_->inset()));
1155 rowSlice.pit() = row.pit();
1156 rowSlice.pos() = row.pos();
1158 // Adapt to cursor row scroll offset if applicable.
1159 if (bv_->currentRowSlice() == rowSlice)
1160 offset = bv_->horizScrollOffset();
1163 pos_type pos = row.pos();
1166 x = row.left_margin;
1167 else if (x <= row.left_margin) {
1168 pos = row.front().left_pos();
1169 x = row.left_margin;
1170 } else if (x >= row.width()) {
1171 pos = row.back().right_pos();
1174 double w = row.left_margin;
1175 Row::const_iterator cit = row.begin();
1176 Row::const_iterator cend = row.end();
1177 for ( ; cit != cend; ++cit) {
1178 if (w <= x && w + cit->full_width() > x) {
1179 int x_offset = int(x - w);
1180 pos = cit->x2pos(x_offset);
1181 x = int(x_offset + w);
1184 w += cit->full_width();
1186 if (cit == row.end()) {
1187 pos = row.back().right_pos();
1190 /** This tests for the case where the cursor is placed
1191 * just before a font direction change. See comment on
1192 * the boundary_ member in DocIterator.h to understand
1193 * how boundary helps here.
1195 else if (pos == cit->endpos
1196 && ((!cit->isRTL() && cit + 1 != row.end()
1197 && (cit + 1)->isRTL())
1198 || (cit->isRTL() && cit != row.begin()
1199 && !(cit - 1)->isRTL())))
1203 /** This tests for the case where the cursor is set at the end
1204 * of a row which has been broken due something else than a
1205 * separator (a display inset or a forced breaking of the
1206 * row). We know that there is a separator when the end of the
1207 * row is larger than the end of its last element.
1209 if (!row.empty() && pos == row.back().endpos
1210 && row.back().endpos == row.endpos()) {
1211 Inset const * inset = row.back().inset;
1212 if (inset && (inset->lyxCode() == NEWLINE_CODE
1213 || inset->lyxCode() == SEPARATOR_CODE))
1214 pos = row.back().pos;
1216 boundary = row.right_boundary();
1220 //LYXERR0("getPosNearX ==> pos=" << pos << ", boundary=" << boundary);
1226 pos_type TextMetrics::x2pos(pit_type pit, int row, int x) const
1228 // We play safe and use parMetrics(pit) to make sure the
1229 // ParagraphMetrics will be redone and OK to use if needed.
1230 // Otherwise we would use an empty ParagraphMetrics in
1231 // upDownInText() while in selection mode.
1232 ParagraphMetrics const & pm = parMetrics(pit);
1234 LBUFERR(row < int(pm.rows().size()));
1236 Row const & r = pm.rows()[row];
1237 return getPosNearX(r, x, bound);
1241 void TextMetrics::newParMetricsDown()
1243 pair<pit_type, ParagraphMetrics> const & last = *par_metrics_.rbegin();
1244 pit_type const pit = last.first + 1;
1245 if (pit == int(text_->paragraphs().size()))
1248 // do it and update its position.
1250 par_metrics_[pit].setPosition(last.second.position()
1251 + last.second.descent() + par_metrics_[pit].ascent());
1255 void TextMetrics::newParMetricsUp()
1257 pair<pit_type, ParagraphMetrics> const & first = *par_metrics_.begin();
1258 if (first.first == 0)
1261 pit_type const pit = first.first - 1;
1262 // do it and update its position.
1264 par_metrics_[pit].setPosition(first.second.position()
1265 - first.second.ascent() - par_metrics_[pit].descent());
1268 // y is screen coordinate
1269 pit_type TextMetrics::getPitNearY(int y)
1271 LASSERT(!text_->paragraphs().empty(), return -1);
1272 LASSERT(!par_metrics_.empty(), return -1);
1273 LYXERR(Debug::DEBUG, "y: " << y << " cache size: " << par_metrics_.size());
1275 // look for highest numbered paragraph with y coordinate less than given y
1278 ParMetricsCache::const_iterator it = par_metrics_.begin();
1279 ParMetricsCache::const_iterator et = par_metrics_.end();
1280 ParMetricsCache::const_iterator last = et;
1283 ParagraphMetrics const & pm = it->second;
1285 if (y < it->second.position() - int(pm.ascent())) {
1286 // We are looking for a position that is before the first paragraph in
1287 // the cache (which is in priciple off-screen, that is before the
1290 // We are already at the first paragraph in the inset.
1292 // OK, this is the paragraph we are looking for.
1293 pit = it->first - 1;
1298 ParagraphMetrics const & pm_last = par_metrics_[last->first];
1300 if (y >= last->second.position() + int(pm_last.descent())) {
1301 // We are looking for a position that is after the last paragraph in
1302 // the cache (which is in priciple off-screen), that is before the
1304 pit = last->first + 1;
1305 if (pit == int(text_->paragraphs().size()))
1306 // We are already at the last paragraph in the inset.
1308 // OK, this is the paragraph we are looking for.
1309 newParMetricsDown();
1313 for (; it != et; ++it) {
1314 LYXERR(Debug::DEBUG, "examining: pit: " << it->first
1315 << " y: " << it->second.position());
1317 ParagraphMetrics const & pm = par_metrics_[it->first];
1319 if (it->first >= pit && int(it->second.position()) - int(pm.ascent()) <= y) {
1321 yy = it->second.position();
1325 LYXERR(Debug::DEBUG, "found best y: " << yy << " for pit: " << pit);
1331 Row const & TextMetrics::getPitAndRowNearY(int & y, pit_type & pit,
1332 bool assert_in_view, bool up)
1334 ParagraphMetrics const & pm = par_metrics_[pit];
1336 int yy = pm.position() - pm.ascent();
1337 LBUFERR(!pm.rows().empty());
1338 RowList::const_iterator rit = pm.rows().begin();
1339 RowList::const_iterator rlast = pm.rows().end();
1341 for (; rit != rlast; yy += rit->height(), ++rit)
1342 if (yy + rit->height() > y)
1345 if (assert_in_view) {
1346 if (!up && yy + rit->height() > y) {
1347 if (rit != pm.rows().begin()) {
1350 } else if (pit != 0) {
1353 ParagraphMetrics const & pm2 = par_metrics_[pit];
1354 rit = pm2.rows().end();
1358 } else if (up && yy != y) {
1360 y = yy + rit->height();
1362 } else if (pit < int(text_->paragraphs().size()) - 1) {
1364 newParMetricsDown();
1365 ParagraphMetrics const & pm2 = par_metrics_[pit];
1366 rit = pm2.rows().begin();
1375 // x,y are absolute screen coordinates
1376 // sets cursor recursively descending into nested editable insets
1377 Inset * TextMetrics::editXY(Cursor & cur, int x, int y,
1378 bool assert_in_view, bool up)
1380 if (lyxerr.debugging(Debug::WORKAREA)) {
1381 LYXERR0("TextMetrics::editXY(cur, " << x << ", " << y << ")");
1382 cur.bv().coordCache().dump();
1384 pit_type pit = getPitNearY(y);
1385 LASSERT(pit != -1, return 0);
1386 Row const & row = getPitAndRowNearY(y, pit, assert_in_view, up);
1389 // Do we cover an inset?
1390 InsetList::InsetTable * it = checkInsetHit(pit, x, y);
1393 // No inset, set position in the text
1394 bool bound = false; // is modified by getPosNearX
1395 cur.pos() = getPosNearX(row, x, bound);
1396 cur.boundary(bound);
1397 cur.setCurrentFont();
1402 Inset * inset = it->inset;
1403 //lyxerr << "inset " << inset << " hit at x: " << x << " y: " << y << endl;
1405 // Set position in front of inset
1406 cur.pos() = it->pos;
1407 cur.boundary(false);
1410 // Try to descend recursively inside the inset.
1411 Inset * edited = inset->editXY(cur, x, y);
1412 // FIXME: it is not clear that the test on position is needed
1413 // Remove it if/when semantics of editXY is clarified
1414 if (cur.text() == text_ && cur.pos() == it->pos) {
1415 // non-editable inset, set cursor after the inset if x is
1416 // nearer to that position (bug 9628)
1417 bool bound = false; // is modified by getPosNearX
1418 cur.pos() = getPosNearX(row, x, bound);
1419 cur.boundary(bound);
1420 cur.setCurrentFont();
1424 if (cur.top().text() == text_)
1425 cur.setCurrentFont();
1430 void TextMetrics::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1432 LASSERT(text_ == cur.text(), return);
1433 pit_type const pit = getPitNearY(y);
1434 LASSERT(pit != -1, return);
1436 ParagraphMetrics const & pm = par_metrics_[pit];
1438 int yy = pm.position() - pm.ascent();
1439 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y <<
1440 " pit: " << pit << " yy: " << yy);
1443 LBUFERR(pm.rows().size());
1444 for (; r < int(pm.rows().size()) - 1; ++r) {
1445 Row const & row = pm.rows()[r];
1446 if (int(yy + row.height()) > y)
1451 Row const & row = pm.rows()[r];
1453 LYXERR(Debug::DEBUG, "row " << r << " from pos: " << row.pos());
1457 pos_type const pos = getPosNearX(row, xx, bound);
1459 LYXERR(Debug::DEBUG, "setting cursor pit: " << pit << " pos: " << pos);
1461 text_->setCursor(cur, pit, pos, true, bound);
1462 // remember new position.
1467 //takes screen x,y coordinates
1468 InsetList::InsetTable * TextMetrics::checkInsetHit(pit_type pit, int x, int y)
1470 Paragraph const & par = text_->paragraphs()[pit];
1471 CoordCache::Insets const & insetCache = bv_->coordCache().getInsets();
1473 LYXERR(Debug::DEBUG, "x: " << x << " y: " << y << " pit: " << pit);
1475 InsetList::const_iterator iit = par.insetList().begin();
1476 InsetList::const_iterator iend = par.insetList().end();
1477 for (; iit != iend; ++iit) {
1478 Inset * inset = iit->inset;
1480 LYXERR(Debug::DEBUG, "examining inset " << inset);
1482 if (!insetCache.has(inset)) {
1483 LYXERR(Debug::DEBUG, "inset has no cached position");
1487 Dimension const & dim = insetCache.dim(inset);
1488 Point p = insetCache.xy(inset);
1490 LYXERR(Debug::DEBUG, "xo: " << p.x_ << "..." << p.x_ + dim.wid
1491 << " yo: " << p.y_ - dim.asc << "..." << p.y_ + dim.des);
1493 if (x >= p.x_ && x <= p.x_ + dim.wid
1494 && y >= p.y_ - dim.asc && y <= p.y_ + dim.des) {
1495 LYXERR(Debug::DEBUG, "Hit inset: " << inset);
1496 return const_cast<InsetList::InsetTable *>(&(*iit));
1500 LYXERR(Debug::DEBUG, "No inset hit. ");
1505 //takes screen x,y coordinates
1506 Inset * TextMetrics::checkInsetHit(int x, int y)
1508 pit_type const pit = getPitNearY(y);
1509 LASSERT(pit != -1, return 0);
1510 InsetList::InsetTable * it = checkInsetHit(pit, x, y);
1519 Row::const_iterator const
1520 TextMetrics::findRowElement(Row const & row, pos_type const pos,
1521 bool const boundary, double & x) const
1524 * When boundary is true, position i is in the row element (pos, endpos)
1527 * whereas, when boundary is false, the test is
1529 * The correction below allows to handle both cases.
1531 int const boundary_corr = (boundary && pos) ? -1 : 0;
1533 x = row.left_margin;
1535 /** Early return in trivial cases
1536 * 1) the row is empty
1537 * 2) the position is the left-most position of the row; there
1538 * is a quirk here however: if the first element is virtual
1539 * (end-of-par marker for example), then we have to look
1543 || (pos == row.begin()->left_pos() && !boundary
1544 && !row.begin()->isVirtual()))
1547 Row::const_iterator cit = row.begin();
1548 for ( ; cit != row.end() ; ++cit) {
1549 /** Look whether the cursor is inside the element's
1550 * span. Note that it is necessary to take the
1551 * boundary into account, and to accept virtual
1552 * elements, which have pos == endpos.
1554 if (pos + boundary_corr >= cit->pos
1555 && (pos + boundary_corr < cit->endpos || cit->isVirtual())) {
1556 x += cit->pos2x(pos);
1559 x += cit->full_width();
1562 if (cit == row.end())
1569 int TextMetrics::cursorX(CursorSlice const & sl,
1570 bool boundary) const
1572 LASSERT(sl.text() == text_, return 0);
1574 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1575 if (pm.rows().empty())
1577 Row const & row = pm.getRow(sl.pos(), boundary);
1578 pos_type const pos = sl.pos();
1581 findRowElement(row, pos, boundary, x);
1587 int TextMetrics::cursorY(CursorSlice const & sl, bool boundary) const
1589 //lyxerr << "TextMetrics::cursorY: boundary: " << boundary << endl;
1590 ParagraphMetrics const & pm = par_metrics_[sl.pit()];
1591 if (pm.rows().empty())
1595 h -= par_metrics_[0].rows()[0].ascent();
1596 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1597 h += par_metrics_[pit].height();
1600 if (pos && boundary)
1602 size_t const rend = pm.pos2row(pos);
1603 for (size_t rit = 0; rit != rend; ++rit)
1604 h += pm.rows()[rit].height();
1605 h += pm.rows()[rend].ascent();
1610 // the cursor set functions have a special mechanism. When they
1611 // realize you left an empty paragraph, they will delete it.
1613 bool TextMetrics::cursorHome(Cursor & cur)
1615 LASSERT(text_ == cur.text(), return false);
1616 ParagraphMetrics const & pm = par_metrics_[cur.pit()];
1617 Row const & row = pm.getRow(cur.pos(),cur.boundary());
1618 return text_->setCursor(cur, cur.pit(), row.pos());
1622 bool TextMetrics::cursorEnd(Cursor & cur)
1624 LASSERT(text_ == cur.text(), return false);
1625 // if not on the last row of the par, put the cursor before
1626 // the final space exept if I have a spanning inset or one string
1627 // is so long that we force a break.
1628 pos_type end = cur.textRow().endpos();
1630 // empty text, end-1 is no valid position
1632 bool boundary = false;
1633 if (end != cur.lastpos()) {
1634 if (!cur.paragraph().isLineSeparator(end-1)
1635 && !cur.paragraph().isNewline(end-1)
1636 && !cur.paragraph().isEnvSeparator(end-1))
1640 } else if (cur.paragraph().isEnvSeparator(end-1))
1642 return text_->setCursor(cur, cur.pit(), end, true, boundary);
1646 void TextMetrics::deleteLineForward(Cursor & cur)
1648 LASSERT(text_ == cur.text(), return);
1649 if (cur.lastpos() == 0) {
1650 // Paragraph is empty, so we just go forward
1651 text_->cursorForward(cur);
1654 cur.setSelection(true); // to avoid deletion
1657 // What is this test for ??? (JMarc)
1658 if (!cur.selection())
1659 text_->deleteWordForward(cur);
1661 cap::cutSelection(cur, true, false);
1662 cur.checkBufferStructure();
1667 bool TextMetrics::isLastRow(pit_type pit, Row const & row) const
1669 ParagraphList const & pars = text_->paragraphs();
1670 return row.endpos() >= pars[pit].size()
1671 && pit + 1 == pit_type(pars.size());
1675 bool TextMetrics::isFirstRow(pit_type pit, Row const & row) const
1677 return row.pos() == 0 && pit == 0;
1681 int TextMetrics::leftMargin(int max_width, pit_type pit) const
1683 return leftMargin(max_width, pit, text_->paragraphs()[pit].size());
1687 int TextMetrics::leftMargin(int max_width,
1688 pit_type const pit, pos_type const pos) const
1690 ParagraphList const & pars = text_->paragraphs();
1692 LASSERT(pit >= 0, return 0);
1693 LASSERT(pit < int(pars.size()), return 0);
1694 Paragraph const & par = pars[pit];
1695 LASSERT(pos >= 0, return 0);
1696 LASSERT(pos <= par.size(), return 0);
1697 Buffer const & buffer = bv_->buffer();
1698 //lyxerr << "TextMetrics::leftMargin: pit: " << pit << " pos: " << pos << endl;
1699 DocumentClass const & tclass = buffer.params().documentClass();
1700 Layout const & layout = par.layout();
1702 docstring parindent = layout.parindent;
1706 if (text_->isMainText())
1707 l_margin += bv_->leftMargin();
1709 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1710 tclass.leftmargin());
1712 int depth = par.getDepth();
1714 // find the next level paragraph
1715 pit_type newpar = text_->outerHook(pit);
1716 if (newpar != pit_type(pars.size())) {
1717 if (pars[newpar].layout().isEnvironment()) {
1718 int nestmargin = depth * nestMargin();
1719 if (text_->isMainText())
1720 nestmargin += changebarMargin();
1721 l_margin = max(leftMargin(max_width, newpar), nestmargin);
1722 // Remove the parindent that has been added
1723 // if the paragraph was empty.
1724 if (pars[newpar].empty() &&
1725 buffer.params().paragraph_separation ==
1726 BufferParams::ParagraphIndentSeparation) {
1727 docstring pi = pars[newpar].layout().parindent;
1728 l_margin -= theFontMetrics(
1729 buffer.params().getFont()).signedWidth(pi);
1732 if (tclass.isDefaultLayout(par.layout())
1733 || tclass.isPlainLayout(par.layout())) {
1734 if (pars[newpar].params().noindent())
1737 parindent = pars[newpar].layout().parindent;
1742 // This happens after sections or environments in standard classes.
1743 // We have to check the previous layout at same depth.
1744 if (buffer.params().paragraph_separation ==
1745 BufferParams::ParagraphSkipSeparation)
1747 else if (pit > 0 && pars[pit - 1].getDepth() >= par.getDepth()) {
1748 pit_type prev = text_->depthHook(pit, par.getDepth());
1749 if (par.layout() == pars[prev].layout()) {
1751 && pars[pit - 1].layout().nextnoindent)
1753 } else if (pars[prev].layout().nextnoindent)
1757 FontInfo const labelfont = text_->labelFont(par);
1758 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
1760 switch (layout.margintype) {
1761 case MARGIN_DYNAMIC:
1762 if (!layout.leftmargin.empty()) {
1763 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
1766 if (!par.labelString().empty()) {
1767 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1768 l_margin += labelfont_metrics.width(par.labelString());
1769 l_margin += labelfont_metrics.width(layout.labelsep);
1773 case MARGIN_MANUAL: {
1774 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1775 // The width of an empty par, even with manual label, should be 0
1776 if (!par.empty() && pos >= par.beginOfBody()) {
1777 if (!par.getLabelWidthString().empty()) {
1778 docstring labstr = par.getLabelWidthString();
1779 l_margin += labelfont_metrics.width(labstr);
1780 l_margin += labelfont_metrics.width(layout.labelsep);
1786 case MARGIN_STATIC: {
1787 l_margin += theFontMetrics(buffer.params().getFont()).
1788 signedWidth(layout.leftmargin) * 4 / (par.getDepth() + 4);
1792 case MARGIN_FIRST_DYNAMIC:
1793 if (layout.labeltype == LABEL_MANUAL) {
1794 // if we are at position 0, we are never in the body
1795 if (pos > 0 && pos >= par.beginOfBody())
1796 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1798 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1800 // Special case to fix problems with
1802 || (layout.labeltype == LABEL_STATIC
1803 && layout.latextype == LATEX_ENVIRONMENT
1804 && !text_->isFirstInSequence(pit))) {
1805 l_margin += labelfont_metrics.signedWidth(layout.leftmargin);
1806 } else if (!layout.labelIsAbove()) {
1807 l_margin += labelfont_metrics.signedWidth(layout.labelindent);
1808 l_margin += labelfont_metrics.width(layout.labelsep);
1809 l_margin += labelfont_metrics.width(par.labelString());
1813 case MARGIN_RIGHT_ADDRESS_BOX: {
1815 // The left margin depends on the widest row in this paragraph.
1816 // This code is wrong because it depends on the rows, but at the
1817 // same time this function is used in redoParagraph to construct
1819 ParagraphMetrics const & pm = par_metrics_[pit];
1820 RowList::const_iterator rit = pm.rows().begin();
1821 RowList::const_iterator end = pm.rows().end();
1822 int minfill = max_width;
1823 for ( ; rit != end; ++rit)
1824 if (rit->fill() < minfill)
1825 minfill = rit->fill();
1826 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(layout.leftmargin);
1827 l_margin += minfill;
1829 // also wrong, but much shorter.
1830 l_margin += max_width / 2;
1835 if (!par.params().leftIndent().zero())
1836 l_margin += par.params().leftIndent().inPixels(max_width, labelfont_metrics.em());
1840 if (par.params().align() == LYX_ALIGN_LAYOUT)
1841 align = layout.align;
1843 align = par.params().align();
1845 // set the correct parindent
1847 && (layout.labeltype == LABEL_NO_LABEL
1848 || layout.labeltype == LABEL_ABOVE
1849 || layout.labeltype == LABEL_CENTERED
1850 || (layout.labeltype == LABEL_STATIC
1851 && layout.latextype == LATEX_ENVIRONMENT
1852 && !text_->isFirstInSequence(pit)))
1853 && (align == LYX_ALIGN_BLOCK || align == LYX_ALIGN_LEFT)
1854 && !par.params().noindent()
1855 // in some insets, paragraphs are never indented
1856 && !text_->inset().neverIndent()
1857 // display style insets are always centered, omit indentation
1860 && par.getInset(pos)->display())
1861 && (!(tclass.isDefaultLayout(par.layout())
1862 || tclass.isPlainLayout(par.layout()))
1863 || buffer.params().paragraph_separation
1864 == BufferParams::ParagraphIndentSeparation)) {
1865 // use the parindent of the layout when the
1866 // default indentation is used otherwise use
1867 // the indentation set in the document
1869 if (buffer.params().getIndentation().asLyXCommand() == "default")
1870 l_margin += theFontMetrics(
1871 buffer.params().getFont()).signedWidth(parindent);
1873 l_margin += buffer.params().getIndentation().inPixels(*bv_);
1880 void TextMetrics::draw(PainterInfo & pi, int x, int y) const
1882 if (par_metrics_.empty())
1888 ParMetricsCache::iterator it = par_metrics_.begin();
1889 ParMetricsCache::iterator const pm_end = par_metrics_.end();
1890 y -= it->second.ascent();
1891 for (; it != pm_end; ++it) {
1892 ParagraphMetrics const & pmi = it->second;
1894 pit_type const pit = it->first;
1895 // Save the paragraph position in the cache.
1896 it->second.setPosition(y);
1897 drawParagraph(pi, pit, x, y);
1903 void TextMetrics::drawParagraph(PainterInfo & pi, pit_type const pit, int const x, int y) const
1905 ParagraphMetrics const & pm = par_metrics_[pit];
1906 if (pm.rows().empty())
1909 bool const original_drawing_state = pi.pain.isDrawingEnabled();
1910 int const ww = bv_->workHeight();
1911 size_t const nrows = pm.rows().size();
1913 Cursor const & cur = bv_->cursor();
1914 DocIterator sel_beg = cur.selectionBegin();
1915 DocIterator sel_end = cur.selectionEnd();
1916 bool selection = cur.selection()
1917 // This is our text.
1918 && cur.text() == text_
1919 // if the anchor is outside, this is not our selection
1920 && cur.normalAnchor().text() == text_
1921 && pit >= sel_beg.pit() && pit <= sel_end.pit();
1923 // We store the begin and end pos of the selection relative to this par
1924 DocIterator sel_beg_par = cur.selectionBegin();
1925 DocIterator sel_end_par = cur.selectionEnd();
1927 // We care only about visible selection.
1929 if (pit != sel_beg.pit()) {
1930 sel_beg_par.pit() = pit;
1931 sel_beg_par.pos() = 0;
1933 if (pit != sel_end.pit()) {
1934 sel_end_par.pit() = pit;
1935 sel_end_par.pos() = sel_end_par.lastpos();
1939 for (size_t i = 0; i != nrows; ++i) {
1941 Row const & row = pm.rows()[i];
1946 CursorSlice rowSlice(const_cast<InsetText &>(text_->inset()));
1947 rowSlice.pit() = pit;
1948 rowSlice.pos() = row.pos();
1950 bool const inside = (y + row.descent() >= 0
1951 && y - row.ascent() < ww);
1953 // Adapt to cursor row scroll offset if applicable.
1954 if (bv_->currentRowSlice() == rowSlice)
1955 row_x -= bv_->horizScrollOffset();
1957 // It is not needed to draw on screen if we are not inside.
1958 pi.pain.setDrawingEnabled(inside && original_drawing_state);
1960 RowPainter rp(pi, *text_, pit, row, row_x, y);
1963 row.setSelectionAndMargins(sel_beg_par, sel_end_par);
1965 row.setSelection(-1, -1);
1967 // The row knows nothing about the paragraph, so we have to check
1968 // whether this row is the first or last and update the margins.
1969 if (row.selection()) {
1970 if (row.sel_beg == 0)
1971 row.begin_margin_sel = sel_beg.pit() < pit;
1972 if (row.sel_end == sel_end_par.lastpos())
1973 row.end_margin_sel = sel_end.pit() > pit;
1976 // Row signature; has row changed since last paint?
1977 if (pi.pain.isDrawingEnabled())
1978 row.setCrc(pm.computeRowSignature(row, *bv_));
1979 bool row_has_changed = row.changed()
1980 || rowSlice == bv_->lastRowSlice();
1982 // Take this opportunity to spellcheck the row contents.
1983 if (row_has_changed && pi.do_spellcheck && lyxrc.spellcheck_continuously) {
1984 text_->getPar(pit).spellCheck();
1987 // Don't paint the row if a full repaint has not been requested
1988 // and if it has not changed.
1989 if (!pi.full_repaint && !row_has_changed) {
1990 // Paint only the insets if the text itself is
1992 rp.paintOnlyInsets();
1997 // Clear background of this row if paragraph background was not
1998 // already cleared because of a full repaint.
1999 if (!pi.full_repaint && row_has_changed) {
2000 LYXERR(Debug::PAINTING, "Clear rect@("
2001 << max(row_x, 0) << ", " << y - row.ascent() << ")="
2002 << width() << " x " << row.height());
2003 pi.pain.fillRectangle(max(row_x, 0), y - row.ascent(),
2004 width(), row.height(), pi.background_color);
2007 // Instrumentation for testing row cache (see also
2009 if (lyxerr.debugging(Debug::PAINTING) && inside
2010 && (row.selection() || pi.full_repaint || row_has_changed)) {
2011 string const foreword = text_->isMainText() ?
2012 "main text redraw " : "inset text redraw: ";
2013 LYXERR(Debug::PAINTING, foreword << "pit=" << pit << " row=" << i
2014 << " row_selection=" << row.selection()
2015 << " full_repaint=" << pi.full_repaint
2016 << " row_has_changed=" << row_has_changed
2017 << " drawingEnabled=" << pi.pain.isDrawingEnabled());
2020 // Backup full_repaint status and force full repaint
2021 // for inner insets as the Row has been cleared out.
2022 bool tmp = pi.full_repaint;
2023 pi.full_repaint = true;
2025 rp.paintSelection();
2028 rp.paintChangeBar();
2029 bool const is_rtl = text_->isRTL(text_->getPar(pit));
2030 if (i == 0 && !is_rtl)
2032 if (i == nrows - 1 && is_rtl)
2035 if (i == nrows - 1 && !is_rtl)
2037 if (i == 0 && is_rtl)
2039 rp.paintTooLargeMarks(row_x + row.left_x() < 0,
2040 row_x + row.right_x() > bv_->workWidth());
2043 // Restore full_repaint status.
2044 pi.full_repaint = tmp;
2046 // Re-enable screen drawing for future use of the painter.
2047 pi.pain.setDrawingEnabled(original_drawing_state);
2049 //LYXERR(Debug::PAINTING, ".");
2053 void TextMetrics::completionPosAndDim(Cursor const & cur, int & x, int & y,
2054 Dimension & dim) const
2056 Cursor const & bvcur = cur.bv().cursor();
2058 // get word in front of cursor
2059 docstring word = text_->previousWord(bvcur.top());
2060 DocIterator wordStart = bvcur;
2061 wordStart.pos() -= word.length();
2063 // get position on screen of the word start and end
2064 //FIXME: Is it necessary to explicitly set this to false?
2065 wordStart.boundary(false);
2066 Point lxy = cur.bv().getPos(wordStart);
2067 Point rxy = cur.bv().getPos(bvcur);
2069 // calculate dimensions of the word
2071 row.pos(wordStart.pos());
2072 row.endpos(bvcur.pos());
2073 setRowHeight(row, bvcur.pit(), false);
2074 dim = row.dimension();
2075 dim.wid = abs(rxy.x_ - lxy.x_);
2077 // calculate position of word
2079 x = min(rxy.x_, lxy.x_);
2081 //lyxerr << "wid=" << dim.width() << " x=" << x << " y=" << y << " lxy.x_=" << lxy.x_ << " rxy.x_=" << rxy.x_ << " word=" << word << std::endl;
2082 //lyxerr << " wordstart=" << wordStart << " bvcur=" << bvcur << " cur=" << cur << std::endl;
2085 int defaultRowHeight()
2087 return int(theFontMetrics(sane_font).maxHeight() * 1.2);