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, Change & change)
157 BufferParams const & bp = buf.params();
159 if (token[0] != '\\') {
160 string::const_iterator cit = token.begin();
161 for (; cit != token.end(); ++cit)
162 par.insertChar(par.size(), (*cit), font, change);
163 } else if (token == "\\begin_layout") {
165 string layoutname = lex.getString();
167 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
170 LyXTextClass const & tclass = bp.getLyXTextClass();
172 if (layoutname.empty()) {
173 layoutname = tclass.defaultLayoutName();
176 bool hasLayout = tclass.hasLayout(layoutname);
179 buf.error(ErrorItem(_("Unknown layout"),
180 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
181 layoutname, tclass.name()), par.id(), 0, par.size()));
182 layoutname = tclass.defaultLayoutName();
185 par.layout(bp.getLyXTextClass()[layoutname]);
187 // Test whether the layout is obsolete.
188 LyXLayout_ptr const & layout = par.layout();
189 if (!layout->obsoleted_by().empty())
190 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
192 par.params().read(lex);
194 } else if (token == "\\end_layout") {
195 lyxerr << BOOST_CURRENT_FUNCTION
196 << ": Solitary \\end_layout in line "
197 << lex.getLineNo() << "\n"
198 << "Missing \\begin_layout?.\n";
199 } else if (token == "\\end_inset") {
200 lyxerr << BOOST_CURRENT_FUNCTION
201 << ": Solitary \\end_inset in line "
202 << lex.getLineNo() << "\n"
203 << "Missing \\begin_inset?.\n";
204 } else if (token == "\\begin_inset") {
205 InsetBase * inset = readInset(lex, buf);
207 par.insertInset(par.size(), inset, font, change);
210 string line = lex.getString();
211 buf.error(ErrorItem(_("Unknown Inset"), line,
212 par.id(), 0, par.size()));
214 } else if (token == "\\family") {
216 font.setLyXFamily(lex.getString());
217 } else if (token == "\\series") {
219 font.setLyXSeries(lex.getString());
220 } else if (token == "\\shape") {
222 font.setLyXShape(lex.getString());
223 } else if (token == "\\size") {
225 font.setLyXSize(lex.getString());
226 } else if (token == "\\lang") {
228 string const tok = lex.getString();
229 Language const * lang = languages.getLanguage(tok);
231 font.setLanguage(lang);
233 font.setLanguage(bp.language);
234 lex.printError("Unknown language `$$Token'");
236 } else if (token == "\\numeric") {
238 font.setNumber(font.setLyXMisc(lex.getString()));
239 } else if (token == "\\emph") {
241 font.setEmph(font.setLyXMisc(lex.getString()));
242 } else if (token == "\\bar") {
244 string const tok = lex.getString();
247 font.setUnderbar(LyXFont::ON);
248 else if (tok == "no")
249 font.setUnderbar(LyXFont::OFF);
250 else if (tok == "default")
251 font.setUnderbar(LyXFont::INHERIT);
253 lex.printError("Unknown bar font flag "
255 } else if (token == "\\noun") {
257 font.setNoun(font.setLyXMisc(lex.getString()));
258 } else if (token == "\\color") {
260 font.setLyXColor(lex.getString());
261 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
263 // Insets don't make sense in a free-spacing context! ---Kayvan
264 if (par.isFreeSpacing()) {
265 if (token == "\\InsetSpace")
266 par.insertChar(par.size(), ' ', font, change);
267 else if (lex.isOK()) {
269 string const next_token = lex.getString();
270 if (next_token == "\\-")
271 par.insertChar(par.size(), '-', font, change);
273 lex.printError("Token `$$Token' "
275 "paragraph layout!");
279 auto_ptr<InsetBase> inset;
280 if (token == "\\SpecialChar" )
281 inset.reset(new InsetSpecialChar);
283 inset.reset(new InsetSpace);
284 inset->read(buf, lex);
285 par.insertInset(par.size(), inset.release(),
288 } else if (token == "\\i") {
289 auto_ptr<InsetBase> inset(new InsetLatexAccent);
290 inset->read(buf, lex);
291 par.insertInset(par.size(), inset.release(), font, change);
292 } else if (token == "\\backslash") {
293 par.insertChar(par.size(), '\\', font, change);
294 } else if (token == "\\newline") {
295 auto_ptr<InsetBase> inset(new InsetNewline);
296 inset->read(buf, lex);
297 par.insertInset(par.size(), inset.release(), font, change);
298 } else if (token == "\\LyXTable") {
299 auto_ptr<InsetBase> inset(new InsetTabular(buf));
300 inset->read(buf, lex);
301 par.insertInset(par.size(), inset.release(), font, change);
302 } else if (token == "\\bibitem") {
303 InsetCommandParams p("bibitem", "dummy");
304 auto_ptr<InsetBibitem> inset(new InsetBibitem(p));
305 inset->read(buf, lex);
306 par.insertInset(par.size(), inset.release(), font, change);
307 } else if (token == "\\hfill") {
308 par.insertInset(par.size(), new InsetHFill, font, change);
309 } else if (token == "\\lyxline") {
310 par.insertInset(par.size(), new InsetLine, font, change);
311 } else if (token == "\\newpage") {
312 par.insertInset(par.size(), new InsetPagebreak, font, change);
313 } else if (token == "\\change_unchanged") {
314 // Hack ! Needed for empty paragraphs :/
315 // FIXME: is it still ??
318 change = Change(Change::UNCHANGED);
319 } else if (token == "\\change_inserted") {
321 std::istringstream is(lex.getString());
325 change = Change(Change::INSERTED, bp.author_map[aid], ct);
326 } else if (token == "\\change_deleted") {
328 std::istringstream is(lex.getString());
332 change = Change(Change::DELETED, bp.author_map[aid], ct);
335 buf.error(ErrorItem(_("Unknown token"),
336 bformat(_("Unknown token: %1$s %2$s\n"), token, lex.getString()),
337 par.id(), 0, par.size()));
342 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex)
345 string token = lex.getString();
351 readParToken(buf, par, lex, token, font, change);
354 token = lex.getString();
359 if (token == "\\end_layout") {
360 //Ok, paragraph finished
364 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
365 << token << '\'' << endl;
366 if (token == "\\begin_layout" || token == "\\end_document"
367 || token == "\\end_inset" || token == "\\begin_deeper"
368 || token == "\\end_deeper") {
369 lex.pushToken(token);
370 lyxerr << "Paragraph ended in line "
371 << lex.getLineNo() << "\n"
372 << "Missing \\end_layout.\n";
376 // Initialize begin_of_body_ on load; redoParagraph maintains
377 par.setBeginOfBody();
385 BufferView * LyXText::bv() const
387 BOOST_ASSERT(bv_owner != 0);
392 double LyXText::spacing(Paragraph const & par) const
394 if (par.params().spacing().isDefault())
395 return bv()->buffer()->params().spacing().getValue();
396 return par.params().spacing().getValue();
400 int LyXText::width() const
406 int LyXText::height() const
408 return dim_.height();
412 int LyXText::singleWidth(Paragraph const & par, pos_type pos) const
414 return singleWidth(par, pos, par.getChar(pos), getFont(par, pos));
418 int LyXText::singleWidth(Paragraph const & par,
419 pos_type pos, char c, LyXFont const & font) const
421 // The most common case is handled first (Asger)
422 if (IsPrintable(c)) {
423 Language const * language = font.language();
424 if (language->RightToLeft()) {
425 if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
426 lyxrc.font_norm_type == LyXRC::ISO_10646_1)
427 && language->lang() == "arabic") {
428 if (Encodings::IsComposeChar_arabic(c))
430 c = par.transformChar(c, pos);
431 } else if (language->lang() == "hebrew" &&
432 Encodings::IsComposeChar_hebrew(c))
435 return font_metrics::width(c, font);
438 if (c == Paragraph::META_INSET)
439 return par.getInset(pos)->width();
441 return font_metrics::width(c, font);
445 int LyXText::leftMargin(pit_type pit) const
447 BOOST_ASSERT(pit >= 0);
448 BOOST_ASSERT(pit < int(pars_.size()));
449 return leftMargin(pit, pars_[pit].size());
453 int LyXText::leftMargin(pit_type const pit, pos_type const pos) const
455 BOOST_ASSERT(pit >= 0);
456 BOOST_ASSERT(pit < int(pars_.size()));
457 Paragraph const & par = pars_[pit];
458 BOOST_ASSERT(pos >= 0);
459 BOOST_ASSERT(pos <= par.size());
460 //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
461 LyXTextClass const & tclass =
462 bv()->buffer()->params().getLyXTextClass();
463 LyXLayout_ptr const & layout = par.layout();
465 string parindent = layout->parindent;
470 l_margin += changebarMargin();
472 l_margin += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
474 if (par.getDepth() != 0) {
475 // find the next level paragraph
476 pit_type newpar = outerHook(pit, pars_);
477 if (newpar != pit_type(pars_.size())) {
478 if (pars_[newpar].layout()->isEnvironment()) {
479 l_margin = leftMargin(newpar);
481 if (par.layout() == tclass.defaultLayout()) {
482 if (pars_[newpar].params().noindent())
485 parindent = pars_[newpar].layout()->parindent;
490 LyXFont const labelfont = getLabelFont(par);
491 switch (layout->margintype) {
493 if (!layout->leftmargin.empty())
494 l_margin += font_metrics::signedWidth(layout->leftmargin,
495 tclass.defaultfont());
496 if (!par.getLabelstring().empty()) {
497 l_margin += font_metrics::signedWidth(layout->labelindent,
499 l_margin += font_metrics::width(par.getLabelstring(),
501 l_margin += font_metrics::width(layout->labelsep, labelfont);
506 l_margin += font_metrics::signedWidth(layout->labelindent, labelfont);
507 // The width of an empty par, even with manual label, should be 0
508 if (!par.empty() && pos >= par.beginOfBody()) {
509 if (!par.getLabelWidthString().empty()) {
510 l_margin += font_metrics::width(par.getLabelWidthString(),
512 l_margin += font_metrics::width(layout->labelsep, labelfont);
518 l_margin += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
519 / (par.getDepth() + 4);
522 case MARGIN_FIRST_DYNAMIC:
523 if (layout->labeltype == LABEL_MANUAL) {
524 if (pos >= par.beginOfBody()) {
525 l_margin += font_metrics::signedWidth(layout->leftmargin,
528 l_margin += font_metrics::signedWidth(layout->labelindent,
532 // Special case to fix problems with
534 || (layout->labeltype == LABEL_STATIC
535 && layout->latextype == LATEX_ENVIRONMENT
536 && !isFirstInSequence(pit, pars_))) {
537 l_margin += font_metrics::signedWidth(layout->leftmargin,
539 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
540 && layout->labeltype != LABEL_BIBLIO
541 && layout->labeltype !=
542 LABEL_CENTERED_TOP_ENVIRONMENT) {
543 l_margin += font_metrics::signedWidth(layout->labelindent,
545 l_margin += font_metrics::width(layout->labelsep, labelfont);
546 l_margin += font_metrics::width(par.getLabelstring(),
551 case MARGIN_RIGHT_ADDRESS_BOX: {
553 // ok, a terrible hack. The left margin depends on the widest
554 // row in this paragraph.
555 RowList::iterator rit = par.rows().begin();
556 RowList::iterator end = par.rows().end();
558 #warning This is wrong.
560 int minfill = maxwidth_;
561 for ( ; rit != end; ++rit)
562 if (rit->fill() < minfill)
563 minfill = rit->fill();
564 l_margin += font_metrics::signedWidth(layout->leftmargin,
565 tclass.defaultfont());
568 // also wrong, but much shorter.
569 l_margin += maxwidth_ / 2;
574 if (!par.params().leftIndent().zero())
575 l_margin += par.params().leftIndent().inPixels(maxwidth_);
579 if (par.params().align() == LYX_ALIGN_LAYOUT)
580 align = layout->align;
582 align = par.params().align();
584 // set the correct parindent
586 && (layout->labeltype == LABEL_NO_LABEL
587 || layout->labeltype == LABEL_TOP_ENVIRONMENT
588 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
589 || (layout->labeltype == LABEL_STATIC
590 && layout->latextype == LATEX_ENVIRONMENT
591 && !isFirstInSequence(pit, pars_)))
592 && align == LYX_ALIGN_BLOCK
593 && !par.params().noindent()
594 // in some insets, paragraphs are never indented
595 && !(par.inInset() && par.inInset()->neverIndent())
596 // display style insets are always centered, omit indentation
599 && par.getInset(pos)->display())
600 && (par.layout() != tclass.defaultLayout()
601 || bv()->buffer()->params().paragraph_separation ==
602 BufferParams::PARSEP_INDENT))
604 l_margin += font_metrics::signedWidth(parindent, tclass.defaultfont());
611 int LyXText::rightMargin(Paragraph const & par) const
613 // We do not want rightmargins on inner texts.
614 if (bv()->text() != this)
617 LyXTextClass const & tclass = bv()->buffer()->params().getLyXTextClass();
620 + font_metrics::signedWidth(tclass.rightmargin(),
621 tclass.defaultfont())
622 + font_metrics::signedWidth(par.layout()->rightmargin,
623 tclass.defaultfont())
624 * 4 / (par.getDepth() + 4);
630 int LyXText::labelEnd(pit_type const pit) const
632 // labelEnd is only needed if the layout fills a flushleft label.
633 if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
635 // return the beginning of the body
636 return leftMargin(pit);
642 // this needs special handling - only newlines count as a break point
643 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
645 pos_type const end = par.size();
648 if (par.isNewline(i))
657 void LyXText::rowBreakPoint(pit_type const pit, Row & row) const
659 Paragraph const & par = pars_[pit];
660 pos_type const end = par.size();
661 pos_type const pos = row.pos();
667 // maximum pixel width of a row
668 int width = maxwidth_ - rightMargin(par); // - leftMargin(pit, row);
674 LyXLayout_ptr const & layout = par.layout();
676 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
677 row.endpos(addressBreakPoint(pos, par));
681 pos_type const body_pos = par.beginOfBody();
684 // Now we iterate through until we reach the right margin
685 // or the end of the par, then choose the possible break
688 int const left = leftMargin(pit, pos);
691 // pixel width since last breakpoint
694 FontIterator fi = FontIterator(*this, par, pos);
695 pos_type point = end;
697 for ( ; i < end; ++i, ++fi) {
698 char const c = par.getChar(i);
699 int thiswidth = singleWidth(par, i, c, *fi);
701 // add the auto-hfill from label end to the body
702 if (body_pos && i == body_pos) {
703 int add = font_metrics::width(layout->labelsep, getLabelFont(par));
704 if (par.isLineSeparator(i - 1))
705 add -= singleWidth(par, i - 1);
707 add = std::max(add, labelEnd(pit) - x);
712 chunkwidth += thiswidth;
714 // break before a character that will fall off
715 // the right of the row
717 // if no break before, break here
718 if (point == end || chunkwidth >= width - left) {
725 // exit on last registered breakpoint:
729 if (par.isNewline(i)) {
735 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
740 if (par.isInset(i) && par.getInset(i)->display()) {
746 if (!par.isInset(i) || par.getInset(i)->isChar()) {
747 // some insets are line separators too
748 if (par.isLineSeparator(i)) {
749 // register breakpoint:
756 // maybe found one, but the par is short enough.
757 if (i == end && x < width)
760 // manual labels cannot be broken in LaTeX. But we
761 // want to make our on-screen rendering of footnotes
763 if (body_pos && point < body_pos)
770 void LyXText::setRowWidth(pit_type const pit, Row & row) const
772 // get the pure distance
773 pos_type const end = row.endpos();
775 Paragraph const & par = pars_[pit];
776 string const & labelsep = par.layout()->labelsep;
777 int w = leftMargin(pit, row.pos());
779 pos_type const body_pos = par.beginOfBody();
780 pos_type i = row.pos();
783 FontIterator fi = FontIterator(*this, par, i);
784 for ( ; i < end; ++i, ++fi) {
785 if (body_pos > 0 && i == body_pos) {
786 w += font_metrics::width(labelsep, getLabelFont(par));
787 if (par.isLineSeparator(i - 1))
788 w -= singleWidth(par, i - 1);
789 w = max(w, labelEnd(pit));
791 char const c = par.getChar(i);
792 w += singleWidth(par, i, c, *fi);
796 if (body_pos > 0 && body_pos >= end) {
797 w += font_metrics::width(labelsep, getLabelFont(par));
798 if (end > 0 && par.isLineSeparator(end - 1))
799 w -= singleWidth(par, end - 1);
800 w = max(w, labelEnd(pit));
803 row.width(w + rightMargin(par));
807 // returns the minimum space a manual label needs on the screen in pixel
808 int LyXText::labelFill(Paragraph const & par, Row const & row) const
810 pos_type last = par.beginOfBody();
812 BOOST_ASSERT(last > 0);
814 // -1 because a label ends with a space that is in the label
817 // a separator at this end does not count
818 if (par.isLineSeparator(last))
822 for (pos_type i = row.pos(); i <= last; ++i)
823 w += singleWidth(par, i);
825 string const & label = par.params().labelWidthString();
829 return max(0, font_metrics::width(label, getLabelFont(par)) - w);
833 LColor_color LyXText::backgroundColor() const
835 return LColor_color(LColor::color(background_color_));
839 void LyXText::setHeightOfRow(pit_type const pit, Row & row)
841 Paragraph const & par = pars_[pit];
842 // get the maximum ascent and the maximum descent
843 double layoutasc = 0;
844 double layoutdesc = 0;
845 double const dh = defaultRowHeight();
847 // ok, let us initialize the maxasc and maxdesc value.
848 // Only the fontsize count. The other properties
849 // are taken from the layoutfont. Nicer on the screen :)
850 LyXLayout_ptr const & layout = par.layout();
852 // as max get the first character of this row then it can
853 // increase but not decrease the height. Just some point to
854 // start with so we don't have to do the assignment below too
856 LyXFont font = getFont(par, row.pos());
857 LyXFont::FONT_SIZE const tmpsize = font.size();
858 font = getLayoutFont(pit);
859 LyXFont::FONT_SIZE const size = font.size();
860 font.setSize(tmpsize);
862 LyXFont labelfont = getLabelFont(par);
864 // these are minimum values
865 double const spacing_val = layout->spacing.getValue() * spacing(par);
866 //lyxerr << "spacing_val = " << spacing_val << endl;
867 int maxasc = int(font_metrics::maxAscent(font) * spacing_val);
868 int maxdesc = int(font_metrics::maxDescent(font) * spacing_val);
870 // insets may be taller
871 InsetList::const_iterator ii = par.insetlist.begin();
872 InsetList::const_iterator iend = par.insetlist.end();
873 for ( ; ii != iend; ++ii) {
874 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
875 maxasc = max(maxasc, ii->inset->ascent());
876 maxdesc = max(maxdesc, ii->inset->descent());
880 // Check if any custom fonts are larger (Asger)
881 // This is not completely correct, but we can live with the small,
882 // cosmetic error for now.
884 pos_type const pos_end = row.endpos();
886 LyXFont::FONT_SIZE maxsize =
887 par.highestFontInRange(row.pos(), pos_end, size);
888 if (maxsize > font.size()) {
889 font.setSize(maxsize);
890 maxasc = max(maxasc, font_metrics::maxAscent(font));
891 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
894 // This is nicer with box insets:
901 if (row.pos() == 0) {
902 BufferParams const & bufparams = bv()->buffer()->params();
903 // some parksips VERY EASY IMPLEMENTATION
904 if (bv()->buffer()->params().paragraph_separation
905 == BufferParams::PARSEP_SKIP
907 && ((layout->isParagraph() && par.getDepth() == 0)
908 || (pars_[pit - 1].layout()->isParagraph()
909 && pars_[pit - 1].getDepth() == 0)))
911 maxasc += bufparams.getDefSkip().inPixels(*bv());
914 if (par.params().startOfAppendix())
915 maxasc += int(3 * dh);
917 // This is special code for the chapter, since the label of this
918 // layout is printed in an extra row
919 if (layout->counter == "chapter"
920 && !par.params().labelString().empty()) {
921 labeladdon = int(font_metrics::maxHeight(labelfont)
922 * layout->spacing.getValue()
926 // special code for the top label
927 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
928 || layout->labeltype == LABEL_BIBLIO
929 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
930 && isFirstInSequence(pit, paragraphs())
931 && !par.getLabelstring().empty())
934 font_metrics::maxHeight(labelfont)
935 * layout->spacing.getValue()
937 + (layout->topsep + layout->labelbottomsep) * dh);
940 // Add the layout spaces, for example before and after
941 // a section, or between the items of a itemize or enumerate
944 pit_type prev = depthHook(pit, pars_, par.getDepth());
946 && pars_[prev].layout() == layout
947 && pars_[prev].getDepth() == par.getDepth()
948 && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
950 layoutasc = layout->itemsep * dh;
951 } else if (pit != 0 || row.pos() != 0) {
952 if (layout->topsep > 0)
953 layoutasc = layout->topsep * dh;
956 prev = outerHook(pit, pars_);
957 if (prev != pit_type(pars_.size())) {
958 maxasc += int(pars_[prev].layout()->parsep * dh);
959 } else if (pit != 0) {
960 if (pars_[pit - 1].getDepth() != 0 ||
961 pars_[pit - 1].layout() == layout) {
962 maxasc += int(layout->parsep * dh);
967 // is it a bottom line?
968 if (row.endpos() >= par.size()) {
969 // add the layout spaces, for example before and after
970 // a section, or between the items of a itemize or enumerate
972 pit_type nextpit = pit + 1;
973 if (nextpit != pit_type(pars_.size())) {
978 if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
979 usual = pars_[cpit].layout()->bottomsep * dh;
980 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
981 if (pars_[cpit].layout() != pars_[nextpit].layout()
982 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
984 unusual = pars_[cpit].layout()->bottomsep * dh;
986 layoutdesc = max(unusual, usual);
987 } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
988 if (pars_[cpit].layout() != pars_[nextpit].layout()
989 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
990 layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
995 // incalculate the layout spaces
996 maxasc += int(layoutasc * 2 / (2 + pars_[pit].getDepth()));
997 maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
999 // Top and bottom margin of the document (only at top-level)
1000 if (bv_owner->text() == this) {
1001 if (pit == 0 && row.pos() == 0)
1003 if (pit + 1 == pars_.size() && row.endpos() == par.size())
1007 row.ascent(maxasc + labeladdon);
1008 row.descent(maxdesc);
1016 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1018 BOOST_ASSERT(this == cur.text());
1019 // allow only if at start or end, or all previous is new text
1020 Paragraph & cpar = cur.paragraph();
1021 pit_type cpit = cur.pit();
1023 if (cur.pos() != 0 && cur.pos() != cur.lastpos()
1024 && cpar.isChangeEdited(0, cur.pos()))
1027 LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1028 LyXLayout_ptr const & layout = cpar.layout();
1030 // this is only allowed, if the current paragraph is not empty
1031 // or caption and if it has not the keepempty flag active
1032 if (cur.lastpos() == 0 && !cpar.allowEmpty()
1033 && layout->labeltype != LABEL_SENSITIVE)
1036 // a layout change may affect also the following paragraph
1037 recUndo(cur.pit(), undoSpan(cur.pit()) - 1);
1039 // Always break behind a space
1040 // It is better to erase the space (Dekel)
1041 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1042 cpar.erase(cur.pos());
1044 // How should the layout for the new paragraph be?
1045 int preserve_layout = 0;
1047 preserve_layout = 2;
1049 preserve_layout = layout->isEnvironment();
1051 // We need to remember this before we break the paragraph, because
1052 // that invalidates the layout variable
1053 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1055 // we need to set this before we insert the paragraph.
1056 bool const isempty = cpar.allowEmpty() && cpar.empty();
1058 ::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1059 cur.pos(), preserve_layout);
1061 // After this, neither paragraph contains any rows!
1064 pit_type next_par = cpit + 1;
1066 // well this is the caption hack since one caption is really enough
1069 // set to standard-layout
1070 pars_[cpit].applyLayout(tclass.defaultLayout());
1072 // set to standard-layout
1073 pars_[next_par].applyLayout(tclass.defaultLayout());
1076 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1077 pars_[next_par].erase(0);
1079 updateCounters(cur.buffer());
1081 // This check is necessary. Otherwise the new empty paragraph will
1082 // be deleted automatically. And it is more friendly for the user!
1083 if (cur.pos() != 0 || isempty)
1084 setCursor(cur, cur.pit() + 1, 0);
1086 setCursor(cur, cur.pit(), 0);
1090 // insert a character, moves all the following breaks in the
1091 // same Paragraph one to the right and make a rebreak
1092 void LyXText::insertChar(LCursor & cur, char c)
1094 BOOST_ASSERT(this == cur.text());
1095 BOOST_ASSERT(c != Paragraph::META_INSET);
1097 recordUndo(cur, Undo::INSERT);
1099 Paragraph & par = cur.paragraph();
1100 // try to remove this
1101 pit_type const pit = cur.pit();
1103 bool const freeSpacing = par.layout()->free_spacing ||
1104 par.isFreeSpacing();
1106 if (lyxrc.auto_number) {
1107 static string const number_operators = "+-/*";
1108 static string const number_unary_operators = "+-";
1109 static string const number_seperators = ".,:";
1111 if (current_font.number() == LyXFont::ON) {
1112 if (!IsDigit(c) && !contains(number_operators, c) &&
1113 !(contains(number_seperators, c) &&
1115 cur.pos() != cur.lastpos() &&
1116 getFont(par, cur.pos()).number() == LyXFont::ON &&
1117 getFont(par, cur.pos() - 1).number() == LyXFont::ON)
1119 number(cur); // Set current_font.number to OFF
1120 } else if (IsDigit(c) &&
1121 real_current_font.isVisibleRightToLeft()) {
1122 number(cur); // Set current_font.number to ON
1124 if (cur.pos() != 0) {
1125 char const c = par.getChar(cur.pos() - 1);
1126 if (contains(number_unary_operators, c) &&
1128 || par.isSeparator(cur.pos() - 2)
1129 || par.isNewline(cur.pos() - 2))
1131 setCharFont(pit, cur.pos() - 1, current_font);
1132 } else if (contains(number_seperators, c)
1134 && getFont(par, cur.pos() - 2).number() == LyXFont::ON) {
1135 setCharFont(pit, cur.pos() - 1, current_font);
1141 // First check, if there will be two blanks together or a blank at
1142 // the beginning of a paragraph.
1143 // I decided to handle blanks like normal characters, the main
1144 // difference are the special checks when calculating the row.fill
1145 // (blank does not count at the end of a row) and the check here
1147 // The bug is triggered when we type in a description environment:
1148 // The current_font is not changed when we go from label to main text
1149 // and it should (along with realtmpfont) when we type the space.
1150 // CHECK There is a bug here! (Asger)
1152 // store the current font. This is because of the use of cursor
1153 // movements. The moving cursor would refresh the current font
1154 LyXFont realtmpfont = real_current_font;
1155 LyXFont rawtmpfont = current_font;
1157 // When the free-spacing option is set for the current layout,
1158 // disable the double-space checking
1159 if (!freeSpacing && IsLineSeparatorChar(c)) {
1160 if (cur.pos() == 0) {
1161 static bool sent_space_message = false;
1162 if (!sent_space_message) {
1163 cur.message(_("You cannot insert a space at the "
1164 "beginning of a paragraph. Please read the Tutorial."));
1165 sent_space_message = true;
1169 BOOST_ASSERT(cur.pos() > 0);
1170 if ((par.isLineSeparator(cur.pos() - 1)
1171 || par.isNewline(cur.pos() - 1))
1172 && par.lookupChange(cur.pos() - 1) != Change::DELETED) {
1173 static bool sent_space_message = false;
1174 if (!sent_space_message) {
1175 cur.message(_("You cannot type two spaces this way. "
1176 "Please read the Tutorial."));
1177 sent_space_message = true;
1183 par.insertChar(cur.pos(), c, rawtmpfont);
1185 current_font = rawtmpfont;
1186 real_current_font = realtmpfont;
1187 //setCursor(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1188 setCursor(cur, cur.pit(), cur.pos() + 1, false, true);
1193 void LyXText::charInserted()
1195 // Here we call finishUndo for every 20 characters inserted.
1196 // This is from my experience how emacs does it. (Lgb)
1197 static unsigned int counter;
1208 LyXText::computeRowMetrics(pit_type const pit, Row const & row) const
1211 Paragraph const & par = pars_[pit];
1213 double w = dim_.wid - row.width();
1215 bool const is_rtl = isRTL(par);
1217 result.x = rightMargin(par);
1219 result.x = leftMargin(pit, row.pos());
1221 // is there a manual margin with a manual label
1222 LyXLayout_ptr const & layout = par.layout();
1224 if (layout->margintype == MARGIN_MANUAL
1225 && layout->labeltype == LABEL_MANUAL) {
1226 /// We might have real hfills in the label part
1227 int nlh = numberOfLabelHfills(par, row);
1229 // A manual label par (e.g. List) has an auto-hfill
1230 // between the label text and the body of the
1232 // But we don't want to do this auto hfill if the par
1237 if (nlh && !par.getLabelWidthString().empty())
1238 result.label_hfill = labelFill(par, row) / double(nlh);
1241 // are there any hfills in the row?
1242 int const nh = numberOfHfills(par, row);
1246 result.hfill = w / nh;
1247 // we don't have to look at the alignment if it is ALIGN_LEFT and
1248 // if the row is already larger then the permitted width as then
1249 // we force the LEFT_ALIGN'edness!
1250 } else if (int(row.width()) < maxwidth_) {
1251 // is it block, flushleft or flushright?
1252 // set x how you need it
1254 if (par.params().align() == LYX_ALIGN_LAYOUT)
1255 align = layout->align;
1257 align = par.params().align();
1259 // Display-style insets should always be on a centred row
1260 // The test on par.size() is to catch zero-size pars, which
1261 // would trigger the assert in Paragraph::getInset().
1262 //inset = par.size() ? par.getInset(row.pos()) : 0;
1264 && par.isInset(row.pos())
1265 && par.getInset(row.pos())->display())
1267 align = LYX_ALIGN_CENTER;
1271 case LYX_ALIGN_BLOCK: {
1272 int const ns = numberOfSeparators(par, row);
1273 bool disp_inset = false;
1274 if (row.endpos() < par.size()) {
1275 InsetBase const * in = par.getInset(row.endpos());
1277 disp_inset = in->display();
1279 // If we have separators, this is not the last row of a
1280 // par, does not end in newline, and is not row above a
1281 // display inset... then stretch it
1283 && row.endpos() < par.size()
1284 && !par.isNewline(row.endpos() - 1)
1287 result.separator = w / ns;
1288 } else if (is_rtl) {
1293 case LYX_ALIGN_RIGHT:
1296 case LYX_ALIGN_CENTER:
1302 bidi.computeTables(par, *bv()->buffer(), row);
1304 pos_type body_pos = par.beginOfBody();
1305 pos_type end = row.endpos();
1308 && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1310 result.x += font_metrics::width(layout->labelsep, getLabelFont(par));
1311 if (body_pos <= end)
1312 result.x += result.label_hfill;
1320 // the cursor set functions have a special mechanism. When they
1321 // realize, that you left an empty paragraph, they will delete it.
1323 bool LyXText::cursorRightOneWord(LCursor & cur)
1325 BOOST_ASSERT(this == cur.text());
1329 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1333 // Skip through initial nonword stuff.
1334 // Treat floats and insets as words.
1335 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1337 // Advance through word.
1338 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1341 return setCursor(cur, old.pit(), old.pos());
1345 bool LyXText::cursorLeftOneWord(LCursor & cur)
1347 BOOST_ASSERT(this == cur.text());
1351 if (old.pos() == 0 && old.pit() != 0) {
1353 old.pos() = old.lastpos();
1355 // Skip through initial nonword stuff.
1356 // Treat floats and insets as words.
1357 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
1359 // Advance through word.
1360 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
1363 return setCursor(cur, old.pit(), old.pos());
1367 void LyXText::selectWord(LCursor & cur, word_location loc)
1369 BOOST_ASSERT(this == cur.text());
1370 CursorSlice from = cur.top();
1371 CursorSlice to = cur.top();
1372 getWord(from, to, loc);
1373 if (cur.top() != from)
1374 setCursor(cur, from.pit(), from.pos());
1378 setCursor(cur, to.pit(), to.pos());
1383 // Select the word currently under the cursor when no
1384 // selection is currently set
1385 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1387 BOOST_ASSERT(this == cur.text());
1388 if (cur.selection())
1390 selectWord(cur, loc);
1391 return cur.selection();
1395 void LyXText::acceptChange(LCursor & cur)
1397 BOOST_ASSERT(this == cur.text());
1398 if (!cur.selection() && cur.lastpos() != 0)
1401 CursorSlice const & startc = cur.selBegin();
1402 CursorSlice const & endc = cur.selEnd();
1403 if (startc.pit() == endc.pit()) {
1404 recordUndoSelection(cur, Undo::INSERT);
1405 pars_[startc.pit()].acceptChange(startc.pos(), endc.pos());
1407 cur.clearSelection();
1408 setCursorIntern(cur, startc.pit(), 0);
1410 #ifdef WITH_WARNINGS
1411 #warning handle multi par selection
1416 void LyXText::rejectChange(LCursor & cur)
1418 BOOST_ASSERT(this == cur.text());
1419 if (!cur.selection() && cur.lastpos() != 0)
1422 CursorSlice const & startc = cur.selBegin();
1423 CursorSlice const & endc = cur.selEnd();
1424 if (startc.pit() == endc.pit()) {
1425 recordUndoSelection(cur, Undo::INSERT);
1426 pars_[startc.pit()].rejectChange(startc.pos(), endc.pos());
1428 cur.clearSelection();
1429 setCursorIntern(cur, startc.pit(), 0);
1431 #ifdef WITH_WARNINGS
1432 #warning handle multi par selection
1437 // Delete from cursor up to the end of the current or next word.
1438 void LyXText::deleteWordForward(LCursor & cur)
1440 BOOST_ASSERT(this == cur.text());
1441 if (cur.lastpos() == 0)
1445 cur.selection() = true;
1446 cursorRightOneWord(cur);
1448 cutSelection(cur, true, false);
1453 // Delete from cursor to start of current or prior word.
1454 void LyXText::deleteWordBackward(LCursor & cur)
1456 BOOST_ASSERT(this == cur.text());
1457 if (cur.lastpos() == 0)
1461 cur.selection() = true;
1462 cursorLeftOneWord(cur);
1464 cutSelection(cur, true, false);
1469 // Kill to end of line.
1470 void LyXText::deleteLineForward(LCursor & cur)
1472 BOOST_ASSERT(this == cur.text());
1473 if (cur.lastpos() == 0) {
1474 // Paragraph is empty, so we just go to the right
1478 cur.selection() = true; // to avoid deletion
1481 // What is this test for ??? (JMarc)
1482 if (!cur.selection())
1483 deleteWordForward(cur);
1485 cutSelection(cur, true, false);
1490 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1492 BOOST_ASSERT(this == cur.text());
1496 if (cur.selection()) {
1497 from = cur.selBegin();
1501 getWord(from, to, lyx::PARTIAL_WORD);
1502 setCursor(cur, to.pit(), to.pos() + 1);
1505 recordUndoSelection(cur);
1507 pos_type pos = from.pos();
1508 int par = from.pit();
1510 while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1512 if (pos == pars_[pit].size()) {
1517 unsigned char c = pars_[pit].getChar(pos);
1518 if (c != Paragraph::META_INSET) {
1520 case text_lowercase:
1523 case text_capitalization:
1525 action = text_lowercase;
1527 case text_uppercase:
1532 #ifdef WITH_WARNINGS
1535 pars_[pit].setChar(pos, c);
1541 void LyXText::Delete(LCursor & cur)
1543 BOOST_ASSERT(this == cur.text());
1545 if (cur.pos() != cur.lastpos()) {
1546 recordUndo(cur, Undo::DELETE, cur.pit());
1547 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1549 } else if (cur.pit() != cur.lastpit()) {
1552 setCursorIntern(cur, cur.pit()+1, 0, false, false);
1553 if (pars_[cur.pit()].layout() == pars_[scur.pit()].layout()) {
1554 recordUndo(scur, Undo::DELETE, scur.pit());
1557 setCursorIntern(scur, scur.pit(), scur.pos(), false, scur.boundary());
1563 void LyXText::backspace(LCursor & cur)
1565 BOOST_ASSERT(this == cur.text());
1566 if (cur.pos() == 0) {
1567 // The cursor is at the beginning of a paragraph, so
1568 // the the backspace will collapse two paragraphs into
1571 // but it's not allowed unless it's new
1572 Paragraph & par = cur.paragraph();
1573 if (par.isChangeEdited(0, par.size()))
1576 // we may paste some paragraphs
1578 // is it an empty paragraph?
1579 pos_type lastpos = cur.lastpos();
1580 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1581 // This is an empty paragraph and we delete it just
1582 // by moving the cursor one step
1583 // left and let the DeleteEmptyParagraphMechanism
1584 // handle the actual deletion of the paragraph.
1586 if (cur.pit() != 0) {
1587 // For KeepEmpty layouts we need to get
1588 // rid of the keepEmpty setting first.
1589 // And the only way to do this is to
1590 // reset the layout to something
1591 // else: f.ex. the default layout.
1592 if (par.allowEmpty()) {
1593 Buffer & buf = cur.buffer();
1594 BufferParams const & bparams = buf.params();
1595 par.layout(bparams.getLyXTextClass().defaultLayout());
1604 recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1606 pit_type tmppit = cur.pit();
1607 // We used to do cursorLeftIntern() here, but it is
1608 // not a good idea since it triggers the auto-delete
1609 // mechanism. So we do a cursorLeftIntern()-lite,
1610 // without the dreaded mechanism. (JMarc)
1611 if (cur.pit() != 0) {
1612 // steps into the above paragraph.
1613 setCursorIntern(cur, cur.pit() - 1,
1614 pars_[cur.pit() - 1].size(),
1618 // Pasting is not allowed, if the paragraphs have different
1619 // layout. I think it is a real bug of all other
1620 // word processors to allow it. It confuses the user.
1621 // Correction: Pasting is always allowed with standard-layout
1622 // Correction (Jug 20050717): Remove check about alignment!
1623 Buffer & buf = cur.buffer();
1624 BufferParams const & bufparams = buf.params();
1625 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1626 pit_type const cpit = cur.pit();
1629 && (pars_[cpit].layout() == pars_[tmppit].layout()
1630 || pars_[tmppit].layout() == tclass.defaultLayout()))
1632 mergeParagraph(bufparams, pars_, cpit);
1634 if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1637 // the counters may have changed
1638 updateCounters(cur.buffer());
1639 setCursor(cur, cur.pit(), cur.pos(), false);
1642 // this is the code for a normal backspace, not pasting
1644 recordUndo(cur, Undo::DELETE);
1645 // We used to do cursorLeftIntern() here, but it is
1646 // not a good idea since it triggers the auto-delete
1647 // mechanism. So we do a cursorLeftIntern()-lite,
1648 // without the dreaded mechanism. (JMarc)
1649 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1650 false, cur.boundary());
1651 cur.paragraph().erase(cur.pos());
1654 if (cur.pos() == cur.lastpos())
1655 setCurrentFont(cur);
1657 setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1661 Row const & LyXText::firstRow() const
1663 return *paragraphs().front().rows().begin();
1667 bool LyXText::redoParagraph(pit_type const pit)
1669 // remove rows of paragraph, keep track of height changes
1670 Paragraph & par = pars_[pit];
1672 // Add bibitem insets if necessary
1673 if (par.layout()->labeltype == LABEL_BIBLIO) {
1674 bool hasbibitem(false);
1675 if (!par.insetlist.empty()
1676 // Insist on it being in pos 0
1677 && par.getChar(0) == Paragraph::META_INSET) {
1678 InsetBase * inset = par.insetlist.begin()->inset;
1679 if (inset->lyxCode() == InsetBase::BIBITEM_CODE)
1683 InsetBibitem * inset(new
1684 InsetBibitem(InsetCommandParams("bibitem")));
1685 par.insertInset(0, static_cast<InsetBase *>(inset));
1686 bv()->cursor().posRight();
1691 InsetList::iterator ii = par.insetlist.begin();
1692 InsetList::iterator iend = par.insetlist.end();
1693 for (; ii != iend; ++ii) {
1695 int const w = maxwidth_ - leftMargin(pit) - rightMargin(par);
1696 MetricsInfo mi(bv(), getFont(par, ii->pos), w);
1697 ii->inset->metrics(mi, dim);
1700 // rebreak the paragraph
1704 par.setBeginOfBody();
1708 rowBreakPoint(pit, row);
1709 setRowWidth(pit, row);
1710 setHeightOfRow(pit, row);
1711 par.rows().push_back(row);
1712 dim.wid = std::max(dim.wid, row.width());
1713 dim.des += row.height();
1715 } while (z < par.size());
1717 dim.asc += par.rows()[0].ascent();
1718 dim.des -= par.rows()[0].ascent();
1720 bool const same = dim == par.dim();
1723 //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1729 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1731 //BOOST_ASSERT(mi.base.textwidth);
1732 if (mi.base.textwidth)
1733 maxwidth_ = mi.base.textwidth;
1734 //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1735 // << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1736 // save the caller's font locally:
1737 font_ = mi.base.font;
1741 for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1743 Paragraph & par = paragraphs()[pit];
1745 if (w < par.width())
1750 dim.asc = pars_[0].ascent();
1751 dim.des = h - dim.asc;
1757 // only used for inset right now. should also be used for main text
1758 void LyXText::draw(PainterInfo & pi, int x, int y) const
1760 paintTextInset(*this, pi, x, y);
1765 // only used for inset right now. should also be used for main text
1766 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1768 LCursor & cur = pi.base.bv->cursor();
1769 if (!cur.selection())
1771 if (!ptr_cmp(cur.text(), this))
1774 lyxerr << "draw selection at " << x << endl;
1776 // is there a better way of getting these two iterators?
1777 DocIterator beg = cur;
1778 DocIterator end = cur;
1780 beg.top() = cur.selBegin();
1781 end.top() = cur.selEnd();
1783 // the selection doesn't touch the visible screen
1784 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1785 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1788 Paragraph const & par1 = pars_[beg.pit()];
1789 Paragraph const & par2 = pars_[end.pit()];
1791 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1792 Row const & row2 = par2.getRow(end.pos(), end.boundary());
1795 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1800 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1801 int const startx = cursorX(beg.top(), begin.boundary());
1802 x1 = isRTL(par1) ? startx : 0;
1803 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
1807 if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
1808 y2 = pi.base.bv->workHeight();
1812 y2 = bv_funcs::getPos(end).y_ + row2.descent();
1813 int const endx = cursorX(end.top(), end.boundary());
1814 X1 = isRTL(par2) ? 0 : endx;
1815 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
1818 lyxerr << " y1: " << y1 << " y2: " << y2
1819 << " xo: " << xo_ << " wid: " << dim_.wid
1822 // paint big rectangle in one go
1823 pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
1825 // reset background at begin of first selected line
1826 pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
1827 LColor::background);
1829 // reset background at end of last selected line
1830 pi.pain.fillRectangle(x + X1, y2 - row2.height(),
1831 X2 - X1, row2.height(), LColor::background);
1836 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
1838 LCursor & cur = pi.base.bv->cursor();
1839 if (!cur.selection())
1841 if (!ptr_cmp(cur.text(), this))
1844 lyxerr[Debug::DEBUG]
1845 << BOOST_CURRENT_FUNCTION
1846 << "draw selection at " << x
1849 // is there a better way of getting these two iterators?
1850 DocIterator beg = cur;
1851 DocIterator end = cur;
1853 beg.top() = cur.selBegin();
1854 end.top() = cur.selEnd();
1856 // the selection doesn't touch the visible screen
1857 if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1858 || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1861 Paragraph const & par1 = pars_[beg.pit()];
1862 Paragraph const & par2 = pars_[end.pit()];
1864 bool const above = (bv_funcs::status(pi.base.bv, beg)
1865 == bv_funcs::CUR_ABOVE);
1866 bool const below = (bv_funcs::status(pi.base.bv, end)
1867 == bv_funcs::CUR_BELOW);
1875 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1876 y1 = bv_funcs::getPos(beg, beg.boundary()).y_ - row1.ascent();
1877 y2 = y1 + row1.height();
1878 int const startx = cursorX(beg.top(), beg.boundary());
1879 x1 = !isRTL(par1) ? startx : 0;
1880 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
1885 Y1 = pi.base.bv->workHeight();
1886 Y2 = pi.base.bv->workHeight();
1890 Row const & row2 = par2.getRow(end.pos(), end.boundary());
1891 Y1 = bv_funcs::getPos(end, end.boundary()).y_ - row2.ascent();
1892 Y2 = Y1 + row2.height();
1893 int const endx = cursorX(end.top(), end.boundary());
1894 X1 = !isRTL(par2) ? 0 : endx;
1895 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
1898 if (!above && !below && &par1.getRow(beg.pos(), beg.boundary())
1899 == &par2.getRow(end.pos(), end.boundary()))
1901 // paint only one rectangle
1902 int const b( !isRTL(par1) ? x + x1 : x + X1 );
1903 int const w( !isRTL(par1) ? X2 - x1 : x2 - X1 );
1904 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
1908 lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
1909 << "X1:" << X1 << " x2: " << X2 << " wid: " << dim_.wid
1912 // paint upper rectangle
1913 pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
1915 // paint bottom rectangle
1916 pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
1918 // paint center rectangle
1919 pi.pain.fillRectangle(x, y2, dim_.wid,
1920 Y1 - y2, LColor::selection);
1924 bool LyXText::isLastRow(pit_type pit, Row const & row) const
1926 return row.endpos() >= pars_[pit].size()
1927 && pit + 1 == pit_type(paragraphs().size());
1931 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
1933 return row.pos() == 0 && pit == 0;
1937 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1938 word_location const loc)
1940 Paragraph const & from_par = pars_[from.pit()];
1942 case lyx::WHOLE_WORD_STRICT:
1943 if (from.pos() == 0 || from.pos() == from_par.size()
1944 || !from_par.isLetter(from.pos())
1945 || !from_par.isLetter(from.pos() - 1)) {
1949 // no break here, we go to the next
1951 case lyx::WHOLE_WORD:
1952 // If we are already at the beginning of a word, do nothing
1953 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1955 // no break here, we go to the next
1957 case lyx::PREVIOUS_WORD:
1958 // always move the cursor to the beginning of previous word
1959 while (from.pos() && from_par.isLetter(from.pos() - 1))
1962 case lyx::NEXT_WORD:
1963 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1966 case lyx::PARTIAL_WORD:
1967 // no need to move the 'from' cursor
1971 Paragraph & to_par = pars_[to.pit()];
1972 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1977 void LyXText::write(Buffer const & buf, std::ostream & os) const
1979 ParagraphList::const_iterator pit = paragraphs().begin();
1980 ParagraphList::const_iterator end = paragraphs().end();
1981 Paragraph::depth_type dth = 0;
1982 for (; pit != end; ++pit)
1983 pit->write(buf, os, buf.params(), dth);
1987 bool LyXText::read(Buffer const & buf, LyXLex & lex)
1989 Paragraph::depth_type depth = 0;
1991 while (lex.isOK()) {
1993 string const token = lex.getString();
1998 if (token == "\\end_inset") {
2002 if (token == "\\end_body") {
2006 if (token == "\\begin_body") {
2010 if (token == "\\end_document") {
2014 if (token == "\\begin_layout") {
2015 lex.pushToken(token);
2018 par.params().depth(depth);
2019 if (buf.params().tracking_changes)
2021 par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
2022 pars_.push_back(par);
2024 // FIXME: goddamn InsetTabular makes us pass a Buffer
2026 ::readParagraph(buf, pars_.back(), lex);
2028 } else if (token == "\\begin_deeper") {
2030 } else if (token == "\\end_deeper") {
2032 lex.printError("\\end_deeper: " "depth is already null");
2037 lyxerr << "Handling unknown body token: `"
2038 << token << '\'' << endl;
2045 int LyXText::ascent() const
2051 int LyXText::descent() const
2057 int LyXText::cursorX(CursorSlice const & sl, bool boundary) const
2059 pit_type const pit = sl.pit();
2060 Paragraph const & par = pars_[pit];
2061 if (par.rows().empty())
2064 pos_type ppos = sl.pos();
2065 // Correct position in front of big insets
2066 bool const boundary_correction = ppos != 0 && boundary;
2067 if (boundary_correction)
2070 Row const & row = par.getRow(sl.pos(), boundary);
2072 pos_type cursor_vpos = 0;
2074 RowMetrics const m = computeRowMetrics(pit, row);
2077 pos_type const row_pos = row.pos();
2078 pos_type const end = row.endpos();
2081 cursor_vpos = row_pos;
2082 else if (ppos >= end)
2083 cursor_vpos = isRTL(par) ? row_pos : end;
2084 else if (ppos > row_pos && ppos >= end)
2085 // Place cursor after char at (logical) position pos - 1
2086 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
2087 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
2089 // Place cursor before char at (logical) position ppos
2090 cursor_vpos = (bidi.level(ppos) % 2 == 0)
2091 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
2093 pos_type body_pos = par.beginOfBody();
2095 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2098 // Use font span to speed things up, see below
2102 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2103 pos_type pos = bidi.vis2log(vpos);
2104 if (body_pos > 0 && pos == body_pos - 1) {
2106 + font_metrics::width(par.layout()->labelsep,
2108 if (par.isLineSeparator(body_pos - 1))
2109 x -= singleWidth(par, body_pos - 1);
2112 // Use font span to speed things up, see above
2113 if (pos < font_span.first || pos > font_span.last) {
2114 font_span = par.fontSpan(pos);
2115 font = getFont(par, pos);
2118 x += singleWidth(par, pos, par.getChar(pos), font);
2120 if (hfillExpansion(par, row, pos))
2121 x += (pos >= body_pos) ? m.hfill : m.label_hfill;
2122 else if (par.isSeparator(pos) && pos >= body_pos)
2126 // see correction above
2127 if (boundary_correction)
2128 if (getFont(par, ppos).isRightToLeft())
2129 x -= singleWidth(par, ppos);
2131 x += singleWidth(par, ppos);
2137 int LyXText::cursorY(CursorSlice const & sl, bool boundary) const
2139 //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
2140 Paragraph const & par = getPar(sl.pit());
2142 h -= pars_[0].rows()[0].ascent();
2143 for (pit_type pit = 0; pit < sl.pit(); ++pit)
2144 h += pars_[pit].height();
2146 if (pos && boundary)
2148 size_t const rend = par.pos2row(pos);
2149 for (size_t rit = 0; rit != rend; ++rit)
2150 h += par.rows()[rit].height();
2151 h += par.rows()[rend].ascent();
2156 // Returns the current font and depth as a message.
2157 string LyXText::currentState(LCursor & cur)
2159 BOOST_ASSERT(this == cur.text());
2160 Buffer & buf = cur.buffer();
2161 Paragraph const & par = cur.paragraph();
2162 std::ostringstream os;
2164 bool const show_change = buf.params().tracking_changes
2165 && cur.pos() != cur.lastpos()
2166 && par.lookupChange(cur.pos()) != Change::UNCHANGED;
2169 Change change = par.lookupChangeFull(cur.pos());
2170 Author const & a = buf.params().authors().get(change.author);
2171 os << _("Change: ") << a.name();
2172 if (!a.email().empty())
2173 os << " (" << a.email() << ")";
2174 if (change.changetime)
2175 os << _(" at ") << ctime(&change.changetime);
2179 // I think we should only show changes from the default
2181 LyXFont font = real_current_font;
2182 font.reduce(buf.params().getLyXTextClass().defaultfont());
2184 // avoid _(...) re-entrance problem
2185 string const s = font.stateText(&buf.params());
2186 os << bformat(_("Font: %1$s"), s);
2188 // os << bformat(_("Font: %1$s"), font.stateText(&buf.params));
2190 // The paragraph depth
2191 int depth = cur.paragraph().getDepth();
2193 os << bformat(_(", Depth: %1$d"), depth);
2195 // The paragraph spacing, but only if different from
2197 Spacing const & spacing = par.params().spacing();
2198 if (!spacing.isDefault()) {
2199 os << _(", Spacing: ");
2200 switch (spacing.getSpace()) {
2201 case Spacing::Single:
2204 case Spacing::Onehalf:
2207 case Spacing::Double:
2210 case Spacing::Other:
2211 os << _("Other (") << spacing.getValueAsString() << ')';
2213 case Spacing::Default:
2214 // should never happen, do nothing
2219 #ifdef DEVEL_VERSION
2220 os << _(", Inset: ") << &cur.inset();
2221 os << _(", Paragraph: ") << cur.pit();
2222 os << _(", Id: ") << par.id();
2223 os << _(", Position: ") << cur.pos();
2224 os << _(", Boundary: ") << cur.boundary();
2225 // Row & row = cur.textRow();
2226 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2232 string LyXText::getPossibleLabel(LCursor & cur) const
2234 pit_type pit = cur.pit();
2236 LyXLayout_ptr layout = pars_[pit].layout();
2238 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2239 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2240 if (layout2->latextype != LATEX_PARAGRAPH) {
2246 string text = layout->latexname().substr(0, 3);
2247 if (layout->latexname() == "theorem")
2248 text = "thm"; // Create a correct prefix for prettyref
2251 if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2254 string par_text = pars_[pit].asString(cur.buffer(), false);
2255 for (int i = 0; i < lyxrc.label_init_length; ++i) {
2256 if (par_text.empty())
2259 par_text = split(par_text, head, ' ');
2260 // Is it legal to use spaces in labels ?
2270 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2274 // Paragraph const & par = pars_[pit];
2275 // Row const & r = par.rows()[row];
2276 // int pos = r.pos();
2277 // for (; currx < x && pos < r.endpos(); ++pos) {
2279 // currx += singleWidth(par, pos);
2281 // if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2287 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2289 BOOST_ASSERT(row < int(pars_[pit].rows().size()));
2291 Row const & r = pars_[pit].rows()[row];
2292 return r.pos() + getColumnNearX(pit, r, x, bound);
2296 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2298 // Paragraph const & par = pars_[pit];
2299 // Row const & r = par.rows()[row];
2305 // x,y are screen coordinates
2306 // sets cursor only within this LyXText
2307 void LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2309 pit_type pit = getPitNearY(y);
2310 int yy = theCoords.get(this, pit).y_ - pars_[pit].ascent();
2311 lyxerr[Debug::DEBUG]
2312 << BOOST_CURRENT_FUNCTION
2316 << " yy: " << yy << endl;
2318 Paragraph const & par = pars_[pit];
2320 BOOST_ASSERT(par.rows().size());
2321 for (; r < int(par.rows().size()) - 1; ++r) {
2322 Row const & row = par.rows()[r];
2323 if (int(yy + row.height()) > y)
2328 Row const & row = par.rows()[r];
2330 lyxerr[Debug::DEBUG]
2331 << BOOST_CURRENT_FUNCTION
2333 << " from pos: " << row.pos()
2338 pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2340 lyxerr[Debug::DEBUG]
2341 << BOOST_CURRENT_FUNCTION
2342 << ": setting cursor pit: " << pit
2346 setCursor(cur, pit, pos, true, bound);