3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Jürgen Vigna
14 * Full author contact details are available in file CREDITS.
23 #include "buffer_funcs.h"
24 #include "bufferparams.h"
25 #include "BufferView.h"
27 #include "coordcache.h"
28 #include "CutAndPaste.h"
30 #include "dispatchresult.h"
32 #include "errorlist.h"
33 #include "funcrequest.h"
35 #include "FontIterator.h"
39 #include "lyxlength.h"
43 #include "lyxrow_funcs.h"
44 #include "metricsinfo.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "rowpainter.h"
51 #include "WordLangTuple.h"
53 #include "frontends/font_metrics.h"
54 #include "frontends/LyXView.h"
55 #include "frontends/Painter.h"
57 #include "insets/insettext.h"
58 #include "insets/insetbibitem.h"
59 #include "insets/insethfill.h"
60 #include "insets/insetlatexaccent.h"
61 #include "insets/insetline.h"
62 #include "insets/insetnewline.h"
63 #include "insets/insetpagebreak.h"
64 #include "insets/insetoptarg.h"
65 #include "insets/insetspace.h"
66 #include "insets/insetspecialchar.h"
67 #include "insets/insettabular.h"
69 #include "support/lstrings.h"
70 #include "support/textutils.h"
71 #include "support/convert.h"
77 using lyx::word_location;
79 using lyx::support::bformat;
80 using lyx::support::contains;
81 using lyx::support::lowercase;
82 using lyx::support::split;
83 using lyx::support::uppercase;
85 using lyx::cap::cutSelection;
98 int numberOfSeparators(Paragraph const & par, Row const & row)
100 pos_type const first = max(row.pos(), par.beginOfBody());
101 pos_type const last = row.endpos() - 1;
103 for (pos_type p = first; p < last; ++p) {
104 if (par.isSeparator(p))
111 int numberOfLabelHfills(Paragraph const & par, Row const & row)
113 pos_type last = row.endpos() - 1;
114 pos_type first = row.pos();
116 // hfill *DO* count at the beginning of paragraphs!
118 while (first < last && par.isHfill(first))
122 last = min(last, par.beginOfBody());
124 for (pos_type p = first; p < last; ++p) {
132 int numberOfHfills(Paragraph const & par, Row const & row)
134 pos_type const last = row.endpos() - 1;
135 pos_type first = row.pos();
137 // hfill *DO* count at the beginning of paragraphs!
139 while (first < last && par.isHfill(first))
143 first = max(first, par.beginOfBody());
146 for (pos_type p = first; p < last; ++p) {
154 void readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
155 string const & token, LyXFont & font)
157 static Change change;
159 BufferParams const & bp = buf.params();
161 if (token[0] != '\\') {
162 string::const_iterator cit = token.begin();
163 for (; cit != token.end(); ++cit)
164 par.insertChar(par.size(), (*cit), font, change);
165 } else if (token == "\\begin_layout") {
167 string layoutname = lex.getString();
169 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
172 LyXTextClass const & tclass = bp.getLyXTextClass();
174 if (layoutname.empty()) {
175 layoutname = tclass.defaultLayoutName();
178 bool hasLayout = tclass.hasLayout(layoutname);
181 buf.error(ErrorItem(_("Unknown layout"),
182 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
183 layoutname, tclass.name()), par.id(), 0, par.size()));
184 layoutname = tclass.defaultLayoutName();
187 par.layout(bp.getLyXTextClass()[layoutname]);
189 // Test whether the layout is obsolete.
190 LyXLayout_ptr const & layout = par.layout();
191 if (!layout->obsoleted_by().empty())
192 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
194 par.params().read(lex);
196 } else if (token == "\\end_layout") {
197 lyxerr << BOOST_CURRENT_FUNCTION
198 << ": Solitary \\end_layout in line "
199 << lex.getLineNo() << "\n"
200 << "Missing \\begin_layout?.\n";
201 } else if (token == "\\end_inset") {
202 lyxerr << BOOST_CURRENT_FUNCTION
203 << ": Solitary \\end_inset in line "
204 << lex.getLineNo() << "\n"
205 << "Missing \\begin_inset?.\n";
206 } else if (token == "\\begin_inset") {
207 InsetBase * inset = readInset(lex, buf);
209 par.insertInset(par.size(), inset, font, change);
212 string line = lex.getString();
213 buf.error(ErrorItem(_("Unknown Inset"), line,
214 par.id(), 0, par.size()));
216 } else if (token == "\\family") {
218 font.setLyXFamily(lex.getString());
219 } else if (token == "\\series") {
221 font.setLyXSeries(lex.getString());
222 } else if (token == "\\shape") {
224 font.setLyXShape(lex.getString());
225 } else if (token == "\\size") {
227 font.setLyXSize(lex.getString());
228 } else if (token == "\\lang") {
230 string const tok = lex.getString();
231 Language const * lang = languages.getLanguage(tok);
233 font.setLanguage(lang);
235 font.setLanguage(bp.language);
236 lex.printError("Unknown language `$$Token'");
238 } else if (token == "\\numeric") {
240 font.setNumber(font.setLyXMisc(lex.getString()));
241 } else if (token == "\\emph") {
243 font.setEmph(font.setLyXMisc(lex.getString()));
244 } else if (token == "\\bar") {
246 string const tok = lex.getString();
249 font.setUnderbar(LyXFont::ON);
250 else if (tok == "no")
251 font.setUnderbar(LyXFont::OFF);
252 else if (tok == "default")
253 font.setUnderbar(LyXFont::INHERIT);
255 lex.printError("Unknown bar font flag "
257 } else if (token == "\\noun") {
259 font.setNoun(font.setLyXMisc(lex.getString()));
260 } else if (token == "\\color") {
262 font.setLyXColor(lex.getString());
263 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
265 // Insets don't make sense in a free-spacing context! ---Kayvan
266 if (par.isFreeSpacing()) {
267 if (token == "\\InsetSpace")
268 par.insertChar(par.size(), ' ', font, change);
269 else if (lex.isOK()) {
271 string const next_token = lex.getString();
272 if (next_token == "\\-")
273 par.insertChar(par.size(), '-', font, change);
275 lex.printError("Token `$$Token' "
277 "paragraph layout!");
281 auto_ptr<InsetBase> inset;
282 if (token == "\\SpecialChar" )
283 inset.reset(new InsetSpecialChar);
285 inset.reset(new InsetSpace);
286 inset->read(buf, lex);
287 par.insertInset(par.size(), inset.release(),
290 } else if (token == "\\i") {
291 auto_ptr<InsetBase> inset(new InsetLatexAccent);
292 inset->read(buf, lex);
293 par.insertInset(par.size(), inset.release(), font, change);
294 } else if (token == "\\backslash") {
295 par.insertChar(par.size(), '\\', font, change);
296 } else if (token == "\\newline") {
297 auto_ptr<InsetBase> inset(new InsetNewline);
298 inset->read(buf, lex);
299 par.insertInset(par.size(), inset.release(), font, change);
300 } else if (token == "\\LyXTable") {
301 auto_ptr<InsetBase> inset(new InsetTabular(buf));
302 inset->read(buf, lex);
303 par.insertInset(par.size(), inset.release(), font, change);
304 } else if (token == "\\bibitem") {
305 InsetCommandParams p("bibitem", "dummy");
306 auto_ptr<InsetBibitem> inset(new InsetBibitem(p));
307 inset->read(buf, lex);
308 par.insertInset(par.size(), inset.release(), font, change);
309 } else if (token == "\\hfill") {
310 par.insertInset(par.size(), new InsetHFill, font, change);
311 } else if (token == "\\lyxline") {
312 par.insertInset(par.size(), new InsetLine, font, change);
313 } else if (token == "\\newpage") {
314 par.insertInset(par.size(), new InsetPagebreak, font, change);
315 } else if (token == "\\change_unchanged") {
316 // Hack ! Needed for empty paragraphs :/
317 // FIXME: is it still ??
320 change = Change(Change::UNCHANGED);
321 } else if (token == "\\change_inserted") {
323 std::istringstream is(lex.getString());
327 change = Change(Change::INSERTED, bp.author_map[aid], ct);
328 } else if (token == "\\change_deleted") {
330 std::istringstream is(lex.getString());
334 change = Change(Change::DELETED, bp.author_map[aid], ct);
337 buf.error(ErrorItem(_("Unknown token"),
338 bformat(_("Unknown token: %1$s %2$s\n"), token, lex.getString()),
339 par.id(), 0, par.size()));
344 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex)
347 string token = lex.getString();
352 readParToken(buf, par, lex, token, font);
355 token = lex.getString();
360 if (token == "\\end_layout") {
361 //Ok, paragraph finished
365 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
366 << token << '\'' << endl;
367 if (token == "\\begin_layout" || token == "\\end_document"
368 || token == "\\end_inset" || token == "\\begin_deeper"
369 || token == "\\end_deeper") {
370 lex.pushToken(token);
371 lyxerr << "Paragraph ended in line "
372 << lex.getLineNo() << "\n"
373 << "Missing \\end_layout.\n";
377 // Initialize begin_of_body_ on load; redoParagraph maintains
378 par.setBeginOfBody();
386 BufferView * LyXText::bv() const
388 BOOST_ASSERT(bv_owner != 0);
393 double LyXText::spacing(Paragraph const & par) const
395 if (par.params().spacing().isDefault())
396 return bv()->buffer()->params().spacing().getValue();
397 return par.params().spacing().getValue();
401 int LyXText::width() const
407 int LyXText::height() const
409 return dim_.height();
413 int LyXText::singleWidth(Paragraph const & par, pos_type pos) const
415 return singleWidth(par, pos, par.getChar(pos), getFont(par, pos));
419 int LyXText::singleWidth(Paragraph const & par,
420 pos_type pos, char c, LyXFont const & font) const
422 BOOST_ASSERT(pos < par.size());
424 // The most common case is handled first (Asger)
425 if (IsPrintable(c)) {
426 Language const * language = font.language();
427 if (language->RightToLeft()) {
428 if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
429 lyxrc.font_norm_type == LyXRC::ISO_10646_1)
430 && language->lang() == "arabic") {
431 if (Encodings::IsComposeChar_arabic(c))
433 c = par.transformChar(c, pos);
434 } else if (language->lang() == "hebrew" &&
435 Encodings::IsComposeChar_hebrew(c))
438 return font_metrics::width(c, font);
441 if (c == Paragraph::META_INSET)
442 return par.getInset(pos)->width();
444 return font_metrics::width(c, font);
448 int LyXText::leftMargin(pit_type pit) const
450 BOOST_ASSERT(pit >= 0);
451 BOOST_ASSERT(pit < int(pars_.size()));
452 return leftMargin(pit, pars_[pit].size());
456 int LyXText::leftMargin(pit_type const pit, pos_type const pos) const
458 BOOST_ASSERT(pit >= 0);
459 BOOST_ASSERT(pit < int(pars_.size()));
460 Paragraph const & par = pars_[pit];
461 BOOST_ASSERT(pos >= 0);
462 BOOST_ASSERT(pos <= par.size());
463 //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
464 LyXTextClass const & tclass =
465 bv()->buffer()->params().getLyXTextClass();
466 LyXLayout_ptr const & layout = par.layout();
468 string parindent = layout->parindent;
473 l_margin += changebarMargin();
475 l_margin += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
477 if (par.getDepth() != 0) {
478 // find the next level paragraph
479 pit_type newpar = outerHook(pit, pars_);
480 if (newpar != pit_type(pars_.size())) {
481 if (pars_[newpar].layout()->isEnvironment()) {
482 l_margin = leftMargin(newpar);
484 if (par.layout() == tclass.defaultLayout()) {
485 if (pars_[newpar].params().noindent())
488 parindent = pars_[newpar].layout()->parindent;
493 LyXFont const labelfont = getLabelFont(par);
494 switch (layout->margintype) {
496 if (!layout->leftmargin.empty())
497 l_margin += font_metrics::signedWidth(layout->leftmargin,
498 tclass.defaultfont());
499 if (!par.getLabelstring().empty()) {
500 l_margin += font_metrics::signedWidth(layout->labelindent,
502 l_margin += font_metrics::width(par.getLabelstring(),
504 l_margin += font_metrics::width(layout->labelsep, labelfont);
509 l_margin += font_metrics::signedWidth(layout->labelindent, labelfont);
510 // The width of an empty par, even with manual label, should be 0
511 if (!par.empty() && pos >= par.beginOfBody()) {
512 if (!par.getLabelWidthString().empty()) {
513 l_margin += font_metrics::width(par.getLabelWidthString(),
515 l_margin += font_metrics::width(layout->labelsep, labelfont);
521 l_margin += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
522 / (par.getDepth() + 4);
525 case MARGIN_FIRST_DYNAMIC:
526 if (layout->labeltype == LABEL_MANUAL) {
527 if (pos >= par.beginOfBody()) {
528 l_margin += font_metrics::signedWidth(layout->leftmargin,
531 l_margin += font_metrics::signedWidth(layout->labelindent,
535 // Special case to fix problems with
537 || (layout->labeltype == LABEL_STATIC
538 && layout->latextype == LATEX_ENVIRONMENT
539 && !isFirstInSequence(pit, pars_))) {
540 l_margin += font_metrics::signedWidth(layout->leftmargin,
542 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
543 && layout->labeltype != LABEL_BIBLIO
544 && layout->labeltype !=
545 LABEL_CENTERED_TOP_ENVIRONMENT) {
546 l_margin += font_metrics::signedWidth(layout->labelindent,
548 l_margin += font_metrics::width(layout->labelsep, labelfont);
549 l_margin += font_metrics::width(par.getLabelstring(),
554 case MARGIN_RIGHT_ADDRESS_BOX: {
556 // ok, a terrible hack. The left margin depends on the widest
557 // row in this paragraph.
558 RowList::iterator rit = par.rows().begin();
559 RowList::iterator end = par.rows().end();
561 #warning This is wrong.
563 int minfill = maxwidth_;
564 for ( ; rit != end; ++rit)
565 if (rit->fill() < minfill)
566 minfill = rit->fill();
567 l_margin += font_metrics::signedWidth(layout->leftmargin,
568 tclass.defaultfont());
571 // also wrong, but much shorter.
572 l_margin += maxwidth_ / 2;
577 if (!par.params().leftIndent().zero())
578 l_margin += par.params().leftIndent().inPixels(maxwidth_);
582 if (par.params().align() == LYX_ALIGN_LAYOUT)
583 align = layout->align;
585 align = par.params().align();
587 // set the correct parindent
589 && (layout->labeltype == LABEL_NO_LABEL
590 || layout->labeltype == LABEL_TOP_ENVIRONMENT
591 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
592 || (layout->labeltype == LABEL_STATIC
593 && layout->latextype == LATEX_ENVIRONMENT
594 && !isFirstInSequence(pit, pars_)))
595 && align == LYX_ALIGN_BLOCK
596 && !par.params().noindent()
597 // display style insets are always centered, omit indentation
600 && par.getInset(pos)->display())
601 // in charstyles, tabulars and ert paragraphs are never indented!
602 && ((par.ownerCode() != InsetBase::TEXT_CODE || isMainText())
603 && par.ownerCode() != InsetBase::ERT_CODE
604 && par.ownerCode() != InsetBase::CHARSTYLE_CODE)
605 && (par.layout() != tclass.defaultLayout()
606 || bv()->buffer()->params().paragraph_separation ==
607 BufferParams::PARSEP_INDENT))
609 l_margin += font_metrics::signedWidth(parindent, tclass.defaultfont());
616 int LyXText::rightMargin(Paragraph const & par) const
618 // We do not want rightmargins on inner texts.
619 if (bv()->text() != this)
622 LyXTextClass const & tclass = bv()->buffer()->params().getLyXTextClass();
625 + font_metrics::signedWidth(tclass.rightmargin(),
626 tclass.defaultfont())
627 + font_metrics::signedWidth(par.layout()->rightmargin,
628 tclass.defaultfont())
629 * 4 / (par.getDepth() + 4);
635 int LyXText::labelEnd(pit_type const pit) const
637 // labelEnd is only needed if the layout fills a flushleft label.
638 if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
640 // return the beginning of the body
641 return leftMargin(pit);
647 // this needs special handling - only newlines count as a break point
648 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
650 pos_type const end = par.size();
653 if (par.isNewline(i))
662 void LyXText::rowBreakPoint(pit_type const pit, Row & row) const
664 Paragraph const & par = pars_[pit];
665 pos_type const end = par.size();
666 pos_type const pos = row.pos();
672 // maximum pixel width of a row
673 int width = maxwidth_ - rightMargin(par); // - leftMargin(pit, row);
679 LyXLayout_ptr const & layout = par.layout();
681 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
682 row.endpos(addressBreakPoint(pos, par));
686 pos_type const body_pos = par.beginOfBody();
689 // Now we iterate through until we reach the right margin
690 // or the end of the par, then choose the possible break
693 int const left = leftMargin(pit, pos);
696 // pixel width since last breakpoint
699 FontIterator fi = FontIterator(*this, par, pos);
700 pos_type point = end;
702 for ( ; i < end; ++i, ++fi) {
703 char const c = par.getChar(i);
706 int thiswidth = singleWidth(par, i, c, *fi);
708 // add the auto-hfill from label end to the body
709 if (body_pos && i == body_pos) {
710 int add = font_metrics::width(layout->labelsep, getLabelFont(par));
711 if (par.isLineSeparator(i - 1))
712 add -= singleWidth(par, i - 1);
714 add = std::max(add, labelEnd(pit) - x);
719 chunkwidth += thiswidth;
722 // break before a character that will fall off
723 // the right of the row
725 // if no break before, break here
726 if (point == end || chunkwidth >= width - left) {
733 // exit on last registered breakpoint:
737 if (par.isNewline(i)) {
743 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
748 if (par.isInset(i) && par.getInset(i)->display()) {
754 if (!par.isInset(i) || par.getInset(i)->isChar()) {
755 // some insets are line separators too
756 if (par.isLineSeparator(i)) {
757 // register breakpoint:
764 // maybe found one, but the par is short enough.
765 if (i == end && x < width)
768 // manual labels cannot be broken in LaTeX. But we
769 // want to make our on-screen rendering of footnotes
771 if (body_pos && point < body_pos)
778 void LyXText::setRowWidth(pit_type const pit, Row & row) const
780 // get the pure distance
781 pos_type const end = row.endpos();
783 Paragraph const & par = pars_[pit];
784 string const & labelsep = par.layout()->labelsep;
785 int w = leftMargin(pit, row.pos());
787 pos_type const body_pos = par.beginOfBody();
788 pos_type i = row.pos();
791 FontIterator fi = FontIterator(*this, par, i);
792 for ( ; i < end; ++i, ++fi) {
793 if (body_pos > 0 && i == body_pos) {
794 w += font_metrics::width(labelsep, getLabelFont(par));
795 if (par.isLineSeparator(i - 1))
796 w -= singleWidth(par, i - 1);
797 w = max(w, labelEnd(pit));
799 char const c = par.getChar(i);
800 w += singleWidth(par, i, c, *fi);
804 if (body_pos > 0 && body_pos >= end) {
805 w += font_metrics::width(labelsep, getLabelFont(par));
806 if (end > 0 && par.isLineSeparator(end - 1))
807 w -= singleWidth(par, end - 1);
808 w = max(w, labelEnd(pit));
811 row.width(w + rightMargin(par));
815 // returns the minimum space a manual label needs on the screen in pixel
816 int LyXText::labelFill(Paragraph const & par, Row const & row) const
818 pos_type last = par.beginOfBody();
820 BOOST_ASSERT(last > 0);
822 // -1 because a label ends with a space that is in the label
825 // a separator at this end does not count
826 if (par.isLineSeparator(last))
830 for (pos_type i = row.pos(); i <= last; ++i)
831 w += singleWidth(par, i);
833 string const & label = par.params().labelWidthString();
837 return max(0, font_metrics::width(label, getLabelFont(par)) - w);
841 LColor_color LyXText::backgroundColor() const
843 return LColor_color(LColor::color(background_color_));
847 void LyXText::setHeightOfRow(pit_type const pit, Row & row)
849 Paragraph const & par = pars_[pit];
850 // get the maximum ascent and the maximum descent
851 double layoutasc = 0;
852 double layoutdesc = 0;
853 double const dh = defaultRowHeight();
855 // ok, let us initialize the maxasc and maxdesc value.
856 // Only the fontsize count. The other properties
857 // are taken from the layoutfont. Nicer on the screen :)
858 LyXLayout_ptr const & layout = par.layout();
860 // as max get the first character of this row then it can
861 // increase but not decrease the height. Just some point to
862 // start with so we don't have to do the assignment below too
864 LyXFont font = getFont(par, row.pos());
865 LyXFont::FONT_SIZE const tmpsize = font.size();
866 font = getLayoutFont(pit);
867 LyXFont::FONT_SIZE const size = font.size();
868 font.setSize(tmpsize);
870 LyXFont labelfont = getLabelFont(par);
872 // these are minimum values
873 double const spacing_val = layout->spacing.getValue() * spacing(par);
874 //lyxerr << "spacing_val = " << spacing_val << endl;
875 int maxasc = int(font_metrics::maxAscent(font) * spacing_val);
876 int maxdesc = int(font_metrics::maxDescent(font) * spacing_val);
878 // insets may be taller
879 InsetList::const_iterator ii = par.insetlist.begin();
880 InsetList::const_iterator iend = par.insetlist.end();
881 for ( ; ii != iend; ++ii) {
882 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
883 maxasc = max(maxasc, ii->inset->ascent());
884 maxdesc = max(maxdesc, ii->inset->descent());
888 // Check if any custom fonts are larger (Asger)
889 // This is not completely correct, but we can live with the small,
890 // cosmetic error for now.
892 pos_type const pos_end = row.endpos();
894 LyXFont::FONT_SIZE maxsize =
895 par.highestFontInRange(row.pos(), pos_end, size);
896 if (maxsize > font.size()) {
897 font.setSize(maxsize);
898 maxasc = max(maxasc, font_metrics::maxAscent(font));
899 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
902 // This is nicer with box insets:
909 if (row.pos() == 0) {
910 BufferParams const & bufparams = bv()->buffer()->params();
911 // some parksips VERY EASY IMPLEMENTATION
912 if (bv()->buffer()->params().paragraph_separation
913 == BufferParams::PARSEP_SKIP
915 && ((layout->isParagraph() && par.getDepth() == 0)
916 || (pars_[pit - 1].layout()->isParagraph()
917 && pars_[pit - 1].getDepth() == 0)))
919 maxasc += bufparams.getDefSkip().inPixels(*bv());
922 if (par.params().startOfAppendix())
923 maxasc += int(3 * dh);
925 // This is special code for the chapter, since the label of this
926 // layout is printed in an extra row
927 if (layout->counter == "chapter"
928 && !par.params().labelString().empty()) {
929 labeladdon = int(font_metrics::maxHeight(labelfont)
930 * layout->spacing.getValue()
934 // special code for the top label
935 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
936 || layout->labeltype == LABEL_BIBLIO
937 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
938 && isFirstInSequence(pit, paragraphs())
939 && !par.getLabelstring().empty())
942 font_metrics::maxHeight(labelfont)
943 * layout->spacing.getValue()
945 + (layout->topsep + layout->labelbottomsep) * dh);
948 // Add the layout spaces, for example before and after
949 // a section, or between the items of a itemize or enumerate
952 pit_type prev = depthHook(pit, pars_, par.getDepth());
954 && pars_[prev].layout() == layout
955 && pars_[prev].getDepth() == par.getDepth()
956 && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
958 layoutasc = layout->itemsep * dh;
959 } else if (pit != 0 || row.pos() != 0) {
960 if (layout->topsep > 0)
961 layoutasc = layout->topsep * dh;
964 prev = outerHook(pit, pars_);
965 if (prev != pit_type(pars_.size())) {
966 maxasc += int(pars_[prev].layout()->parsep * dh);
967 } else if (pit != 0) {
968 if (pars_[pit - 1].getDepth() != 0 ||
969 pars_[pit - 1].layout() == layout) {
970 maxasc += int(layout->parsep * dh);
975 // is it a bottom line?
976 if (row.endpos() >= par.size()) {
977 // add the layout spaces, for example before and after
978 // a section, or between the items of a itemize or enumerate
980 pit_type nextpit = pit + 1;
981 if (nextpit != pit_type(pars_.size())) {
986 if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
987 usual = pars_[cpit].layout()->bottomsep * dh;
988 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
989 if (pars_[cpit].layout() != pars_[nextpit].layout()
990 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
992 unusual = pars_[cpit].layout()->bottomsep * dh;
994 layoutdesc = max(unusual, usual);
995 } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
996 if (pars_[cpit].layout() != pars_[nextpit].layout()
997 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
998 layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
1003 // incalculate the layout spaces
1004 maxasc += int(layoutasc * 2 / (2 + pars_[pit].getDepth()));
1005 maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
1007 // Top and bottom margin of the document (only at top-level)
1008 if (bv_owner->text() == this) {
1009 if (pit == 0 && row.pos() == 0)
1011 if (pit + 1 == pars_.size() && row.endpos() == par.size())
1015 row.ascent(maxasc + labeladdon);
1016 row.descent(maxdesc);
1024 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1026 BOOST_ASSERT(this == cur.text());
1027 // allow only if at start or end, or all previous is new text
1028 Paragraph & cpar = cur.paragraph();
1029 pit_type cpit = cur.pit();
1031 if (cur.pos() != 0 && cur.pos() != cur.lastpos()
1032 && cpar.isChangeEdited(0, cur.pos()))
1035 LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1036 LyXLayout_ptr const & layout = cpar.layout();
1038 // this is only allowed, if the current paragraph is not empty
1039 // or caption and if it has not the keepempty flag active
1040 if (cur.lastpos() == 0 && !cpar.allowEmpty()
1041 && layout->labeltype != LABEL_SENSITIVE)
1044 // a layout change may affect also the following paragraph
1045 recUndo(cur.pit(), undoSpan(cur.pit()) - 1);
1047 // Always break behind a space
1048 // It is better to erase the space (Dekel)
1049 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1050 cpar.erase(cur.pos());
1052 // How should the layout for the new paragraph be?
1053 int preserve_layout = 0;
1055 preserve_layout = 2;
1057 preserve_layout = layout->isEnvironment();
1059 // We need to remember this before we break the paragraph, because
1060 // that invalidates the layout variable
1061 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1063 // we need to set this before we insert the paragraph.
1064 bool const isempty = cpar.allowEmpty() && cpar.empty();
1066 ::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1067 cur.pos(), preserve_layout);
1069 // After this, neither paragraph contains any rows!
1072 pit_type next_par = cpit + 1;
1074 // well this is the caption hack since one caption is really enough
1077 // set to standard-layout
1078 pars_[cpit].applyLayout(tclass.defaultLayout());
1080 // set to standard-layout
1081 pars_[next_par].applyLayout(tclass.defaultLayout());
1084 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1085 pars_[next_par].erase(0);
1087 updateCounters(cur.buffer());
1089 // This check is necessary. Otherwise the new empty paragraph will
1090 // be deleted automatically. And it is more friendly for the user!
1091 if (cur.pos() != 0 || isempty)
1092 setCursor(cur, cur.pit() + 1, 0);
1094 setCursor(cur, cur.pit(), 0);
1098 // insert a character, moves all the following breaks in the
1099 // same Paragraph one to the right and make a rebreak
1100 void LyXText::insertChar(LCursor & cur, char c)
1102 BOOST_ASSERT(this == cur.text());
1103 BOOST_ASSERT(c != Paragraph::META_INSET);
1105 recordUndo(cur, Undo::INSERT);
1107 Paragraph & par = cur.paragraph();
1108 // try to remove this
1109 pit_type const pit = cur.pit();
1111 bool const freeSpacing = par.layout()->free_spacing ||
1112 par.isFreeSpacing();
1114 if (lyxrc.auto_number) {
1115 static string const number_operators = "+-/*";
1116 static string const number_unary_operators = "+-";
1117 static string const number_seperators = ".,:";
1119 if (current_font.number() == LyXFont::ON) {
1120 if (!IsDigit(c) && !contains(number_operators, c) &&
1121 !(contains(number_seperators, c) &&
1123 cur.pos() != cur.lastpos() &&
1124 getFont(par, cur.pos()).number() == LyXFont::ON &&
1125 getFont(par, cur.pos() - 1).number() == LyXFont::ON)
1127 number(cur); // Set current_font.number to OFF
1128 } else if (IsDigit(c) &&
1129 real_current_font.isVisibleRightToLeft()) {
1130 number(cur); // Set current_font.number to ON
1132 if (cur.pos() != 0) {
1133 char const c = par.getChar(cur.pos() - 1);
1134 if (contains(number_unary_operators, c) &&
1136 || par.isSeparator(cur.pos() - 2)
1137 || par.isNewline(cur.pos() - 2))
1139 setCharFont(pit, cur.pos() - 1, current_font);
1140 } else if (contains(number_seperators, c)
1142 && getFont(par, cur.pos() - 2).number() == LyXFont::ON) {
1143 setCharFont(pit, cur.pos() - 1, current_font);
1149 // First check, if there will be two blanks together or a blank at
1150 // the beginning of a paragraph.
1151 // I decided to handle blanks like normal characters, the main
1152 // difference are the special checks when calculating the row.fill
1153 // (blank does not count at the end of a row) and the check here
1155 // The bug is triggered when we type in a description environment:
1156 // The current_font is not changed when we go from label to main text
1157 // and it should (along with realtmpfont) when we type the space.
1158 // CHECK There is a bug here! (Asger)
1160 // store the current font. This is because of the use of cursor
1161 // movements. The moving cursor would refresh the current font
1162 LyXFont realtmpfont = real_current_font;
1163 LyXFont rawtmpfont = current_font;
1165 // When the free-spacing option is set for the current layout,
1166 // disable the double-space checking
1167 if (!freeSpacing && IsLineSeparatorChar(c)) {
1168 if (cur.pos() == 0) {
1169 static bool sent_space_message = false;
1170 if (!sent_space_message) {
1171 cur.message(_("You cannot insert a space at the "
1172 "beginning of a paragraph. Please read the Tutorial."));
1173 sent_space_message = true;
1177 BOOST_ASSERT(cur.pos() > 0);
1178 if (par.isLineSeparator(cur.pos() - 1)
1179 || par.isNewline(cur.pos() - 1)) {
1180 static bool sent_space_message = false;
1181 if (!sent_space_message) {
1182 cur.message(_("You cannot type two spaces this way. "
1183 "Please read the Tutorial."));
1184 sent_space_message = true;
1190 par.insertChar(cur.pos(), c, rawtmpfont);
1192 current_font = rawtmpfont;
1193 real_current_font = realtmpfont;
1194 //setCursor(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1195 setCursor(cur, cur.pit(), cur.pos() + 1, false, true);
1200 void LyXText::charInserted()
1202 // Here we call finishUndo for every 20 characters inserted.
1203 // This is from my experience how emacs does it. (Lgb)
1204 static unsigned int counter;
1215 LyXText::computeRowMetrics(pit_type const pit, Row const & row) const
1218 Paragraph const & par = pars_[pit];
1220 double w = dim_.wid - row.width();
1222 bool const is_rtl = isRTL(par);
1224 result.x = rightMargin(par);
1226 result.x = leftMargin(pit, row.pos());
1228 // is there a manual margin with a manual label
1229 LyXLayout_ptr const & layout = par.layout();
1231 if (layout->margintype == MARGIN_MANUAL
1232 && layout->labeltype == LABEL_MANUAL) {
1233 /// We might have real hfills in the label part
1234 int nlh = numberOfLabelHfills(par, row);
1236 // A manual label par (e.g. List) has an auto-hfill
1237 // between the label text and the body of the
1239 // But we don't want to do this auto hfill if the par
1244 if (nlh && !par.getLabelWidthString().empty())
1245 result.label_hfill = labelFill(par, row) / double(nlh);
1248 // are there any hfills in the row?
1249 int const nh = numberOfHfills(par, row);
1253 result.hfill = w / nh;
1254 // we don't have to look at the alignment if it is ALIGN_LEFT and
1255 // if the row is already larger then the permitted width as then
1256 // we force the LEFT_ALIGN'edness!
1257 } else if (int(row.width()) < maxwidth_) {
1258 // is it block, flushleft or flushright?
1259 // set x how you need it
1261 if (par.params().align() == LYX_ALIGN_LAYOUT)
1262 align = layout->align;
1264 align = par.params().align();
1266 // Display-style insets should always be on a centred row
1267 // The test on par.size() is to catch zero-size pars, which
1268 // would trigger the assert in Paragraph::getInset().
1269 //inset = par.size() ? par.getInset(row.pos()) : 0;
1271 && par.isInset(row.pos())
1272 && par.getInset(row.pos())->display())
1274 align = LYX_ALIGN_CENTER;
1278 case LYX_ALIGN_BLOCK: {
1279 int const ns = numberOfSeparators(par, row);
1280 bool disp_inset = false;
1281 if (row.endpos() < par.size()) {
1282 InsetBase const * in = par.getInset(row.endpos());
1284 disp_inset = in->display();
1286 // If we have separators, this is not the last row of a
1287 // par, does not end in newline, and is not row above a
1288 // display inset... then stretch it
1290 && row.endpos() < par.size()
1291 && !par.isNewline(row.endpos() - 1)
1294 result.separator = w / ns;
1295 } else if (is_rtl) {
1300 case LYX_ALIGN_RIGHT:
1303 case LYX_ALIGN_CENTER:
1309 bidi.computeTables(par, *bv()->buffer(), row);
1311 pos_type body_pos = par.beginOfBody();
1312 pos_type end = row.endpos();
1315 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1317 result.x += font_metrics::width(layout->labelsep, getLabelFont(par));
1318 if (body_pos <= end)
1319 result.x += result.label_hfill;
1327 // the cursor set functions have a special mechanism. When they
1328 // realize, that you left an empty paragraph, they will delete it.
1330 bool LyXText::cursorRightOneWord(LCursor & cur)
1332 BOOST_ASSERT(this == cur.text());
1336 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1340 // Skip through initial nonword stuff.
1341 // Treat floats and insets as words.
1342 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1344 // Advance through word.
1345 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1348 return setCursor(cur, old.pit(), old.pos());
1352 bool LyXText::cursorLeftOneWord(LCursor & cur)
1354 BOOST_ASSERT(this == cur.text());
1358 if (old.pos() == 0 && old.pit() != 0) {
1360 old.pos() = old.lastpos();
1362 // Skip through initial nonword stuff.
1363 // Treat floats and insets as words.
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 CursorSlice const & startc = cur.selBegin();
1409 CursorSlice const & endc = cur.selEnd();
1410 if (startc.pit() == endc.pit()) {
1411 recordUndoSelection(cur, Undo::INSERT);
1412 pars_[startc.pit()].acceptChange(startc.pos(), endc.pos());
1414 cur.clearSelection();
1415 setCursorIntern(cur, startc.pit(), 0);
1417 #ifdef WITH_WARNINGS
1418 #warning handle multi par selection
1423 void LyXText::rejectChange(LCursor & cur)
1425 BOOST_ASSERT(this == cur.text());
1426 if (!cur.selection() && cur.lastpos() != 0)
1429 CursorSlice const & startc = cur.selBegin();
1430 CursorSlice const & endc = cur.selEnd();
1431 if (startc.pit() == endc.pit()) {
1432 recordUndoSelection(cur, Undo::INSERT);
1433 pars_[startc.pit()].rejectChange(startc.pos(), endc.pos());
1435 cur.clearSelection();
1436 setCursorIntern(cur, startc.pit(), 0);
1438 #ifdef WITH_WARNINGS
1439 #warning handle multi par selection
1444 // Delete from cursor up to the end of the current or next word.
1445 void LyXText::deleteWordForward(LCursor & cur)
1447 BOOST_ASSERT(this == cur.text());
1448 if (cur.lastpos() == 0)
1452 cur.selection() = true;
1453 cursorRightOneWord(cur);
1455 cutSelection(cur, true, false);
1460 // Delete from cursor to start of current or prior word.
1461 void LyXText::deleteWordBackward(LCursor & cur)
1463 BOOST_ASSERT(this == cur.text());
1464 if (cur.lastpos() == 0)
1468 cur.selection() = true;
1469 cursorLeftOneWord(cur);
1471 cutSelection(cur, true, false);
1476 // Kill to end of line.
1477 void LyXText::deleteLineForward(LCursor & cur)
1479 BOOST_ASSERT(this == cur.text());
1480 if (cur.lastpos() == 0) {
1481 // Paragraph is empty, so we just go to the right
1485 cur.selection() = true; // to avoid deletion
1488 // What is this test for ??? (JMarc)
1489 if (!cur.selection())
1490 deleteWordForward(cur);
1492 cutSelection(cur, true, false);
1497 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1499 BOOST_ASSERT(this == cur.text());
1503 if (cur.selection()) {
1504 from = cur.selBegin();
1508 getWord(from, to, lyx::PARTIAL_WORD);
1509 setCursor(cur, to.pit(), to.pos() + 1);
1512 recordUndoSelection(cur);
1514 pos_type pos = from.pos();
1515 int par = from.pit();
1517 while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1519 if (pos == pars_[pit].size()) {
1524 unsigned char c = pars_[pit].getChar(pos);
1525 if (c != Paragraph::META_INSET) {
1527 case text_lowercase:
1530 case text_capitalization:
1532 action = text_lowercase;
1534 case text_uppercase:
1539 #ifdef WITH_WARNINGS
1542 pars_[pit].setChar(pos, c);
1548 void LyXText::Delete(LCursor & cur)
1550 BOOST_ASSERT(this == cur.text());
1552 if (cur.pos() != cur.lastpos()) {
1553 recordUndo(cur, Undo::DELETE, cur.pit());
1554 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1556 } else if (cur.pit() != cur.lastpit()) {
1559 setCursorIntern(cur, cur.pit()+1, 0, false, false);
1560 if (pars_[cur.pit()].layout() == pars_[scur.pit()].layout()) {
1561 recordUndo(scur, Undo::DELETE, scur.pit());
1564 setCursorIntern(scur, scur.pit(), scur.pos(), false, scur.boundary());
1570 void LyXText::backspace(LCursor & cur)
1572 BOOST_ASSERT(this == cur.text());
1573 if (cur.pos() == 0) {
1574 // The cursor is at the beginning of a paragraph, so
1575 // the the backspace will collapse two paragraphs into
1578 // but it's not allowed unless it's new
1579 Paragraph & par = cur.paragraph();
1580 if (par.isChangeEdited(0, par.size()))
1583 // we may paste some paragraphs
1585 // is it an empty paragraph?
1586 pos_type lastpos = cur.lastpos();
1587 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1588 // This is an empty paragraph and we delete it just
1589 // by moving the cursor one step
1590 // left and let the DeleteEmptyParagraphMechanism
1591 // handle the actual deletion of the paragraph.
1593 if (cur.pit() != 0) {
1594 // For KeepEmpty layouts we need to get
1595 // rid of the keepEmpty setting first.
1596 // And the only way to do this is to
1597 // reset the layout to something
1598 // else: f.ex. the default layout.
1599 if (par.allowEmpty()) {
1600 Buffer & buf = cur.buffer();
1601 BufferParams const & bparams = buf.params();
1602 par.layout(bparams.getLyXTextClass().defaultLayout());
1611 recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1613 pit_type tmppit = cur.pit();
1614 // We used to do cursorLeftIntern() here, but it is
1615 // not a good idea since it triggers the auto-delete
1616 // mechanism. So we do a cursorLeftIntern()-lite,
1617 // without the dreaded mechanism. (JMarc)
1618 if (cur.pit() != 0) {
1619 // steps into the above paragraph.
1620 setCursorIntern(cur, cur.pit() - 1,
1621 pars_[cur.pit() - 1].size(),
1625 // Pasting is not allowed, if the paragraphs have different
1626 // layout. I think it is a real bug of all other
1627 // word processors to allow it. It confuses the user.
1628 // Correction: Pasting is always allowed with standard-layout
1629 // Correction (Jug 20050717): Remove check about alignment!
1630 Buffer & buf = cur.buffer();
1631 BufferParams const & bufparams = buf.params();
1632 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1633 pit_type const cpit = cur.pit();
1636 && (pars_[cpit].layout() == pars_[tmppit].layout()
1637 || pars_[tmppit].layout() == tclass.defaultLayout()))
1639 mergeParagraph(bufparams, pars_, cpit);
1641 if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1644 // the counters may have changed
1645 updateCounters(cur.buffer());
1646 setCursor(cur, cur.pit(), cur.pos(), false);
1649 // this is the code for a normal backspace, not pasting
1651 recordUndo(cur, Undo::DELETE);
1652 // We used to do cursorLeftIntern() here, but it is
1653 // not a good idea since it triggers the auto-delete
1654 // mechanism. So we do a cursorLeftIntern()-lite,
1655 // without the dreaded mechanism. (JMarc)
1656 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1657 false, cur.boundary());
1658 cur.paragraph().erase(cur.pos());
1661 if (cur.pos() == cur.lastpos())
1662 setCurrentFont(cur);
1664 setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1668 Paragraph & LyXText::getPar(pit_type par) const
1670 //lyxerr << "getPar: " << par << " from " << paragraphs().size() << endl;
1671 BOOST_ASSERT(par >= 0);
1672 BOOST_ASSERT(par < int(paragraphs().size()));
1673 return paragraphs()[par];
1677 Row const & LyXText::firstRow() const
1679 return *paragraphs().front().rows().begin();
1683 bool LyXText::redoParagraph(pit_type const pit)
1685 // remove rows of paragraph, keep track of height changes
1686 Paragraph & par = pars_[pit];
1688 // Add bibitem insets if necessary
1689 if (par.layout()->labeltype == LABEL_BIBLIO) {
1690 bool hasbibitem(false);
1691 if (!par.insetlist.empty()
1692 // Insist on it being in pos 0
1693 && par.getChar(0) == Paragraph::META_INSET) {
1694 InsetBase * inset = par.insetlist.begin()->inset;
1695 if (inset->lyxCode() == InsetBase::BIBITEM_CODE)
1699 InsetBibitem * inset(new
1700 InsetBibitem(InsetCommandParams("bibitem")));
1701 par.insertInset(0, static_cast<InsetBase *>(inset));
1702 bv()->cursor().posRight();
1707 InsetList::iterator ii = par.insetlist.begin();
1708 InsetList::iterator iend = par.insetlist.end();
1709 for (; ii != iend; ++ii) {
1711 int const w = maxwidth_ - leftMargin(pit) - rightMargin(par);
1712 MetricsInfo mi(bv(), getFont(par, ii->pos), w);
1713 ii->inset->metrics(mi, dim);
1716 // rebreak the paragraph
1720 par.setBeginOfBody();
1724 rowBreakPoint(pit, row);
1725 setRowWidth(pit, row);
1726 setHeightOfRow(pit, row);
1727 par.rows().push_back(row);
1728 dim.wid = std::max(dim.wid, row.width());
1729 dim.des += row.height();
1731 } while (z < par.size());
1733 dim.asc += par.rows()[0].ascent();
1734 dim.des -= par.rows()[0].ascent();
1736 bool const same = dim == par.dim();
1739 //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1745 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1747 //BOOST_ASSERT(mi.base.textwidth);
1748 if (mi.base.textwidth)
1749 maxwidth_ = mi.base.textwidth;
1750 //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1751 // << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1752 // save the caller's font locally:
1753 font_ = mi.base.font;
1757 for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1759 Paragraph & par = paragraphs()[pit];
1761 if (w < par.width())
1766 dim.asc = pars_[0].ascent();
1767 dim.des = h - dim.asc;
1773 // only used for inset right now. should also be used for main text
1774 void LyXText::draw(PainterInfo & pi, int x, int y) const
1776 paintTextInset(*this, pi, x, y);
1781 // only used for inset right now. should also be used for main text
1782 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1784 LCursor & cur = pi.base.bv->cursor();
1785 if (!cur.selection())
1787 if (!ptr_cmp(cur.text(), this))
1790 lyxerr << "draw selection at " << x << endl;
1792 // is there a better way of getting these two iterators?
1793 DocIterator beg = cur;
1794 DocIterator end = cur;
1796 beg.top() = cur.selBegin();
1797 end.top() = cur.selEnd();
1799 // the selection doesn't touch the visible screen
1800 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1801 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1804 Paragraph const & par1 = pars_[beg.pit()];
1805 Paragraph const & par2 = pars_[end.pit()];
1807 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1808 Row const & row2 = par2.getRow(end.pos(), end.boundary());
1811 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1816 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1817 int const startx = cursorX(beg.top(), begin.boundary());
1818 x1 = isRTL(par1) ? startx : 0;
1819 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
1823 if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
1824 y2 = pi.base.bv->workHeight();
1828 y2 = bv_funcs::getPos(end).y_ + row2.descent();
1829 int const endx = cursorX(end.top(), end.boundary());
1830 X1 = isRTL(par2) ? 0 : endx;
1831 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
1834 lyxerr << " y1: " << y1 << " y2: " << y2
1835 << " xo: " << xo_ << " wid: " << dim_.wid
1838 // paint big rectangle in one go
1839 pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
1841 // reset background at begin of first selected line
1842 pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
1843 LColor::background);
1845 // reset background at end of last selected line
1846 pi.pain.fillRectangle(x + X1, y2 - row2.height(),
1847 X2 - X1, row2.height(), LColor::background);
1852 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
1854 LCursor & cur = pi.base.bv->cursor();
1855 if (!cur.selection())
1857 if (!ptr_cmp(cur.text(), this))
1860 lyxerr[Debug::DEBUG]
1861 << BOOST_CURRENT_FUNCTION
1862 << "draw selection at " << x
1865 // is there a better way of getting these two iterators?
1866 DocIterator beg = cur;
1867 DocIterator end = cur;
1869 beg.top() = cur.selBegin();
1870 end.top() = cur.selEnd();
1872 // the selection doesn't touch the visible screen
1873 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1874 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1877 Paragraph const & par1 = pars_[beg.pit()];
1878 Paragraph const & par2 = pars_[end.pit()];
1880 bool const above = (bv_funcs::status(pi.base.bv, beg)
1881 == bv_funcs::CUR_ABOVE);
1882 bool const below = (bv_funcs::status(pi.base.bv, end)
1883 == bv_funcs::CUR_BELOW);
1891 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1892 y1 = bv_funcs::getPos(beg, beg.boundary()).y_ - row1.ascent();
1893 y2 = y1 + row1.height();
1894 int const startx = cursorX(beg.top(), beg.boundary());
1895 x1 = !isRTL(par1) ? startx : 0;
1896 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
1901 Y1 = pi.base.bv->workHeight();
1902 Y2 = pi.base.bv->workHeight();
1906 Row const & row2 = par2.getRow(end.pos(), end.boundary());
1907 Y1 = bv_funcs::getPos(end, end.boundary()).y_ - row2.ascent();
1908 Y2 = Y1 + row2.height();
1909 int const endx = cursorX(end.top(), end.boundary());
1910 X1 = !isRTL(par2) ? 0 : endx;
1911 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
1914 if (!above && !below && &par1.getRow(beg.pos(), end.boundary())
1915 == &par2.getRow(end.pos(), end.boundary()))
1917 // paint only one rectangle
1918 pi.pain.fillRectangle(x + x1, y1, X2 - x1, y2 - y1,
1923 lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
1924 << "X1:" << X1 << " x2: " << X2 << " wid: " << dim_.wid
1927 // paint upper rectangle
1928 pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
1930 // paint bottom rectangle
1931 pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
1933 // paint center rectangle
1934 pi.pain.fillRectangle(x, y2, dim_.wid,
1935 Y1 - y2, LColor::selection);
1939 bool LyXText::isLastRow(pit_type pit, Row const & row) const
1941 return row.endpos() >= pars_[pit].size()
1942 && pit + 1 == pit_type(paragraphs().size());
1946 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
1948 return row.pos() == 0 && pit == 0;
1952 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1953 word_location const loc)
1955 Paragraph const & from_par = pars_[from.pit()];
1957 case lyx::WHOLE_WORD_STRICT:
1958 if (from.pos() == 0 || from.pos() == from_par.size()
1959 || !from_par.isLetter(from.pos())
1960 || !from_par.isLetter(from.pos() - 1)) {
1964 // no break here, we go to the next
1966 case lyx::WHOLE_WORD:
1967 // If we are already at the beginning of a word, do nothing
1968 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1970 // no break here, we go to the next
1972 case lyx::PREVIOUS_WORD:
1973 // always move the cursor to the beginning of previous word
1974 while (from.pos() && from_par.isLetter(from.pos() - 1))
1977 case lyx::NEXT_WORD:
1978 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1981 case lyx::PARTIAL_WORD:
1982 // no need to move the 'from' cursor
1986 Paragraph & to_par = pars_[to.pit()];
1987 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1992 void LyXText::write(Buffer const & buf, std::ostream & os) const
1994 ParagraphList::const_iterator pit = paragraphs().begin();
1995 ParagraphList::const_iterator end = paragraphs().end();
1996 Paragraph::depth_type dth = 0;
1997 for (; pit != end; ++pit)
1998 pit->write(buf, os, buf.params(), dth);
2002 bool LyXText::read(Buffer const & buf, LyXLex & lex)
2004 static Change current_change;
2006 Paragraph::depth_type depth = 0;
2008 while (lex.isOK()) {
2010 string const token = lex.getString();
2015 if (token == "\\end_inset") {
2019 if (token == "\\end_body") {
2023 if (token == "\\begin_body") {
2027 if (token == "\\end_document") {
2031 if (token == "\\begin_layout") {
2032 lex.pushToken(token);
2035 par.params().depth(depth);
2036 if (buf.params().tracking_changes)
2038 par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
2039 pars_.push_back(par);
2041 // FIXME: goddamn InsetTabular makes us pass a Buffer
2043 ::readParagraph(buf, pars_.back(), lex);
2045 } else if (token == "\\begin_deeper") {
2047 } else if (token == "\\end_deeper") {
2049 lex.printError("\\end_deeper: " "depth is already null");
2054 lyxerr << "Handling unknown body token: `"
2055 << token << '\'' << endl;
2062 int LyXText::ascent() const
2068 int LyXText::descent() const
2074 int LyXText::cursorX(CursorSlice const & sl, bool boundary) const
2076 pit_type const pit = sl.pit();
2077 Paragraph const & par = pars_[pit];
2078 if (par.rows().empty())
2081 pos_type ppos = sl.pos();
2082 // Correct position in front of big insets
2083 bool const boundary_correction = ppos != 0 && boundary;
2084 if (boundary_correction)
2087 Row const & row = par.getRow(sl.pos(), boundary);
2089 pos_type cursor_vpos = 0;
2091 RowMetrics const m = computeRowMetrics(pit, row);
2094 pos_type const row_pos = row.pos();
2095 pos_type const end = row.endpos();
2098 cursor_vpos = row_pos;
2099 else if (ppos >= end)
2100 cursor_vpos = isRTL(par) ? row_pos : end;
2101 else if (ppos > row_pos && ppos >= end)
2102 // Place cursor after char at (logical) position pos - 1
2103 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
2104 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
2106 // Place cursor before char at (logical) position ppos
2107 cursor_vpos = (bidi.level(ppos) % 2 == 0)
2108 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
2110 pos_type body_pos = par.beginOfBody();
2112 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2115 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2116 pos_type pos = bidi.vis2log(vpos);
2117 if (body_pos > 0 && pos == body_pos - 1) {
2119 + font_metrics::width(par.layout()->labelsep,
2121 if (par.isLineSeparator(body_pos - 1))
2122 x -= singleWidth(par, body_pos - 1);
2125 x += singleWidth(par, pos);
2127 if (hfillExpansion(par, row, pos))
2128 x += (pos >= body_pos) ? m.hfill : m.label_hfill;
2129 else if (par.isSeparator(pos) && pos >= body_pos)
2133 // see correction above
2134 if (boundary_correction)
2135 x += singleWidth(par, ppos);
2141 int LyXText::cursorY(CursorSlice const & sl, bool boundary) const
2143 //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
2144 Paragraph const & par = getPar(sl.pit());
2146 h -= pars_[0].rows()[0].ascent();
2147 for (pit_type pit = 0; pit < sl.pit(); ++pit)
2148 h += pars_[pit].height();
2150 if (pos && boundary)
2152 size_t const rend = par.pos2row(pos);
2153 for (size_t rit = 0; rit != rend; ++rit)
2154 h += par.rows()[rit].height();
2155 h += par.rows()[rend].ascent();
2160 // Returns the current font and depth as a message.
2161 string LyXText::currentState(LCursor & cur)
2163 BOOST_ASSERT(this == cur.text());
2164 Buffer & buf = cur.buffer();
2165 Paragraph const & par = cur.paragraph();
2166 std::ostringstream os;
2168 bool const show_change = buf.params().tracking_changes
2169 && cur.pos() != cur.lastpos()
2170 && par.lookupChange(cur.pos()) != Change::UNCHANGED;
2173 Change change = par.lookupChangeFull(cur.pos());
2174 Author const & a = buf.params().authors().get(change.author);
2175 os << _("Change: ") << a.name();
2176 if (!a.email().empty())
2177 os << " (" << a.email() << ")";
2178 if (change.changetime)
2179 os << _(" at ") << ctime(&change.changetime);
2183 // I think we should only show changes from the default
2185 LyXFont font = real_current_font;
2186 font.reduce(buf.params().getLyXTextClass().defaultfont());
2188 // avoid _(...) re-entrance problem
2189 string const s = font.stateText(&buf.params());
2190 os << bformat(_("Font: %1$s"), s);
2192 // os << bformat(_("Font: %1$s"), font.stateText(&buf.params));
2194 // The paragraph depth
2195 int depth = cur.paragraph().getDepth();
2197 os << bformat(_(", Depth: %1$d"), depth);
2199 // The paragraph spacing, but only if different from
2201 Spacing const & spacing = par.params().spacing();
2202 if (!spacing.isDefault()) {
2203 os << _(", Spacing: ");
2204 switch (spacing.getSpace()) {
2205 case Spacing::Single:
2208 case Spacing::Onehalf:
2211 case Spacing::Double:
2214 case Spacing::Other:
2215 os << _("Other (") << spacing.getValueAsString() << ')';
2217 case Spacing::Default:
2218 // should never happen, do nothing
2223 #ifdef DEVEL_VERSION
2224 os << _(", Inset: ") << &cur.inset();
2225 os << _(", Paragraph: ") << cur.pit();
2226 os << _(", Id: ") << par.id();
2227 os << _(", Position: ") << cur.pos();
2228 os << _(", Boundary: ") << cur.boundary();
2229 // Row & row = cur.textRow();
2230 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2236 string LyXText::getPossibleLabel(LCursor & cur) const
2238 pit_type pit = cur.pit();
2240 LyXLayout_ptr layout = pars_[pit].layout();
2242 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2243 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2244 if (layout2->latextype != LATEX_PARAGRAPH) {
2250 string text = layout->latexname().substr(0, 3);
2251 if (layout->latexname() == "theorem")
2252 text = "thm"; // Create a correct prefix for prettyref
2255 if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2258 string par_text = pars_[pit].asString(cur.buffer(), false);
2259 for (int i = 0; i < lyxrc.label_init_length; ++i) {
2260 if (par_text.empty())
2263 par_text = split(par_text, head, ' ');
2264 // Is it legal to use spaces in labels ?
2274 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2278 // Paragraph const & par = pars_[pit];
2279 // Row const & r = par.rows()[row];
2280 // int pos = r.pos();
2281 // for (; currx < x && pos < r.endpos(); ++pos) {
2283 // currx += singleWidth(par, pos);
2285 // if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2291 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2293 BOOST_ASSERT(row < int(pars_[pit].rows().size()));
2295 Row const & r = pars_[pit].rows()[row];
2296 return r.pos() + getColumnNearX(pit, r, x, bound);
2300 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2302 // Paragraph const & par = pars_[pit];
2303 // Row const & r = par.rows()[row];
2309 // x,y are screen coordinates
2310 // sets cursor only within this LyXText
2311 void LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2313 pit_type pit = getPitNearY(y);
2314 int yy = theCoords.get(this, pit).y_ - pars_[pit].ascent();
2315 lyxerr[Debug::DEBUG]
2316 << BOOST_CURRENT_FUNCTION
2320 << " yy: " << yy << endl;
2322 Paragraph const & par = pars_[pit];
2324 BOOST_ASSERT(par.rows().size());
2325 for (; r < int(par.rows().size()) - 1; ++r) {
2326 Row const & row = par.rows()[r];
2327 if (int(yy + row.height()) > y)
2332 Row const & row = par.rows()[r];
2334 lyxerr[Debug::DEBUG]
2335 << BOOST_CURRENT_FUNCTION
2337 << " from pos: " << row.pos()
2342 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2344 lyxerr[Debug::DEBUG]
2345 << BOOST_CURRENT_FUNCTION
2346 << ": setting cursor pit: " << pit
2350 setCursor(cur, pit, pos, true, bound);