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>
80 using lyx::word_location;
82 using lyx::support::bformat;
83 using lyx::support::contains;
84 using lyx::support::lowercase;
85 using lyx::support::split;
86 using lyx::support::uppercase;
88 using lyx::cap::cutSelection;
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() - 1;
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)
160 BufferParams const & bp = buf.params();
162 if (token[0] != '\\') {
163 string::const_iterator cit = token.begin();
164 for (; cit != token.end(); ++cit)
165 par.insertChar(par.size(), (*cit), font, change);
166 } else if (token == "\\begin_layout") {
168 string layoutname = lex.getString();
170 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
173 LyXTextClass const & tclass = bp.getLyXTextClass();
175 if (layoutname.empty()) {
176 layoutname = tclass.defaultLayoutName();
179 bool hasLayout = tclass.hasLayout(layoutname);
182 buf.error(ErrorItem(_("Unknown layout"),
183 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
184 layoutname, tclass.name()), par.id(), 0, par.size()));
185 layoutname = tclass.defaultLayoutName();
188 par.layout(bp.getLyXTextClass()[layoutname]);
190 // Test whether the layout is obsolete.
191 LyXLayout_ptr const & layout = par.layout();
192 if (!layout->obsoleted_by().empty())
193 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
195 par.params().read(lex);
197 } else if (token == "\\end_layout") {
198 lyxerr << BOOST_CURRENT_FUNCTION
199 << ": Solitary \\end_layout in line "
200 << lex.getLineNo() << "\n"
201 << "Missing \\begin_layout?.\n";
202 } else if (token == "\\end_inset") {
203 lyxerr << BOOST_CURRENT_FUNCTION
204 << ": Solitary \\end_inset in line "
205 << lex.getLineNo() << "\n"
206 << "Missing \\begin_inset?.\n";
207 } else if (token == "\\begin_inset") {
208 InsetBase * inset = readInset(lex, buf);
210 par.insertInset(par.size(), inset, font, change);
213 string line = lex.getString();
214 buf.error(ErrorItem(_("Unknown Inset"), line,
215 par.id(), 0, par.size()));
217 } else if (token == "\\family") {
219 font.setLyXFamily(lex.getString());
220 } else if (token == "\\series") {
222 font.setLyXSeries(lex.getString());
223 } else if (token == "\\shape") {
225 font.setLyXShape(lex.getString());
226 } else if (token == "\\size") {
228 font.setLyXSize(lex.getString());
229 } else if (token == "\\lang") {
231 string const tok = lex.getString();
232 Language const * lang = languages.getLanguage(tok);
234 font.setLanguage(lang);
236 font.setLanguage(bp.language);
237 lex.printError("Unknown language `$$Token'");
239 } else if (token == "\\numeric") {
241 font.setNumber(font.setLyXMisc(lex.getString()));
242 } else if (token == "\\emph") {
244 font.setEmph(font.setLyXMisc(lex.getString()));
245 } else if (token == "\\bar") {
247 string const tok = lex.getString();
250 font.setUnderbar(LyXFont::ON);
251 else if (tok == "no")
252 font.setUnderbar(LyXFont::OFF);
253 else if (tok == "default")
254 font.setUnderbar(LyXFont::INHERIT);
256 lex.printError("Unknown bar font flag "
258 } else if (token == "\\noun") {
260 font.setNoun(font.setLyXMisc(lex.getString()));
261 } else if (token == "\\color") {
263 font.setLyXColor(lex.getString());
264 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
266 // Insets don't make sense in a free-spacing context! ---Kayvan
267 if (par.isFreeSpacing()) {
268 if (token == "\\InsetSpace")
269 par.insertChar(par.size(), ' ', font, change);
270 else if (lex.isOK()) {
272 string const next_token = lex.getString();
273 if (next_token == "\\-")
274 par.insertChar(par.size(), '-', font, change);
276 lex.printError("Token `$$Token' "
278 "paragraph layout!");
282 auto_ptr<InsetBase> inset;
283 if (token == "\\SpecialChar" )
284 inset.reset(new InsetSpecialChar);
286 inset.reset(new InsetSpace);
287 inset->read(buf, lex);
288 par.insertInset(par.size(), inset.release(),
291 } else if (token == "\\i") {
292 auto_ptr<InsetBase> inset(new InsetLatexAccent);
293 inset->read(buf, lex);
294 par.insertInset(par.size(), inset.release(), font, change);
295 } else if (token == "\\backslash") {
296 par.insertChar(par.size(), '\\', font, change);
297 } else if (token == "\\newline") {
298 auto_ptr<InsetBase> inset(new InsetNewline);
299 inset->read(buf, lex);
300 par.insertInset(par.size(), inset.release(), font, change);
301 } else if (token == "\\LyXTable") {
302 auto_ptr<InsetBase> inset(new InsetTabular(buf));
303 inset->read(buf, lex);
304 par.insertInset(par.size(), inset.release(), font, change);
305 } else if (token == "\\bibitem") {
306 InsetCommandParams p("bibitem", "dummy");
307 auto_ptr<InsetBibitem> inset(new InsetBibitem(p));
308 inset->read(buf, lex);
309 par.insertInset(par.size(), inset.release(), font, change);
310 } else if (token == "\\hfill") {
311 par.insertInset(par.size(), new InsetHFill, font, change);
312 } else if (token == "\\lyxline") {
313 par.insertInset(par.size(), new InsetLine, font, change);
314 } else if (token == "\\newpage") {
315 par.insertInset(par.size(), new InsetPagebreak, font, change);
316 } else if (token == "\\change_unchanged") {
317 // Hack ! Needed for empty paragraphs :/
318 // FIXME: is it still ??
323 change = Change(Change::UNCHANGED);
324 } else if (token == "\\change_inserted") {
326 std::istringstream is(lex.getString());
330 change = Change(Change::INSERTED, bp.author_map[aid], ct);
331 } else if (token == "\\change_deleted") {
333 std::istringstream is(lex.getString());
337 change = Change(Change::DELETED, bp.author_map[aid], ct);
340 buf.error(ErrorItem(_("Unknown token"),
341 bformat(_("Unknown token: %1$s %2$s\n"), token, lex.getString()),
342 par.id(), 0, par.size()));
347 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex)
350 string token = lex.getString();
356 readParToken(buf, par, lex, token, font, change);
359 token = lex.getString();
364 if (token == "\\end_layout") {
365 //Ok, paragraph finished
369 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
370 << token << '\'' << endl;
371 if (token == "\\begin_layout" || token == "\\end_document"
372 || token == "\\end_inset" || token == "\\begin_deeper"
373 || token == "\\end_deeper") {
374 lex.pushToken(token);
375 lyxerr << "Paragraph ended in line "
376 << lex.getLineNo() << "\n"
377 << "Missing \\end_layout.\n";
381 // Final change goes to paragraph break:
382 par.setChangeFull(par.size(), change);
384 // Initialize begin_of_body_ on load; redoParagraph maintains
385 par.setBeginOfBody();
393 BufferView * LyXText::bv() const
395 BOOST_ASSERT(bv_owner != 0);
400 double LyXText::spacing(Paragraph const & par) const
402 if (par.params().spacing().isDefault())
403 return bv()->buffer()->params().spacing().getValue();
404 return par.params().spacing().getValue();
408 int LyXText::width() const
414 int LyXText::height() const
416 return dim_.height();
420 int LyXText::singleWidth(Paragraph const & par, pos_type pos) const
422 return singleWidth(par, pos, par.getChar(pos), getFont(par, pos));
426 int LyXText::singleWidth(Paragraph const & par,
427 pos_type pos, char c, LyXFont const & font) const
429 // The most common case is handled first (Asger)
430 if (isPrintable(c)) {
431 Language const * language = font.language();
432 if (language->rightToLeft()) {
433 if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
434 lyxrc.font_norm_type == LyXRC::ISO_10646_1)
435 && language->lang() == "arabic") {
436 if (Encodings::isComposeChar_arabic(c))
438 c = par.transformChar(c, pos);
439 } else if (language->lang() == "hebrew" &&
440 Encodings::isComposeChar_hebrew(c))
443 return font_metrics::width(c, font);
446 if (c == Paragraph::META_INSET)
447 return par.getInset(pos)->width();
449 return font_metrics::width(c, font);
453 int LyXText::leftMargin(pit_type pit) const
455 BOOST_ASSERT(pit >= 0);
456 BOOST_ASSERT(pit < int(pars_.size()));
457 return leftMargin(pit, pars_[pit].size());
461 int LyXText::leftMargin(pit_type const pit, pos_type const pos) const
463 BOOST_ASSERT(pit >= 0);
464 BOOST_ASSERT(pit < int(pars_.size()));
465 Paragraph const & par = pars_[pit];
466 BOOST_ASSERT(pos >= 0);
467 BOOST_ASSERT(pos <= par.size());
468 //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
469 LyXTextClass const & tclass =
470 bv()->buffer()->params().getLyXTextClass();
471 LyXLayout_ptr const & layout = par.layout();
473 string parindent = layout->parindent;
478 l_margin += changebarMargin();
480 l_margin += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
482 if (par.getDepth() != 0) {
483 // find the next level paragraph
484 pit_type newpar = outerHook(pit, pars_);
485 if (newpar != pit_type(pars_.size())) {
486 if (pars_[newpar].layout()->isEnvironment()) {
487 l_margin = leftMargin(newpar);
489 if (par.layout() == tclass.defaultLayout()) {
490 if (pars_[newpar].params().noindent())
493 parindent = pars_[newpar].layout()->parindent;
498 // This happens after sections in standard classes. The 1.3.x
499 // code compared depths too, but it does not seem necessary
501 if (par.layout() == tclass.defaultLayout()
502 && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
505 LyXFont const labelfont = getLabelFont(par);
506 switch (layout->margintype) {
508 if (!layout->leftmargin.empty())
509 l_margin += font_metrics::signedWidth(layout->leftmargin,
510 tclass.defaultfont());
511 if (!par.getLabelstring().empty()) {
512 l_margin += font_metrics::signedWidth(layout->labelindent,
514 l_margin += font_metrics::width(par.getLabelstring(),
516 l_margin += font_metrics::width(layout->labelsep, labelfont);
521 l_margin += font_metrics::signedWidth(layout->labelindent, labelfont);
522 // The width of an empty par, even with manual label, should be 0
523 if (!par.empty() && pos >= par.beginOfBody()) {
524 if (!par.getLabelWidthString().empty()) {
525 l_margin += font_metrics::width(par.getLabelWidthString(),
527 l_margin += font_metrics::width(layout->labelsep, labelfont);
533 l_margin += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
534 / (par.getDepth() + 4);
537 case MARGIN_FIRST_DYNAMIC:
538 if (layout->labeltype == LABEL_MANUAL) {
539 if (pos >= par.beginOfBody()) {
540 l_margin += font_metrics::signedWidth(layout->leftmargin,
543 l_margin += font_metrics::signedWidth(layout->labelindent,
547 // Special case to fix problems with
549 || (layout->labeltype == LABEL_STATIC
550 && layout->latextype == LATEX_ENVIRONMENT
551 && !isFirstInSequence(pit, pars_))) {
552 l_margin += font_metrics::signedWidth(layout->leftmargin,
554 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
555 && layout->labeltype != LABEL_BIBLIO
556 && layout->labeltype !=
557 LABEL_CENTERED_TOP_ENVIRONMENT) {
558 l_margin += font_metrics::signedWidth(layout->labelindent,
560 l_margin += font_metrics::width(layout->labelsep, labelfont);
561 l_margin += font_metrics::width(par.getLabelstring(),
566 case MARGIN_RIGHT_ADDRESS_BOX: {
568 // ok, a terrible hack. The left margin depends on the widest
569 // row in this paragraph.
570 RowList::iterator rit = par.rows().begin();
571 RowList::iterator end = par.rows().end();
573 #warning This is wrong.
575 int minfill = maxwidth_;
576 for ( ; rit != end; ++rit)
577 if (rit->fill() < minfill)
578 minfill = rit->fill();
579 l_margin += font_metrics::signedWidth(layout->leftmargin,
580 tclass.defaultfont());
583 // also wrong, but much shorter.
584 l_margin += maxwidth_ / 2;
589 if (!par.params().leftIndent().zero())
590 l_margin += par.params().leftIndent().inPixels(maxwidth_);
594 if (par.params().align() == LYX_ALIGN_LAYOUT)
595 align = layout->align;
597 align = par.params().align();
599 // set the correct parindent
601 && (layout->labeltype == LABEL_NO_LABEL
602 || layout->labeltype == LABEL_TOP_ENVIRONMENT
603 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
604 || (layout->labeltype == LABEL_STATIC
605 && layout->latextype == LATEX_ENVIRONMENT
606 && !isFirstInSequence(pit, pars_)))
607 && align == LYX_ALIGN_BLOCK
608 && !par.params().noindent()
609 // in some insets, paragraphs are never indented
610 && !(par.inInset() && par.inInset()->neverIndent())
611 // display style insets are always centered, omit indentation
614 && par.getInset(pos)->display())
615 && (par.layout() != tclass.defaultLayout()
616 || bv()->buffer()->params().paragraph_separation ==
617 BufferParams::PARSEP_INDENT))
619 l_margin += font_metrics::signedWidth(parindent, tclass.defaultfont());
626 int LyXText::rightMargin(Paragraph const & par) const
628 // We do not want rightmargins on inner texts.
629 if (bv()->text() != this)
632 LyXTextClass const & tclass = bv()->buffer()->params().getLyXTextClass();
635 + font_metrics::signedWidth(tclass.rightmargin(),
636 tclass.defaultfont())
637 + font_metrics::signedWidth(par.layout()->rightmargin,
638 tclass.defaultfont())
639 * 4 / (par.getDepth() + 4);
645 int LyXText::labelEnd(pit_type const pit) const
647 // labelEnd is only needed if the layout fills a flushleft label.
648 if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
650 // return the beginning of the body
651 return leftMargin(pit);
657 // this needs special handling - only newlines count as a break point
658 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
660 pos_type const end = par.size();
663 if (par.isNewline(i))
672 void LyXText::rowBreakPoint(pit_type const pit, Row & row) const
674 Paragraph const & par = pars_[pit];
675 pos_type const end = par.size();
676 pos_type const pos = row.pos();
682 // maximum pixel width of a row
683 int width = maxwidth_ - rightMargin(par); // - leftMargin(pit, row);
689 LyXLayout_ptr const & layout = par.layout();
691 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
692 row.endpos(addressBreakPoint(pos, par));
696 pos_type const body_pos = par.beginOfBody();
699 // Now we iterate through until we reach the right margin
700 // or the end of the par, then choose the possible break
703 int const left = leftMargin(pit, pos);
706 // pixel width since last breakpoint
709 FontIterator fi = FontIterator(*this, par, pos);
710 pos_type point = end;
712 for ( ; i < end; ++i, ++fi) {
713 char const c = par.getChar(i);
714 int thiswidth = singleWidth(par, i, c, *fi);
716 // add the auto-hfill from label end to the body
717 if (body_pos && i == body_pos) {
718 int add = font_metrics::width(layout->labelsep, getLabelFont(par));
719 if (par.isLineSeparator(i - 1))
720 add -= singleWidth(par, i - 1);
722 add = std::max(add, labelEnd(pit) - x);
727 chunkwidth += thiswidth;
729 // break before a character that will fall off
730 // the right of the row
732 // if no break before, break here
733 if (point == end || chunkwidth >= width - left) {
740 // exit on last registered breakpoint:
744 if (par.isNewline(i)) {
750 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
755 if (par.isInset(i) && par.getInset(i)->display()) {
761 if (!par.isInset(i) || par.getInset(i)->isChar()) {
762 // some insets are line separators too
763 if (par.isLineSeparator(i)) {
764 // register breakpoint:
771 // maybe found one, but the par is short enough.
772 if (i == end && x < width)
775 // manual labels cannot be broken in LaTeX. But we
776 // want to make our on-screen rendering of footnotes
778 if (body_pos && point < body_pos)
785 void LyXText::setRowWidth(pit_type const pit, Row & row) const
787 // get the pure distance
788 pos_type const end = row.endpos();
790 Paragraph const & par = pars_[pit];
791 string const & labelsep = par.layout()->labelsep;
792 int w = leftMargin(pit, row.pos());
794 pos_type const body_pos = par.beginOfBody();
795 pos_type i = row.pos();
798 FontIterator fi = FontIterator(*this, par, i);
799 for ( ; i < end; ++i, ++fi) {
800 if (body_pos > 0 && i == body_pos) {
801 w += font_metrics::width(labelsep, getLabelFont(par));
802 if (par.isLineSeparator(i - 1))
803 w -= singleWidth(par, i - 1);
804 w = max(w, labelEnd(pit));
806 char const c = par.getChar(i);
807 w += singleWidth(par, i, c, *fi);
811 if (body_pos > 0 && body_pos >= end) {
812 w += font_metrics::width(labelsep, getLabelFont(par));
813 if (end > 0 && par.isLineSeparator(end - 1))
814 w -= singleWidth(par, end - 1);
815 w = max(w, labelEnd(pit));
818 row.width(w + rightMargin(par));
822 // returns the minimum space a manual label needs on the screen in pixel
823 int LyXText::labelFill(Paragraph const & par, Row const & row) const
825 pos_type last = par.beginOfBody();
827 BOOST_ASSERT(last > 0);
829 // -1 because a label ends with a space that is in the label
832 // a separator at this end does not count
833 if (par.isLineSeparator(last))
837 for (pos_type i = row.pos(); i <= last; ++i)
838 w += singleWidth(par, i);
840 string const & label = par.params().labelWidthString();
844 return max(0, font_metrics::width(label, getLabelFont(par)) - w);
848 LColor_color LyXText::backgroundColor() const
850 return LColor_color(LColor::color(background_color_));
854 void LyXText::setHeightOfRow(pit_type const pit, Row & row)
856 Paragraph const & par = pars_[pit];
857 // get the maximum ascent and the maximum descent
858 double layoutasc = 0;
859 double layoutdesc = 0;
860 double const dh = defaultRowHeight();
862 // ok, let us initialize the maxasc and maxdesc value.
863 // Only the fontsize count. The other properties
864 // are taken from the layoutfont. Nicer on the screen :)
865 LyXLayout_ptr const & layout = par.layout();
867 // as max get the first character of this row then it can
868 // increase but not decrease the height. Just some point to
869 // start with so we don't have to do the assignment below too
871 LyXFont font = getFont(par, row.pos());
872 LyXFont::FONT_SIZE const tmpsize = font.size();
873 font = getLayoutFont(pit);
874 LyXFont::FONT_SIZE const size = font.size();
875 font.setSize(tmpsize);
877 LyXFont labelfont = getLabelFont(par);
879 // these are minimum values
880 double const spacing_val = layout->spacing.getValue() * spacing(par);
881 //lyxerr << "spacing_val = " << spacing_val << endl;
882 int maxasc = int(font_metrics::maxAscent(font) * spacing_val);
883 int maxdesc = int(font_metrics::maxDescent(font) * spacing_val);
885 // insets may be taller
886 InsetList::const_iterator ii = par.insetlist.begin();
887 InsetList::const_iterator iend = par.insetlist.end();
888 for ( ; ii != iend; ++ii) {
889 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
890 maxasc = max(maxasc, ii->inset->ascent());
891 maxdesc = max(maxdesc, ii->inset->descent());
895 // Check if any custom fonts are larger (Asger)
896 // This is not completely correct, but we can live with the small,
897 // cosmetic error for now.
899 pos_type const pos_end = row.endpos();
901 LyXFont::FONT_SIZE maxsize =
902 par.highestFontInRange(row.pos(), pos_end, size);
903 if (maxsize > font.size()) {
904 font.setSize(maxsize);
905 maxasc = max(maxasc, font_metrics::maxAscent(font));
906 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
909 // This is nicer with box insets:
916 if (row.pos() == 0) {
917 BufferParams const & bufparams = bv()->buffer()->params();
918 // some parksips VERY EASY IMPLEMENTATION
919 if (bv()->buffer()->params().paragraph_separation
920 == BufferParams::PARSEP_SKIP
922 && ((layout->isParagraph() && par.getDepth() == 0)
923 || (pars_[pit - 1].layout()->isParagraph()
924 && pars_[pit - 1].getDepth() == 0)))
926 maxasc += bufparams.getDefSkip().inPixels(*bv());
929 if (par.params().startOfAppendix())
930 maxasc += int(3 * dh);
932 // This is special code for the chapter, since the label of this
933 // layout is printed in an extra row
934 if (layout->counter == "chapter"
935 && !par.params().labelString().empty()) {
936 labeladdon = int(font_metrics::maxHeight(labelfont)
937 * layout->spacing.getValue()
941 // special code for the top label
942 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
943 || layout->labeltype == LABEL_BIBLIO
944 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
945 && isFirstInSequence(pit, paragraphs())
946 && !par.getLabelstring().empty())
949 font_metrics::maxHeight(labelfont)
950 * layout->spacing.getValue()
952 + (layout->topsep + layout->labelbottomsep) * dh);
955 // Add the layout spaces, for example before and after
956 // a section, or between the items of a itemize or enumerate
959 pit_type prev = depthHook(pit, pars_, par.getDepth());
961 && pars_[prev].layout() == layout
962 && pars_[prev].getDepth() == par.getDepth()
963 && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
965 layoutasc = layout->itemsep * dh;
966 } else if (pit != 0 || row.pos() != 0) {
967 if (layout->topsep > 0)
968 layoutasc = layout->topsep * dh;
971 prev = outerHook(pit, pars_);
972 if (prev != pit_type(pars_.size())) {
973 maxasc += int(pars_[prev].layout()->parsep * dh);
974 } else if (pit != 0) {
975 if (pars_[pit - 1].getDepth() != 0 ||
976 pars_[pit - 1].layout() == layout) {
977 maxasc += int(layout->parsep * dh);
982 // is it a bottom line?
983 if (row.endpos() >= par.size()) {
984 // add the layout spaces, for example before and after
985 // a section, or between the items of a itemize or enumerate
987 pit_type nextpit = pit + 1;
988 if (nextpit != pit_type(pars_.size())) {
993 if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
994 usual = pars_[cpit].layout()->bottomsep * dh;
995 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
996 if (pars_[cpit].layout() != pars_[nextpit].layout()
997 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
999 unusual = pars_[cpit].layout()->bottomsep * dh;
1001 layoutdesc = max(unusual, usual);
1002 } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
1003 if (pars_[cpit].layout() != pars_[nextpit].layout()
1004 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1005 layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
1010 // incalculate the layout spaces
1011 maxasc += int(layoutasc * 2 / (2 + pars_[pit].getDepth()));
1012 maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
1014 // Top and bottom margin of the document (only at top-level)
1015 if (bv_owner->text() == this) {
1016 if (pit == 0 && row.pos() == 0)
1018 if (pit + 1 == pit_type(pars_.size()) &&
1019 row.endpos() == par.size())
1023 row.ascent(maxasc + labeladdon);
1024 row.descent(maxdesc);
1032 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1034 BOOST_ASSERT(this == cur.text());
1036 Paragraph & cpar = cur.paragraph();
1037 pit_type cpit = cur.pit();
1039 LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1040 LyXLayout_ptr const & layout = cpar.layout();
1042 // this is only allowed, if the current paragraph is not empty
1043 // or caption and if it has not the keepempty flag active
1044 if (cur.lastpos() == 0 && !cpar.allowEmpty()
1045 && layout->labeltype != LABEL_SENSITIVE)
1048 // a layout change may affect also the following paragraph
1049 recUndo(cur.pit(), undoSpan(cur.pit()) - 1);
1051 // Always break behind a space
1052 // It is better to erase the space (Dekel)
1053 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1054 cpar.erase(cur.pos());
1056 // How should the layout for the new paragraph be?
1057 int preserve_layout = 0;
1059 preserve_layout = 2;
1061 preserve_layout = layout->isEnvironment();
1063 // We need to remember this before we break the paragraph, because
1064 // that invalidates the layout variable
1065 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1067 // we need to set this before we insert the paragraph.
1068 bool const isempty = cpar.allowEmpty() && cpar.empty();
1070 ::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1071 cur.pos(), preserve_layout);
1073 // After this, neither paragraph contains any rows!
1076 pit_type next_par = cpit + 1;
1078 // well this is the caption hack since one caption is really enough
1081 // set to standard-layout
1082 pars_[cpit].applyLayout(tclass.defaultLayout());
1084 // set to standard-layout
1085 pars_[next_par].applyLayout(tclass.defaultLayout());
1088 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1089 pars_[next_par].erase(0);
1091 ParIterator current_it(cur);
1092 ParIterator next_it(cur); next_it.pit() = next_par;
1094 if (needsUpdateCounters(cur.buffer(), current_it)
1095 || needsUpdateCounters(cur.buffer(), next_it))
1096 updateCounters(cur.buffer());
1098 // Mark "carriage return" as inserted if change tracking:
1099 if (cur.buffer().params().tracking_changes) {
1100 cur.paragraph().setChange(cur.paragraph().size(),
1104 // This check is necessary. Otherwise the new empty paragraph will
1105 // be deleted automatically. And it is more friendly for the user!
1106 if (cur.pos() != 0 || isempty)
1107 setCursor(cur, cur.pit() + 1, 0);
1109 setCursor(cur, cur.pit(), 0);
1113 // insert a character, moves all the following breaks in the
1114 // same Paragraph one to the right and make a rebreak
1115 void LyXText::insertChar(LCursor & cur, char c)
1117 BOOST_ASSERT(this == cur.text());
1118 BOOST_ASSERT(c != Paragraph::META_INSET);
1120 recordUndo(cur, Undo::INSERT);
1122 Paragraph & par = cur.paragraph();
1123 // try to remove this
1124 pit_type const pit = cur.pit();
1126 bool const freeSpacing = par.layout()->free_spacing ||
1127 par.isFreeSpacing();
1129 if (lyxrc.auto_number) {
1130 static string const number_operators = "+-/*";
1131 static string const number_unary_operators = "+-";
1132 static string const number_seperators = ".,:";
1134 if (current_font.number() == LyXFont::ON) {
1135 if (!isDigit(c) && !contains(number_operators, c) &&
1136 !(contains(number_seperators, c) &&
1138 cur.pos() != cur.lastpos() &&
1139 getFont(par, cur.pos()).number() == LyXFont::ON &&
1140 getFont(par, cur.pos() - 1).number() == LyXFont::ON)
1142 number(cur); // Set current_font.number to OFF
1143 } else if (isDigit(c) &&
1144 real_current_font.isVisibleRightToLeft()) {
1145 number(cur); // Set current_font.number to ON
1147 if (cur.pos() != 0) {
1148 char const c = par.getChar(cur.pos() - 1);
1149 if (contains(number_unary_operators, c) &&
1151 || par.isSeparator(cur.pos() - 2)
1152 || par.isNewline(cur.pos() - 2))
1154 setCharFont(pit, cur.pos() - 1, current_font);
1155 } else if (contains(number_seperators, c)
1157 && getFont(par, cur.pos() - 2).number() == LyXFont::ON) {
1158 setCharFont(pit, cur.pos() - 1, current_font);
1164 // First check, if there will be two blanks together or a blank at
1165 // the beginning of a paragraph.
1166 // I decided to handle blanks like normal characters, the main
1167 // difference are the special checks when calculating the row.fill
1168 // (blank does not count at the end of a row) and the check here
1170 // When the free-spacing option is set for the current layout,
1171 // disable the double-space checking
1172 if (!freeSpacing && isLineSeparatorChar(c)) {
1173 if (cur.pos() == 0) {
1174 static bool sent_space_message = false;
1175 if (!sent_space_message) {
1176 cur.message(_("You cannot insert a space at the "
1177 "beginning of a paragraph. Please read the Tutorial."));
1178 sent_space_message = true;
1182 BOOST_ASSERT(cur.pos() > 0);
1183 if ((par.isLineSeparator(cur.pos() - 1)
1184 || par.isNewline(cur.pos() - 1))
1185 && par.lookupChange(cur.pos() - 1) != Change::DELETED) {
1186 static bool sent_space_message = false;
1187 if (!sent_space_message) {
1188 cur.message(_("You cannot type two spaces this way. "
1189 "Please read the Tutorial."));
1190 sent_space_message = true;
1196 par.insertChar(cur.pos(), c, current_font);
1197 setCursor(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1202 void LyXText::charInserted()
1204 // Here we call finishUndo for every 20 characters inserted.
1205 // This is from my experience how emacs does it. (Lgb)
1206 static unsigned int counter;
1217 LyXText::computeRowMetrics(pit_type const pit, Row const & row) const
1220 Paragraph const & par = pars_[pit];
1222 double w = dim_.wid - row.width();
1224 bool const is_rtl = isRTL(par);
1226 result.x = rightMargin(par);
1228 result.x = leftMargin(pit, row.pos());
1230 // is there a manual margin with a manual label
1231 LyXLayout_ptr const & layout = par.layout();
1233 if (layout->margintype == MARGIN_MANUAL
1234 && layout->labeltype == LABEL_MANUAL) {
1235 /// We might have real hfills in the label part
1236 int nlh = numberOfLabelHfills(par, row);
1238 // A manual label par (e.g. List) has an auto-hfill
1239 // between the label text and the body of the
1241 // But we don't want to do this auto hfill if the par
1246 if (nlh && !par.getLabelWidthString().empty())
1247 result.label_hfill = labelFill(par, row) / double(nlh);
1250 // are there any hfills in the row?
1251 int const nh = numberOfHfills(par, row);
1255 result.hfill = w / nh;
1256 // we don't have to look at the alignment if it is ALIGN_LEFT and
1257 // if the row is already larger then the permitted width as then
1258 // we force the LEFT_ALIGN'edness!
1259 } else if (int(row.width()) < maxwidth_) {
1260 // is it block, flushleft or flushright?
1261 // set x how you need it
1263 if (par.params().align() == LYX_ALIGN_LAYOUT)
1264 align = layout->align;
1266 align = par.params().align();
1268 // Display-style insets should always be on a centred row
1269 // The test on par.size() is to catch zero-size pars, which
1270 // would trigger the assert in Paragraph::getInset().
1271 //inset = par.size() ? par.getInset(row.pos()) : 0;
1273 && par.isInset(row.pos())
1274 && par.getInset(row.pos())->display())
1276 align = LYX_ALIGN_CENTER;
1280 case LYX_ALIGN_BLOCK: {
1281 int const ns = numberOfSeparators(par, row);
1282 bool disp_inset = false;
1283 if (row.endpos() < par.size()) {
1284 InsetBase const * in = par.getInset(row.endpos());
1286 disp_inset = in->display();
1288 // If we have separators, this is not the last row of a
1289 // par, does not end in newline, and is not row above a
1290 // display inset... then stretch it
1292 && row.endpos() < par.size()
1293 && !par.isNewline(row.endpos() - 1)
1296 result.separator = w / ns;
1297 } else if (is_rtl) {
1302 case LYX_ALIGN_RIGHT:
1305 case LYX_ALIGN_CENTER:
1311 bidi.computeTables(par, *bv()->buffer(), row);
1313 pos_type body_pos = par.beginOfBody();
1314 pos_type end = row.endpos();
1317 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1319 result.x += font_metrics::width(layout->labelsep, getLabelFont(par));
1320 if (body_pos <= end)
1321 result.x += result.label_hfill;
1329 // the cursor set functions have a special mechanism. When they
1330 // realize, that you left an empty paragraph, they will delete it.
1332 bool LyXText::cursorRightOneWord(LCursor & cur)
1334 BOOST_ASSERT(this == cur.text());
1338 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1342 // Advance through word.
1343 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1345 // Skip through trailing nonword stuff.
1346 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1349 return setCursor(cur, old.pit(), old.pos());
1353 bool LyXText::cursorLeftOneWord(LCursor & cur)
1355 BOOST_ASSERT(this == cur.text());
1359 if (old.pos() == 0 && old.pit() != 0) {
1361 old.pos() = old.lastpos();
1363 // Skip through initial nonword stuff.
1364 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
1366 // Advance through word.
1367 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
1370 return setCursor(cur, old.pit(), old.pos());
1374 void LyXText::selectWord(LCursor & cur, word_location loc)
1376 BOOST_ASSERT(this == cur.text());
1377 CursorSlice from = cur.top();
1378 CursorSlice to = cur.top();
1379 getWord(from, to, loc);
1380 if (cur.top() != from)
1381 setCursor(cur, from.pit(), from.pos());
1385 setCursor(cur, to.pit(), to.pos());
1390 // Select the word currently under the cursor when no
1391 // selection is currently set
1392 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1394 BOOST_ASSERT(this == cur.text());
1395 if (cur.selection())
1397 selectWord(cur, loc);
1398 return cur.selection();
1402 void LyXText::acceptChange(LCursor & cur)
1404 BOOST_ASSERT(this == cur.text());
1405 if (!cur.selection() && cur.lastpos() != 0)
1408 recordUndoSelection(cur, Undo::INSERT);
1410 DocIterator it = cur.selectionBegin();
1411 DocIterator et = cur.selectionEnd();
1412 pit_type pit = it.pit();
1413 Change::Type const type = pars_[pit].lookupChange(it.pos());
1414 for (; pit <= et.pit(); ++pit) {
1415 pos_type left = ( pit == it.pit() ? it.pos() : 0 );
1417 ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1418 pars_[pit].acceptChange(left, right);
1420 if (type == Change::DELETED) {
1421 ParagraphList & plist = paragraphs();
1422 if (it.pit() + 1 < et.pit())
1423 pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1424 boost::next(plist.begin(), et.pit()));
1426 // Paragraph merge if appropriate:
1427 if (pars_[it.pit()].lookupChange(pars_[it.pit()].size())
1428 == Change::DELETED) {
1429 setCursorIntern(cur, it.pit() + 1, 0);
1434 cur.clearSelection();
1435 setCursorIntern(cur, it.pit(), 0);
1439 void LyXText::rejectChange(LCursor & cur)
1441 BOOST_ASSERT(this == cur.text());
1442 if (!cur.selection() && cur.lastpos() != 0)
1445 recordUndoSelection(cur, Undo::INSERT);
1447 DocIterator it = cur.selectionBegin();
1448 DocIterator et = cur.selectionEnd();
1449 pit_type pit = it.pit();
1450 Change::Type const type = pars_[pit].lookupChange(it.pos());
1451 for (; pit <= et.pit(); ++pit) {
1452 pos_type left = ( pit == it.pit() ? it.pos() : 0 );
1454 ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1455 pars_[pit].rejectChange(left, right);
1457 if (type == Change::INSERTED) {
1458 ParagraphList & plist = paragraphs();
1459 if (it.pit() + 1 < et.pit())
1460 pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1461 boost::next(plist.begin(), et.pit()));
1462 // Paragraph merge if appropriate:
1463 if (pars_[it.pit()].lookupChange(pars_[it.pit()].size())
1464 == Change::INSERTED) {
1465 setCursorIntern(cur, it.pit() + 1, 0);
1470 cur.clearSelection();
1471 setCursorIntern(cur, it.pit(), 0);
1475 // Delete from cursor up to the end of the current or next word.
1476 void LyXText::deleteWordForward(LCursor & cur)
1478 BOOST_ASSERT(this == cur.text());
1479 if (cur.lastpos() == 0)
1483 cur.selection() = true;
1484 cursorRightOneWord(cur);
1486 cutSelection(cur, true, false);
1491 // Delete from cursor to start of current or prior word.
1492 void LyXText::deleteWordBackward(LCursor & cur)
1494 BOOST_ASSERT(this == cur.text());
1495 if (cur.lastpos() == 0)
1499 cur.selection() = true;
1500 cursorLeftOneWord(cur);
1502 cutSelection(cur, true, false);
1507 // Kill to end of line.
1508 void LyXText::deleteLineForward(LCursor & cur)
1510 BOOST_ASSERT(this == cur.text());
1511 if (cur.lastpos() == 0) {
1512 // Paragraph is empty, so we just go to the right
1516 cur.selection() = true; // to avoid deletion
1519 // What is this test for ??? (JMarc)
1520 if (!cur.selection())
1521 deleteWordForward(cur);
1523 cutSelection(cur, true, false);
1528 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1530 BOOST_ASSERT(this == cur.text());
1534 if (cur.selection()) {
1535 from = cur.selBegin();
1539 getWord(from, to, lyx::PARTIAL_WORD);
1540 cursorRightOneWord(cur);
1543 recordUndoSelection(cur);
1545 pos_type pos = from.pos();
1546 int par = from.pit();
1548 while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1550 if (pos == pars_[pit].size()) {
1555 unsigned char c = pars_[pit].getChar(pos);
1556 if (c != Paragraph::META_INSET) {
1558 case text_lowercase:
1561 case text_capitalization:
1563 action = text_lowercase;
1565 case text_uppercase:
1570 #ifdef WITH_WARNINGS
1573 pars_[pit].setChar(pos, c);
1579 bool LyXText::erase(LCursor & cur)
1581 BOOST_ASSERT(this == cur.text());
1582 bool needsUpdate = false;
1584 if (cur.pos() != cur.lastpos()) {
1585 recordUndo(cur, Undo::DELETE, cur.pit());
1586 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1587 needsUpdate = backspace(cur);
1588 if (cur.paragraph().lookupChange(cur.pos()) == Change::DELETED)
1590 } else if (cur.pit() != cur.lastpit()) {
1593 setCursorIntern(cur, cur.pit() + 1, 0, false, false);
1594 if (pars_[cur.pit()].layout() == pars_[scur.pit()].layout()) {
1595 recordUndo(scur, Undo::DELETE, scur.pit());
1596 needsUpdate = backspace(cur);
1597 if (cur.buffer().params().tracking_changes) {
1598 // move forward after the paragraph break is DELETED
1599 Paragraph & par = cur.paragraph();
1600 if (par.lookupChange(par.size()) == Change::DELETED)
1601 setCursorIntern(cur, cur.pit() + 1, 0);
1604 setCursorIntern(scur, scur.pit(), scur.pos(), false, scur.boundary());
1611 bool LyXText::backspacePos0(LCursor & cur)
1613 BOOST_ASSERT(this == cur.text());
1614 bool needsUpdate = false;
1616 Paragraph & par = cur.paragraph();
1617 // is it an empty paragraph?
1618 pos_type lastpos = cur.lastpos();
1619 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1620 // This is an empty paragraph and we delete it just
1621 // by moving the cursor one step
1622 // left and let the DeleteEmptyParagraphMechanism
1623 // handle the actual deletion of the paragraph.
1625 if (cur.pit() != 0) {
1626 // For KeepEmpty layouts we need to get
1627 // rid of the keepEmpty setting first.
1628 // And the only way to do this is to
1629 // reset the layout to something
1630 // else: f.ex. the default layout.
1631 if (par.allowEmpty()) {
1632 Buffer & buf = cur.buffer();
1633 BufferParams const & bparams = buf.params();
1634 par.layout(bparams.getLyXTextClass().defaultLayout());
1643 recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1645 pit_type tmppit = cur.pit();
1646 // We used to do cursorLeftIntern() here, but it is
1647 // not a good idea since it triggers the auto-delete
1648 // mechanism. So we do a cursorLeftIntern()-lite,
1649 // without the dreaded mechanism. (JMarc)
1650 if (cur.pit() != 0) {
1651 // steps into the above paragraph.
1652 setCursorIntern(cur, cur.pit() - 1,
1653 pars_[cur.pit() - 1].size(),
1657 // Pasting is not allowed, if the paragraphs have different
1658 // layout. I think it is a real bug of all other
1659 // word processors to allow it. It confuses the user.
1660 // Correction: Pasting is always allowed with standard-layout
1661 // Correction (Jug 20050717): Remove check about alignment!
1662 Buffer & buf = cur.buffer();
1663 BufferParams const & bufparams = buf.params();
1664 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1665 pit_type const cpit = cur.pit();
1668 && (pars_[cpit].layout() == pars_[tmppit].layout()
1669 || pars_[tmppit].layout() == tclass.defaultLayout()))
1671 mergeParagraph(bufparams, pars_, cpit);
1674 if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1677 // the counters may have changed
1678 ParIterator par_it(cur);
1679 if (needsUpdateCounters(cur.buffer(), par_it))
1680 updateCounters(cur.buffer());
1682 setCursor(cur, cur.pit(), cur.pos(), false);
1688 bool LyXText::backspace(LCursor & cur)
1690 BOOST_ASSERT(this == cur.text());
1691 bool needsUpdate = false;
1692 if (cur.pos() == 0) {
1693 // The cursor is at the beginning of a paragraph, so
1694 // the the backspace will collapse two paragraphs into
1697 if (cur.pit() != 0 && cur.buffer().params().tracking_changes) {
1698 // Previous paragraph, mark "carriage return" as
1700 Paragraph & par = pars_[cur.pit() - 1];
1701 // Take care of a just inserted para break:
1702 if (par.lookupChange(par.size()) != Change::INSERTED) {
1703 par.setChange(par.size(), Change::DELETED);
1704 setCursorIntern(cur, cur.pit() - 1, par.size());
1709 needsUpdate = backspacePos0(cur);
1712 // this is the code for a normal backspace, not pasting
1714 recordUndo(cur, Undo::DELETE);
1715 // We used to do cursorLeftIntern() here, but it is
1716 // not a good idea since it triggers the auto-delete
1717 // mechanism. So we do a cursorLeftIntern()-lite,
1718 // without the dreaded mechanism. (JMarc)
1719 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1720 false, cur.boundary());
1721 cur.paragraph().erase(cur.pos());
1724 if (cur.pos() == cur.lastpos())
1725 setCurrentFont(cur);
1727 setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1733 Row const & LyXText::firstRow() const
1735 return *paragraphs().front().rows().begin();
1739 bool LyXText::redoParagraph(pit_type const pit)
1741 // remove rows of paragraph, keep track of height changes
1742 Paragraph & par = pars_[pit];
1744 // Add bibitem insets if necessary
1745 if (par.layout()->labeltype == LABEL_BIBLIO) {
1746 bool hasbibitem(false);
1747 if (!par.insetlist.empty()
1748 // Insist on it being in pos 0
1749 && par.getChar(0) == Paragraph::META_INSET) {
1750 InsetBase * inset = par.insetlist.begin()->inset;
1751 if (inset->lyxCode() == InsetBase::BIBITEM_CODE)
1755 InsetBibitem * inset(new
1756 InsetBibitem(InsetCommandParams("bibitem")));
1757 par.insertInset(0, static_cast<InsetBase *>(inset));
1758 bv()->cursor().posRight();
1763 // FIXME: We should always use getFont(), see documentation of
1764 // noFontChange() in insetbase.h.
1765 LyXFont const bufferfont = bv()->buffer()->params().getFont();
1766 InsetList::iterator ii = par.insetlist.begin();
1767 InsetList::iterator iend = par.insetlist.end();
1768 for (; ii != iend; ++ii) {
1770 int const w = maxwidth_ - leftMargin(pit, ii->pos) - rightMargin(par);
1771 LyXFont const & font = ii->inset->noFontChange() ?
1773 getFont(par, ii->pos);
1774 MetricsInfo mi(bv(), font, w);
1775 ii->inset->metrics(mi, dim);
1778 // rebreak the paragraph
1782 par.setBeginOfBody();
1786 rowBreakPoint(pit, row);
1787 setRowWidth(pit, row);
1788 setHeightOfRow(pit, row);
1789 par.rows().push_back(row);
1790 dim.wid = std::max(dim.wid, row.width());
1791 dim.des += row.height();
1793 } while (z < par.size());
1795 // Make sure that if a par ends in newline, there is one more row
1797 // FIXME this is a dirty trick. Now the _same_ position in the
1798 // paragraph occurs in _two_ different rows, and has two different
1799 // display positions, leading to weird behaviour when moving up/down.
1800 if (z > 0 && par.isNewline(z - 1)) {
1803 setRowWidth(pit, row);
1804 setHeightOfRow(pit, row);
1805 par.rows().push_back(row);
1806 dim.des += row.height();
1809 dim.asc += par.rows()[0].ascent();
1810 dim.des -= par.rows()[0].ascent();
1812 bool const same = dim == par.dim();
1815 //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1821 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1823 //BOOST_ASSERT(mi.base.textwidth);
1824 if (mi.base.textwidth)
1825 maxwidth_ = mi.base.textwidth;
1826 //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1827 // << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1828 // save the caller's font locally:
1829 font_ = mi.base.font;
1833 for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1835 Paragraph & par = paragraphs()[pit];
1837 if (w < par.width())
1842 dim.asc = pars_[0].ascent();
1843 dim.des = h - dim.asc;
1849 // only used for inset right now. should also be used for main text
1850 void LyXText::draw(PainterInfo & pi, int x, int y) const
1852 paintTextInset(*this, pi, x, y);
1857 // only used for inset right now. should also be used for main text
1858 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1860 LCursor & cur = pi.base.bv->cursor();
1861 if (!cur.selection())
1863 if (!ptr_cmp(cur.text(), this))
1866 lyxerr << "draw selection at " << x << endl;
1868 DocIterator beg = cur.selectionBegin();
1869 DocIterator end = cur.selectionEnd();
1871 // the selection doesn't touch the visible screen
1872 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1873 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1876 Paragraph const & par1 = pars_[beg.pit()];
1877 Paragraph const & par2 = pars_[end.pit()];
1879 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1880 Row const & row2 = par2.getRow(end.pos(), end.boundary());
1883 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1888 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1889 int const startx = cursorX(beg.top(), begin.boundary());
1890 x1 = isRTL(par1) ? startx : 0;
1891 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
1895 if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
1896 y2 = pi.base.bv->workHeight();
1900 y2 = bv_funcs::getPos(end).y_ + row2.descent();
1901 int const endx = cursorX(end.top(), end.boundary());
1902 X1 = isRTL(par2) ? 0 : endx;
1903 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
1906 lyxerr << " y1: " << y1 << " y2: " << y2
1907 << " xo: " << xo_ << " wid: " << dim_.wid
1910 // paint big rectangle in one go
1911 pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
1913 // reset background at begin of first selected line
1914 pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
1915 LColor::background);
1917 // reset background at end of last selected line
1918 pi.pain.fillRectangle(x + X1, y2 - row2.height(),
1919 X2 - X1, row2.height(), LColor::background);
1924 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
1926 LCursor & cur = pi.base.bv->cursor();
1927 if (!cur.selection())
1929 if (!ptr_cmp(cur.text(), this))
1932 lyxerr[Debug::DEBUG]
1933 << BOOST_CURRENT_FUNCTION
1934 << "draw selection at " << x
1937 DocIterator beg = cur.selectionBegin();
1938 DocIterator end = cur.selectionEnd();
1940 // the selection doesn't touch the visible screen
1941 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1942 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1945 Paragraph const & par1 = pars_[beg.pit()];
1946 Paragraph const & par2 = pars_[end.pit()];
1948 bool const above = (bv_funcs::status(pi.base.bv, beg)
1949 == bv_funcs::CUR_ABOVE);
1950 bool const below = (bv_funcs::status(pi.base.bv, end)
1951 == bv_funcs::CUR_BELOW);
1959 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1960 y1 = bv_funcs::getPos(beg, beg.boundary()).y_ - row1.ascent();
1961 y2 = y1 + row1.height();
1962 int const startx = cursorX(beg.top(), beg.boundary());
1963 x1 = !isRTL(par1) ? startx : 0;
1964 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
1969 Y1 = pi.base.bv->workHeight();
1970 Y2 = pi.base.bv->workHeight();
1974 Row const & row2 = par2.getRow(end.pos(), end.boundary());
1975 Y1 = bv_funcs::getPos(end, end.boundary()).y_ - row2.ascent();
1976 Y2 = Y1 + row2.height();
1977 int const endx = cursorX(end.top(), end.boundary());
1978 X1 = !isRTL(par2) ? 0 : endx;
1979 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
1982 if (!above && !below && &par1.getRow(beg.pos(), beg.boundary())
1983 == &par2.getRow(end.pos(), end.boundary()))
1985 // paint only one rectangle
1986 int const b( !isRTL(par1) ? x + x1 : x + X1 );
1987 int const w( !isRTL(par1) ? X2 - x1 : x2 - X1 );
1988 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
1992 lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
1993 << "X1:" << X1 << " x2: " << X2 << " wid: " << dim_.wid
1996 // paint upper rectangle
1997 pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
1999 // paint bottom rectangle
2000 pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
2002 // paint center rectangle
2003 pi.pain.fillRectangle(x, y2, dim_.wid,
2004 Y1 - y2, LColor::selection);
2008 bool LyXText::isLastRow(pit_type pit, Row const & row) const
2010 return row.endpos() >= pars_[pit].size()
2011 && pit + 1 == pit_type(paragraphs().size());
2015 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
2017 return row.pos() == 0 && pit == 0;
2021 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
2022 word_location const loc)
2024 Paragraph const & from_par = pars_[from.pit()];
2026 case lyx::WHOLE_WORD_STRICT:
2027 if (from.pos() == 0 || from.pos() == from_par.size()
2028 || !from_par.isLetter(from.pos())
2029 || !from_par.isLetter(from.pos() - 1)) {
2033 // no break here, we go to the next
2035 case lyx::WHOLE_WORD:
2036 // If we are already at the beginning of a word, do nothing
2037 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
2039 // no break here, we go to the next
2041 case lyx::PREVIOUS_WORD:
2042 // always move the cursor to the beginning of previous word
2043 while (from.pos() && from_par.isLetter(from.pos() - 1))
2046 case lyx::NEXT_WORD:
2047 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
2050 case lyx::PARTIAL_WORD:
2051 // no need to move the 'from' cursor
2055 Paragraph & to_par = pars_[to.pit()];
2056 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
2061 void LyXText::write(Buffer const & buf, std::ostream & os) const
2063 ParagraphList::const_iterator pit = paragraphs().begin();
2064 ParagraphList::const_iterator end = paragraphs().end();
2065 Paragraph::depth_type dth = 0;
2066 for (; pit != end; ++pit)
2067 pit->write(buf, os, buf.params(), dth);
2071 bool LyXText::read(Buffer const & buf, LyXLex & lex)
2073 Paragraph::depth_type depth = 0;
2075 while (lex.isOK()) {
2077 string const token = lex.getString();
2082 if (token == "\\end_inset") {
2086 if (token == "\\end_body") {
2090 if (token == "\\begin_body") {
2094 if (token == "\\end_document") {
2098 if (token == "\\begin_layout") {
2099 lex.pushToken(token);
2102 par.params().depth(depth);
2103 if (buf.params().tracking_changes)
2105 par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
2106 pars_.push_back(par);
2108 // FIXME: goddamn InsetTabular makes us pass a Buffer
2110 ::readParagraph(buf, pars_.back(), lex);
2112 } else if (token == "\\begin_deeper") {
2114 } else if (token == "\\end_deeper") {
2116 lex.printError("\\end_deeper: " "depth is already null");
2121 lyxerr << "Handling unknown body token: `"
2122 << token << '\'' << endl;
2129 int LyXText::ascent() const
2135 int LyXText::descent() const
2141 int LyXText::cursorX(CursorSlice const & sl, bool boundary) const
2143 pit_type const pit = sl.pit();
2144 Paragraph const & par = pars_[pit];
2145 if (par.rows().empty())
2148 pos_type ppos = sl.pos();
2149 // Correct position in front of big insets
2150 bool const boundary_correction = ppos != 0 && boundary;
2151 if (boundary_correction)
2154 Row const & row = par.getRow(sl.pos(), boundary);
2156 pos_type cursor_vpos = 0;
2158 RowMetrics const m = computeRowMetrics(pit, row);
2161 pos_type const row_pos = row.pos();
2162 pos_type const end = row.endpos();
2165 cursor_vpos = row_pos;
2166 else if (ppos >= end)
2167 cursor_vpos = isRTL(par) ? row_pos : end;
2168 else if (ppos > row_pos && ppos >= end)
2169 // Place cursor after char at (logical) position pos - 1
2170 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
2171 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
2173 // Place cursor before char at (logical) position ppos
2174 cursor_vpos = (bidi.level(ppos) % 2 == 0)
2175 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
2177 pos_type body_pos = par.beginOfBody();
2179 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2182 // Use font span to speed things up, see below
2186 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2187 pos_type pos = bidi.vis2log(vpos);
2188 if (body_pos > 0 && pos == body_pos - 1) {
2190 + font_metrics::width(par.layout()->labelsep,
2192 if (par.isLineSeparator(body_pos - 1))
2193 x -= singleWidth(par, body_pos - 1);
2196 // Use font span to speed things up, see above
2197 if (pos < font_span.first || pos > font_span.last) {
2198 font_span = par.fontSpan(pos);
2199 font = getFont(par, pos);
2202 x += singleWidth(par, pos, par.getChar(pos), font);
2204 if (hfillExpansion(par, row, pos))
2205 x += (pos >= body_pos) ? m.hfill : m.label_hfill;
2206 else if (par.isSeparator(pos) && pos >= body_pos)
2210 // see correction above
2211 if (boundary_correction)
2212 if (getFont(par, ppos).isVisibleRightToLeft())
2213 x -= singleWidth(par, ppos);
2215 x += singleWidth(par, ppos);
2217 // Make sure inside an inset we always count from the left
2218 // edge (bidi!) -- MV
2219 if (sl.pos() < par.size()) {
2220 font = getFont(par, sl.pos());
2221 if (!boundary && font.isVisibleRightToLeft()
2222 && par.isInset(sl.pos()))
2223 x -= par.getInset(sl.pos())->width();
2229 int LyXText::cursorY(CursorSlice const & sl, bool boundary) const
2231 //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
2232 Paragraph const & par = getPar(sl.pit());
2234 h -= pars_[0].rows()[0].ascent();
2235 for (pit_type pit = 0; pit < sl.pit(); ++pit)
2236 h += pars_[pit].height();
2238 if (pos && boundary)
2240 size_t const rend = par.pos2row(pos);
2241 for (size_t rit = 0; rit != rend; ++rit)
2242 h += par.rows()[rit].height();
2243 h += par.rows()[rend].ascent();
2248 // Returns the current font and depth as a message.
2249 string LyXText::currentState(LCursor & cur)
2251 BOOST_ASSERT(this == cur.text());
2252 Buffer & buf = cur.buffer();
2253 Paragraph const & par = cur.paragraph();
2254 std::ostringstream os;
2256 bool const show_change = buf.params().tracking_changes
2257 && par.lookupChange(cur.pos()) != Change::UNCHANGED;
2259 if (buf.params().tracking_changes)
2263 Change change = par.lookupChangeFull(cur.pos());
2264 Author const & a = buf.params().authors().get(change.author);
2265 os << _("Change: ") << a.name();
2266 if (!a.email().empty())
2267 os << " (" << a.email() << ")";
2268 if (change.changetime)
2269 os << _(" at ") << ctime(&change.changetime);
2273 // I think we should only show changes from the default
2275 // No, from the document font (MV)
2276 LyXFont font = real_current_font;
2277 font.reduce(buf.params().getFont());
2279 // avoid _(...) re-entrance problem
2280 string const s = font.stateText(&buf.params());
2281 os << bformat(_("Font: %1$s"), s);
2283 // os << bformat(_("Font: %1$s"), font.stateText(&buf.params));
2285 // The paragraph depth
2286 int depth = cur.paragraph().getDepth();
2288 os << bformat(_(", Depth: %1$d"), depth);
2290 // The paragraph spacing, but only if different from
2292 Spacing const & spacing = par.params().spacing();
2293 if (!spacing.isDefault()) {
2294 os << _(", Spacing: ");
2295 switch (spacing.getSpace()) {
2296 case Spacing::Single:
2299 case Spacing::Onehalf:
2302 case Spacing::Double:
2305 case Spacing::Other:
2306 os << _("Other (") << spacing.getValueAsString() << ')';
2308 case Spacing::Default:
2309 // should never happen, do nothing
2314 #ifdef DEVEL_VERSION
2315 os << _(", Inset: ") << &cur.inset();
2316 os << _(", Paragraph: ") << cur.pit();
2317 os << _(", Id: ") << par.id();
2318 os << _(", Position: ") << cur.pos();
2319 os << _(", Boundary: ") << cur.boundary();
2320 // Row & row = cur.textRow();
2321 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2327 string LyXText::getPossibleLabel(LCursor & cur) const
2329 pit_type pit = cur.pit();
2331 LyXLayout_ptr layout = pars_[pit].layout();
2333 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2334 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2335 if (layout2->latextype != LATEX_PARAGRAPH) {
2341 string name = layout->latexname();
2343 // for captions, we want the abbreviation of the float type
2344 if (layout->labeltype == LABEL_SENSITIVE) {
2345 // Search for the first float or wrap inset in the iterator
2346 size_t i = cur.depth();
2349 InsetBase * const in = &cur[i].inset();
2350 if (in->lyxCode() == InsetBase::FLOAT_CODE
2351 || in->lyxCode() == InsetBase::WRAP_CODE) {
2352 name = in->getInsetName();
2358 string text = name.substr(0, 3);
2359 if (name == "theorem")
2360 text = "thm"; // Create a correct prefix for prettyref
2363 if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2366 string par_text = pars_[pit].asString(cur.buffer(), false);
2367 for (int i = 0; i < lyxrc.label_init_length; ++i) {
2368 if (par_text.empty())
2371 par_text = split(par_text, head, ' ');
2372 // Is it legal to use spaces in labels ?
2382 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2386 // Paragraph const & par = pars_[pit];
2387 // Row const & r = par.rows()[row];
2388 // int pos = r.pos();
2389 // for (; currx < x && pos < r.endpos(); ++pos) {
2391 // currx += singleWidth(par, pos);
2393 // if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2399 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2401 BOOST_ASSERT(row < int(pars_[pit].rows().size()));
2403 Row const & r = pars_[pit].rows()[row];
2404 return r.pos() + getColumnNearX(pit, r, x, bound);
2408 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2410 // Paragraph const & par = pars_[pit];
2411 // Row const & r = par.rows()[row];
2417 // x,y are screen coordinates
2418 // sets cursor only within this LyXText
2419 bool LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2421 pit_type pit = getPitNearY(y);
2422 int yy = theCoords.get(this, pit).y_ - pars_[pit].ascent();
2423 lyxerr[Debug::DEBUG]
2424 << BOOST_CURRENT_FUNCTION
2428 << " yy: " << yy << endl;
2430 Paragraph const & par = pars_[pit];
2432 BOOST_ASSERT(par.rows().size());
2433 for (; r < int(par.rows().size()) - 1; ++r) {
2434 Row const & row = par.rows()[r];
2435 if (int(yy + row.height()) > y)
2440 Row const & row = par.rows()[r];
2442 lyxerr[Debug::DEBUG]
2443 << BOOST_CURRENT_FUNCTION
2445 << " from pos: " << row.pos()
2450 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2452 lyxerr[Debug::DEBUG]
2453 << BOOST_CURRENT_FUNCTION
2454 << ": setting cursor pit: " << pit
2458 return setCursor(cur, pit, pos, true, bound);