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 "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/FontMetrics.h"
54 #include "frontends/Painter.h"
56 #include "insets/insettext.h"
57 #include "insets/insetbibitem.h"
58 #include "insets/insethfill.h"
59 #include "insets/insetlatexaccent.h"
60 #include "insets/insetline.h"
61 #include "insets/insetnewline.h"
62 #include "insets/insetpagebreak.h"
63 #include "insets/insetoptarg.h"
64 #include "insets/insetspace.h"
65 #include "insets/insetspecialchar.h"
66 #include "insets/insettabular.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
70 #include "support/convert.h"
72 #include <boost/current_function.hpp>
79 using support::bformat;
80 using support::contains;
81 using support::lowercase;
83 using support::uppercase;
85 using cap::cutSelection;
86 using cap::pasteParagraphList;
88 using frontend::FontMetrics;
101 int numberOfSeparators(Paragraph const & par, Row const & row)
103 pos_type const first = max(row.pos(), par.beginOfBody());
104 pos_type const last = row.endpos() - 1;
106 for (pos_type p = first; p < last; ++p) {
107 if (par.isSeparator(p))
114 int numberOfLabelHfills(Paragraph const & par, Row const & row)
116 pos_type last = row.endpos() - 1;
117 pos_type first = row.pos();
119 // hfill *DO* count at the beginning of paragraphs!
121 while (first < last && par.isHfill(first))
125 last = min(last, par.beginOfBody());
127 for (pos_type p = first; p < last; ++p) {
135 int numberOfHfills(Paragraph const & par, Row const & row)
137 pos_type const last = row.endpos();
138 pos_type first = row.pos();
140 // hfill *DO* count at the beginning of paragraphs!
142 while (first < last && par.isHfill(first))
146 first = max(first, par.beginOfBody());
149 for (pos_type p = first; p < last; ++p) {
157 void readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
158 string const & token, LyXFont & font, Change & change, ErrorList & errorList)
160 BufferParams const & bp = buf.params();
162 if (token[0] != '\\') {
164 string::const_iterator cit = token.begin();
165 for (; cit != token.end(); ++cit)
166 par.insertChar(par.size(), (*cit), font, change);
168 docstring dstr = lex.getDocString();
169 docstring::const_iterator cit = dstr.begin();
170 docstring::const_iterator cend = dstr.end();
171 for (; cit != cend; ++cit)
172 par.insertChar(par.size(), *cit, font, change);
174 } else if (token == "\\begin_layout") {
176 string layoutname = lex.getString();
178 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
179 change = Change(Change::UNCHANGED);
181 LyXTextClass const & tclass = bp.getLyXTextClass();
183 if (layoutname.empty()) {
184 layoutname = tclass.defaultLayoutName();
187 bool hasLayout = tclass.hasLayout(layoutname);
190 errorList.push_back(ErrorItem(_("Unknown layout"),
191 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
192 from_utf8(layoutname), from_utf8(tclass.name())), par.id(), 0, par.size()));
193 layoutname = tclass.defaultLayoutName();
196 par.layout(bp.getLyXTextClass()[layoutname]);
198 // Test whether the layout is obsolete.
199 LyXLayout_ptr const & layout = par.layout();
200 if (!layout->obsoleted_by().empty())
201 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
203 par.params().read(lex);
205 } else if (token == "\\end_layout") {
206 lyxerr << BOOST_CURRENT_FUNCTION
207 << ": Solitary \\end_layout in line "
208 << lex.getLineNo() << "\n"
209 << "Missing \\begin_layout?.\n";
210 } else if (token == "\\end_inset") {
211 lyxerr << BOOST_CURRENT_FUNCTION
212 << ": Solitary \\end_inset in line "
213 << lex.getLineNo() << "\n"
214 << "Missing \\begin_inset?.\n";
215 } else if (token == "\\begin_inset") {
216 InsetBase * inset = readInset(lex, buf);
218 par.insertInset(par.size(), inset, font, change);
221 docstring line = from_utf8(lex.getString());
222 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
223 par.id(), 0, par.size()));
225 } else if (token == "\\family") {
227 font.setLyXFamily(lex.getString());
228 } else if (token == "\\series") {
230 font.setLyXSeries(lex.getString());
231 } else if (token == "\\shape") {
233 font.setLyXShape(lex.getString());
234 } else if (token == "\\size") {
236 font.setLyXSize(lex.getString());
237 } else if (token == "\\lang") {
239 string const tok = lex.getString();
240 Language const * lang = languages.getLanguage(tok);
242 font.setLanguage(lang);
244 font.setLanguage(bp.language);
245 lex.printError("Unknown language `$$Token'");
247 } else if (token == "\\numeric") {
249 font.setNumber(font.setLyXMisc(lex.getString()));
250 } else if (token == "\\emph") {
252 font.setEmph(font.setLyXMisc(lex.getString()));
253 } else if (token == "\\bar") {
255 string const tok = lex.getString();
258 font.setUnderbar(LyXFont::ON);
259 else if (tok == "no")
260 font.setUnderbar(LyXFont::OFF);
261 else if (tok == "default")
262 font.setUnderbar(LyXFont::INHERIT);
264 lex.printError("Unknown bar font flag "
266 } else if (token == "\\noun") {
268 font.setNoun(font.setLyXMisc(lex.getString()));
269 } else if (token == "\\color") {
271 font.setLyXColor(lex.getString());
272 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
274 // Insets don't make sense in a free-spacing context! ---Kayvan
275 if (par.isFreeSpacing()) {
276 if (token == "\\InsetSpace")
277 par.insertChar(par.size(), ' ', font, change);
278 else if (lex.isOK()) {
280 string const next_token = lex.getString();
281 if (next_token == "\\-")
282 par.insertChar(par.size(), '-', font, change);
284 lex.printError("Token `$$Token' "
286 "paragraph layout!");
290 auto_ptr<InsetBase> inset;
291 if (token == "\\SpecialChar" )
292 inset.reset(new InsetSpecialChar);
294 inset.reset(new InsetSpace);
295 inset->read(buf, lex);
296 par.insertInset(par.size(), inset.release(),
299 } else if (token == "\\i") {
300 auto_ptr<InsetBase> inset(new InsetLatexAccent);
301 inset->read(buf, lex);
302 par.insertInset(par.size(), inset.release(), font, change);
303 } else if (token == "\\backslash") {
304 par.insertChar(par.size(), '\\', font, change);
305 } else if (token == "\\newline") {
306 auto_ptr<InsetBase> inset(new InsetNewline);
307 inset->read(buf, lex);
308 par.insertInset(par.size(), inset.release(), font, change);
309 } else if (token == "\\LyXTable") {
310 auto_ptr<InsetBase> inset(new InsetTabular(buf));
311 inset->read(buf, lex);
312 par.insertInset(par.size(), inset.release(), font, change);
313 } else if (token == "\\hfill") {
314 par.insertInset(par.size(), new InsetHFill, font, change);
315 } else if (token == "\\lyxline") {
316 par.insertInset(par.size(), new InsetLine, font, change);
317 } else if (token == "\\newpage") {
318 par.insertInset(par.size(), new InsetPagebreak, font, change);
319 } else if (token == "\\change_unchanged") {
320 // Hack ! Needed for empty paragraphs :/
321 // FIXME: change tracking (MG)
322 // set empty 'par' to INSERTED???
323 change = Change(Change::UNCHANGED);
324 } else if (token == "\\change_inserted") {
326 std::istringstream is(lex.getString());
330 if (aid >= bp.author_map.size()) {
331 errorList.push_back(ErrorItem(_("Change tracking error"),
332 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
333 par.id(), 0, par.size()));
335 change = Change(Change::UNCHANGED);
337 change = Change(Change::INSERTED, bp.author_map[aid], ct);
338 } else if (token == "\\change_deleted") {
340 std::istringstream is(lex.getString());
344 if (aid >= bp.author_map.size()) {
345 errorList.push_back(ErrorItem(_("Change tracking error"),
346 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
347 par.id(), 0, par.size()));
349 change = Change(Change::UNCHANGED);
351 change = Change(Change::DELETED, bp.author_map[aid], ct);
354 errorList.push_back(ErrorItem(_("Unknown token"),
355 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
356 from_utf8(lex.getString())),
357 par.id(), 0, par.size()));
362 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex,
363 ErrorList & errorList)
366 string token = lex.getString();
368 Change change(Change::UNCHANGED);
372 readParToken(buf, par, lex, token, font, change, errorList);
375 token = lex.getString();
380 if (token == "\\end_layout") {
381 //Ok, paragraph finished
385 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
386 << token << '\'' << endl;
387 if (token == "\\begin_layout" || token == "\\end_document"
388 || token == "\\end_inset" || token == "\\begin_deeper"
389 || token == "\\end_deeper") {
390 lex.pushToken(token);
391 lyxerr << "Paragraph ended in line "
392 << lex.getLineNo() << "\n"
393 << "Missing \\end_layout.\n";
397 // Final change goes to paragraph break:
398 par.setChange(par.size(), change);
400 // Initialize begin_of_body_ on load; redoParagraph maintains
401 par.setBeginOfBody();
409 BufferView * LyXText::bv() const
411 BOOST_ASSERT(bv_owner != 0);
416 double LyXText::spacing(Paragraph const & par) const
418 if (par.params().spacing().isDefault())
419 return bv()->buffer()->params().spacing().getValue();
420 return par.params().spacing().getValue();
424 int LyXText::width() const
430 int LyXText::height() const
432 return dim_.height();
436 int LyXText::singleWidth(Paragraph const & par, pos_type pos) const
438 return singleWidth(par, pos, par.getChar(pos), getFont(par, pos));
442 int LyXText::singleWidth(Paragraph const & par,
443 pos_type pos, char_type c, LyXFont const & font) const
445 // The most common case is handled first (Asger)
446 if (isPrintable(c)) {
447 Language const * language = font.language();
448 if (language->rightToLeft()) {
449 if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
450 lyxrc.font_norm_type == LyXRC::ISO_10646_1)
451 && language->lang() == "arabic") {
452 if (Encodings::isComposeChar_arabic(c))
454 c = par.transformChar(c, pos);
455 } else if (language->lang() == "hebrew" &&
456 Encodings::isComposeChar_hebrew(c))
459 return theFontMetrics(font).width(c);
462 if (c == Paragraph::META_INSET)
463 return par.getInset(pos)->width();
465 return theFontMetrics(font).width(c);
469 int LyXText::leftMargin(pit_type pit) const
471 BOOST_ASSERT(pit >= 0);
472 BOOST_ASSERT(pit < int(pars_.size()));
473 return leftMargin(pit, pars_[pit].size());
477 int LyXText::leftMargin(pit_type const pit, pos_type const pos) const
479 BOOST_ASSERT(pit >= 0);
480 BOOST_ASSERT(pit < int(pars_.size()));
481 Paragraph const & par = pars_[pit];
482 BOOST_ASSERT(pos >= 0);
483 BOOST_ASSERT(pos <= par.size());
484 //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
485 BufferParams const & params = bv()->buffer()->params();
486 LyXTextClass const & tclass = params.getLyXTextClass();
487 LyXLayout_ptr const & layout = par.layout();
489 string parindent = layout->parindent;
494 l_margin += changebarMargin();
497 docstring leftm = from_utf8(tclass.leftmargin());
498 l_margin += theFontMetrics(params.getFont()).signedWidth(leftm);
500 if (par.getDepth() != 0) {
501 // find the next level paragraph
502 pit_type newpar = outerHook(pit, pars_);
503 if (newpar != pit_type(pars_.size())) {
504 if (pars_[newpar].layout()->isEnvironment()) {
505 l_margin = leftMargin(newpar);
507 if (par.layout() == tclass.defaultLayout()) {
508 if (pars_[newpar].params().noindent())
511 parindent = pars_[newpar].layout()->parindent;
516 // This happens after sections in standard classes. The 1.3.x
517 // code compared depths too, but it does not seem necessary
519 if (par.layout() == tclass.defaultLayout()
520 && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
523 LyXFont const labelfont = getLabelFont(par);
524 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
526 switch (layout->margintype) {
528 if (!layout->leftmargin.empty()) {
530 docstring leftm = from_utf8(layout->leftmargin);
531 l_margin += theFontMetrics(params.getFont()).signedWidth(leftm);
533 if (!par.getLabelstring().empty()) {
535 docstring labin = from_utf8(layout->labelindent);
536 l_margin += labelfont_metrics.signedWidth(labin);
537 docstring labstr = par.getLabelstring();
538 l_margin += labelfont_metrics.width(labstr);
539 docstring labsep = from_utf8(layout->labelsep);
540 l_margin += labelfont_metrics.width(labsep);
544 case MARGIN_MANUAL: {
546 docstring labin = from_utf8(layout->labelindent);
547 l_margin += labelfont_metrics.signedWidth(labin);
548 // The width of an empty par, even with manual label, should be 0
549 if (!par.empty() && pos >= par.beginOfBody()) {
550 if (!par.getLabelWidthString().empty()) {
551 docstring labstr = par.getLabelWidthString();
552 l_margin += labelfont_metrics.width(labstr);
553 docstring labsep = from_utf8(layout->labelsep);
554 l_margin += labelfont_metrics.width(labsep);
560 case MARGIN_STATIC: {
562 docstring leftm = from_utf8(layout->leftmargin);
563 l_margin += theFontMetrics(params.getFont()).signedWidth(leftm)
564 * 4 / (par.getDepth() + 4);
568 case MARGIN_FIRST_DYNAMIC:
569 if (layout->labeltype == LABEL_MANUAL) {
570 if (pos >= par.beginOfBody()) {
572 l_margin += labelfont_metrics.signedWidth(
573 from_utf8(layout->leftmargin));
576 l_margin += labelfont_metrics.signedWidth(
577 from_utf8(layout->labelindent));
580 // Special case to fix problems with
582 || (layout->labeltype == LABEL_STATIC
583 && layout->latextype == LATEX_ENVIRONMENT
584 && !isFirstInSequence(pit, pars_))) {
586 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->leftmargin));
587 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
588 && layout->labeltype != LABEL_BIBLIO
589 && layout->labeltype !=
590 LABEL_CENTERED_TOP_ENVIRONMENT) {
591 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->labelindent));
592 l_margin += labelfont_metrics.width(from_utf8(layout->labelsep));
593 l_margin += labelfont_metrics.width(par.getLabelstring());
597 case MARGIN_RIGHT_ADDRESS_BOX: {
599 // ok, a terrible hack. The left margin depends on the widest
600 // row in this paragraph.
601 RowList::iterator rit = par.rows().begin();
602 RowList::iterator end = par.rows().end();
604 #warning This is wrong.
606 int minfill = maxwidth_;
607 for ( ; rit != end; ++rit)
608 if (rit->fill() < minfill)
609 minfill = rit->fill();
610 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
613 // also wrong, but much shorter.
614 l_margin += maxwidth_ / 2;
619 if (!par.params().leftIndent().zero())
620 l_margin += par.params().leftIndent().inPixels(maxwidth_);
624 if (par.params().align() == LYX_ALIGN_LAYOUT)
625 align = layout->align;
627 align = par.params().align();
629 // set the correct parindent
631 && (layout->labeltype == LABEL_NO_LABEL
632 || layout->labeltype == LABEL_TOP_ENVIRONMENT
633 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
634 || (layout->labeltype == LABEL_STATIC
635 && layout->latextype == LATEX_ENVIRONMENT
636 && !isFirstInSequence(pit, pars_)))
637 && align == LYX_ALIGN_BLOCK
638 && !par.params().noindent()
639 // in some insets, paragraphs are never indented
640 && !(par.inInset() && par.inInset()->neverIndent())
641 // display style insets are always centered, omit indentation
644 && par.getInset(pos)->display())
645 && (par.layout() != tclass.defaultLayout()
646 || bv()->buffer()->params().paragraph_separation ==
647 BufferParams::PARSEP_INDENT))
649 docstring din = from_utf8(parindent);
650 l_margin += theFontMetrics(params.getFont()).signedWidth(din);
657 int LyXText::rightMargin(Paragraph const & par) const
659 // FIXME: the correct way is to only call rightMargin() only
660 // within the main LyXText. The following test is thus bogus.
661 LyXText const & text = bv()->buffer()->text();
662 // We do not want rightmargins on inner texts.
666 BufferParams const & params = bv()->buffer()->params();
667 LyXTextClass const & tclass = params.getLyXTextClass();
668 docstring trmarg = from_utf8(tclass.rightmargin());
669 docstring lrmarg = from_utf8(par.layout()->rightmargin);
670 FontMetrics const & fm = theFontMetrics(params.getFont());
673 + fm.signedWidth(trmarg)
674 + fm.signedWidth(lrmarg)
675 * 4 / (par.getDepth() + 4);
681 int LyXText::labelEnd(pit_type const pit) const
683 // labelEnd is only needed if the layout fills a flushleft label.
684 if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
686 // return the beginning of the body
687 return leftMargin(pit);
693 // this needs special handling - only newlines count as a break point
694 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
696 pos_type const end = par.size();
699 if (par.isNewline(i))
708 void LyXText::rowBreakPoint(pit_type const pit, Row & row) const
710 Paragraph const & par = pars_[pit];
711 pos_type const end = par.size();
712 pos_type const pos = row.pos();
718 // maximum pixel width of a row
719 int width = maxwidth_ - rightMargin(par); // - leftMargin(pit, row);
725 LyXLayout_ptr const & layout = par.layout();
727 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
728 row.endpos(addressBreakPoint(pos, par));
732 pos_type const body_pos = par.beginOfBody();
735 // Now we iterate through until we reach the right margin
736 // or the end of the par, then choose the possible break
739 int const left = leftMargin(pit, pos);
742 // pixel width since last breakpoint
745 FontIterator fi = FontIterator(*this, par, pos);
746 pos_type point = end;
748 FontMetrics const & fm = theFontMetrics(getLabelFont(par));
749 for ( ; i < end; ++i, ++fi) {
750 char_type const c = par.getChar(i);
751 int thiswidth = singleWidth(par, i, c, *fi);
753 // add the auto-hfill from label end to the body
754 if (body_pos && i == body_pos) {
755 docstring lsep = from_utf8(layout->labelsep);
756 int add = fm.width(lsep);
757 if (par.isLineSeparator(i - 1))
758 add -= singleWidth(par, i - 1);
760 add = std::max(add, labelEnd(pit) - x);
765 chunkwidth += thiswidth;
767 // break before a character that will fall off
768 // the right of the row
770 // if no break before, break here
771 if (point == end || chunkwidth >= width - left) {
778 // exit on last registered breakpoint:
782 if (par.isNewline(i)) {
788 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
793 if (par.isInset(i) && par.getInset(i)->display()) {
799 if (!par.isInset(i) || par.getInset(i)->isChar()) {
800 // some insets are line separators too
801 if (par.isLineSeparator(i)) {
802 // register breakpoint:
809 // maybe found one, but the par is short enough.
810 if (i == end && x < width)
813 // manual labels cannot be broken in LaTeX. But we
814 // want to make our on-screen rendering of footnotes
816 if (body_pos && point < body_pos)
823 void LyXText::setRowWidth(pit_type const pit, Row & row) const
825 // get the pure distance
826 pos_type const end = row.endpos();
828 Paragraph const & par = pars_[pit];
829 docstring const labelsep = from_utf8(par.layout()->labelsep);
830 int w = leftMargin(pit, row.pos());
832 pos_type const body_pos = par.beginOfBody();
833 pos_type i = row.pos();
835 FontMetrics const & fm = theFontMetrics(getLabelFont(par));
838 FontIterator fi = FontIterator(*this, par, i);
839 for ( ; i < end; ++i, ++fi) {
840 if (body_pos > 0 && i == body_pos) {
841 w += fm.width(labelsep);
842 if (par.isLineSeparator(i - 1))
843 w -= singleWidth(par, i - 1);
844 w = max(w, labelEnd(pit));
846 char_type const c = par.getChar(i);
847 w += singleWidth(par, i, c, *fi);
851 if (body_pos > 0 && body_pos >= end) {
852 w += fm.width(labelsep);
853 if (end > 0 && par.isLineSeparator(end - 1))
854 w -= singleWidth(par, end - 1);
855 w = max(w, labelEnd(pit));
858 row.width(w + rightMargin(par));
862 // returns the minimum space a manual label needs on the screen in pixel
863 int LyXText::labelFill(Paragraph const & par, Row const & row) const
865 pos_type last = par.beginOfBody();
867 BOOST_ASSERT(last > 0);
869 // -1 because a label ends with a space that is in the label
872 // a separator at this end does not count
873 if (par.isLineSeparator(last))
877 for (pos_type i = row.pos(); i <= last; ++i)
878 w += singleWidth(par, i);
880 docstring const & label = par.params().labelWidthString();
884 FontMetrics const & fm = theFontMetrics(getLabelFont(par));
886 return max(0, fm.width(label) - w);
890 LColor_color LyXText::backgroundColor() const
892 return LColor_color(LColor::color(background_color_));
896 void LyXText::setHeightOfRow(pit_type const pit, Row & row)
898 Paragraph const & par = pars_[pit];
899 // get the maximum ascent and the maximum descent
900 double layoutasc = 0;
901 double layoutdesc = 0;
902 double const dh = defaultRowHeight();
904 // ok, let us initialize the maxasc and maxdesc value.
905 // Only the fontsize count. The other properties
906 // are taken from the layoutfont. Nicer on the screen :)
907 LyXLayout_ptr const & layout = par.layout();
909 // as max get the first character of this row then it can
910 // increase but not decrease the height. Just some point to
911 // start with so we don't have to do the assignment below too
913 LyXFont font = getFont(par, row.pos());
914 LyXFont::FONT_SIZE const tmpsize = font.size();
915 font = getLayoutFont(pit);
916 LyXFont::FONT_SIZE const size = font.size();
917 font.setSize(tmpsize);
919 LyXFont labelfont = getLabelFont(par);
921 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
922 FontMetrics const & fontmetrics = theFontMetrics(font);
924 // these are minimum values
925 double const spacing_val = layout->spacing.getValue() * spacing(par);
926 //lyxerr << "spacing_val = " << spacing_val << endl;
927 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
928 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
930 // insets may be taller
931 InsetList::const_iterator ii = par.insetlist.begin();
932 InsetList::const_iterator iend = par.insetlist.end();
933 for ( ; ii != iend; ++ii) {
934 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
935 maxasc = max(maxasc, ii->inset->ascent());
936 maxdesc = max(maxdesc, ii->inset->descent());
940 // Check if any custom fonts are larger (Asger)
941 // This is not completely correct, but we can live with the small,
942 // cosmetic error for now.
944 pos_type const pos_end = row.endpos();
946 LyXFont::FONT_SIZE maxsize =
947 par.highestFontInRange(row.pos(), pos_end, size);
948 if (maxsize > font.size()) {
949 font.setSize(maxsize);
950 maxasc = max(maxasc, fontmetrics.maxAscent());
951 maxdesc = max(maxdesc, fontmetrics.maxDescent());
954 // This is nicer with box insets:
961 if (row.pos() == 0) {
962 BufferParams const & bufparams = bv()->buffer()->params();
963 // some parksips VERY EASY IMPLEMENTATION
964 if (bv()->buffer()->params().paragraph_separation
965 == BufferParams::PARSEP_SKIP
967 && ((layout->isParagraph() && par.getDepth() == 0)
968 || (pars_[pit - 1].layout()->isParagraph()
969 && pars_[pit - 1].getDepth() == 0)))
971 maxasc += bufparams.getDefSkip().inPixels(*bv());
974 if (par.params().startOfAppendix())
975 maxasc += int(3 * dh);
977 // This is special code for the chapter, since the label of this
978 // layout is printed in an extra row
979 if (layout->counter == "chapter"
980 && !par.params().labelString().empty()) {
981 labeladdon = int(labelfont_metrics.maxHeight()
982 * layout->spacing.getValue()
986 // special code for the top label
987 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
988 || layout->labeltype == LABEL_BIBLIO
989 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
990 && isFirstInSequence(pit, paragraphs())
991 && !par.getLabelstring().empty())
994 labelfont_metrics.maxHeight()
995 * layout->spacing.getValue()
997 + (layout->topsep + layout->labelbottomsep) * dh);
1000 // Add the layout spaces, for example before and after
1001 // a section, or between the items of a itemize or enumerate
1004 pit_type prev = depthHook(pit, pars_, par.getDepth());
1006 && pars_[prev].layout() == layout
1007 && pars_[prev].getDepth() == par.getDepth()
1008 && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
1010 layoutasc = layout->itemsep * dh;
1011 } else if (pit != 0 || row.pos() != 0) {
1012 if (layout->topsep > 0)
1013 layoutasc = layout->topsep * dh;
1016 prev = outerHook(pit, pars_);
1017 if (prev != pit_type(pars_.size())) {
1018 maxasc += int(pars_[prev].layout()->parsep * dh);
1019 } else if (pit != 0) {
1020 if (pars_[pit - 1].getDepth() != 0 ||
1021 pars_[pit - 1].layout() == layout) {
1022 maxasc += int(layout->parsep * dh);
1027 // is it a bottom line?
1028 if (row.endpos() >= par.size()) {
1029 // add the layout spaces, for example before and after
1030 // a section, or between the items of a itemize or enumerate
1032 pit_type nextpit = pit + 1;
1033 if (nextpit != pit_type(pars_.size())) {
1034 pit_type cpit = pit;
1038 if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
1039 usual = pars_[cpit].layout()->bottomsep * dh;
1040 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
1041 if (pars_[cpit].layout() != pars_[nextpit].layout()
1042 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1044 unusual = pars_[cpit].layout()->bottomsep * dh;
1046 layoutdesc = max(unusual, usual);
1047 } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
1048 if (pars_[cpit].layout() != pars_[nextpit].layout()
1049 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1050 layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
1055 // incalculate the layout spaces
1056 maxasc += int(layoutasc * 2 / (2 + pars_[pit].getDepth()));
1057 maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
1059 // FIXME: the correct way is to do the following is to move the
1060 // following code in another method specially tailored for the
1061 // main LyXText. The following test is thus bogus.
1062 LyXText const & text = bv_owner->buffer()->text();
1063 // Top and bottom margin of the document (only at top-level)
1064 if (&text == this) {
1065 if (pit == 0 && row.pos() == 0)
1067 if (pit + 1 == pit_type(pars_.size()) &&
1068 row.endpos() == par.size())
1072 row.ascent(maxasc + labeladdon);
1073 row.descent(maxdesc);
1081 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1083 BOOST_ASSERT(this == cur.text());
1085 Paragraph & cpar = cur.paragraph();
1086 pit_type cpit = cur.pit();
1088 LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1089 LyXLayout_ptr const & layout = cpar.layout();
1091 // this is only allowed, if the current paragraph is not empty
1092 // or caption and if it has not the keepempty flag active
1093 if (cur.lastpos() == 0 && !cpar.allowEmpty()
1094 && layout->labeltype != LABEL_SENSITIVE)
1097 // a layout change may affect also the following paragraph
1098 recUndo(cur.pit(), undoSpan(cur.pit()) - 1);
1100 // Always break behind a space
1101 // It is better to erase the space (Dekel)
1102 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1103 // FIXME: change tracking (MG)
1104 cpar.erase(cur.pos(), cur.buffer().params().trackChanges);
1106 // How should the layout for the new paragraph be?
1107 int preserve_layout = 0;
1109 preserve_layout = 2;
1111 preserve_layout = layout->isEnvironment();
1113 // We need to remember this before we break the paragraph, because
1114 // that invalidates the layout variable
1115 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1117 // we need to set this before we insert the paragraph.
1118 bool const isempty = cpar.allowEmpty() && cpar.empty();
1120 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1121 cur.pos(), preserve_layout);
1123 // After this, neither paragraph contains any rows!
1126 pit_type next_par = cpit + 1;
1128 // well this is the caption hack since one caption is really enough
1131 // set to standard-layout
1132 pars_[cpit].applyLayout(tclass.defaultLayout());
1134 // set to standard-layout
1135 pars_[next_par].applyLayout(tclass.defaultLayout());
1138 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1139 // FIXME: change tracking (MG)
1140 pars_[next_par].erase(0, cur.buffer().params().trackChanges);
1142 ParIterator current_it(cur);
1143 ParIterator last_it(cur);
1147 updateLabels(cur.buffer(), current_it, last_it);
1149 // Mark "carriage return" as inserted if change tracking:
1150 if (cur.buffer().params().trackChanges) {
1151 // FIXME: Change tracking (MG)
1152 cur.paragraph().setChange(cur.paragraph().size(),
1153 Change(Change::INSERTED));
1156 // This check is necessary. Otherwise the new empty paragraph will
1157 // be deleted automatically. And it is more friendly for the user!
1158 if (cur.pos() != 0 || isempty)
1159 setCursor(cur, cur.pit() + 1, 0);
1161 setCursor(cur, cur.pit(), 0);
1165 // insert a character, moves all the following breaks in the
1166 // same Paragraph one to the right and make a rebreak
1167 void LyXText::insertChar(LCursor & cur, char_type c)
1169 BOOST_ASSERT(this == cur.text());
1170 BOOST_ASSERT(c != Paragraph::META_INSET);
1172 recordUndo(cur, Undo::INSERT);
1174 Paragraph & par = cur.paragraph();
1175 // try to remove this
1176 pit_type const pit = cur.pit();
1178 bool const freeSpacing = par.layout()->free_spacing ||
1179 par.isFreeSpacing();
1181 if (lyxrc.auto_number) {
1182 static docstring const number_operators = from_ascii("+-/*");
1183 static docstring const number_unary_operators = from_ascii("+-");
1184 static docstring const number_seperators = from_ascii(".,:");
1186 if (current_font.number() == LyXFont::ON) {
1187 if (!isDigit(c) && !contains(number_operators, c) &&
1188 !(contains(number_seperators, c) &&
1190 cur.pos() != cur.lastpos() &&
1191 getFont(par, cur.pos()).number() == LyXFont::ON &&
1192 getFont(par, cur.pos() - 1).number() == LyXFont::ON)
1194 number(cur); // Set current_font.number to OFF
1195 } else if (isDigit(c) &&
1196 real_current_font.isVisibleRightToLeft()) {
1197 number(cur); // Set current_font.number to ON
1199 if (cur.pos() != 0) {
1200 char_type const c = par.getChar(cur.pos() - 1);
1201 if (contains(number_unary_operators, c) &&
1203 || par.isSeparator(cur.pos() - 2)
1204 || par.isNewline(cur.pos() - 2))
1206 setCharFont(pit, cur.pos() - 1, current_font);
1207 } else if (contains(number_seperators, c)
1209 && getFont(par, cur.pos() - 2).number() == LyXFont::ON) {
1210 setCharFont(pit, cur.pos() - 1, current_font);
1216 // First check, if there will be two blanks together or a blank at
1217 // the beginning of a paragraph.
1218 // I decided to handle blanks like normal characters, the main
1219 // difference are the special checks when calculating the row.fill
1220 // (blank does not count at the end of a row) and the check here
1222 // When the free-spacing option is set for the current layout,
1223 // disable the double-space checking
1224 if (!freeSpacing && isLineSeparatorChar(c)) {
1225 if (cur.pos() == 0) {
1226 static bool sent_space_message = false;
1227 if (!sent_space_message) {
1228 cur.message(_("You cannot insert a space at the "
1229 "beginning of a paragraph. Please read the Tutorial."));
1230 sent_space_message = true;
1234 BOOST_ASSERT(cur.pos() > 0);
1235 if ((par.isLineSeparator(cur.pos() - 1)
1236 || par.isNewline(cur.pos() - 1))
1237 // FIXME: change tracking (MG)
1238 && par.lookupChange(cur.pos() - 1) != Change(Change::DELETED)) {
1239 static bool sent_space_message = false;
1240 if (!sent_space_message) {
1241 cur.message(_("You cannot type two spaces this way. "
1242 "Please read the Tutorial."));
1243 sent_space_message = true;
1249 // FIXME: change tracking (MG)
1250 par.insertChar(cur.pos(), c, current_font, Change(Change::INSERTED));
1251 setCursor(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1256 void LyXText::charInserted()
1258 // Here we call finishUndo for every 20 characters inserted.
1259 // This is from my experience how emacs does it. (Lgb)
1260 static unsigned int counter;
1271 LyXText::computeRowMetrics(pit_type const pit, Row const & row) const
1274 Paragraph const & par = pars_[pit];
1276 double w = dim_.wid - row.width();
1278 bool const is_rtl = isRTL(par);
1280 result.x = rightMargin(par);
1282 result.x = leftMargin(pit, row.pos());
1284 // is there a manual margin with a manual label
1285 LyXLayout_ptr const & layout = par.layout();
1287 if (layout->margintype == MARGIN_MANUAL
1288 && layout->labeltype == LABEL_MANUAL) {
1289 /// We might have real hfills in the label part
1290 int nlh = numberOfLabelHfills(par, row);
1292 // A manual label par (e.g. List) has an auto-hfill
1293 // between the label text and the body of the
1295 // But we don't want to do this auto hfill if the par
1300 if (nlh && !par.getLabelWidthString().empty())
1301 result.label_hfill = labelFill(par, row) / double(nlh);
1304 // are there any hfills in the row?
1305 int const nh = numberOfHfills(par, row);
1309 result.hfill = w / nh;
1310 // we don't have to look at the alignment if it is ALIGN_LEFT and
1311 // if the row is already larger then the permitted width as then
1312 // we force the LEFT_ALIGN'edness!
1313 } else if (int(row.width()) < maxwidth_) {
1314 // is it block, flushleft or flushright?
1315 // set x how you need it
1317 if (par.params().align() == LYX_ALIGN_LAYOUT)
1318 align = layout->align;
1320 align = par.params().align();
1322 // Display-style insets should always be on a centred row
1323 // The test on par.size() is to catch zero-size pars, which
1324 // would trigger the assert in Paragraph::getInset().
1325 //inset = par.size() ? par.getInset(row.pos()) : 0;
1327 && par.isInset(row.pos())
1328 && par.getInset(row.pos())->display())
1330 align = LYX_ALIGN_CENTER;
1334 case LYX_ALIGN_BLOCK: {
1335 int const ns = numberOfSeparators(par, row);
1336 bool disp_inset = false;
1337 if (row.endpos() < par.size()) {
1338 InsetBase const * in = par.getInset(row.endpos());
1340 disp_inset = in->display();
1342 // If we have separators, this is not the last row of a
1343 // par, does not end in newline, and is not row above a
1344 // display inset... then stretch it
1346 && row.endpos() < par.size()
1347 && !par.isNewline(row.endpos() - 1)
1350 result.separator = w / ns;
1351 } else if (is_rtl) {
1356 case LYX_ALIGN_RIGHT:
1359 case LYX_ALIGN_CENTER:
1365 bidi.computeTables(par, *bv()->buffer(), row);
1367 pos_type body_pos = par.beginOfBody();
1368 pos_type end = row.endpos();
1371 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1373 docstring const lsep = from_utf8(layout->labelsep);
1374 result.x += theFontMetrics(getLabelFont(par)).width(lsep);
1375 if (body_pos <= end)
1376 result.x += result.label_hfill;
1384 // the cursor set functions have a special mechanism. When they
1385 // realize, that you left an empty paragraph, they will delete it.
1387 bool LyXText::cursorRightOneWord(LCursor & cur)
1389 BOOST_ASSERT(this == cur.text());
1393 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1397 // Advance through word.
1398 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1400 // Skip through trailing nonword stuff.
1401 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1404 return setCursor(cur, old.pit(), old.pos());
1408 bool LyXText::cursorLeftOneWord(LCursor & cur)
1410 BOOST_ASSERT(this == cur.text());
1414 if (old.pos() == 0 && old.pit() != 0) {
1416 old.pos() = old.lastpos();
1418 // Skip through initial nonword stuff.
1419 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
1421 // Advance through word.
1422 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
1425 return setCursor(cur, old.pit(), old.pos());
1429 void LyXText::selectWord(LCursor & cur, word_location loc)
1431 BOOST_ASSERT(this == cur.text());
1432 CursorSlice from = cur.top();
1433 CursorSlice to = cur.top();
1434 getWord(from, to, loc);
1435 if (cur.top() != from)
1436 setCursor(cur, from.pit(), from.pos());
1440 setCursor(cur, to.pit(), to.pos());
1445 // Select the word currently under the cursor when no
1446 // selection is currently set
1447 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1449 BOOST_ASSERT(this == cur.text());
1450 if (cur.selection())
1452 selectWord(cur, loc);
1453 return cur.selection();
1457 void LyXText::acceptChange(LCursor & cur)
1459 BOOST_ASSERT(this == cur.text());
1460 if (!cur.selection() && cur.lastpos() != 0)
1463 recordUndoSelection(cur, Undo::INSERT);
1465 DocIterator it = cur.selectionBegin();
1466 DocIterator et = cur.selectionEnd();
1467 pit_type pit = it.pit();
1468 Change::Type const type = pars_[pit].lookupChange(it.pos()).type;
1469 for (; pit <= et.pit(); ++pit) {
1470 pos_type left = ( pit == it.pit() ? it.pos() : 0 );
1472 ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1473 pars_[pit].acceptChange(left, right);
1475 if (type == Change::DELETED) {
1476 ParagraphList & plist = paragraphs();
1477 if (it.pit() + 1 < et.pit())
1478 pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1479 boost::next(plist.begin(), et.pit()));
1481 // Paragraph merge if appropriate:
1482 // FIXME: change tracking (MG)
1483 if (pars_[it.pit()].lookupChange(pars_[it.pit()].size())
1484 == Change(Change::DELETED)) {
1485 setCursorIntern(cur, it.pit() + 1, 0);
1490 cur.clearSelection();
1491 setCursorIntern(cur, it.pit(), 0);
1495 void LyXText::rejectChange(LCursor & cur)
1497 BOOST_ASSERT(this == cur.text());
1498 if (!cur.selection() && cur.lastpos() != 0)
1501 recordUndoSelection(cur, Undo::INSERT);
1503 DocIterator it = cur.selectionBegin();
1504 DocIterator et = cur.selectionEnd();
1505 pit_type pit = it.pit();
1506 Change::Type const type = pars_[pit].lookupChange(it.pos()).type;
1507 for (; pit <= et.pit(); ++pit) {
1508 pos_type left = ( pit == it.pit() ? it.pos() : 0 );
1510 ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1511 pars_[pit].rejectChange(left, right);
1513 if (type == Change::INSERTED) {
1514 ParagraphList & plist = paragraphs();
1515 if (it.pit() + 1 < et.pit())
1516 pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1517 boost::next(plist.begin(), et.pit()));
1518 // Paragraph merge if appropriate:
1519 // FIXME: change tracking (MG)
1520 if (pars_[it.pit()].lookupChange(pars_[it.pit()].size())
1521 == Change(Change::INSERTED)) {
1522 setCursorIntern(cur, it.pit() + 1, 0);
1527 cur.clearSelection();
1528 setCursorIntern(cur, it.pit(), 0);
1532 // Delete from cursor up to the end of the current or next word.
1533 void LyXText::deleteWordForward(LCursor & cur)
1535 BOOST_ASSERT(this == cur.text());
1536 if (cur.lastpos() == 0)
1540 cur.selection() = true;
1541 cursorRightOneWord(cur);
1543 cutSelection(cur, true, false);
1548 // Delete from cursor to start of current or prior word.
1549 void LyXText::deleteWordBackward(LCursor & cur)
1551 BOOST_ASSERT(this == cur.text());
1552 if (cur.lastpos() == 0)
1556 cur.selection() = true;
1557 cursorLeftOneWord(cur);
1559 cutSelection(cur, true, false);
1564 // Kill to end of line.
1565 void LyXText::deleteLineForward(LCursor & cur)
1567 BOOST_ASSERT(this == cur.text());
1568 if (cur.lastpos() == 0) {
1569 // Paragraph is empty, so we just go to the right
1573 cur.selection() = true; // to avoid deletion
1576 // What is this test for ??? (JMarc)
1577 if (!cur.selection())
1578 deleteWordForward(cur);
1580 cutSelection(cur, true, false);
1585 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1587 BOOST_ASSERT(this == cur.text());
1591 if (cur.selection()) {
1592 from = cur.selBegin();
1596 getWord(from, to, PARTIAL_WORD);
1597 cursorRightOneWord(cur);
1600 recordUndoSelection(cur);
1602 pos_type pos = from.pos();
1603 int par = from.pit();
1605 while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1607 if (pos == pars_[pit].size()) {
1612 char_type c = pars_[pit].getChar(pos);
1613 if (c != Paragraph::META_INSET) {
1615 case text_lowercase:
1618 case text_capitalization:
1620 action = text_lowercase;
1622 case text_uppercase:
1628 // FIXME: change tracking (MG)
1629 // sorry but we are no longer allowed to set a single character directly
1630 // we have to rewrite this method in terms of erase&insert operations
1631 //pars_[pit].setChar(pos, c);
1637 bool LyXText::erase(LCursor & cur)
1639 BOOST_ASSERT(this == cur.text());
1640 bool needsUpdate = false;
1642 if (cur.pos() != cur.lastpos()) {
1643 recordUndo(cur, Undo::DELETE, cur.pit());
1644 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1645 needsUpdate = backspace(cur);
1646 // FIXME: change tracking (MG)
1647 if (cur.paragraph().lookupChange(cur.pos()) == Change(Change::DELETED))
1649 } else if (cur.pit() != cur.lastpit()) {
1652 setCursorIntern(cur, cur.pit() + 1, 0, false, false);
1653 if (pars_[cur.pit()].layout() == pars_[scur.pit()].layout()) {
1654 recordUndo(scur, Undo::DELETE, scur.pit());
1655 needsUpdate = backspace(cur);
1656 if (cur.buffer().params().trackChanges) {
1657 // FIXME: Change tracking (MG)
1658 // move forward after the paragraph break is DELETED
1659 Paragraph & par = cur.paragraph();
1660 // FIXME: change tracking (MG)
1661 if (par.lookupChange(par.size()) == Change(Change::DELETED))
1662 setCursorIntern(cur, cur.pit() + 1, 0);
1665 setCursorIntern(scur, scur.pit(), scur.pos(), false, scur.boundary());
1668 needsUpdate = dissolveInset(cur);
1674 bool LyXText::backspacePos0(LCursor & cur)
1676 BOOST_ASSERT(this == cur.text());
1677 bool needsUpdate = false;
1679 Paragraph & par = cur.paragraph();
1680 // is it an empty paragraph?
1681 pos_type lastpos = cur.lastpos();
1682 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1683 // This is an empty paragraph and we delete it just
1684 // by moving the cursor one step
1685 // left and let the DeleteEmptyParagraphMechanism
1686 // handle the actual deletion of the paragraph.
1688 if (cur.pit() != 0) {
1689 // For KeepEmpty layouts we need to get
1690 // rid of the keepEmpty setting first.
1691 // And the only way to do this is to
1692 // reset the layout to something
1693 // else: f.ex. the default layout.
1694 if (par.allowEmpty()) {
1695 Buffer & buf = cur.buffer();
1696 BufferParams const & bparams = buf.params();
1697 par.layout(bparams.getLyXTextClass().defaultLayout());
1706 recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1708 pit_type tmppit = cur.pit();
1709 // We used to do cursorLeftIntern() here, but it is
1710 // not a good idea since it triggers the auto-delete
1711 // mechanism. So we do a cursorLeftIntern()-lite,
1712 // without the dreaded mechanism. (JMarc)
1713 if (cur.pit() != 0) {
1714 // steps into the above paragraph.
1715 setCursorIntern(cur, cur.pit() - 1,
1716 pars_[cur.pit() - 1].size(),
1720 // Pasting is not allowed, if the paragraphs have different
1721 // layout. I think it is a real bug of all other
1722 // word processors to allow it. It confuses the user.
1723 // Correction: Pasting is always allowed with standard-layout
1724 // Correction (Jug 20050717): Remove check about alignment!
1725 Buffer & buf = cur.buffer();
1726 BufferParams const & bufparams = buf.params();
1727 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1728 pit_type const cpit = cur.pit();
1731 && (pars_[cpit].layout() == pars_[tmppit].layout()
1732 || pars_[tmppit].layout() == tclass.defaultLayout()))
1734 mergeParagraph(bufparams, pars_, cpit);
1737 if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1740 // the counters may have changed
1741 ParIterator par_it(cur);
1742 updateLabels(cur.buffer(), par_it);
1744 setCursor(cur, cur.pit(), cur.pos(), false);
1750 bool LyXText::backspace(LCursor & cur)
1752 BOOST_ASSERT(this == cur.text());
1753 bool needsUpdate = false;
1754 if (cur.pos() == 0) {
1756 return dissolveInset(cur);
1758 // The cursor is at the beginning of a paragraph, so
1759 // the the backspace will collapse two paragraphs into
1762 if (cur.pit() != 0 && cur.buffer().params().trackChanges) {
1763 // FIXME: Change tracking (MG)
1764 // Previous paragraph, mark "carriage return" as
1766 Paragraph & par = pars_[cur.pit() - 1];
1767 // Take care of a just inserted para break:
1768 // FIXME: change tracking (MG)
1769 if (par.lookupChange(par.size()) != Change(Change::INSERTED)) {
1770 // FIXME: change tracking (MG)
1771 par.setChange(par.size(), Change(Change::DELETED));
1772 setCursorIntern(cur, cur.pit() - 1, par.size());
1777 needsUpdate = backspacePos0(cur);
1780 // this is the code for a normal backspace, not pasting
1782 recordUndo(cur, Undo::DELETE);
1783 // We used to do cursorLeftIntern() here, but it is
1784 // not a good idea since it triggers the auto-delete
1785 // mechanism. So we do a cursorLeftIntern()-lite,
1786 // without the dreaded mechanism. (JMarc)
1787 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1788 false, cur.boundary());
1789 // FIXME: change tracking (MG)
1790 cur.paragraph().erase(cur.pos(), cur.buffer().params().trackChanges);
1793 if (cur.pos() == cur.lastpos())
1794 setCurrentFont(cur);
1796 setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1802 bool LyXText::dissolveInset(LCursor & cur) {
1803 BOOST_ASSERT(this == cur.text());
1805 if (isMainText() || cur.inset().nargs() != 1)
1808 recordUndoInset(cur);
1809 cur.selHandle(false);
1811 pos_type spos = cur.pos();
1812 pit_type spit = cur.pit();
1813 ParagraphList plist;
1814 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1815 plist = paragraphs();
1817 // store cursor offset
1821 Buffer & b = cur.buffer();
1822 // FIXME: change tracking (MG)
1823 cur.paragraph().erase(cur.pos(), b.params().trackChanges);
1824 if (!plist.empty()) {
1825 pasteParagraphList(cur, plist, b.params().textclass,
1826 b.errorList("Paste"));
1828 cur.pit() = std::min(cur.lastpit(), spit);
1829 cur.pos() = std::min(cur.lastpos(), spos);
1831 cur.clearSelection();
1837 Row const & LyXText::firstRow() const
1839 return *paragraphs().front().rows().begin();
1843 bool LyXText::redoParagraph(pit_type const pit)
1845 // remove rows of paragraph, keep track of height changes
1846 Paragraph & par = pars_[pit];
1848 // Add bibitem insets if necessary
1849 if (par.layout()->labeltype == LABEL_BIBLIO) {
1850 bool hasbibitem(false);
1851 if (!par.insetlist.empty()
1852 // Insist on it being in pos 0
1853 && par.getChar(0) == Paragraph::META_INSET) {
1854 InsetBase * inset = par.insetlist.begin()->inset;
1855 if (inset->lyxCode() == InsetBase::BIBITEM_CODE)
1859 InsetBibitem * inset(new
1860 InsetBibitem(InsetCommandParams("bibitem")));
1861 // FIXME: change tracking (MG)
1862 par.insertInset(0, static_cast<InsetBase *>(inset), Change(Change::INSERTED));
1863 bv()->cursor().posRight();
1868 // FIXME: We should always use getFont(), see documentation of
1869 // noFontChange() in insetbase.h.
1870 LyXFont const bufferfont = bv()->buffer()->params().getFont();
1871 InsetList::iterator ii = par.insetlist.begin();
1872 InsetList::iterator iend = par.insetlist.end();
1873 for (; ii != iend; ++ii) {
1875 int const w = maxwidth_ - leftMargin(pit, ii->pos) - rightMargin(par);
1876 LyXFont const & font = ii->inset->noFontChange() ?
1878 getFont(par, ii->pos);
1879 MetricsInfo mi(bv(), font, w);
1880 ii->inset->metrics(mi, dim);
1883 // rebreak the paragraph
1887 par.setBeginOfBody();
1891 rowBreakPoint(pit, row);
1892 setRowWidth(pit, row);
1893 setHeightOfRow(pit, row);
1894 par.rows().push_back(row);
1895 dim.wid = std::max(dim.wid, row.width());
1896 dim.des += row.height();
1898 } while (z < par.size());
1900 // Make sure that if a par ends in newline, there is one more row
1902 // FIXME this is a dirty trick. Now the _same_ position in the
1903 // paragraph occurs in _two_ different rows, and has two different
1904 // display positions, leading to weird behaviour when moving up/down.
1905 if (z > 0 && par.isNewline(z - 1)) {
1908 setRowWidth(pit, row);
1909 setHeightOfRow(pit, row);
1910 par.rows().push_back(row);
1911 dim.des += row.height();
1914 dim.asc += par.rows()[0].ascent();
1915 dim.des -= par.rows()[0].ascent();
1917 bool const same = dim == par.dim();
1920 //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1926 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1928 //BOOST_ASSERT(mi.base.textwidth);
1929 if (mi.base.textwidth)
1930 maxwidth_ = mi.base.textwidth;
1931 //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1932 // << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1933 // save the caller's font locally:
1934 font_ = mi.base.font;
1938 for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1940 Paragraph & par = paragraphs()[pit];
1942 if (w < par.width())
1947 dim.asc = pars_[0].ascent();
1948 dim.des = h - dim.asc;
1954 // only used for inset right now. should also be used for main text
1955 void LyXText::draw(PainterInfo & pi, int x, int y) const
1957 paintTextInset(*this, pi, x, y);
1962 // only used for inset right now. should also be used for main text
1963 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1965 LCursor & cur = pi.base.bv->cursor();
1966 if (!cur.selection())
1968 if (!ptr_cmp(cur.text(), this))
1971 lyxerr << "draw selection at " << x << endl;
1973 DocIterator beg = cur.selectionBegin();
1974 DocIterator end = cur.selectionEnd();
1976 // the selection doesn't touch the visible screen
1977 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1978 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1981 Paragraph const & par1 = pars_[beg.pit()];
1982 Paragraph const & par2 = pars_[end.pit()];
1984 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1985 Row const & row2 = par2.getRow(end.pos(), end.boundary());
1988 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1993 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1994 int const startx = cursorX(beg.top(), begin.boundary());
1995 x1 = isRTL(par1) ? startx : 0;
1996 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
2000 if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
2001 y2 = pi.base.bv->workHeight();
2005 y2 = bv_funcs::getPos(end).y_ + row2.descent();
2006 int const endx = cursorX(end.top(), end.boundary());
2007 X1 = isRTL(par2) ? 0 : endx;
2008 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
2011 lyxerr << " y1: " << y1 << " y2: " << y2
2012 << " xo: " << xo_ << " wid: " << dim_.wid
2015 // paint big rectangle in one go
2016 pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
2018 // reset background at begin of first selected line
2019 pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
2020 LColor::background);
2022 // reset background at end of last selected line
2023 pi.pain.fillRectangle(x + X1, y2 - row2.height(),
2024 X2 - X1, row2.height(), LColor::background);
2029 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
2031 LCursor & cur = pi.base.bv->cursor();
2032 if (!cur.selection())
2034 if (!ptr_cmp(cur.text(), this))
2037 lyxerr[Debug::DEBUG]
2038 << BOOST_CURRENT_FUNCTION
2039 << "draw selection at " << x
2042 DocIterator beg = cur.selectionBegin();
2043 DocIterator end = cur.selectionEnd();
2045 BufferView * bv = pi.base.bv;
2047 // the selection doesn't touch the visible screen
2048 if (bv_funcs::status(bv, beg) == bv_funcs::CUR_BELOW
2049 || bv_funcs::status(bv, end) == bv_funcs::CUR_ABOVE)
2052 Paragraph const & par1 = pars_[beg.pit()];
2053 Paragraph const & par2 = pars_[end.pit()];
2055 bool const above = (bv_funcs::status(bv, beg)
2056 == bv_funcs::CUR_ABOVE);
2057 bool const below = (bv_funcs::status(bv, end)
2058 == bv_funcs::CUR_BELOW);
2066 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
2067 y1 = bv_funcs::getPos(*bv, beg, beg.boundary()).y_ - row1.ascent();
2068 y2 = y1 + row1.height();
2069 int const startx = cursorX(beg.top(), beg.boundary());
2070 x1 = !isRTL(par1) ? startx : 0;
2071 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
2076 Y1 = bv->workHeight();
2077 Y2 = bv->workHeight();
2081 Row const & row2 = par2.getRow(end.pos(), end.boundary());
2082 Y1 = bv_funcs::getPos(*bv, end, end.boundary()).y_ - row2.ascent();
2083 Y2 = Y1 + row2.height();
2084 int const endx = cursorX(end.top(), end.boundary());
2085 X1 = !isRTL(par2) ? 0 : endx;
2086 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
2089 if (!above && !below && &par1.getRow(beg.pos(), beg.boundary())
2090 == &par2.getRow(end.pos(), end.boundary()))
2092 // paint only one rectangle
2093 int const b( !isRTL(par1) ? x + x1 : x + X1 );
2094 int const w( !isRTL(par1) ? X2 - x1 : x2 - X1 );
2095 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
2099 lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
2100 << "X1:" << X1 << " x2: " << X2 << " wid: " << dim_.wid
2103 // paint upper rectangle
2104 pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
2106 // paint bottom rectangle
2107 pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
2109 // paint center rectangle
2110 pi.pain.fillRectangle(x, y2, dim_.wid,
2111 Y1 - y2, LColor::selection);
2115 bool LyXText::isLastRow(pit_type pit, Row const & row) const
2117 return row.endpos() >= pars_[pit].size()
2118 && pit + 1 == pit_type(paragraphs().size());
2122 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
2124 return row.pos() == 0 && pit == 0;
2128 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
2129 word_location const loc)
2131 Paragraph const & from_par = pars_[from.pit()];
2133 case WHOLE_WORD_STRICT:
2134 if (from.pos() == 0 || from.pos() == from_par.size()
2135 || !from_par.isLetter(from.pos())
2136 || !from_par.isLetter(from.pos() - 1)) {
2140 // no break here, we go to the next
2143 // If we are already at the beginning of a word, do nothing
2144 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
2146 // no break here, we go to the next
2149 // always move the cursor to the beginning of previous word
2150 while (from.pos() && from_par.isLetter(from.pos() - 1))
2154 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
2158 // no need to move the 'from' cursor
2162 Paragraph & to_par = pars_[to.pit()];
2163 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
2168 void LyXText::write(Buffer const & buf, std::ostream & os) const
2170 ParagraphList::const_iterator pit = paragraphs().begin();
2171 ParagraphList::const_iterator end = paragraphs().end();
2173 for (; pit != end; ++pit)
2174 pit->write(buf, os, buf.params(), dth);
2178 bool LyXText::read(Buffer const & buf, LyXLex & lex, ErrorList & errorList)
2180 depth_type depth = 0;
2182 while (lex.isOK()) {
2184 string const token = lex.getString();
2189 if (token == "\\end_inset")
2192 if (token == "\\end_body")
2195 if (token == "\\begin_body")
2198 if (token == "\\end_document")
2201 if (token == "\\begin_layout") {
2202 lex.pushToken(token);
2205 par.params().depth(depth);
2206 par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
2207 pars_.push_back(par);
2209 // FIXME: goddamn InsetTabular makes us pass a Buffer
2211 lyx::readParagraph(buf, pars_.back(), lex, errorList);
2213 } else if (token == "\\begin_deeper") {
2215 } else if (token == "\\end_deeper") {
2217 lex.printError("\\end_deeper: " "depth is already null");
2222 lyxerr << "Handling unknown body token: `"
2223 << token << '\'' << endl;
2230 int LyXText::ascent() const
2236 int LyXText::descent() const
2242 int LyXText::cursorX(CursorSlice const & sl, bool boundary) const
2244 pit_type const pit = sl.pit();
2245 Paragraph const & par = pars_[pit];
2246 if (par.rows().empty())
2249 pos_type ppos = sl.pos();
2250 // Correct position in front of big insets
2251 bool const boundary_correction = ppos != 0 && boundary;
2252 if (boundary_correction)
2255 Row const & row = par.getRow(sl.pos(), boundary);
2257 pos_type cursor_vpos = 0;
2259 RowMetrics const m = computeRowMetrics(pit, row);
2262 pos_type const row_pos = row.pos();
2263 pos_type const end = row.endpos();
2266 cursor_vpos = row_pos;
2267 else if (ppos >= end)
2268 cursor_vpos = isRTL(par) ? row_pos : end;
2269 else if (ppos > row_pos && ppos >= end)
2270 // Place cursor after char at (logical) position pos - 1
2271 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
2272 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
2274 // Place cursor before char at (logical) position ppos
2275 cursor_vpos = (bidi.level(ppos) % 2 == 0)
2276 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
2278 pos_type body_pos = par.beginOfBody();
2280 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2283 // Use font span to speed things up, see below
2286 FontMetrics const & labelfm = theFontMetrics(getLabelFont(par));
2288 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2289 pos_type pos = bidi.vis2log(vpos);
2290 if (body_pos > 0 && pos == body_pos - 1) {
2292 docstring const lsep = from_utf8(par.layout()->labelsep);
2293 x += m.label_hfill + labelfm.width(lsep);
2294 if (par.isLineSeparator(body_pos - 1))
2295 x -= singleWidth(par, body_pos - 1);
2298 // Use font span to speed things up, see above
2299 if (pos < font_span.first || pos > font_span.last) {
2300 font_span = par.fontSpan(pos);
2301 font = getFont(par, pos);
2304 x += singleWidth(par, pos, par.getChar(pos), font);
2306 if (par.hfillExpansion(row, pos))
2307 x += (pos >= body_pos) ? m.hfill : m.label_hfill;
2308 else if (par.isSeparator(pos) && pos >= body_pos)
2312 // see correction above
2313 if (boundary_correction)
2314 if (getFont(par, ppos).isVisibleRightToLeft())
2315 x -= singleWidth(par, ppos);
2317 x += singleWidth(par, ppos);
2319 // Make sure inside an inset we always count from the left
2320 // edge (bidi!) -- MV
2321 if (sl.pos() < par.size()) {
2322 font = getFont(par, sl.pos());
2323 if (!boundary && font.isVisibleRightToLeft()
2324 && par.isInset(sl.pos()))
2325 x -= par.getInset(sl.pos())->width();
2331 int LyXText::cursorY(CursorSlice const & sl, bool boundary) const
2333 //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
2334 Paragraph const & par = getPar(sl.pit());
2335 if (par.rows().empty())
2339 h -= pars_[0].rows()[0].ascent();
2340 for (pit_type pit = 0; pit < sl.pit(); ++pit)
2341 h += pars_[pit].height();
2343 if (pos && boundary)
2345 size_t const rend = par.pos2row(pos);
2346 for (size_t rit = 0; rit != rend; ++rit)
2347 h += par.rows()[rit].height();
2348 h += par.rows()[rend].ascent();
2353 // Returns the current font and depth as a message.
2354 string LyXText::currentState(LCursor & cur)
2356 BOOST_ASSERT(this == cur.text());
2357 Buffer & buf = cur.buffer();
2358 Paragraph const & par = cur.paragraph();
2359 std::ostringstream os;
2361 // FIXME: change tracking (MG)
2362 bool const show_change = par.lookupChange(cur.pos()) != Change(Change::UNCHANGED);
2364 if (buf.params().trackChanges)
2368 Change change = par.lookupChange(cur.pos());
2369 Author const & a = buf.params().authors().get(change.author);
2370 os << to_utf8(_("Change: ")) << a.name();
2371 if (!a.email().empty())
2372 os << " (" << a.email() << ")";
2373 if (change.changetime)
2374 os << to_utf8(_(" at ")) << ctime(&change.changetime);
2378 // I think we should only show changes from the default
2380 // No, from the document font (MV)
2381 LyXFont font = real_current_font;
2382 font.reduce(buf.params().getFont());
2384 // avoid to_utf8(_(...)) re-entrance problem
2385 string const s = font.stateText(&buf.params());
2386 os << to_utf8(bformat(_("Font: %1$s"), from_utf8(s)));
2388 // os << to_utf8(bformat(_("Font: %1$s"), font.stateText(&buf.params)));
2390 // The paragraph depth
2391 int depth = cur.paragraph().getDepth();
2393 os << to_utf8(bformat(_(", Depth: %1$d"), depth));
2395 // The paragraph spacing, but only if different from
2397 Spacing const & spacing = par.params().spacing();
2398 if (!spacing.isDefault()) {
2399 os << to_utf8(_(", Spacing: "));
2400 switch (spacing.getSpace()) {
2401 case Spacing::Single:
2402 os << to_utf8(_("Single"));
2404 case Spacing::Onehalf:
2405 os << to_utf8(_("OneHalf"));
2407 case Spacing::Double:
2408 os << to_utf8(_("Double"));
2410 case Spacing::Other:
2411 os << to_utf8(_("Other (")) << spacing.getValueAsString() << ')';
2413 case Spacing::Default:
2414 // should never happen, do nothing
2419 #ifdef DEVEL_VERSION
2420 os << to_utf8(_(", Inset: ")) << &cur.inset();
2421 os << to_utf8(_(", Paragraph: ")) << cur.pit();
2422 os << to_utf8(_(", Id: ")) << par.id();
2423 os << to_utf8(_(", Position: ")) << cur.pos();
2424 os << to_utf8(_(", Boundary: ")) << cur.boundary();
2425 // Row & row = cur.textRow();
2426 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2432 string LyXText::getPossibleLabel(LCursor & cur) const
2434 pit_type pit = cur.pit();
2436 LyXLayout_ptr layout = pars_[pit].layout();
2438 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2439 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2440 if (layout2->latextype != LATEX_PARAGRAPH) {
2446 string name = layout->latexname();
2448 // for captions, we want the abbreviation of the float type
2449 if (layout->labeltype == LABEL_SENSITIVE) {
2450 // Search for the first float or wrap inset in the iterator
2451 size_t i = cur.depth();
2454 InsetBase * const in = &cur[i].inset();
2455 if (in->lyxCode() == InsetBase::FLOAT_CODE
2456 || in->lyxCode() == InsetBase::WRAP_CODE) {
2457 name = in->getInsetName();
2463 string text = name.substr(0, 3);
2464 if (name == "theorem")
2465 text = "thm"; // Create a correct prefix for prettyref
2468 if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2472 string par_text = to_utf8(pars_[pit].asString(cur.buffer(), false));
2473 for (int i = 0; i < lyxrc.label_init_length; ++i) {
2474 if (par_text.empty())
2477 par_text = split(par_text, head, ' ');
2478 // Is it legal to use spaces in labels ?
2488 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2492 // Paragraph const & par = pars_[pit];
2493 // Row const & r = par.rows()[row];
2494 // int pos = r.pos();
2495 // for (; currx < x && pos < r.endpos(); ++pos) {
2497 // currx += singleWidth(par, pos);
2499 // if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2505 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2507 BOOST_ASSERT(row < int(pars_[pit].rows().size()));
2509 Row const & r = pars_[pit].rows()[row];
2510 return r.pos() + getColumnNearX(pit, r, x, bound);
2514 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2516 // Paragraph const & par = pars_[pit];
2517 // Row const & r = par.rows()[row];
2523 // x,y are screen coordinates
2524 // sets cursor only within this LyXText
2525 bool LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2527 BOOST_ASSERT(this == cur.text());
2528 pit_type pit = getPitNearY(y);
2529 int yy = cur.bv().coordCache().get(this, pit).y_ - pars_[pit].ascent();
2530 lyxerr[Debug::DEBUG]
2531 << BOOST_CURRENT_FUNCTION
2535 << " yy: " << yy << endl;
2537 Paragraph const & par = pars_[pit];
2539 BOOST_ASSERT(par.rows().size());
2540 for (; r < int(par.rows().size()) - 1; ++r) {
2541 Row const & row = par.rows()[r];
2542 if (int(yy + row.height()) > y)
2547 Row const & row = par.rows()[r];
2549 lyxerr[Debug::DEBUG]
2550 << BOOST_CURRENT_FUNCTION
2552 << " from pos: " << row.pos()
2557 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2559 lyxerr[Debug::DEBUG]
2560 << BOOST_CURRENT_FUNCTION
2561 << ": setting cursor pit: " << pit
2565 return setCursor(cur, pit, pos, true, bound);