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 "pariterator.h"
28 #include "coordcache.h"
29 #include "CutAndPaste.h"
31 #include "dispatchresult.h"
33 #include "errorlist.h"
34 #include "funcrequest.h"
36 #include "FontIterator.h"
40 #include "lyxlength.h"
44 #include "lyxrow_funcs.h"
45 #include "metricsinfo.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "rowpainter.h"
52 #include "WordLangTuple.h"
54 #include "frontends/font_metrics.h"
55 #include "frontends/LyXView.h"
56 #include "frontends/Painter.h"
58 #include "insets/insettext.h"
59 #include "insets/insetbibitem.h"
60 #include "insets/insethfill.h"
61 #include "insets/insetlatexaccent.h"
62 #include "insets/insetline.h"
63 #include "insets/insetnewline.h"
64 #include "insets/insetpagebreak.h"
65 #include "insets/insetoptarg.h"
66 #include "insets/insetspace.h"
67 #include "insets/insetspecialchar.h"
68 #include "insets/insettabular.h"
70 #include "support/lstrings.h"
71 #include "support/textutils.h"
72 #include "support/convert.h"
74 #include <boost/current_function.hpp>
82 using lyx::word_location;
84 using lyx::support::bformat;
85 using lyx::support::contains;
86 using lyx::support::lowercase;
87 using lyx::support::split;
88 using lyx::support::uppercase;
90 using lyx::cap::cutSelection;
91 using lyx::cap::pasteParagraphList;
104 int numberOfSeparators(Paragraph const & par, Row const & row)
106 pos_type const first = max(row.pos(), par.beginOfBody());
107 pos_type const last = row.endpos() - 1;
109 for (pos_type p = first; p < last; ++p) {
110 if (par.isSeparator(p))
117 int numberOfLabelHfills(Paragraph const & par, Row const & row)
119 pos_type last = row.endpos() - 1;
120 pos_type first = row.pos();
122 // hfill *DO* count at the beginning of paragraphs!
124 while (first < last && par.isHfill(first))
128 last = min(last, par.beginOfBody());
130 for (pos_type p = first; p < last; ++p) {
138 int numberOfHfills(Paragraph const & par, Row const & row)
140 pos_type const last = row.endpos();
141 pos_type first = row.pos();
143 // hfill *DO* count at the beginning of paragraphs!
145 while (first < last && par.isHfill(first))
149 first = max(first, par.beginOfBody());
152 for (pos_type p = first; p < last; ++p) {
160 void readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
161 string const & token, LyXFont & font, Change & change, ErrorList & errorList)
163 BufferParams const & bp = buf.params();
165 if (token[0] != '\\') {
167 string::const_iterator cit = token.begin();
168 for (; cit != token.end(); ++cit)
169 par.insertChar(par.size(), (*cit), font, change);
171 lyx::docstring dstr = lex.getDocString();
172 lyx::docstring::const_iterator cit = dstr.begin();
173 lyx::docstring::const_iterator cend = dstr.end();
174 for (; cit != cend; ++cit)
175 par.insertChar(par.size(), *cit, font, change);
177 } else if (token == "\\begin_layout") {
179 string layoutname = lex.getString();
181 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
184 LyXTextClass const & tclass = bp.getLyXTextClass();
186 if (layoutname.empty()) {
187 layoutname = tclass.defaultLayoutName();
190 bool hasLayout = tclass.hasLayout(layoutname);
193 errorList.push_back(ErrorItem(_("Unknown layout"),
194 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
195 lyx::from_utf8(layoutname), lyx::from_utf8(tclass.name())), par.id(), 0, par.size()));
196 layoutname = tclass.defaultLayoutName();
199 par.layout(bp.getLyXTextClass()[layoutname]);
201 // Test whether the layout is obsolete.
202 LyXLayout_ptr const & layout = par.layout();
203 if (!layout->obsoleted_by().empty())
204 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
206 par.params().read(lex);
208 } else if (token == "\\end_layout") {
209 lyxerr << BOOST_CURRENT_FUNCTION
210 << ": Solitary \\end_layout in line "
211 << lex.getLineNo() << "\n"
212 << "Missing \\begin_layout?.\n";
213 } else if (token == "\\end_inset") {
214 lyxerr << BOOST_CURRENT_FUNCTION
215 << ": Solitary \\end_inset in line "
216 << lex.getLineNo() << "\n"
217 << "Missing \\begin_inset?.\n";
218 } else if (token == "\\begin_inset") {
219 InsetBase * inset = readInset(lex, buf);
221 par.insertInset(par.size(), inset, font, change);
224 docstring line = lyx::from_utf8(lex.getString());
225 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
226 par.id(), 0, par.size()));
228 } else if (token == "\\family") {
230 font.setLyXFamily(lex.getString());
231 } else if (token == "\\series") {
233 font.setLyXSeries(lex.getString());
234 } else if (token == "\\shape") {
236 font.setLyXShape(lex.getString());
237 } else if (token == "\\size") {
239 font.setLyXSize(lex.getString());
240 } else if (token == "\\lang") {
242 string const tok = lex.getString();
243 Language const * lang = languages.getLanguage(tok);
245 font.setLanguage(lang);
247 font.setLanguage(bp.language);
248 lex.printError("Unknown language `$$Token'");
250 } else if (token == "\\numeric") {
252 font.setNumber(font.setLyXMisc(lex.getString()));
253 } else if (token == "\\emph") {
255 font.setEmph(font.setLyXMisc(lex.getString()));
256 } else if (token == "\\bar") {
258 string const tok = lex.getString();
261 font.setUnderbar(LyXFont::ON);
262 else if (tok == "no")
263 font.setUnderbar(LyXFont::OFF);
264 else if (tok == "default")
265 font.setUnderbar(LyXFont::INHERIT);
267 lex.printError("Unknown bar font flag "
269 } else if (token == "\\noun") {
271 font.setNoun(font.setLyXMisc(lex.getString()));
272 } else if (token == "\\color") {
274 font.setLyXColor(lex.getString());
275 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
277 // Insets don't make sense in a free-spacing context! ---Kayvan
278 if (par.isFreeSpacing()) {
279 if (token == "\\InsetSpace")
280 par.insertChar(par.size(), ' ', font, change);
281 else if (lex.isOK()) {
283 string const next_token = lex.getString();
284 if (next_token == "\\-")
285 par.insertChar(par.size(), '-', font, change);
287 lex.printError("Token `$$Token' "
289 "paragraph layout!");
293 auto_ptr<InsetBase> inset;
294 if (token == "\\SpecialChar" )
295 inset.reset(new InsetSpecialChar);
297 inset.reset(new InsetSpace);
298 inset->read(buf, lex);
299 par.insertInset(par.size(), inset.release(),
302 } else if (token == "\\i") {
303 auto_ptr<InsetBase> inset(new InsetLatexAccent);
304 inset->read(buf, lex);
305 par.insertInset(par.size(), inset.release(), font, change);
306 } else if (token == "\\backslash") {
307 par.insertChar(par.size(), '\\', font, change);
308 } else if (token == "\\newline") {
309 auto_ptr<InsetBase> inset(new InsetNewline);
310 inset->read(buf, lex);
311 par.insertInset(par.size(), inset.release(), font, change);
312 } else if (token == "\\LyXTable") {
313 auto_ptr<InsetBase> inset(new InsetTabular(buf));
314 inset->read(buf, lex);
315 par.insertInset(par.size(), inset.release(), font, change);
316 } else if (token == "\\bibitem") {
317 InsetCommandParams p("bibitem", "dummy");
318 auto_ptr<InsetBibitem> inset(new InsetBibitem(p));
319 inset->read(buf, lex);
320 par.insertInset(par.size(), inset.release(), font, change);
321 } else if (token == "\\hfill") {
322 par.insertInset(par.size(), new InsetHFill, font, change);
323 } else if (token == "\\lyxline") {
324 par.insertInset(par.size(), new InsetLine, font, change);
325 } else if (token == "\\newpage") {
326 par.insertInset(par.size(), new InsetPagebreak, font, change);
327 } else if (token == "\\change_unchanged") {
328 // Hack ! Needed for empty paragraphs :/
329 // FIXME: is it still ??
334 change = Change(Change::UNCHANGED);
335 } else if (token == "\\change_inserted") {
337 std::istringstream is(lex.getString());
341 if (aid >= bp.author_map.size()) {
342 errorList.push_back(ErrorItem(_("Change tracking error"),
343 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
344 par.id(), 0, par.size()));
346 change = Change(Change::UNCHANGED);
348 change = Change(Change::INSERTED, bp.author_map[aid], ct);
349 } else if (token == "\\change_deleted") {
351 std::istringstream is(lex.getString());
355 if (aid >= bp.author_map.size()) {
356 errorList.push_back(ErrorItem(_("Change tracking error"),
357 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
358 par.id(), 0, par.size()));
360 change = Change(Change::UNCHANGED);
362 change = Change(Change::DELETED, bp.author_map[aid], ct);
365 errorList.push_back(ErrorItem(_("Unknown token"),
366 bformat(_("Unknown token: %1$s %2$s\n"), lyx::from_utf8(token),
367 lyx::from_utf8(lex.getString())),
368 par.id(), 0, par.size()));
373 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex, ErrorList & errorList)
376 string token = lex.getString();
382 readParToken(buf, par, lex, token, font, change, errorList);
385 token = lex.getString();
390 if (token == "\\end_layout") {
391 //Ok, paragraph finished
395 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
396 << token << '\'' << endl;
397 if (token == "\\begin_layout" || token == "\\end_document"
398 || token == "\\end_inset" || token == "\\begin_deeper"
399 || token == "\\end_deeper") {
400 lex.pushToken(token);
401 lyxerr << "Paragraph ended in line "
402 << lex.getLineNo() << "\n"
403 << "Missing \\end_layout.\n";
407 // Final change goes to paragraph break:
408 par.setChange(par.size(), change);
410 // Initialize begin_of_body_ on load; redoParagraph maintains
411 par.setBeginOfBody();
419 BufferView * LyXText::bv() const
421 BOOST_ASSERT(bv_owner != 0);
426 double LyXText::spacing(Paragraph const & par) const
428 if (par.params().spacing().isDefault())
429 return bv()->buffer()->params().spacing().getValue();
430 return par.params().spacing().getValue();
434 int LyXText::width() const
440 int LyXText::height() const
442 return dim_.height();
446 int LyXText::singleWidth(Paragraph const & par, pos_type pos) const
448 return singleWidth(par, pos, par.getChar(pos), getFont(par, pos));
452 int LyXText::singleWidth(Paragraph const & par,
453 pos_type pos, char_type c, LyXFont const & font) const
455 // The most common case is handled first (Asger)
456 if (isPrintable(c)) {
457 Language const * language = font.language();
458 if (language->rightToLeft()) {
459 if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
460 lyxrc.font_norm_type == LyXRC::ISO_10646_1)
461 && language->lang() == "arabic") {
462 if (Encodings::isComposeChar_arabic(c))
464 c = par.transformChar(c, pos);
465 } else if (language->lang() == "hebrew" &&
466 Encodings::isComposeChar_hebrew(c))
469 return font_metrics::width(c, font);
472 if (c == Paragraph::META_INSET)
473 return par.getInset(pos)->width();
475 return font_metrics::width(c, font);
479 int LyXText::leftMargin(pit_type pit) const
481 BOOST_ASSERT(pit >= 0);
482 BOOST_ASSERT(pit < int(pars_.size()));
483 return leftMargin(pit, pars_[pit].size());
487 int LyXText::leftMargin(pit_type const pit, pos_type const pos) const
489 BOOST_ASSERT(pit >= 0);
490 BOOST_ASSERT(pit < int(pars_.size()));
491 Paragraph const & par = pars_[pit];
492 BOOST_ASSERT(pos >= 0);
493 BOOST_ASSERT(pos <= par.size());
494 //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
495 BufferParams const & params = bv()->buffer()->params();
496 LyXTextClass const & tclass = params.getLyXTextClass();
497 LyXLayout_ptr const & layout = par.layout();
499 string parindent = layout->parindent;
504 l_margin += changebarMargin();
506 string leftm = tclass.leftmargin();
507 docstring dleft(leftm.begin(), leftm.end());
508 l_margin += font_metrics::signedWidth(dleft, params.getFont());
510 if (par.getDepth() != 0) {
511 // find the next level paragraph
512 pit_type newpar = outerHook(pit, pars_);
513 if (newpar != pit_type(pars_.size())) {
514 if (pars_[newpar].layout()->isEnvironment()) {
515 l_margin = leftMargin(newpar);
517 if (par.layout() == tclass.defaultLayout()) {
518 if (pars_[newpar].params().noindent())
521 parindent = pars_[newpar].layout()->parindent;
526 // This happens after sections in standard classes. The 1.3.x
527 // code compared depths too, but it does not seem necessary
529 if (par.layout() == tclass.defaultLayout()
530 && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
533 LyXFont const labelfont = getLabelFont(par);
534 switch (layout->margintype) {
536 if (!layout->leftmargin.empty()) {
537 string leftm = layout->leftmargin;
538 docstring dleft(leftm.begin(), leftm.end());
539 l_margin += font_metrics::signedWidth(dleft,
542 if (!par.getLabelstring().empty()) {
543 string labin = layout->labelindent;
544 docstring dlabin(labin.begin(), labin.end());
545 l_margin += font_metrics::signedWidth(dlabin,
547 string labstr = par.getLabelstring();
548 docstring dlabstr(labstr.begin(), labstr.end());
549 l_margin += font_metrics::width(dlabstr,
551 string labsep = layout->labelsep;
552 docstring dlabsep(labsep.begin(), labsep.end());
553 l_margin += font_metrics::width(dlabsep, labelfont);
557 case MARGIN_MANUAL: {
558 string labin = layout->labelindent;
559 docstring dlabin(labin.begin(), labin.end());
560 l_margin += font_metrics::signedWidth(dlabin, labelfont);
561 // The width of an empty par, even with manual label, should be 0
562 if (!par.empty() && pos >= par.beginOfBody()) {
563 if (!par.getLabelWidthString().empty()) {
564 string labstr = par.getLabelWidthString();
565 docstring dlabstr(labstr.begin(), labstr.end());
566 l_margin += font_metrics::width(dlabstr,
568 string labsep = layout->labelsep;
569 docstring dlabsep(labsep.begin(), labsep.end());
570 l_margin += font_metrics::width(dlabsep, labelfont);
576 case MARGIN_STATIC: {
577 string leftm = layout->leftmargin;
578 docstring dleft(leftm.begin(), leftm.end());
579 l_margin += font_metrics::signedWidth(dleft, params.getFont()) * 4
580 / (par.getDepth() + 4);
584 case MARGIN_FIRST_DYNAMIC:
585 if (layout->labeltype == LABEL_MANUAL) {
586 if (pos >= par.beginOfBody()) {
587 string leftm = layout->leftmargin;
588 docstring dleft(leftm.begin(), leftm.end());
589 l_margin += font_metrics::signedWidth(dleft,
592 string labin = layout->labelindent;
593 docstring dlabin(labin.begin(), labin.end());
594 l_margin += font_metrics::signedWidth(dlabin,
598 // Special case to fix problems with
600 || (layout->labeltype == LABEL_STATIC
601 && layout->latextype == LATEX_ENVIRONMENT
602 && !isFirstInSequence(pit, pars_))) {
603 string leftm = layout->leftmargin;
604 docstring dleft(leftm.begin(), leftm.end());
605 l_margin += font_metrics::signedWidth(dleft,
607 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
608 && layout->labeltype != LABEL_BIBLIO
609 && layout->labeltype !=
610 LABEL_CENTERED_TOP_ENVIRONMENT) {
611 string labin = layout->labelindent;
612 docstring dlabin(labin.begin(), labin.end());
613 l_margin += font_metrics::signedWidth(dlabin,
615 string labsep = layout->labelsep;
616 docstring dlabsep(labsep.begin(), labsep.end());
617 l_margin += font_metrics::width(dlabsep, labelfont);
618 string labstr = par.getLabelstring();
619 docstring dlabstr(labstr.begin(), labstr.end());
620 l_margin += font_metrics::width(dlabstr, labelfont);
624 case MARGIN_RIGHT_ADDRESS_BOX: {
626 // ok, a terrible hack. The left margin depends on the widest
627 // row in this paragraph.
628 RowList::iterator rit = par.rows().begin();
629 RowList::iterator end = par.rows().end();
631 #warning This is wrong.
633 int minfill = maxwidth_;
634 for ( ; rit != end; ++rit)
635 if (rit->fill() < minfill)
636 minfill = rit->fill();
637 l_margin += font_metrics::signedWidth(layout->leftmargin,
641 // also wrong, but much shorter.
642 l_margin += maxwidth_ / 2;
647 if (!par.params().leftIndent().zero())
648 l_margin += par.params().leftIndent().inPixels(maxwidth_);
652 if (par.params().align() == LYX_ALIGN_LAYOUT)
653 align = layout->align;
655 align = par.params().align();
657 // set the correct parindent
659 && (layout->labeltype == LABEL_NO_LABEL
660 || layout->labeltype == LABEL_TOP_ENVIRONMENT
661 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
662 || (layout->labeltype == LABEL_STATIC
663 && layout->latextype == LATEX_ENVIRONMENT
664 && !isFirstInSequence(pit, pars_)))
665 && align == LYX_ALIGN_BLOCK
666 && !par.params().noindent()
667 // in some insets, paragraphs are never indented
668 && !(par.inInset() && par.inInset()->neverIndent())
669 // display style insets are always centered, omit indentation
672 && par.getInset(pos)->display())
673 && (par.layout() != tclass.defaultLayout()
674 || bv()->buffer()->params().paragraph_separation ==
675 BufferParams::PARSEP_INDENT))
677 docstring din(parindent.begin(), parindent.end());
678 l_margin += font_metrics::signedWidth(din, params.getFont());
685 int LyXText::rightMargin(Paragraph const & par) const
687 // We do not want rightmargins on inner texts.
688 if (bv()->text() != this)
691 BufferParams const & params = bv()->buffer()->params();
692 LyXTextClass const & tclass = params.getLyXTextClass();
693 string trmarg = tclass.rightmargin();
694 docstring dtrmarg(trmarg.begin(), trmarg.end());
695 string lrmarg = par.layout()->rightmargin;
696 docstring dlrmarg(lrmarg.begin(), lrmarg.end());
699 + font_metrics::signedWidth(dtrmarg,
701 + font_metrics::signedWidth(dlrmarg,
703 * 4 / (par.getDepth() + 4);
709 int LyXText::labelEnd(pit_type const pit) const
711 // labelEnd is only needed if the layout fills a flushleft label.
712 if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
714 // return the beginning of the body
715 return leftMargin(pit);
721 // this needs special handling - only newlines count as a break point
722 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
724 pos_type const end = par.size();
727 if (par.isNewline(i))
736 void LyXText::rowBreakPoint(pit_type const pit, Row & row) const
738 Paragraph const & par = pars_[pit];
739 pos_type const end = par.size();
740 pos_type const pos = row.pos();
746 // maximum pixel width of a row
747 int width = maxwidth_ - rightMargin(par); // - leftMargin(pit, row);
753 LyXLayout_ptr const & layout = par.layout();
755 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
756 row.endpos(addressBreakPoint(pos, par));
760 pos_type const body_pos = par.beginOfBody();
763 // Now we iterate through until we reach the right margin
764 // or the end of the par, then choose the possible break
767 int const left = leftMargin(pit, pos);
770 // pixel width since last breakpoint
773 FontIterator fi = FontIterator(*this, par, pos);
774 pos_type point = end;
776 for ( ; i < end; ++i, ++fi) {
777 char_type const c = par.getChar(i);
778 int thiswidth = singleWidth(par, i, c, *fi);
780 // add the auto-hfill from label end to the body
781 if (body_pos && i == body_pos) {
782 string lsep = layout->labelsep;
783 docstring dlsep(lsep.begin(), lsep.end());
784 int add = font_metrics::width(dlsep, getLabelFont(par));
785 if (par.isLineSeparator(i - 1))
786 add -= singleWidth(par, i - 1);
788 add = std::max(add, labelEnd(pit) - x);
793 chunkwidth += thiswidth;
795 // break before a character that will fall off
796 // the right of the row
798 // if no break before, break here
799 if (point == end || chunkwidth >= width - left) {
806 // exit on last registered breakpoint:
810 if (par.isNewline(i)) {
816 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
821 if (par.isInset(i) && par.getInset(i)->display()) {
827 if (!par.isInset(i) || par.getInset(i)->isChar()) {
828 // some insets are line separators too
829 if (par.isLineSeparator(i)) {
830 // register breakpoint:
837 // maybe found one, but the par is short enough.
838 if (i == end && x < width)
841 // manual labels cannot be broken in LaTeX. But we
842 // want to make our on-screen rendering of footnotes
844 if (body_pos && point < body_pos)
851 void LyXText::setRowWidth(pit_type const pit, Row & row) const
853 // get the pure distance
854 pos_type const end = row.endpos();
856 Paragraph const & par = pars_[pit];
857 string const & labelsep = par.layout()->labelsep;
858 docstring dlsep(labelsep.begin(), labelsep.end());
859 int w = leftMargin(pit, row.pos());
861 pos_type const body_pos = par.beginOfBody();
862 pos_type i = row.pos();
865 FontIterator fi = FontIterator(*this, par, i);
866 for ( ; i < end; ++i, ++fi) {
867 if (body_pos > 0 && i == body_pos) {
868 w += font_metrics::width(dlsep, getLabelFont(par));
869 if (par.isLineSeparator(i - 1))
870 w -= singleWidth(par, i - 1);
871 w = max(w, labelEnd(pit));
873 char_type const c = par.getChar(i);
874 w += singleWidth(par, i, c, *fi);
878 if (body_pos > 0 && body_pos >= end) {
879 w += font_metrics::width(dlsep, getLabelFont(par));
880 if (end > 0 && par.isLineSeparator(end - 1))
881 w -= singleWidth(par, end - 1);
882 w = max(w, labelEnd(pit));
885 row.width(w + rightMargin(par));
889 // returns the minimum space a manual label needs on the screen in pixel
890 int LyXText::labelFill(Paragraph const & par, Row const & row) const
892 pos_type last = par.beginOfBody();
894 BOOST_ASSERT(last > 0);
896 // -1 because a label ends with a space that is in the label
899 // a separator at this end does not count
900 if (par.isLineSeparator(last))
904 for (pos_type i = row.pos(); i <= last; ++i)
905 w += singleWidth(par, i);
907 string const & label = par.params().labelWidthString();
911 docstring dlab(label.begin(), label.end());
912 return max(0, font_metrics::width(dlab, getLabelFont(par)) - w);
916 LColor_color LyXText::backgroundColor() const
918 return LColor_color(LColor::color(background_color_));
922 void LyXText::setHeightOfRow(pit_type const pit, Row & row)
924 Paragraph const & par = pars_[pit];
925 // get the maximum ascent and the maximum descent
926 double layoutasc = 0;
927 double layoutdesc = 0;
928 double const dh = defaultRowHeight();
930 // ok, let us initialize the maxasc and maxdesc value.
931 // Only the fontsize count. The other properties
932 // are taken from the layoutfont. Nicer on the screen :)
933 LyXLayout_ptr const & layout = par.layout();
935 // as max get the first character of this row then it can
936 // increase but not decrease the height. Just some point to
937 // start with so we don't have to do the assignment below too
939 LyXFont font = getFont(par, row.pos());
940 LyXFont::FONT_SIZE const tmpsize = font.size();
941 font = getLayoutFont(pit);
942 LyXFont::FONT_SIZE const size = font.size();
943 font.setSize(tmpsize);
945 LyXFont labelfont = getLabelFont(par);
947 // these are minimum values
948 double const spacing_val = layout->spacing.getValue() * spacing(par);
949 //lyxerr << "spacing_val = " << spacing_val << endl;
950 int maxasc = int(font_metrics::maxAscent(font) * spacing_val);
951 int maxdesc = int(font_metrics::maxDescent(font) * spacing_val);
953 // insets may be taller
954 InsetList::const_iterator ii = par.insetlist.begin();
955 InsetList::const_iterator iend = par.insetlist.end();
956 for ( ; ii != iend; ++ii) {
957 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
958 maxasc = max(maxasc, ii->inset->ascent());
959 maxdesc = max(maxdesc, ii->inset->descent());
963 // Check if any custom fonts are larger (Asger)
964 // This is not completely correct, but we can live with the small,
965 // cosmetic error for now.
967 pos_type const pos_end = row.endpos();
969 LyXFont::FONT_SIZE maxsize =
970 par.highestFontInRange(row.pos(), pos_end, size);
971 if (maxsize > font.size()) {
972 font.setSize(maxsize);
973 maxasc = max(maxasc, font_metrics::maxAscent(font));
974 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
977 // This is nicer with box insets:
984 if (row.pos() == 0) {
985 BufferParams const & bufparams = bv()->buffer()->params();
986 // some parksips VERY EASY IMPLEMENTATION
987 if (bv()->buffer()->params().paragraph_separation
988 == BufferParams::PARSEP_SKIP
990 && ((layout->isParagraph() && par.getDepth() == 0)
991 || (pars_[pit - 1].layout()->isParagraph()
992 && pars_[pit - 1].getDepth() == 0)))
994 maxasc += bufparams.getDefSkip().inPixels(*bv());
997 if (par.params().startOfAppendix())
998 maxasc += int(3 * dh);
1000 // This is special code for the chapter, since the label of this
1001 // layout is printed in an extra row
1002 if (layout->counter == "chapter"
1003 && !par.params().labelString().empty()) {
1004 labeladdon = int(font_metrics::maxHeight(labelfont)
1005 * layout->spacing.getValue()
1009 // special code for the top label
1010 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1011 || layout->labeltype == LABEL_BIBLIO
1012 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1013 && isFirstInSequence(pit, paragraphs())
1014 && !par.getLabelstring().empty())
1017 font_metrics::maxHeight(labelfont)
1018 * layout->spacing.getValue()
1020 + (layout->topsep + layout->labelbottomsep) * dh);
1023 // Add the layout spaces, for example before and after
1024 // a section, or between the items of a itemize or enumerate
1027 pit_type prev = depthHook(pit, pars_, par.getDepth());
1029 && pars_[prev].layout() == layout
1030 && pars_[prev].getDepth() == par.getDepth()
1031 && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
1033 layoutasc = layout->itemsep * dh;
1034 } else if (pit != 0 || row.pos() != 0) {
1035 if (layout->topsep > 0)
1036 layoutasc = layout->topsep * dh;
1039 prev = outerHook(pit, pars_);
1040 if (prev != pit_type(pars_.size())) {
1041 maxasc += int(pars_[prev].layout()->parsep * dh);
1042 } else if (pit != 0) {
1043 if (pars_[pit - 1].getDepth() != 0 ||
1044 pars_[pit - 1].layout() == layout) {
1045 maxasc += int(layout->parsep * dh);
1050 // is it a bottom line?
1051 if (row.endpos() >= par.size()) {
1052 // add the layout spaces, for example before and after
1053 // a section, or between the items of a itemize or enumerate
1055 pit_type nextpit = pit + 1;
1056 if (nextpit != pit_type(pars_.size())) {
1057 pit_type cpit = pit;
1061 if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
1062 usual = pars_[cpit].layout()->bottomsep * dh;
1063 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
1064 if (pars_[cpit].layout() != pars_[nextpit].layout()
1065 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1067 unusual = pars_[cpit].layout()->bottomsep * dh;
1069 layoutdesc = max(unusual, usual);
1070 } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
1071 if (pars_[cpit].layout() != pars_[nextpit].layout()
1072 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1073 layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
1078 // incalculate the layout spaces
1079 maxasc += int(layoutasc * 2 / (2 + pars_[pit].getDepth()));
1080 maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
1082 // Top and bottom margin of the document (only at top-level)
1083 if (bv_owner->text() == this) {
1084 if (pit == 0 && row.pos() == 0)
1086 if (pit + 1 == pit_type(pars_.size()) &&
1087 row.endpos() == par.size())
1091 row.ascent(maxasc + labeladdon);
1092 row.descent(maxdesc);
1100 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1102 BOOST_ASSERT(this == cur.text());
1104 Paragraph & cpar = cur.paragraph();
1105 pit_type cpit = cur.pit();
1107 LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1108 LyXLayout_ptr const & layout = cpar.layout();
1110 // this is only allowed, if the current paragraph is not empty
1111 // or caption and if it has not the keepempty flag active
1112 if (cur.lastpos() == 0 && !cpar.allowEmpty()
1113 && layout->labeltype != LABEL_SENSITIVE)
1116 // a layout change may affect also the following paragraph
1117 recUndo(cur.pit(), undoSpan(cur.pit()) - 1);
1119 // Always break behind a space
1120 // It is better to erase the space (Dekel)
1121 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1122 cpar.erase(cur.pos());
1124 // How should the layout for the new paragraph be?
1125 int preserve_layout = 0;
1127 preserve_layout = 2;
1129 preserve_layout = layout->isEnvironment();
1131 // We need to remember this before we break the paragraph, because
1132 // that invalidates the layout variable
1133 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1135 // we need to set this before we insert the paragraph.
1136 bool const isempty = cpar.allowEmpty() && cpar.empty();
1138 ::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1139 cur.pos(), preserve_layout);
1141 // After this, neither paragraph contains any rows!
1144 pit_type next_par = cpit + 1;
1146 // well this is the caption hack since one caption is really enough
1149 // set to standard-layout
1150 pars_[cpit].applyLayout(tclass.defaultLayout());
1152 // set to standard-layout
1153 pars_[next_par].applyLayout(tclass.defaultLayout());
1156 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1157 pars_[next_par].erase(0);
1159 ParIterator current_it(cur);
1160 ParIterator last_it(cur);
1164 updateLabels(cur.buffer(), current_it, last_it);
1166 // Mark "carriage return" as inserted if change tracking:
1167 if (cur.buffer().params().tracking_changes) {
1168 cur.paragraph().setChange(cur.paragraph().size(),
1172 // This check is necessary. Otherwise the new empty paragraph will
1173 // be deleted automatically. And it is more friendly for the user!
1174 if (cur.pos() != 0 || isempty)
1175 setCursor(cur, cur.pit() + 1, 0);
1177 setCursor(cur, cur.pit(), 0);
1181 // insert a character, moves all the following breaks in the
1182 // same Paragraph one to the right and make a rebreak
1183 void LyXText::insertChar(LCursor & cur, char_type c)
1185 BOOST_ASSERT(this == cur.text());
1186 BOOST_ASSERT(c != Paragraph::META_INSET);
1188 recordUndo(cur, Undo::INSERT);
1190 Paragraph & par = cur.paragraph();
1191 // try to remove this
1192 pit_type const pit = cur.pit();
1194 bool const freeSpacing = par.layout()->free_spacing ||
1195 par.isFreeSpacing();
1197 if (lyxrc.auto_number) {
1198 static docstring const number_operators = lyx::from_ascii("+-/*");
1199 static docstring const number_unary_operators = lyx::from_ascii("+-");
1200 static docstring const number_seperators = lyx::from_ascii(".,:");
1202 if (current_font.number() == LyXFont::ON) {
1203 if (!isDigit(c) && !contains(number_operators, c) &&
1204 !(contains(number_seperators, c) &&
1206 cur.pos() != cur.lastpos() &&
1207 getFont(par, cur.pos()).number() == LyXFont::ON &&
1208 getFont(par, cur.pos() - 1).number() == LyXFont::ON)
1210 number(cur); // Set current_font.number to OFF
1211 } else if (isDigit(c) &&
1212 real_current_font.isVisibleRightToLeft()) {
1213 number(cur); // Set current_font.number to ON
1215 if (cur.pos() != 0) {
1216 char_type const c = par.getChar(cur.pos() - 1);
1217 if (contains(number_unary_operators, c) &&
1219 || par.isSeparator(cur.pos() - 2)
1220 || par.isNewline(cur.pos() - 2))
1222 setCharFont(pit, cur.pos() - 1, current_font);
1223 } else if (contains(number_seperators, c)
1225 && getFont(par, cur.pos() - 2).number() == LyXFont::ON) {
1226 setCharFont(pit, cur.pos() - 1, current_font);
1232 // First check, if there will be two blanks together or a blank at
1233 // the beginning of a paragraph.
1234 // I decided to handle blanks like normal characters, the main
1235 // difference are the special checks when calculating the row.fill
1236 // (blank does not count at the end of a row) and the check here
1238 // When the free-spacing option is set for the current layout,
1239 // disable the double-space checking
1240 if (!freeSpacing && isLineSeparatorChar(c)) {
1241 if (cur.pos() == 0) {
1242 static bool sent_space_message = false;
1243 if (!sent_space_message) {
1244 cur.message(_("You cannot insert a space at the "
1245 "beginning of a paragraph. Please read the Tutorial."));
1246 sent_space_message = true;
1250 BOOST_ASSERT(cur.pos() > 0);
1251 if ((par.isLineSeparator(cur.pos() - 1)
1252 || par.isNewline(cur.pos() - 1))
1253 && par.lookupChange(cur.pos() - 1) != Change::DELETED) {
1254 static bool sent_space_message = false;
1255 if (!sent_space_message) {
1256 cur.message(_("You cannot type two spaces this way. "
1257 "Please read the Tutorial."));
1258 sent_space_message = true;
1264 par.insertChar(cur.pos(), c, current_font);
1265 setCursor(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1270 void LyXText::charInserted()
1272 // Here we call finishUndo for every 20 characters inserted.
1273 // This is from my experience how emacs does it. (Lgb)
1274 static unsigned int counter;
1285 LyXText::computeRowMetrics(pit_type const pit, Row const & row) const
1288 Paragraph const & par = pars_[pit];
1290 double w = dim_.wid - row.width();
1292 bool const is_rtl = isRTL(par);
1294 result.x = rightMargin(par);
1296 result.x = leftMargin(pit, row.pos());
1298 // is there a manual margin with a manual label
1299 LyXLayout_ptr const & layout = par.layout();
1301 if (layout->margintype == MARGIN_MANUAL
1302 && layout->labeltype == LABEL_MANUAL) {
1303 /// We might have real hfills in the label part
1304 int nlh = numberOfLabelHfills(par, row);
1306 // A manual label par (e.g. List) has an auto-hfill
1307 // between the label text and the body of the
1309 // But we don't want to do this auto hfill if the par
1314 if (nlh && !par.getLabelWidthString().empty())
1315 result.label_hfill = labelFill(par, row) / double(nlh);
1318 // are there any hfills in the row?
1319 int const nh = numberOfHfills(par, row);
1323 result.hfill = w / nh;
1324 // we don't have to look at the alignment if it is ALIGN_LEFT and
1325 // if the row is already larger then the permitted width as then
1326 // we force the LEFT_ALIGN'edness!
1327 } else if (int(row.width()) < maxwidth_) {
1328 // is it block, flushleft or flushright?
1329 // set x how you need it
1331 if (par.params().align() == LYX_ALIGN_LAYOUT)
1332 align = layout->align;
1334 align = par.params().align();
1336 // Display-style insets should always be on a centred row
1337 // The test on par.size() is to catch zero-size pars, which
1338 // would trigger the assert in Paragraph::getInset().
1339 //inset = par.size() ? par.getInset(row.pos()) : 0;
1341 && par.isInset(row.pos())
1342 && par.getInset(row.pos())->display())
1344 align = LYX_ALIGN_CENTER;
1348 case LYX_ALIGN_BLOCK: {
1349 int const ns = numberOfSeparators(par, row);
1350 bool disp_inset = false;
1351 if (row.endpos() < par.size()) {
1352 InsetBase const * in = par.getInset(row.endpos());
1354 disp_inset = in->display();
1356 // If we have separators, this is not the last row of a
1357 // par, does not end in newline, and is not row above a
1358 // display inset... then stretch it
1360 && row.endpos() < par.size()
1361 && !par.isNewline(row.endpos() - 1)
1364 result.separator = w / ns;
1365 } else if (is_rtl) {
1370 case LYX_ALIGN_RIGHT:
1373 case LYX_ALIGN_CENTER:
1379 bidi.computeTables(par, *bv()->buffer(), row);
1381 pos_type body_pos = par.beginOfBody();
1382 pos_type end = row.endpos();
1385 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1387 string lsep = layout->labelsep;
1388 docstring dlsep(lsep.begin(), lsep.end());
1389 result.x += font_metrics::width(dlsep, getLabelFont(par));
1390 if (body_pos <= end)
1391 result.x += result.label_hfill;
1399 // the cursor set functions have a special mechanism. When they
1400 // realize, that you left an empty paragraph, they will delete it.
1402 bool LyXText::cursorRightOneWord(LCursor & cur)
1404 BOOST_ASSERT(this == cur.text());
1408 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1412 // Advance through word.
1413 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1415 // Skip through trailing nonword stuff.
1416 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1419 return setCursor(cur, old.pit(), old.pos());
1423 bool LyXText::cursorLeftOneWord(LCursor & cur)
1425 BOOST_ASSERT(this == cur.text());
1429 if (old.pos() == 0 && old.pit() != 0) {
1431 old.pos() = old.lastpos();
1433 // Skip through initial nonword stuff.
1434 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
1436 // Advance through word.
1437 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
1440 return setCursor(cur, old.pit(), old.pos());
1444 void LyXText::selectWord(LCursor & cur, word_location loc)
1446 BOOST_ASSERT(this == cur.text());
1447 CursorSlice from = cur.top();
1448 CursorSlice to = cur.top();
1449 getWord(from, to, loc);
1450 if (cur.top() != from)
1451 setCursor(cur, from.pit(), from.pos());
1455 setCursor(cur, to.pit(), to.pos());
1460 // Select the word currently under the cursor when no
1461 // selection is currently set
1462 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1464 BOOST_ASSERT(this == cur.text());
1465 if (cur.selection())
1467 selectWord(cur, loc);
1468 return cur.selection();
1472 void LyXText::acceptChange(LCursor & cur)
1474 BOOST_ASSERT(this == cur.text());
1475 if (!cur.selection() && cur.lastpos() != 0)
1478 recordUndoSelection(cur, Undo::INSERT);
1480 DocIterator it = cur.selectionBegin();
1481 DocIterator et = cur.selectionEnd();
1482 pit_type pit = it.pit();
1483 Change::Type const type = pars_[pit].lookupChange(it.pos()).type;
1484 for (; pit <= et.pit(); ++pit) {
1485 pos_type left = ( pit == it.pit() ? it.pos() : 0 );
1487 ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1488 pars_[pit].acceptChange(left, right);
1490 if (type == Change::DELETED) {
1491 ParagraphList & plist = paragraphs();
1492 if (it.pit() + 1 < et.pit())
1493 pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1494 boost::next(plist.begin(), et.pit()));
1496 // Paragraph merge if appropriate:
1497 if (pars_[it.pit()].lookupChange(pars_[it.pit()].size())
1498 == Change::DELETED) {
1499 setCursorIntern(cur, it.pit() + 1, 0);
1504 cur.clearSelection();
1505 setCursorIntern(cur, it.pit(), 0);
1509 void LyXText::rejectChange(LCursor & cur)
1511 BOOST_ASSERT(this == cur.text());
1512 if (!cur.selection() && cur.lastpos() != 0)
1515 recordUndoSelection(cur, Undo::INSERT);
1517 DocIterator it = cur.selectionBegin();
1518 DocIterator et = cur.selectionEnd();
1519 pit_type pit = it.pit();
1520 Change::Type const type = pars_[pit].lookupChange(it.pos()).type;
1521 for (; pit <= et.pit(); ++pit) {
1522 pos_type left = ( pit == it.pit() ? it.pos() : 0 );
1524 ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1525 pars_[pit].rejectChange(left, right);
1527 if (type == Change::INSERTED) {
1528 ParagraphList & plist = paragraphs();
1529 if (it.pit() + 1 < et.pit())
1530 pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1531 boost::next(plist.begin(), et.pit()));
1532 // Paragraph merge if appropriate:
1533 if (pars_[it.pit()].lookupChange(pars_[it.pit()].size())
1534 == Change::INSERTED) {
1535 setCursorIntern(cur, it.pit() + 1, 0);
1540 cur.clearSelection();
1541 setCursorIntern(cur, it.pit(), 0);
1545 // Delete from cursor up to the end of the current or next word.
1546 void LyXText::deleteWordForward(LCursor & cur)
1548 BOOST_ASSERT(this == cur.text());
1549 if (cur.lastpos() == 0)
1553 cur.selection() = true;
1554 cursorRightOneWord(cur);
1556 cutSelection(cur, true, false);
1561 // Delete from cursor to start of current or prior word.
1562 void LyXText::deleteWordBackward(LCursor & cur)
1564 BOOST_ASSERT(this == cur.text());
1565 if (cur.lastpos() == 0)
1569 cur.selection() = true;
1570 cursorLeftOneWord(cur);
1572 cutSelection(cur, true, false);
1577 // Kill to end of line.
1578 void LyXText::deleteLineForward(LCursor & cur)
1580 BOOST_ASSERT(this == cur.text());
1581 if (cur.lastpos() == 0) {
1582 // Paragraph is empty, so we just go to the right
1586 cur.selection() = true; // to avoid deletion
1589 // What is this test for ??? (JMarc)
1590 if (!cur.selection())
1591 deleteWordForward(cur);
1593 cutSelection(cur, true, false);
1598 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1600 BOOST_ASSERT(this == cur.text());
1604 if (cur.selection()) {
1605 from = cur.selBegin();
1609 getWord(from, to, lyx::PARTIAL_WORD);
1610 cursorRightOneWord(cur);
1613 recordUndoSelection(cur);
1615 pos_type pos = from.pos();
1616 int par = from.pit();
1618 while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1620 if (pos == pars_[pit].size()) {
1625 char_type c = pars_[pit].getChar(pos);
1626 if (c != Paragraph::META_INSET) {
1628 case text_lowercase:
1631 case text_capitalization:
1633 action = text_lowercase;
1635 case text_uppercase:
1640 #ifdef WITH_WARNINGS
1643 pars_[pit].setChar(pos, c);
1649 bool LyXText::erase(LCursor & cur)
1651 BOOST_ASSERT(this == cur.text());
1652 bool needsUpdate = false;
1654 if (cur.pos() != cur.lastpos()) {
1655 recordUndo(cur, Undo::DELETE, cur.pit());
1656 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1657 needsUpdate = backspace(cur);
1658 if (cur.paragraph().lookupChange(cur.pos()) == Change::DELETED)
1660 } else if (cur.pit() != cur.lastpit()) {
1663 setCursorIntern(cur, cur.pit() + 1, 0, false, false);
1664 if (pars_[cur.pit()].layout() == pars_[scur.pit()].layout()) {
1665 recordUndo(scur, Undo::DELETE, scur.pit());
1666 needsUpdate = backspace(cur);
1667 if (cur.buffer().params().tracking_changes) {
1668 // move forward after the paragraph break is DELETED
1669 Paragraph & par = cur.paragraph();
1670 if (par.lookupChange(par.size()) == Change::DELETED)
1671 setCursorIntern(cur, cur.pit() + 1, 0);
1674 setCursorIntern(scur, scur.pit(), scur.pos(), false, scur.boundary());
1677 needsUpdate = dissolveInset(cur);
1683 bool LyXText::backspacePos0(LCursor & cur)
1685 BOOST_ASSERT(this == cur.text());
1686 bool needsUpdate = false;
1688 Paragraph & par = cur.paragraph();
1689 // is it an empty paragraph?
1690 pos_type lastpos = cur.lastpos();
1691 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1692 // This is an empty paragraph and we delete it just
1693 // by moving the cursor one step
1694 // left and let the DeleteEmptyParagraphMechanism
1695 // handle the actual deletion of the paragraph.
1697 if (cur.pit() != 0) {
1698 // For KeepEmpty layouts we need to get
1699 // rid of the keepEmpty setting first.
1700 // And the only way to do this is to
1701 // reset the layout to something
1702 // else: f.ex. the default layout.
1703 if (par.allowEmpty()) {
1704 Buffer & buf = cur.buffer();
1705 BufferParams const & bparams = buf.params();
1706 par.layout(bparams.getLyXTextClass().defaultLayout());
1715 recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1717 pit_type tmppit = cur.pit();
1718 // We used to do cursorLeftIntern() here, but it is
1719 // not a good idea since it triggers the auto-delete
1720 // mechanism. So we do a cursorLeftIntern()-lite,
1721 // without the dreaded mechanism. (JMarc)
1722 if (cur.pit() != 0) {
1723 // steps into the above paragraph.
1724 setCursorIntern(cur, cur.pit() - 1,
1725 pars_[cur.pit() - 1].size(),
1729 // Pasting is not allowed, if the paragraphs have different
1730 // layout. I think it is a real bug of all other
1731 // word processors to allow it. It confuses the user.
1732 // Correction: Pasting is always allowed with standard-layout
1733 // Correction (Jug 20050717): Remove check about alignment!
1734 Buffer & buf = cur.buffer();
1735 BufferParams const & bufparams = buf.params();
1736 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1737 pit_type const cpit = cur.pit();
1740 && (pars_[cpit].layout() == pars_[tmppit].layout()
1741 || pars_[tmppit].layout() == tclass.defaultLayout()))
1743 mergeParagraph(bufparams, pars_, cpit);
1746 if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1749 // the counters may have changed
1750 ParIterator par_it(cur);
1751 updateLabels(cur.buffer(), par_it);
1753 setCursor(cur, cur.pit(), cur.pos(), false);
1759 bool LyXText::backspace(LCursor & cur)
1761 BOOST_ASSERT(this == cur.text());
1762 bool needsUpdate = false;
1763 if (cur.pos() == 0) {
1765 return dissolveInset(cur);
1767 // The cursor is at the beginning of a paragraph, so
1768 // the the backspace will collapse two paragraphs into
1771 if (cur.pit() != 0 && cur.buffer().params().tracking_changes) {
1772 // Previous paragraph, mark "carriage return" as
1774 Paragraph & par = pars_[cur.pit() - 1];
1775 // Take care of a just inserted para break:
1776 if (par.lookupChange(par.size()) != Change::INSERTED) {
1777 par.setChange(par.size(), Change::DELETED);
1778 setCursorIntern(cur, cur.pit() - 1, par.size());
1783 needsUpdate = backspacePos0(cur);
1786 // this is the code for a normal backspace, not pasting
1788 recordUndo(cur, Undo::DELETE);
1789 // We used to do cursorLeftIntern() here, but it is
1790 // not a good idea since it triggers the auto-delete
1791 // mechanism. So we do a cursorLeftIntern()-lite,
1792 // without the dreaded mechanism. (JMarc)
1793 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1794 false, cur.boundary());
1795 cur.paragraph().erase(cur.pos());
1798 if (cur.pos() == cur.lastpos())
1799 setCurrentFont(cur);
1801 setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1807 bool LyXText::dissolveInset(LCursor & cur) {
1808 BOOST_ASSERT(this == cur.text());
1810 if (isMainText() || cur.inset().nargs() != 1)
1813 recordUndoInset(cur);
1814 cur.selHandle(false);
1816 lyx::pos_type spos = cur.pos();
1817 lyx::pit_type spit = cur.pit();
1818 ParagraphList plist;
1819 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1820 plist = paragraphs();
1822 // store cursor offset
1826 cur.paragraph().erase(cur.pos());
1827 if (!plist.empty()) {
1828 Buffer & b = cur.buffer();
1829 pasteParagraphList(cur, plist, b.params().textclass,
1830 b.errorList("Paste"));
1832 cur.pit() = std::min(cur.lastpit(), spit);
1833 cur.pos() = std::min(cur.lastpos(), spos);
1835 cur.clearSelection();
1841 Row const & LyXText::firstRow() const
1843 return *paragraphs().front().rows().begin();
1847 bool LyXText::redoParagraph(pit_type const pit)
1849 // remove rows of paragraph, keep track of height changes
1850 Paragraph & par = pars_[pit];
1852 // Add bibitem insets if necessary
1853 if (par.layout()->labeltype == LABEL_BIBLIO) {
1854 bool hasbibitem(false);
1855 if (!par.insetlist.empty()
1856 // Insist on it being in pos 0
1857 && par.getChar(0) == Paragraph::META_INSET) {
1858 InsetBase * inset = par.insetlist.begin()->inset;
1859 if (inset->lyxCode() == InsetBase::BIBITEM_CODE)
1863 InsetBibitem * inset(new
1864 InsetBibitem(InsetCommandParams("bibitem")));
1865 par.insertInset(0, static_cast<InsetBase *>(inset));
1866 bv()->cursor().posRight();
1871 // FIXME: We should always use getFont(), see documentation of
1872 // noFontChange() in insetbase.h.
1873 LyXFont const bufferfont = bv()->buffer()->params().getFont();
1874 InsetList::iterator ii = par.insetlist.begin();
1875 InsetList::iterator iend = par.insetlist.end();
1876 for (; ii != iend; ++ii) {
1878 int const w = maxwidth_ - leftMargin(pit, ii->pos) - rightMargin(par);
1879 LyXFont const & font = ii->inset->noFontChange() ?
1881 getFont(par, ii->pos);
1882 MetricsInfo mi(bv(), font, w);
1883 ii->inset->metrics(mi, dim);
1886 // rebreak the paragraph
1890 par.setBeginOfBody();
1894 rowBreakPoint(pit, row);
1895 setRowWidth(pit, row);
1896 setHeightOfRow(pit, row);
1897 par.rows().push_back(row);
1898 dim.wid = std::max(dim.wid, row.width());
1899 dim.des += row.height();
1901 } while (z < par.size());
1903 // Make sure that if a par ends in newline, there is one more row
1905 // FIXME this is a dirty trick. Now the _same_ position in the
1906 // paragraph occurs in _two_ different rows, and has two different
1907 // display positions, leading to weird behaviour when moving up/down.
1908 if (z > 0 && par.isNewline(z - 1)) {
1911 setRowWidth(pit, row);
1912 setHeightOfRow(pit, row);
1913 par.rows().push_back(row);
1914 dim.des += row.height();
1917 dim.asc += par.rows()[0].ascent();
1918 dim.des -= par.rows()[0].ascent();
1920 bool const same = dim == par.dim();
1923 //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1929 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1931 //BOOST_ASSERT(mi.base.textwidth);
1932 if (mi.base.textwidth)
1933 maxwidth_ = mi.base.textwidth;
1934 //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1935 // << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1936 // save the caller's font locally:
1937 font_ = mi.base.font;
1941 for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1943 Paragraph & par = paragraphs()[pit];
1945 if (w < par.width())
1950 dim.asc = pars_[0].ascent();
1951 dim.des = h - dim.asc;
1957 // only used for inset right now. should also be used for main text
1958 void LyXText::draw(PainterInfo & pi, int x, int y) const
1960 paintTextInset(*this, pi, x, y);
1965 // only used for inset right now. should also be used for main text
1966 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1968 LCursor & cur = pi.base.bv->cursor();
1969 if (!cur.selection())
1971 if (!ptr_cmp(cur.text(), this))
1974 lyxerr << "draw selection at " << x << endl;
1976 DocIterator beg = cur.selectionBegin();
1977 DocIterator end = cur.selectionEnd();
1979 // the selection doesn't touch the visible screen
1980 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1981 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1984 Paragraph const & par1 = pars_[beg.pit()];
1985 Paragraph const & par2 = pars_[end.pit()];
1987 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1988 Row const & row2 = par2.getRow(end.pos(), end.boundary());
1991 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1996 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1997 int const startx = cursorX(beg.top(), begin.boundary());
1998 x1 = isRTL(par1) ? startx : 0;
1999 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
2003 if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
2004 y2 = pi.base.bv->workHeight();
2008 y2 = bv_funcs::getPos(end).y_ + row2.descent();
2009 int const endx = cursorX(end.top(), end.boundary());
2010 X1 = isRTL(par2) ? 0 : endx;
2011 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
2014 lyxerr << " y1: " << y1 << " y2: " << y2
2015 << " xo: " << xo_ << " wid: " << dim_.wid
2018 // paint big rectangle in one go
2019 pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
2021 // reset background at begin of first selected line
2022 pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
2023 LColor::background);
2025 // reset background at end of last selected line
2026 pi.pain.fillRectangle(x + X1, y2 - row2.height(),
2027 X2 - X1, row2.height(), LColor::background);
2032 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
2034 LCursor & cur = pi.base.bv->cursor();
2035 if (!cur.selection())
2037 if (!ptr_cmp(cur.text(), this))
2040 lyxerr[Debug::DEBUG]
2041 << BOOST_CURRENT_FUNCTION
2042 << "draw selection at " << x
2045 DocIterator beg = cur.selectionBegin();
2046 DocIterator end = cur.selectionEnd();
2048 // the selection doesn't touch the visible screen
2049 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
2050 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
2053 Paragraph const & par1 = pars_[beg.pit()];
2054 Paragraph const & par2 = pars_[end.pit()];
2056 bool const above = (bv_funcs::status(pi.base.bv, beg)
2057 == bv_funcs::CUR_ABOVE);
2058 bool const below = (bv_funcs::status(pi.base.bv, end)
2059 == bv_funcs::CUR_BELOW);
2067 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
2068 y1 = bv_funcs::getPos(beg, beg.boundary()).y_ - row1.ascent();
2069 y2 = y1 + row1.height();
2070 int const startx = cursorX(beg.top(), beg.boundary());
2071 x1 = !isRTL(par1) ? startx : 0;
2072 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
2077 Y1 = pi.base.bv->workHeight();
2078 Y2 = pi.base.bv->workHeight();
2082 Row const & row2 = par2.getRow(end.pos(), end.boundary());
2083 Y1 = bv_funcs::getPos(end, end.boundary()).y_ - row2.ascent();
2084 Y2 = Y1 + row2.height();
2085 int const endx = cursorX(end.top(), end.boundary());
2086 X1 = !isRTL(par2) ? 0 : endx;
2087 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
2090 if (!above && !below && &par1.getRow(beg.pos(), beg.boundary())
2091 == &par2.getRow(end.pos(), end.boundary()))
2093 // paint only one rectangle
2094 int const b( !isRTL(par1) ? x + x1 : x + X1 );
2095 int const w( !isRTL(par1) ? X2 - x1 : x2 - X1 );
2096 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
2100 lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
2101 << "X1:" << X1 << " x2: " << X2 << " wid: " << dim_.wid
2104 // paint upper rectangle
2105 pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
2107 // paint bottom rectangle
2108 pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
2110 // paint center rectangle
2111 pi.pain.fillRectangle(x, y2, dim_.wid,
2112 Y1 - y2, LColor::selection);
2116 bool LyXText::isLastRow(pit_type pit, Row const & row) const
2118 return row.endpos() >= pars_[pit].size()
2119 && pit + 1 == pit_type(paragraphs().size());
2123 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
2125 return row.pos() == 0 && pit == 0;
2129 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
2130 word_location const loc)
2132 Paragraph const & from_par = pars_[from.pit()];
2134 case lyx::WHOLE_WORD_STRICT:
2135 if (from.pos() == 0 || from.pos() == from_par.size()
2136 || !from_par.isLetter(from.pos())
2137 || !from_par.isLetter(from.pos() - 1)) {
2141 // no break here, we go to the next
2143 case lyx::WHOLE_WORD:
2144 // If we are already at the beginning of a word, do nothing
2145 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
2147 // no break here, we go to the next
2149 case lyx::PREVIOUS_WORD:
2150 // always move the cursor to the beginning of previous word
2151 while (from.pos() && from_par.isLetter(from.pos() - 1))
2154 case lyx::NEXT_WORD:
2155 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
2158 case lyx::PARTIAL_WORD:
2159 // no need to move the 'from' cursor
2163 Paragraph & to_par = pars_[to.pit()];
2164 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
2169 void LyXText::write(Buffer const & buf, std::ostream & os) const
2171 ParagraphList::const_iterator pit = paragraphs().begin();
2172 ParagraphList::const_iterator end = paragraphs().end();
2173 Paragraph::depth_type dth = 0;
2174 for (; pit != end; ++pit)
2175 pit->write(buf, os, buf.params(), dth);
2179 bool LyXText::read(Buffer const & buf, LyXLex & lex, ErrorList & errorList)
2181 Paragraph::depth_type depth = 0;
2183 while (lex.isOK()) {
2185 string const token = lex.getString();
2190 if (token == "\\end_inset") {
2194 if (token == "\\end_body") {
2198 if (token == "\\begin_body") {
2202 if (token == "\\end_document") {
2206 if (token == "\\begin_layout") {
2207 lex.pushToken(token);
2210 par.params().depth(depth);
2211 if (buf.params().tracking_changes)
2213 par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
2214 pars_.push_back(par);
2216 // FIXME: goddamn InsetTabular makes us pass a Buffer
2218 ::readParagraph(buf, pars_.back(), lex, errorList);
2220 } else if (token == "\\begin_deeper") {
2222 } else if (token == "\\end_deeper") {
2224 lex.printError("\\end_deeper: " "depth is already null");
2229 lyxerr << "Handling unknown body token: `"
2230 << token << '\'' << endl;
2237 int LyXText::ascent() const
2243 int LyXText::descent() const
2249 int LyXText::cursorX(CursorSlice const & sl, bool boundary) const
2251 pit_type const pit = sl.pit();
2252 Paragraph const & par = pars_[pit];
2253 if (par.rows().empty())
2256 pos_type ppos = sl.pos();
2257 // Correct position in front of big insets
2258 bool const boundary_correction = ppos != 0 && boundary;
2259 if (boundary_correction)
2262 Row const & row = par.getRow(sl.pos(), boundary);
2264 pos_type cursor_vpos = 0;
2266 RowMetrics const m = computeRowMetrics(pit, row);
2269 pos_type const row_pos = row.pos();
2270 pos_type const end = row.endpos();
2273 cursor_vpos = row_pos;
2274 else if (ppos >= end)
2275 cursor_vpos = isRTL(par) ? row_pos : end;
2276 else if (ppos > row_pos && ppos >= end)
2277 // Place cursor after char at (logical) position pos - 1
2278 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
2279 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
2281 // Place cursor before char at (logical) position ppos
2282 cursor_vpos = (bidi.level(ppos) % 2 == 0)
2283 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
2285 pos_type body_pos = par.beginOfBody();
2287 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2290 // Use font span to speed things up, see below
2294 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2295 pos_type pos = bidi.vis2log(vpos);
2296 if (body_pos > 0 && pos == body_pos - 1) {
2297 string lsep = par.layout()->labelsep;
2298 docstring dlsep(lsep.begin(), lsep.end());
2300 + font_metrics::width(dlsep,
2302 if (par.isLineSeparator(body_pos - 1))
2303 x -= singleWidth(par, body_pos - 1);
2306 // Use font span to speed things up, see above
2307 if (pos < font_span.first || pos > font_span.last) {
2308 font_span = par.fontSpan(pos);
2309 font = getFont(par, pos);
2312 x += singleWidth(par, pos, par.getChar(pos), font);
2314 if (hfillExpansion(par, row, pos))
2315 x += (pos >= body_pos) ? m.hfill : m.label_hfill;
2316 else if (par.isSeparator(pos) && pos >= body_pos)
2320 // see correction above
2321 if (boundary_correction)
2322 if (getFont(par, ppos).isVisibleRightToLeft())
2323 x -= singleWidth(par, ppos);
2325 x += singleWidth(par, ppos);
2327 // Make sure inside an inset we always count from the left
2328 // edge (bidi!) -- MV
2329 if (sl.pos() < par.size()) {
2330 font = getFont(par, sl.pos());
2331 if (!boundary && font.isVisibleRightToLeft()
2332 && par.isInset(sl.pos()))
2333 x -= par.getInset(sl.pos())->width();
2339 int LyXText::cursorY(CursorSlice const & sl, bool boundary) const
2341 //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
2342 Paragraph const & par = getPar(sl.pit());
2343 if (par.rows().empty())
2347 h -= pars_[0].rows()[0].ascent();
2348 for (pit_type pit = 0; pit < sl.pit(); ++pit)
2349 h += pars_[pit].height();
2351 if (pos && boundary)
2353 size_t const rend = par.pos2row(pos);
2354 for (size_t rit = 0; rit != rend; ++rit)
2355 h += par.rows()[rit].height();
2356 h += par.rows()[rend].ascent();
2361 // Returns the current font and depth as a message.
2362 string LyXText::currentState(LCursor & cur)
2364 BOOST_ASSERT(this == cur.text());
2365 Buffer & buf = cur.buffer();
2366 Paragraph const & par = cur.paragraph();
2367 std::ostringstream os;
2369 bool const show_change = buf.params().tracking_changes
2370 && par.lookupChange(cur.pos()) != Change::UNCHANGED;
2372 if (buf.params().tracking_changes)
2376 Change change = par.lookupChange(cur.pos());
2377 Author const & a = buf.params().authors().get(change.author);
2378 os << lyx::to_utf8(_("Change: ")) << a.name();
2379 if (!a.email().empty())
2380 os << " (" << a.email() << ")";
2381 if (change.changetime)
2382 os << lyx::to_utf8(_(" at ")) << ctime(&change.changetime);
2386 // I think we should only show changes from the default
2388 // No, from the document font (MV)
2389 LyXFont font = real_current_font;
2390 font.reduce(buf.params().getFont());
2392 // avoid lyx::to_utf8(_(...)) re-entrance problem
2393 string const s = font.stateText(&buf.params());
2394 os << lyx::to_utf8(bformat(_("Font: %1$s"), lyx::from_utf8(s)));
2396 // os << lyx::to_utf8(bformat(_("Font: %1$s"), font.stateText(&buf.params)));
2398 // The paragraph depth
2399 int depth = cur.paragraph().getDepth();
2401 os << lyx::to_utf8(bformat(_(", Depth: %1$d"), depth));
2403 // The paragraph spacing, but only if different from
2405 Spacing const & spacing = par.params().spacing();
2406 if (!spacing.isDefault()) {
2407 os << lyx::to_utf8(_(", Spacing: "));
2408 switch (spacing.getSpace()) {
2409 case Spacing::Single:
2410 os << lyx::to_utf8(_("Single"));
2412 case Spacing::Onehalf:
2413 os << lyx::to_utf8(_("OneHalf"));
2415 case Spacing::Double:
2416 os << lyx::to_utf8(_("Double"));
2418 case Spacing::Other:
2419 os << lyx::to_utf8(_("Other (")) << spacing.getValueAsString() << ')';
2421 case Spacing::Default:
2422 // should never happen, do nothing
2427 #ifdef DEVEL_VERSION
2428 os << lyx::to_utf8(_(", Inset: ")) << &cur.inset();
2429 os << lyx::to_utf8(_(", Paragraph: ")) << cur.pit();
2430 os << lyx::to_utf8(_(", Id: ")) << par.id();
2431 os << lyx::to_utf8(_(", Position: ")) << cur.pos();
2432 os << lyx::to_utf8(_(", Boundary: ")) << cur.boundary();
2433 // Row & row = cur.textRow();
2434 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2440 string LyXText::getPossibleLabel(LCursor & cur) const
2442 pit_type pit = cur.pit();
2444 LyXLayout_ptr layout = pars_[pit].layout();
2446 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2447 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2448 if (layout2->latextype != LATEX_PARAGRAPH) {
2454 string name = layout->latexname();
2456 // for captions, we want the abbreviation of the float type
2457 if (layout->labeltype == LABEL_SENSITIVE) {
2458 // Search for the first float or wrap inset in the iterator
2459 size_t i = cur.depth();
2462 InsetBase * const in = &cur[i].inset();
2463 if (in->lyxCode() == InsetBase::FLOAT_CODE
2464 || in->lyxCode() == InsetBase::WRAP_CODE) {
2465 name = in->getInsetName();
2471 string text = name.substr(0, 3);
2472 if (name == "theorem")
2473 text = "thm"; // Create a correct prefix for prettyref
2476 if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2479 string par_text = pars_[pit].asString(cur.buffer(), false);
2480 for (int i = 0; i < lyxrc.label_init_length; ++i) {
2481 if (par_text.empty())
2484 par_text = split(par_text, head, ' ');
2485 // Is it legal to use spaces in labels ?
2495 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2499 // Paragraph const & par = pars_[pit];
2500 // Row const & r = par.rows()[row];
2501 // int pos = r.pos();
2502 // for (; currx < x && pos < r.endpos(); ++pos) {
2504 // currx += singleWidth(par, pos);
2506 // if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2512 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2514 BOOST_ASSERT(row < int(pars_[pit].rows().size()));
2516 Row const & r = pars_[pit].rows()[row];
2517 return r.pos() + getColumnNearX(pit, r, x, bound);
2521 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2523 // Paragraph const & par = pars_[pit];
2524 // Row const & r = par.rows()[row];
2530 // x,y are screen coordinates
2531 // sets cursor only within this LyXText
2532 bool LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2534 pit_type pit = getPitNearY(y);
2535 int yy = theCoords.get(this, pit).y_ - pars_[pit].ascent();
2536 lyxerr[Debug::DEBUG]
2537 << BOOST_CURRENT_FUNCTION
2541 << " yy: " << yy << endl;
2543 Paragraph const & par = pars_[pit];
2545 BOOST_ASSERT(par.rows().size());
2546 for (; r < int(par.rows().size()) - 1; ++r) {
2547 Row const & row = par.rows()[r];
2548 if (int(yy + row.height()) > y)
2553 Row const & row = par.rows()[r];
2555 lyxerr[Debug::DEBUG]
2556 << BOOST_CURRENT_FUNCTION
2558 << " from pos: " << row.pos()
2563 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2565 lyxerr[Debug::DEBUG]
2566 << BOOST_CURRENT_FUNCTION
2567 << ": setting cursor pit: " << pit
2571 return setCursor(cur, pit, pos, true, bound);