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
14 * Full author contact details are available in file CREDITS.
23 #include "buffer_funcs.h"
24 #include "bufferparams.h"
25 #include "BufferView.h"
27 #include "coordcache.h"
28 #include "CutAndPaste.h"
30 #include "dispatchresult.h"
32 #include "errorlist.h"
33 #include "funcrequest.h"
35 #include "FontIterator.h"
39 #include "lyxlength.h"
43 #include "lyxrow_funcs.h"
44 #include "metricsinfo.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "rowpainter.h"
51 #include "WordLangTuple.h"
53 #include "frontends/font_metrics.h"
54 #include "frontends/LyXView.h"
55 #include "frontends/Painter.h"
57 #include "insets/insettext.h"
58 #include "insets/insetbibitem.h"
59 #include "insets/insethfill.h"
60 #include "insets/insetlatexaccent.h"
61 #include "insets/insetline.h"
62 #include "insets/insetnewline.h"
63 #include "insets/insetpagebreak.h"
64 #include "insets/insetoptarg.h"
65 #include "insets/insetspace.h"
66 #include "insets/insetspecialchar.h"
67 #include "insets/insettabular.h"
69 #include "support/lstrings.h"
70 #include "support/textutils.h"
71 #include "support/convert.h"
77 using lyx::word_location;
79 using lyx::support::bformat;
80 using lyx::support::contains;
81 using lyx::support::lowercase;
82 using lyx::support::split;
83 using lyx::support::uppercase;
85 using lyx::cap::cutSelection;
98 int numberOfSeparators(Paragraph const & par, Row const & row)
100 pos_type const first = max(row.pos(), par.beginOfBody());
101 pos_type const last = row.endpos() - 1;
103 for (pos_type p = first; p < last; ++p) {
104 if (par.isSeparator(p))
111 int numberOfLabelHfills(Paragraph const & par, Row const & row)
113 pos_type last = row.endpos() - 1;
114 pos_type first = row.pos();
116 // hfill *DO* count at the beginning of paragraphs!
118 while (first < last && par.isHfill(first))
122 last = min(last, par.beginOfBody());
124 for (pos_type p = first; p < last; ++p) {
132 int numberOfHfills(Paragraph const & par, Row const & row)
134 pos_type const last = row.endpos() - 1;
135 pos_type first = row.pos();
137 // hfill *DO* count at the beginning of paragraphs!
139 while (first < last && par.isHfill(first))
143 first = max(first, par.beginOfBody());
146 for (pos_type p = first; p < last; ++p) {
154 void readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
155 string const & token, LyXFont & font)
157 static Change change;
159 BufferParams const & bp = buf.params();
161 if (token[0] != '\\') {
162 string::const_iterator cit = token.begin();
163 for (; cit != token.end(); ++cit) {
164 par.insertChar(par.size(), (*cit), font, change);
166 } else if (token == "\\begin_layout") {
168 string layoutname = lex.getString();
170 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
173 LyXTextClass const & tclass = bp.getLyXTextClass();
175 if (layoutname.empty()) {
176 layoutname = tclass.defaultLayoutName();
179 bool hasLayout = tclass.hasLayout(layoutname);
182 buf.error(ErrorItem(_("Unknown layout"),
183 bformat(_("Layout '%1$s' does not exists in textclass '%2$s'\nTrying to use the default instead.\n"),
184 layoutname, tclass.name()), par.id(), 0, par.size()));
185 layoutname = tclass.defaultLayoutName();
188 par.layout(bp.getLyXTextClass()[layoutname]);
190 // Test whether the layout is obsolete.
191 LyXLayout_ptr const & layout = par.layout();
192 if (!layout->obsoleted_by().empty())
193 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
195 par.params().read(lex);
197 } else if (token == "\\end_layout") {
198 lyxerr << "Solitary \\end_layout in line " << lex.getLineNo() << "\n"
199 << "Missing \\begin_layout?.\n";
200 } else if (token == "\\end_inset") {
201 lyxerr << "Solitary \\end_inset in line " << lex.getLineNo() << "\n"
202 << "Missing \\begin_inset?.\n";
203 } else if (token == "\\begin_inset") {
204 InsetBase * inset = readInset(lex, buf);
206 par.insertInset(par.size(), inset, font, change);
209 string line = lex.getString();
210 buf.error(ErrorItem(_("Unknown Inset"), line,
211 par.id(), 0, par.size()));
213 } else if (token == "\\family") {
215 font.setLyXFamily(lex.getString());
216 } else if (token == "\\series") {
218 font.setLyXSeries(lex.getString());
219 } else if (token == "\\shape") {
221 font.setLyXShape(lex.getString());
222 } else if (token == "\\size") {
224 font.setLyXSize(lex.getString());
225 } else if (token == "\\lang") {
227 string const tok = lex.getString();
228 Language const * lang = languages.getLanguage(tok);
230 font.setLanguage(lang);
232 font.setLanguage(bp.language);
233 lex.printError("Unknown language `$$Token'");
235 } else if (token == "\\numeric") {
237 font.setNumber(font.setLyXMisc(lex.getString()));
238 } else if (token == "\\emph") {
240 font.setEmph(font.setLyXMisc(lex.getString()));
241 } else if (token == "\\bar") {
243 string const tok = lex.getString();
246 font.setUnderbar(LyXFont::ON);
247 else if (tok == "no")
248 font.setUnderbar(LyXFont::OFF);
249 else if (tok == "default")
250 font.setUnderbar(LyXFont::INHERIT);
252 lex.printError("Unknown bar font flag "
254 } else if (token == "\\noun") {
256 font.setNoun(font.setLyXMisc(lex.getString()));
257 } else if (token == "\\color") {
259 font.setLyXColor(lex.getString());
260 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
262 // Insets don't make sense in a free-spacing context! ---Kayvan
263 if (par.isFreeSpacing()) {
264 if (token == "\\InsetSpace")
265 par.insertChar(par.size(), ' ', font, change);
266 else if (lex.isOK()) {
268 string const next_token = lex.getString();
269 if (next_token == "\\-")
270 par.insertChar(par.size(), '-', font, change);
272 lex.printError("Token `$$Token' "
274 "paragraph layout!");
278 auto_ptr<InsetBase> inset;
279 if (token == "\\SpecialChar" )
280 inset.reset(new InsetSpecialChar);
282 inset.reset(new InsetSpace);
283 inset->read(buf, lex);
284 par.insertInset(par.size(), inset.release(),
287 } else if (token == "\\i") {
288 auto_ptr<InsetBase> inset(new InsetLatexAccent);
289 inset->read(buf, lex);
290 par.insertInset(par.size(), inset.release(), font, change);
291 } else if (token == "\\backslash") {
292 par.insertChar(par.size(), '\\', font, change);
293 } else if (token == "\\newline") {
294 auto_ptr<InsetBase> inset(new InsetNewline);
295 inset->read(buf, lex);
296 par.insertInset(par.size(), inset.release(), font, change);
297 } else if (token == "\\LyXTable") {
298 auto_ptr<InsetBase> inset(new InsetTabular(buf));
299 inset->read(buf, lex);
300 par.insertInset(par.size(), inset.release(), font, change);
301 } else if (token == "\\bibitem") {
302 InsetCommandParams p("bibitem", "dummy");
303 auto_ptr<InsetBibitem> inset(new InsetBibitem(p));
304 inset->read(buf, lex);
305 par.insertInset(par.size(), inset.release(), font, change);
306 } else if (token == "\\hfill") {
307 par.insertInset(par.size(), new InsetHFill, font, change);
308 } else if (token == "\\lyxline") {
309 par.insertInset(par.size(), new InsetLine, font, change);
310 } else if (token == "\\newpage") {
311 par.insertInset(par.size(), new InsetPagebreak, font, change);
312 } else if (token == "\\change_unchanged") {
313 // Hack ! Needed for empty paragraphs :/
314 // FIXME: is it still ??
317 change = Change(Change::UNCHANGED);
318 } else if (token == "\\change_inserted") {
320 std::istringstream is(lex.getString());
324 change = Change(Change::INSERTED, bp.author_map[aid], ct);
325 } else if (token == "\\change_deleted") {
327 std::istringstream is(lex.getString());
331 change = Change(Change::DELETED, bp.author_map[aid], ct);
334 buf.error(ErrorItem(_("Unknown token"),
335 bformat(_("Unknown token: %1$s %2$s\n"), token, lex.getString()),
336 par.id(), 0, par.size()));
341 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex)
344 string token = lex.getString();
349 readParToken(buf, par, lex, token, font);
352 token = lex.getString();
357 if (token == "\\end_layout") {
358 //Ok, paragraph finished
362 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
363 << token << '\'' << endl;
364 if (token == "\\begin_layout" || token == "\\end_document"
365 || token == "\\end_inset" || token == "\\begin_deeper"
366 || token == "\\end_deeper") {
367 lex.pushToken(token);
368 lyxerr << "Paragraph ended in line "
369 << lex.getLineNo() << "\n"
370 << "Missing \\end_layout.\n";
381 BufferView * LyXText::bv() const
383 BOOST_ASSERT(bv_owner != 0);
388 double LyXText::spacing(Paragraph const & par) const
390 if (par.params().spacing().isDefault())
391 return bv()->buffer()->params().spacing().getValue();
392 return par.params().spacing().getValue();
396 int LyXText::width() const
402 int LyXText::height() const
404 return dim_.height();
408 int LyXText::singleWidth(Paragraph const & par, pos_type pos) const
410 return singleWidth(par, pos, par.getChar(pos), getFont(par, pos));
414 int LyXText::singleWidth(Paragraph const & par,
415 pos_type pos, char c, LyXFont const & font) const
417 BOOST_ASSERT(pos < par.size());
419 // The most common case is handled first (Asger)
420 if (IsPrintable(c)) {
421 if (font.language()->RightToLeft()) {
422 if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
423 lyxrc.font_norm_type == LyXRC::ISO_10646_1)
424 && font.language()->lang() == "arabic") {
425 if (Encodings::IsComposeChar_arabic(c))
427 c = par.transformChar(c, pos);
428 } else if (font.language()->lang() == "hebrew" &&
429 Encodings::IsComposeChar_hebrew(c))
432 return font_metrics::width(c, font);
435 if (c == Paragraph::META_INSET)
436 return par.getInset(pos)->width();
438 if (IsSeparatorChar(c))
440 return font_metrics::width(c, font);
444 int LyXText::leftMargin(pit_type pit) const
446 BOOST_ASSERT(pit >= 0);
447 BOOST_ASSERT(pit < int(pars_.size()));
448 return leftMargin(pit, pars_[pit].size());
452 int LyXText::leftMargin(pit_type const pit, pos_type const pos) const
454 BOOST_ASSERT(pit >= 0);
455 BOOST_ASSERT(pit < int(pars_.size()));
456 Paragraph const & par = pars_[pit];
457 BOOST_ASSERT(pos >= 0);
458 BOOST_ASSERT(pos <= par.size());
459 //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
460 LyXTextClass const & tclass =
461 bv()->buffer()->params().getLyXTextClass();
462 LyXLayout_ptr const & layout = par.layout();
464 string parindent = layout->parindent;
469 l_margin += changebarMargin();
471 l_margin += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
473 if (par.getDepth() != 0) {
474 // find the next level paragraph
475 pit_type newpar = outerHook(pit, pars_);
476 if (newpar != pit_type(pars_.size())) {
477 if (pars_[newpar].layout()->isEnvironment()) {
478 l_margin = leftMargin(newpar);
480 if (par.layout() == tclass.defaultLayout()) {
481 if (pars_[newpar].params().noindent())
484 parindent = pars_[newpar].layout()->parindent;
489 LyXFont const labelfont = getLabelFont(par);
490 switch (layout->margintype) {
492 if (!layout->leftmargin.empty())
493 l_margin += font_metrics::signedWidth(layout->leftmargin,
494 tclass.defaultfont());
495 if (!par.getLabelstring().empty()) {
496 l_margin += font_metrics::signedWidth(layout->labelindent,
498 l_margin += font_metrics::width(par.getLabelstring(),
500 l_margin += font_metrics::width(layout->labelsep, labelfont);
505 l_margin += font_metrics::signedWidth(layout->labelindent, labelfont);
506 // The width of an empty par, even with manual label, should be 0
507 if (!par.empty() && pos >= par.beginOfBody()) {
508 if (!par.getLabelWidthString().empty()) {
509 l_margin += font_metrics::width(par.getLabelWidthString(),
511 l_margin += font_metrics::width(layout->labelsep, labelfont);
517 l_margin += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
518 / (par.getDepth() + 4);
521 case MARGIN_FIRST_DYNAMIC:
522 if (layout->labeltype == LABEL_MANUAL) {
523 if (pos >= par.beginOfBody()) {
524 l_margin += font_metrics::signedWidth(layout->leftmargin,
527 l_margin += font_metrics::signedWidth(layout->labelindent,
531 // Special case to fix problems with
533 || (layout->labeltype == LABEL_STATIC
534 && layout->latextype == LATEX_ENVIRONMENT
535 && !isFirstInSequence(pit, pars_))) {
536 l_margin += font_metrics::signedWidth(layout->leftmargin,
538 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
539 && layout->labeltype != LABEL_BIBLIO
540 && layout->labeltype !=
541 LABEL_CENTERED_TOP_ENVIRONMENT) {
542 l_margin += font_metrics::signedWidth(layout->labelindent,
544 l_margin += font_metrics::width(layout->labelsep, labelfont);
545 l_margin += font_metrics::width(par.getLabelstring(),
550 case MARGIN_RIGHT_ADDRESS_BOX: {
552 // ok, a terrible hack. The left margin depends on the widest
553 // row in this paragraph.
554 RowList::iterator rit = par.rows().begin();
555 RowList::iterator end = par.rows().end();
557 #warning This is wrong.
559 int minfill = maxwidth_;
560 for ( ; rit != end; ++rit)
561 if (rit->fill() < minfill)
562 minfill = rit->fill();
563 l_margin += font_metrics::signedWidth(layout->leftmargin,
564 tclass.defaultfont());
567 // also wrong, but much shorter.
568 l_margin += maxwidth_ / 2;
573 if (!par.params().leftIndent().zero())
574 l_margin += par.params().leftIndent().inPixels(maxwidth_);
578 if (par.params().align() == LYX_ALIGN_LAYOUT)
579 align = layout->align;
581 align = par.params().align();
583 // set the correct parindent
585 && (layout->labeltype == LABEL_NO_LABEL
586 || layout->labeltype == LABEL_TOP_ENVIRONMENT
587 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
588 || (layout->labeltype == LABEL_STATIC
589 && layout->latextype == LATEX_ENVIRONMENT
590 && !isFirstInSequence(pit, pars_)))
591 && align == LYX_ALIGN_BLOCK
592 && !par.params().noindent()
593 // in charstyles, tabulars and ert paragraphs are never indented!
594 && (par.ownerCode() != InsetBase::TEXT_CODE
595 && par.ownerCode() != InsetBase::ERT_CODE
596 && par.ownerCode() != InsetBase::CHARSTYLE_CODE)
597 && (par.layout() != tclass.defaultLayout()
598 || bv()->buffer()->params().paragraph_separation ==
599 BufferParams::PARSEP_INDENT))
601 l_margin += font_metrics::signedWidth(parindent, tclass.defaultfont());
608 int LyXText::rightMargin(Paragraph const & par) const
610 // We do not want rightmargins on inner texts.
611 if (bv()->text() != this)
614 LyXTextClass const & tclass = bv()->buffer()->params().getLyXTextClass();
617 + font_metrics::signedWidth(tclass.rightmargin(),
618 tclass.defaultfont())
619 + font_metrics::signedWidth(par.layout()->rightmargin,
620 tclass.defaultfont())
621 * 4 / (par.getDepth() + 4);
627 int LyXText::labelEnd(pit_type const pit) const
629 // labelEnd is only needed if the layout fills a flushleft label.
630 if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
632 // return the beginning of the body
633 return leftMargin(pit);
639 // this needs special handling - only newlines count as a break point
640 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
642 pos_type const end = par.size();
645 if (par.isNewline(i))
654 void LyXText::rowBreakPoint(pit_type const pit, Row & row) const
656 Paragraph const & par = pars_[pit];
657 pos_type const end = par.size();
658 pos_type const pos = row.pos();
664 // maximum pixel width of a row
665 int width = maxwidth_ - rightMargin(par); // - leftMargin(pit, row);
671 LyXLayout_ptr const & layout = par.layout();
673 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
674 row.endpos(addressBreakPoint(pos, par));
678 pos_type const body_pos = par.beginOfBody();
681 // Now we iterate through until we reach the right margin
682 // or the end of the par, then choose the possible break
685 int const left = leftMargin(pit, pos);
688 // pixel width since last breakpoint
691 FontIterator fi = FontIterator(*this, par, pos);
692 pos_type point = end;
694 for ( ; i < end; ++i, ++fi) {
695 char const c = par.getChar(i);
698 int thiswidth = singleWidth(par, i, c, *fi);
700 // add the auto-hfill from label end to the body
701 if (body_pos && i == body_pos) {
702 int add = font_metrics::width(layout->labelsep, getLabelFont(par));
703 if (par.isLineSeparator(i - 1))
704 add -= singleWidth(par, i - 1);
706 add = std::max(add, labelEnd(pit) - x);
711 chunkwidth += thiswidth;
714 // break before a character that will fall off
715 // the right of the row
717 // if no break before, break here
718 if (point == end || chunkwidth >= width - left) {
725 // exit on last registered breakpoint:
729 if (par.isNewline(i)) {
735 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
740 if (par.isInset(i) && par.getInset(i)->display()) {
746 if (!par.isInset(i) || par.getInset(i)->isChar()) {
747 // some insets are line separators too
748 if (par.isLineSeparator(i)) {
749 // register breakpoint:
756 // maybe found one, but the par is short enough.
757 if (i == end && x < width)
760 // manual labels cannot be broken in LaTeX. But we
761 // want to make our on-screen rendering of footnotes
763 if (body_pos && point < body_pos)
770 void LyXText::setRowWidth(pit_type const pit, Row & row) const
772 // get the pure distance
773 pos_type const end = row.endpos();
775 Paragraph const & par = pars_[pit];
776 string labelsep = par.layout()->labelsep;
777 int w = leftMargin(pit, row.pos());
779 pos_type const body_pos = par.beginOfBody();
780 pos_type i = row.pos();
783 FontIterator fi = FontIterator(*this, par, i);
784 for ( ; i < end; ++i, ++fi) {
785 if (body_pos > 0 && i == body_pos) {
786 w += font_metrics::width(labelsep, getLabelFont(par));
787 if (par.isLineSeparator(i - 1))
788 w -= singleWidth(par, i - 1);
789 w = max(w, labelEnd(pit));
791 char const c = par.getChar(i);
792 w += singleWidth(par, i, c, *fi);
796 if (body_pos > 0 && body_pos >= end) {
797 w += font_metrics::width(labelsep, getLabelFont(par));
798 if (end > 0 && par.isLineSeparator(end - 1))
799 w -= singleWidth(par, end - 1);
800 w = max(w, labelEnd(pit));
803 row.width(w + rightMargin(par));
807 // returns the minimum space a manual label needs on the screen in pixel
808 int LyXText::labelFill(Paragraph const & par, Row const & row) const
810 pos_type last = par.beginOfBody();
812 BOOST_ASSERT(last > 0);
814 // -1 because a label ends with a space that is in the label
817 // a separator at this end does not count
818 if (par.isLineSeparator(last))
822 for (pos_type i = row.pos(); i <= last; ++i)
823 w += singleWidth(par, i);
825 string const & label = par.params().labelWidthString();
829 return max(0, font_metrics::width(label, getLabelFont(par)) - w);
833 LColor_color LyXText::backgroundColor() const
835 return LColor_color(LColor::color(background_color_));
839 void LyXText::setHeightOfRow(pit_type const pit, Row & row)
841 Paragraph const & par = pars_[pit];
842 // get the maximum ascent and the maximum descent
843 double layoutasc = 0;
844 double layoutdesc = 0;
845 double const dh = defaultRowHeight();
847 // ok, let us initialize the maxasc and maxdesc value.
848 // Only the fontsize count. The other properties
849 // are taken from the layoutfont. Nicer on the screen :)
850 LyXLayout_ptr const & layout = par.layout();
852 // as max get the first character of this row then it can
853 // increase but not decrease the height. Just some point to
854 // start with so we don't have to do the assignment below too
856 LyXFont font = getFont(par, row.pos());
857 LyXFont::FONT_SIZE const tmpsize = font.size();
858 font = getLayoutFont(pit);
859 LyXFont::FONT_SIZE const size = font.size();
860 font.setSize(tmpsize);
862 LyXFont labelfont = getLabelFont(par);
864 // these are minimum values
865 double const spacing_val = layout->spacing.getValue() * spacing(par);
866 //lyxerr << "spacing_val = " << spacing_val << endl;
867 int maxasc = int(font_metrics::maxAscent(font) * spacing_val);
868 int maxdesc = int(font_metrics::maxDescent(font) * spacing_val);
870 // insets may be taller
871 InsetList::const_iterator ii = par.insetlist.begin();
872 InsetList::const_iterator iend = par.insetlist.end();
873 for ( ; ii != iend; ++ii) {
874 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
875 maxasc = max(maxasc, ii->inset->ascent());
876 maxdesc = max(maxdesc, ii->inset->descent());
880 // Check if any custom fonts are larger (Asger)
881 // This is not completely correct, but we can live with the small,
882 // cosmetic error for now.
884 pos_type const pos_end = row.endpos();
886 LyXFont::FONT_SIZE maxsize =
887 par.highestFontInRange(row.pos(), pos_end, size);
888 if (maxsize > font.size()) {
889 font.setSize(maxsize);
890 maxasc = max(maxasc, font_metrics::maxAscent(font));
891 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
894 // This is nicer with box insets:
901 if (row.pos() == 0) {
902 BufferParams const & bufparams = bv()->buffer()->params();
903 // some parksips VERY EASY IMPLEMENTATION
904 if (bv()->buffer()->params().paragraph_separation
905 == BufferParams::PARSEP_SKIP
907 && ((layout->isParagraph() && par.getDepth() == 0)
908 || (pars_[pit - 1].layout()->isParagraph()
909 && pars_[pit - 1].getDepth() == 0)))
911 maxasc += bufparams.getDefSkip().inPixels(*bv());
914 if (pars_[pit].params().startOfAppendix())
915 maxasc += int(3 * dh);
917 // This is special code for the chapter, since the label of this
918 // layout is printed in an extra row
919 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
920 labeladdon = int(font_metrics::maxHeight(labelfont)
921 * layout->spacing.getValue()
925 // special code for the top label
926 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
927 || layout->labeltype == LABEL_BIBLIO
928 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
929 && isFirstInSequence(pit, paragraphs())
930 && !par.getLabelstring().empty())
933 font_metrics::maxHeight(labelfont)
934 * layout->spacing.getValue()
936 + (layout->topsep + layout->labelbottomsep) * dh);
939 // Add the layout spaces, for example before and after
940 // a section, or between the items of a itemize or enumerate
943 pit_type prev = depthHook(pit, pars_, par.getDepth());
945 && pars_[prev].layout() == layout
946 && pars_[prev].getDepth() == par.getDepth()
947 && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
949 layoutasc = layout->itemsep * dh;
950 } else if (pit != 0 || row.pos() != 0) {
951 if (layout->topsep > 0)
952 layoutasc = layout->topsep * dh;
955 prev = outerHook(pit, pars_);
956 if (prev != pit_type(pars_.size())) {
957 maxasc += int(pars_[prev].layout()->parsep * dh);
958 } else if (pit != 0) {
959 if (pars_[pit - 1].getDepth() != 0 ||
960 pars_[pit - 1].layout() == layout) {
961 maxasc += int(layout->parsep * dh);
966 // is it a bottom line?
967 if (row.endpos() >= par.size()) {
968 // add the layout spaces, for example before and after
969 // a section, or between the items of a itemize or enumerate
971 pit_type nextpit = pit + 1;
972 if (nextpit != pit_type(pars_.size())) {
977 if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
978 usual = pars_[cpit].layout()->bottomsep * dh;
979 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
980 if (pars_[cpit].layout() != pars_[nextpit].layout()
981 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
983 unusual = pars_[cpit].layout()->bottomsep * dh;
985 layoutdesc = max(unusual, usual);
986 } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
987 if (pars_[cpit].layout() != pars_[nextpit].layout()
988 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
989 layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
994 // incalculate the layout spaces
995 maxasc += int(layoutasc * 2 / (2 + pars_[pit].getDepth()));
996 maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
998 // Top and bottom margin of the document (only at top-level)
999 if (bv_owner->text() == this) {
1000 if (pit == 0 && row.pos() == 0)
1002 if (pit == pars_.size() - 1 && row.endpos() == par.size())
1006 row.ascent(maxasc + labeladdon);
1007 row.descent(maxdesc);
1015 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1017 BOOST_ASSERT(this == cur.text());
1018 // allow only if at start or end, or all previous is new text
1019 Paragraph & cpar = cur.paragraph();
1020 pit_type cpit = cur.pit();
1022 if (cur.pos() != 0 && cur.pos() != cur.lastpos()
1023 && cpar.isChangeEdited(0, cur.pos()))
1026 LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1027 LyXLayout_ptr const & layout = cpar.layout();
1029 // this is only allowed, if the current paragraph is not empty
1030 // or caption and if it has not the keepempty flag active
1031 if (cur.lastpos() == 0 && !cpar.allowEmpty()
1032 && layout->labeltype != LABEL_SENSITIVE)
1035 // a layout change may affect also the following paragraph
1036 recUndo(cur.pit(), undoSpan(cur.pit()) - 1);
1038 // Always break behind a space
1039 // It is better to erase the space (Dekel)
1040 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1041 cpar.erase(cur.pos());
1043 // How should the layout for the new paragraph be?
1044 int preserve_layout = 0;
1046 preserve_layout = 2;
1048 preserve_layout = layout->isEnvironment();
1050 // We need to remember this before we break the paragraph, because
1051 // that invalidates the layout variable
1052 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1054 // we need to set this before we insert the paragraph.
1055 bool const isempty = cpar.allowEmpty() && cpar.empty();
1057 ::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1058 cur.pos(), preserve_layout);
1060 // After this, neither paragraph contains any rows!
1063 pit_type next_par = cpit + 1;
1065 // well this is the caption hack since one caption is really enough
1068 // set to standard-layout
1069 pars_[cpit].applyLayout(tclass.defaultLayout());
1071 // set to standard-layout
1072 pars_[next_par].applyLayout(tclass.defaultLayout());
1075 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1076 pars_[next_par].erase(0);
1078 updateCounters(cur.buffer());
1080 // This check is necessary. Otherwise the new empty paragraph will
1081 // be deleted automatically. And it is more friendly for the user!
1082 if (cur.pos() != 0 || isempty)
1083 setCursor(cur, cur.pit() + 1, 0);
1085 setCursor(cur, cur.pit(), 0);
1089 // insert a character, moves all the following breaks in the
1090 // same Paragraph one to the right and make a rebreak
1091 void LyXText::insertChar(LCursor & cur, char c)
1093 BOOST_ASSERT(this == cur.text());
1094 BOOST_ASSERT(c != Paragraph::META_INSET);
1096 recordUndo(cur, Undo::INSERT);
1098 Paragraph & par = cur.paragraph();
1099 // try to remove this
1100 pit_type const pit = cur.pit();
1102 bool const freeSpacing = par.layout()->free_spacing ||
1103 par.isFreeSpacing();
1105 if (lyxrc.auto_number) {
1106 static string const number_operators = "+-/*";
1107 static string const number_unary_operators = "+-";
1108 static string const number_seperators = ".,:";
1110 if (current_font.number() == LyXFont::ON) {
1111 if (!IsDigit(c) && !contains(number_operators, c) &&
1112 !(contains(number_seperators, c) &&
1114 cur.pos() != cur.lastpos() &&
1115 getFont(par, cur.pos()).number() == LyXFont::ON &&
1116 getFont(par, cur.pos() - 1).number() == LyXFont::ON)
1118 number(cur); // Set current_font.number to OFF
1119 } else if (IsDigit(c) &&
1120 real_current_font.isVisibleRightToLeft()) {
1121 number(cur); // Set current_font.number to ON
1123 if (cur.pos() != 0) {
1124 char const c = par.getChar(cur.pos() - 1);
1125 if (contains(number_unary_operators, c) &&
1127 || par.isSeparator(cur.pos() - 2)
1128 || par.isNewline(cur.pos() - 2))
1130 setCharFont(pit, cur.pos() - 1, current_font);
1131 } else if (contains(number_seperators, c)
1133 && getFont(par, cur.pos() - 2).number() == LyXFont::ON) {
1134 setCharFont(pit, cur.pos() - 1, current_font);
1140 // First check, if there will be two blanks together or a blank at
1141 // the beginning of a paragraph.
1142 // I decided to handle blanks like normal characters, the main
1143 // difference are the special checks when calculating the row.fill
1144 // (blank does not count at the end of a row) and the check here
1146 // The bug is triggered when we type in a description environment:
1147 // The current_font is not changed when we go from label to main text
1148 // and it should (along with realtmpfont) when we type the space.
1149 // CHECK There is a bug here! (Asger)
1151 // store the current font. This is because of the use of cursor
1152 // movements. The moving cursor would refresh the current font
1153 LyXFont realtmpfont = real_current_font;
1154 LyXFont rawtmpfont = current_font;
1156 // When the free-spacing option is set for the current layout,
1157 // disable the double-space checking
1158 if (!freeSpacing && IsLineSeparatorChar(c)) {
1159 if (cur.pos() == 0) {
1160 static bool sent_space_message = false;
1161 if (!sent_space_message) {
1162 cur.message(_("You cannot insert a space at the "
1163 "beginning of a paragraph. Please read the Tutorial."));
1164 sent_space_message = true;
1168 BOOST_ASSERT(cur.pos() > 0);
1169 if (par.isLineSeparator(cur.pos() - 1)
1170 || par.isNewline(cur.pos() - 1)) {
1171 static bool sent_space_message = false;
1172 if (!sent_space_message) {
1173 cur.message(_("You cannot type two spaces this way. "
1174 "Please read the Tutorial."));
1175 sent_space_message = true;
1181 par.insertChar(cur.pos(), c, rawtmpfont);
1183 current_font = rawtmpfont;
1184 real_current_font = realtmpfont;
1185 setCursor(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1190 void LyXText::charInserted()
1192 // Here we call finishUndo for every 20 characters inserted.
1193 // This is from my experience how emacs does it. (Lgb)
1194 static unsigned int counter;
1205 LyXText::computeRowMetrics(pit_type const pit, Row const & row) const
1208 Paragraph const & par = pars_[pit];
1210 double w = dim_.wid - row.width();
1212 bool const is_rtl = isRTL(par);
1214 result.x = rightMargin(par);
1216 result.x = leftMargin(pit, row.pos());
1218 // is there a manual margin with a manual label
1219 LyXLayout_ptr const & layout = par.layout();
1221 if (layout->margintype == MARGIN_MANUAL
1222 && layout->labeltype == LABEL_MANUAL) {
1223 /// We might have real hfills in the label part
1224 int nlh = numberOfLabelHfills(par, row);
1226 // A manual label par (e.g. List) has an auto-hfill
1227 // between the label text and the body of the
1229 // But we don't want to do this auto hfill if the par
1234 if (nlh && !par.getLabelWidthString().empty())
1235 result.label_hfill = labelFill(par, row) / double(nlh);
1238 // are there any hfills in the row?
1239 int const nh = numberOfHfills(par, row);
1243 result.hfill = w / nh;
1244 // we don't have to look at the alignment if it is ALIGN_LEFT and
1245 // if the row is already larger then the permitted width as then
1246 // we force the LEFT_ALIGN'edness!
1247 } else if (int(row.width()) < maxwidth_) {
1248 // is it block, flushleft or flushright?
1249 // set x how you need it
1251 if (par.params().align() == LYX_ALIGN_LAYOUT)
1252 align = layout->align;
1254 align = par.params().align();
1256 // Display-style insets should always be on a centred row
1257 // The test on par.size() is to catch zero-size pars, which
1258 // would trigger the assert in Paragraph::getInset().
1259 //inset = par.size() ? par.getInset(row.pos()) : 0;
1261 && par.isInset(row.pos())
1262 && par.getInset(row.pos())->display())
1264 align = LYX_ALIGN_CENTER;
1268 case LYX_ALIGN_BLOCK: {
1269 int const ns = numberOfSeparators(par, row);
1270 bool disp_inset = false;
1271 if (row.endpos() < par.size()) {
1272 InsetBase const * in = par.getInset(row.endpos());
1274 disp_inset = in->display();
1276 // If we have separators, this is not the last row of a
1277 // par, does not end in newline, and is not row above a
1278 // display inset... then stretch it
1280 && row.endpos() < par.size()
1281 && !par.isNewline(row.endpos() - 1)
1284 result.separator = w / ns;
1285 } else if (is_rtl) {
1290 case LYX_ALIGN_RIGHT:
1293 case LYX_ALIGN_CENTER:
1299 bidi.computeTables(par, *bv()->buffer(), row);
1301 pos_type body_pos = par.beginOfBody();
1302 pos_type end = row.endpos();
1305 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1307 result.x += font_metrics::width(layout->labelsep, getLabelFont(par));
1308 if (body_pos <= end)
1309 result.x += result.label_hfill;
1317 // the cursor set functions have a special mechanism. When they
1318 // realize, that you left an empty paragraph, they will delete it.
1320 bool LyXText::cursorRightOneWord(LCursor & cur)
1322 BOOST_ASSERT(this == cur.text());
1326 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1330 // Skip through initial nonword stuff.
1331 // Treat floats and insets as words.
1332 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1334 // Advance through word.
1335 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1338 return setCursor(cur, old.pit(), old.pos());
1342 bool LyXText::cursorLeftOneWord(LCursor & cur)
1344 BOOST_ASSERT(this == cur.text());
1348 if (old.pos() == 0 && old.pit() != 0) {
1350 old.pos() = old.lastpos();
1352 // Skip through initial nonword stuff.
1353 // Treat floats and insets as words.
1354 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
1356 // Advance through word.
1357 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
1360 return setCursor(cur, old.pit(), old.pos());
1364 void LyXText::selectWord(LCursor & cur, word_location loc)
1366 BOOST_ASSERT(this == cur.text());
1367 CursorSlice from = cur.top();
1368 CursorSlice to = cur.top();
1369 getWord(from, to, loc);
1370 if (cur.top() != from)
1371 setCursor(cur, from.pit(), from.pos());
1375 setCursor(cur, to.pit(), to.pos());
1380 // Select the word currently under the cursor when no
1381 // selection is currently set
1382 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1384 BOOST_ASSERT(this == cur.text());
1385 if (cur.selection())
1387 selectWord(cur, loc);
1388 return cur.selection();
1392 void LyXText::acceptChange(LCursor & cur)
1394 BOOST_ASSERT(this == cur.text());
1395 if (!cur.selection() && cur.lastpos() != 0)
1398 CursorSlice const & startc = cur.selBegin();
1399 CursorSlice const & endc = cur.selEnd();
1400 if (startc.pit() == endc.pit()) {
1401 recordUndoSelection(cur, Undo::INSERT);
1402 pars_[startc.pit()].acceptChange(startc.pos(), endc.pos());
1404 cur.clearSelection();
1405 setCursorIntern(cur, startc.pit(), 0);
1407 #ifdef WITH_WARNINGS
1408 #warning handle multi par selection
1413 void LyXText::rejectChange(LCursor & cur)
1415 BOOST_ASSERT(this == cur.text());
1416 if (!cur.selection() && cur.lastpos() != 0)
1419 CursorSlice const & startc = cur.selBegin();
1420 CursorSlice const & endc = cur.selEnd();
1421 if (startc.pit() == endc.pit()) {
1422 recordUndoSelection(cur, Undo::INSERT);
1423 pars_[startc.pit()].rejectChange(startc.pos(), endc.pos());
1425 cur.clearSelection();
1426 setCursorIntern(cur, startc.pit(), 0);
1428 #ifdef WITH_WARNINGS
1429 #warning handle multi par selection
1434 // Delete from cursor up to the end of the current or next word.
1435 void LyXText::deleteWordForward(LCursor & cur)
1437 BOOST_ASSERT(this == cur.text());
1438 if (cur.lastpos() == 0)
1442 cur.selection() = true;
1443 cursorRightOneWord(cur);
1445 cutSelection(cur, true, false);
1450 // Delete from cursor to start of current or prior word.
1451 void LyXText::deleteWordBackward(LCursor & cur)
1453 BOOST_ASSERT(this == cur.text());
1454 if (cur.lastpos() == 0)
1458 cur.selection() = true;
1459 cursorLeftOneWord(cur);
1461 cutSelection(cur, true, false);
1466 // Kill to end of line.
1467 void LyXText::deleteLineForward(LCursor & cur)
1469 BOOST_ASSERT(this == cur.text());
1470 if (cur.lastpos() == 0) {
1471 // Paragraph is empty, so we just go to the right
1475 cur.selection() = true; // to avoid deletion
1478 // What is this test for ??? (JMarc)
1479 if (!cur.selection())
1480 deleteWordForward(cur);
1482 cutSelection(cur, true, false);
1487 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1489 BOOST_ASSERT(this == cur.text());
1493 if (cur.selection()) {
1494 from = cur.selBegin();
1498 getWord(from, to, lyx::PARTIAL_WORD);
1499 setCursor(cur, to.pit(), to.pos() + 1);
1502 recordUndoSelection(cur);
1504 pos_type pos = from.pos();
1505 int par = from.pit();
1507 while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1509 if (pos == pars_[pit].size()) {
1514 unsigned char c = pars_[pit].getChar(pos);
1515 if (c != Paragraph::META_INSET) {
1517 case text_lowercase:
1520 case text_capitalization:
1522 action = text_lowercase;
1524 case text_uppercase:
1529 #ifdef WITH_WARNINGS
1532 pars_[pit].setChar(pos, c);
1538 void LyXText::Delete(LCursor & cur)
1540 BOOST_ASSERT(this == cur.text());
1541 if (cur.pos() != cur.lastpos()) {
1542 recordUndo(cur, Undo::DELETE, cur.pit());
1543 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1546 // should we do anything in an else branch?
1550 void LyXText::backspace(LCursor & cur)
1552 BOOST_ASSERT(this == cur.text());
1553 if (cur.pos() == 0) {
1554 // The cursor is at the beginning of a paragraph, so
1555 // the the backspace will collapse two paragraphs into
1558 // but it's not allowed unless it's new
1559 Paragraph & par = cur.paragraph();
1560 if (par.isChangeEdited(0, par.size()))
1563 // we may paste some paragraphs
1565 // is it an empty paragraph?
1566 pos_type lastpos = cur.lastpos();
1567 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1568 // This is an empty paragraph and we delete it just
1569 // by moving the cursor one step
1570 // left and let the DeleteEmptyParagraphMechanism
1571 // handle the actual deletion of the paragraph.
1573 if (cur.pit() != 0) {
1580 recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1582 pit_type tmppit = cur.pit();
1583 // We used to do cursorLeftIntern() here, but it is
1584 // not a good idea since it triggers the auto-delete
1585 // mechanism. So we do a cursorLeftIntern()-lite,
1586 // without the dreaded mechanism. (JMarc)
1587 if (cur.pit() != 0) {
1588 // steps into the above paragraph.
1589 setCursorIntern(cur, cur.pit() - 1,
1590 pars_[cur.pit() - 1].size(),
1594 // Pasting is not allowed, if the paragraphs have different
1595 // layout. I think it is a real bug of all other
1596 // word processors to allow it. It confuses the user.
1597 // Correction: Pasting is always allowed with standard-layout
1598 Buffer & buf = cur.buffer();
1599 BufferParams const & bufparams = buf.params();
1600 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1601 pit_type const cpit = cur.pit();
1604 && (pars_[cpit].layout() == pars_[tmppit].layout()
1605 || pars_[tmppit].layout() == tclass.defaultLayout())
1606 && pars_[cpit].getAlign() == pars_[tmppit].getAlign()) {
1607 mergeParagraph(bufparams, pars_, cpit);
1609 if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1612 // the counters may have changed
1613 updateCounters(cur.buffer());
1614 setCursor(cur, cur.pit(), cur.pos(), false);
1617 // this is the code for a normal backspace, not pasting
1619 recordUndo(cur, Undo::DELETE);
1620 // We used to do cursorLeftIntern() here, but it is
1621 // not a good idea since it triggers the auto-delete
1622 // mechanism. So we do a cursorLeftIntern()-lite,
1623 // without the dreaded mechanism. (JMarc)
1624 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1625 false, cur.boundary());
1626 cur.paragraph().erase(cur.pos());
1629 if (cur.pos() == cur.lastpos())
1630 setCurrentFont(cur);
1632 setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1636 Paragraph & LyXText::getPar(pit_type par) const
1638 //lyxerr << "getPar: " << par << " from " << paragraphs().size() << endl;
1639 BOOST_ASSERT(par >= 0);
1640 BOOST_ASSERT(par < int(paragraphs().size()));
1641 return paragraphs()[par];
1645 Row const & LyXText::firstRow() const
1647 return *paragraphs().front().rows().begin();
1651 void LyXText::redoParagraph(pit_type const pit)
1653 // remove rows of paragraph, keep track of height changes
1654 Paragraph & par = pars_[pit];
1657 InsetList::iterator ii = par.insetlist.begin();
1658 InsetList::iterator iend = par.insetlist.end();
1659 for (; ii != iend; ++ii) {
1661 int const w = maxwidth_ - leftMargin(pit) - rightMargin(par);
1662 MetricsInfo mi(bv(), getFont(par, ii->pos), w);
1663 ii->inset->metrics(mi, dim);
1666 // rebreak the paragraph
1670 par.setBeginOfBody();
1674 rowBreakPoint(pit, row);
1675 setRowWidth(pit, row);
1676 setHeightOfRow(pit, row);
1677 par.rows().push_back(row);
1678 dim.wid = std::max(dim.wid, row.width());
1679 dim.des += row.height();
1681 } while (z < par.size());
1683 dim.asc += par.rows()[0].ascent();
1684 dim.des -= par.rows()[0].ascent();
1686 //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1690 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1692 //BOOST_ASSERT(mi.base.textwidth);
1693 if (mi.base.textwidth)
1694 maxwidth_ = mi.base.textwidth;
1695 //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1696 // << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1700 for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1702 Paragraph & par = paragraphs()[pit];
1704 if (w < par.width())
1709 dim.asc = pars_[0].ascent();
1710 dim.des = h - dim.asc;
1716 // only used for inset right now. should also be used for main text
1717 void LyXText::draw(PainterInfo & pi, int x, int y) const
1719 paintTextInset(*this, pi, x, y);
1724 // only used for inset right now. should also be used for main text
1725 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1727 LCursor & cur = pi.base.bv->cursor();
1728 if (!cur.selection())
1730 if (!ptr_cmp(cur.text(), this))
1733 lyxerr << "draw selection at " << x << endl;
1735 // is there a better way of getting these two iterators?
1736 DocIterator beg = cur;
1737 DocIterator end = cur;
1739 beg.top() = cur.selBegin();
1740 end.top() = cur.selEnd();
1742 // the selection doesn't touch the visible screen
1743 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1744 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1747 Paragraph const & par1 = pars_[beg.pit()];
1748 Paragraph const & par2 = pars_[end.pit()];
1750 Row const & row1 = par1.getRow(beg.pos());
1751 Row const & row2 = par2.getRow(end.pos());
1754 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1759 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1760 int const startx = cursorX(beg.top());
1761 x1 = isRTL(par1) ? startx : 0;
1762 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
1766 if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
1767 y2 = pi.base.bv->workHeight();
1771 y2 = bv_funcs::getPos(end).y_ + row2.descent();
1772 int const endx = cursorX(end.top());
1773 X1 = isRTL(par2) ? 0 : endx;
1774 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
1777 lyxerr << " y1: " << y1 << " y2: " << y2
1778 << " xo: " << xo_ << " wid: " << dim_.wid
1781 // paint big rectangle in one go
1782 pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
1784 // reset background at begin of first selected line
1785 pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
1786 LColor::background);
1788 // reset background at end of last selected line
1789 pi.pain.fillRectangle(x + X1, y2 - row2.height(),
1790 X2 - X1, row2.height(), LColor::background);
1795 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
1797 LCursor & cur = pi.base.bv->cursor();
1798 if (!cur.selection())
1800 if (!ptr_cmp(cur.text(), this))
1803 lyxerr << "draw selection at " << x << endl;
1805 // is there a better way of getting these two iterators?
1806 DocIterator beg = cur;
1807 DocIterator end = cur;
1809 beg.top() = cur.selBegin();
1810 end.top() = cur.selEnd();
1812 // the selection doesn't touch the visible screen
1813 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1814 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1817 Paragraph const & par1 = pars_[beg.pit()];
1818 Paragraph const & par2 = pars_[end.pit()];
1820 bool const above = (bv_funcs::status(pi.base.bv, beg)
1821 == bv_funcs::CUR_ABOVE);
1822 bool const below = (bv_funcs::status(pi.base.bv, end)
1823 == bv_funcs::CUR_BELOW);
1831 Row const & row1 = par1.getRow(beg.pos());
1832 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1833 y2 = y1 + row1.height();
1834 int const startx = cursorX(beg.top());
1835 x1 = !isRTL(par1) ? startx : 0;
1836 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
1841 Y1 = pi.base.bv->workHeight();
1842 Y2 = pi.base.bv->workHeight();
1846 Row const & row2 = par2.getRow(end.pos());
1847 Y1 = bv_funcs::getPos(end).y_ - row2.ascent();
1848 Y2 = Y1 + row2.height();
1849 int const endx = cursorX(end.top());
1850 X1 = !isRTL(par2) ? 0 : endx;
1851 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
1854 if (!above && !below && &par1.getRow(beg.pos())
1855 == &par2.getRow(end.pos()))
1857 // paint only one rectangle
1858 pi.pain.fillRectangle(x + x1, y1, X2 - x1, y2 - y1,
1863 // paint upper rectangle
1864 pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
1866 // paint bottom rectangle
1867 pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
1869 // paint center rectangle
1870 pi.pain.fillRectangle(x, y2, dim_.wid,
1871 Y1 - y2, LColor::selection);
1874 bool LyXText::isLastRow(pit_type pit, Row const & row) const
1876 return row.endpos() >= pars_[pit].size()
1877 && pit + 1 == pit_type(paragraphs().size());
1881 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
1883 return row.pos() == 0 && pit == 0;
1887 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1888 word_location const loc)
1890 Paragraph const & from_par = pars_[from.pit()];
1892 case lyx::WHOLE_WORD_STRICT:
1893 if (from.pos() == 0 || from.pos() == from_par.size()
1894 || !from_par.isLetter(from.pos())
1895 || !from_par.isLetter(from.pos() - 1)) {
1899 // no break here, we go to the next
1901 case lyx::WHOLE_WORD:
1902 // If we are already at the beginning of a word, do nothing
1903 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1905 // no break here, we go to the next
1907 case lyx::PREVIOUS_WORD:
1908 // always move the cursor to the beginning of previous word
1909 while (from.pos() && from_par.isLetter(from.pos() - 1))
1912 case lyx::NEXT_WORD:
1913 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1916 case lyx::PARTIAL_WORD:
1917 // no need to move the 'from' cursor
1921 Paragraph & to_par = pars_[to.pit()];
1922 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1927 void LyXText::write(Buffer const & buf, std::ostream & os) const
1929 ParagraphList::const_iterator pit = paragraphs().begin();
1930 ParagraphList::const_iterator end = paragraphs().end();
1931 Paragraph::depth_type dth = 0;
1932 for (; pit != end; ++pit)
1933 pit->write(buf, os, buf.params(), dth);
1937 bool LyXText::read(Buffer const & buf, LyXLex & lex)
1939 static Change current_change;
1941 Paragraph::depth_type depth = 0;
1943 while (lex.isOK()) {
1945 string const token = lex.getString();
1950 if (token == "\\end_inset") {
1954 if (token == "\\end_body") {
1958 if (token == "\\begin_body") {
1962 if (token == "\\end_document") {
1966 if (token == "\\begin_layout") {
1967 lex.pushToken(token);
1970 par.params().depth(depth);
1971 if (buf.params().tracking_changes)
1973 par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
1974 pars_.push_back(par);
1976 // FIXME: goddamn InsetTabular makes us pass a Buffer
1978 ::readParagraph(buf, pars_.back(), lex);
1980 } else if (token == "\\begin_deeper") {
1982 } else if (token == "\\end_deeper") {
1984 lex.printError("\\end_deeper: " "depth is already null");
1989 lyxerr << "Handling unknown body token: `"
1990 << token << '\'' << endl;
1997 int LyXText::ascent() const
2003 int LyXText::descent() const
2009 int LyXText::cursorX(CursorSlice const & cur) const
2011 pit_type const pit = cur.pit();
2012 Paragraph const & par = pars_[pit];
2013 if (par.rows().empty())
2016 Row const & row = par.getRow(cur.pos());
2018 pos_type pos = cur.pos();
2019 pos_type cursor_vpos = 0;
2021 RowMetrics const m = computeRowMetrics(pit, row);
2024 pos_type const row_pos = row.pos();
2025 pos_type const end = row.endpos();
2028 cursor_vpos = row_pos;
2029 else if (pos >= end)
2030 cursor_vpos = isRTL(par) ? row_pos : end;
2031 else if (pos > row_pos && pos >= end)
2032 // Place cursor after char at (logical) position pos - 1
2033 cursor_vpos = (bidi.level(pos - 1) % 2 == 0)
2034 ? bidi.log2vis(pos - 1) + 1 : bidi.log2vis(pos - 1);
2036 // Place cursor before char at (logical) position pos
2037 cursor_vpos = (bidi.level(pos) % 2 == 0)
2038 ? bidi.log2vis(pos) : bidi.log2vis(pos) + 1;
2040 pos_type body_pos = par.beginOfBody();
2042 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2045 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2046 pos_type pos = bidi.vis2log(vpos);
2047 if (body_pos > 0 && pos == body_pos - 1) {
2049 + font_metrics::width(par.layout()->labelsep,
2051 if (par.isLineSeparator(body_pos - 1))
2052 x -= singleWidth(par, body_pos - 1);
2055 if (hfillExpansion(par, row, pos)) {
2056 x += singleWidth(par, pos);
2057 if (pos >= body_pos)
2061 } else if (par.isSeparator(pos)) {
2062 x += singleWidth(par, pos);
2063 if (pos >= body_pos)
2066 x += singleWidth(par, pos);
2072 int LyXText::cursorY(CursorSlice const & cur) const
2074 Paragraph const & par = getPar(cur.pit());
2076 h -= pars_[0].rows()[0].ascent();
2077 for (pit_type pit = 0; pit < cur.pit(); ++pit)
2078 h += pars_[pit].height();
2079 for (size_t rit = 0, rend = par.pos2row(cur.pos()); rit != rend; ++rit)
2080 h += par.rows()[rit].height();
2081 h += par.rows()[par.pos2row(cur.pos())].ascent();
2086 // Returns the current font and depth as a message.
2087 string LyXText::currentState(LCursor & cur)
2089 BOOST_ASSERT(this == cur.text());
2090 Buffer & buf = cur.buffer();
2091 Paragraph const & par = cur.paragraph();
2092 std::ostringstream os;
2094 bool const show_change = buf.params().tracking_changes
2095 && cur.pos() != cur.lastpos()
2096 && par.lookupChange(cur.pos()) != Change::UNCHANGED;
2099 Change change = par.lookupChangeFull(cur.pos());
2100 Author const & a = buf.params().authors().get(change.author);
2101 os << _("Change: ") << a.name();
2102 if (!a.email().empty())
2103 os << " (" << a.email() << ")";
2104 if (change.changetime)
2105 os << _(" at ") << ctime(&change.changetime);
2109 // I think we should only show changes from the default
2111 LyXFont font = real_current_font;
2112 font.reduce(buf.params().getLyXTextClass().defaultfont());
2114 // avoid _(...) re-entrance problem
2115 string const s = font.stateText(&buf.params());
2116 os << bformat(_("Font: %1$s"), s);
2118 // os << bformat(_("Font: %1$s"), font.stateText(&buf.params));
2120 // The paragraph depth
2121 int depth = cur.paragraph().getDepth();
2123 os << bformat(_(", Depth: %1$d"), depth);
2125 // The paragraph spacing, but only if different from
2127 Spacing const & spacing = par.params().spacing();
2128 if (!spacing.isDefault()) {
2129 os << _(", Spacing: ");
2130 switch (spacing.getSpace()) {
2131 case Spacing::Single:
2134 case Spacing::Onehalf:
2137 case Spacing::Double:
2140 case Spacing::Other:
2141 os << _("Other (") << spacing.getValueAsString() << ')';
2143 case Spacing::Default:
2144 // should never happen, do nothing
2149 #ifdef DEVEL_VERSION
2150 os << _(", Inset: ") << &cur.inset();
2151 os << _(", Paragraph: ") << cur.pit();
2152 os << _(", Id: ") << par.id();
2153 os << _(", Position: ") << cur.pos();
2154 // Row & row = cur.textRow();
2155 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2161 string LyXText::getPossibleLabel(LCursor & cur) const
2163 pit_type pit = cur.pit();
2165 LyXLayout_ptr layout = pars_[pit].layout();
2167 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2168 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2169 if (layout2->latextype != LATEX_PARAGRAPH) {
2175 string text = layout->latexname().substr(0, 3);
2176 if (layout->latexname() == "theorem")
2177 text = "thm"; // Create a correct prefix for prettyref
2180 if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2183 string par_text = pars_[pit].asString(cur.buffer(), false);
2184 for (int i = 0; i < lyxrc.label_init_length; ++i) {
2185 if (par_text.empty())
2188 par_text = split(par_text, head, ' ');
2189 // Is it legal to use spaces in labels ?
2199 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2203 // Paragraph const & par = pars_[pit];
2204 // Row const & r = par.rows()[row];
2205 // int pos = r.pos();
2206 // for (; currx < x && pos < r.endpos(); ++pos) {
2208 // currx += singleWidth(par, pos);
2210 // if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2216 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2218 BOOST_ASSERT(row < pars_[pit].rows().size());
2220 Row const & r = pars_[pit].rows()[row];
2221 return r.pos() + getColumnNearX(pit, r, x, bound);
2225 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2227 // Paragraph const & par = pars_[pit];
2228 // Row const & r = par.rows()[row];
2234 // x,y are screen coordinates
2235 // sets cursor only within this LyXText
2236 void LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2238 pit_type pit = getPitNearY(y);
2239 int yy = theCoords.get(this, pit).y_ - pars_[pit].ascent();
2240 lyxerr << "setCursorFromCoordinates: x: " << x << " y: " << y
2241 << " pit: " << pit << " yy: " << yy << endl;
2243 Paragraph const & par = pars_[pit];
2245 BOOST_ASSERT(par.rows().size());
2246 for (; r < int(par.rows().size()) - 1; ++r) {
2247 Row const & row = par.rows()[r];
2248 if (int(yy + row.height()) > y)
2253 Row const & row = par.rows()[r];
2255 lyxerr << "setCursorFromCoordinates: row " << r
2256 << " from pos: " << row.pos() << endl;
2260 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2261 setCursor(cur, pit, pos, true, bound);