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"
26 #include "bufferview_funcs.h"
28 #include "pariterator.h"
29 #include "coordcache.h"
30 #include "CutAndPaste.h"
32 #include "dispatchresult.h"
34 #include "errorlist.h"
35 #include "funcrequest.h"
37 #include "FontIterator.h"
41 #include "lyxlength.h"
45 #include "metricsinfo.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "rowpainter.h"
52 #include "WordLangTuple.h"
54 #include "frontends/FontMetrics.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"
73 #include <boost/current_function.hpp>
87 using support::bformat;
88 using support::contains;
89 using support::lowercase;
91 using support::uppercase;
93 using cap::cutSelection;
94 using cap::pasteParagraphList;
96 using frontend::FontMetrics;
100 int numberOfSeparators(Paragraph const & par, Row const & row)
102 pos_type const first = max(row.pos(), par.beginOfBody());
103 pos_type const last = row.endpos() - 1;
105 for (pos_type p = first; p < last; ++p) {
106 if (par.isSeparator(p))
113 int numberOfLabelHfills(Paragraph const & par, Row const & row)
115 pos_type last = row.endpos() - 1;
116 pos_type first = row.pos();
118 // hfill *DO* count at the beginning of paragraphs!
120 while (first < last && par.isHfill(first))
124 last = min(last, par.beginOfBody());
126 for (pos_type p = first; p < last; ++p) {
134 int numberOfHfills(Paragraph const & par, Row const & row)
136 pos_type const last = row.endpos();
137 pos_type first = row.pos();
139 // hfill *DO* count at the beginning of paragraphs!
141 while (first < last && par.isHfill(first))
145 first = max(first, par.beginOfBody());
148 for (pos_type p = first; p < last; ++p) {
156 void readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
157 string const & token, LyXFont & font, Change & change, ErrorList & errorList)
159 BufferParams const & bp = buf.params();
161 if (token[0] != '\\') {
163 string::const_iterator cit = token.begin();
164 for (; cit != token.end(); ++cit)
165 par.insertChar(par.size(), (*cit), font, change);
167 docstring dstr = lex.getDocString();
168 docstring::const_iterator cit = dstr.begin();
169 docstring::const_iterator cend = dstr.end();
170 for (; cit != cend; ++cit)
171 par.insertChar(par.size(), *cit, font, change);
173 } else if (token == "\\begin_layout") {
175 string layoutname = lex.getString();
177 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
178 change = Change(Change::UNCHANGED);
180 LyXTextClass const & tclass = bp.getLyXTextClass();
182 if (layoutname.empty()) {
183 layoutname = tclass.defaultLayoutName();
186 bool hasLayout = tclass.hasLayout(layoutname);
189 errorList.push_back(ErrorItem(_("Unknown layout"),
190 bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
191 from_utf8(layoutname), from_utf8(tclass.name())), par.id(), 0, par.size()));
192 layoutname = tclass.defaultLayoutName();
195 par.layout(bp.getLyXTextClass()[layoutname]);
197 // Test whether the layout is obsolete.
198 LyXLayout_ptr const & layout = par.layout();
199 if (!layout->obsoleted_by().empty())
200 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
202 par.params().read(lex);
204 } else if (token == "\\end_layout") {
205 lyxerr << BOOST_CURRENT_FUNCTION
206 << ": Solitary \\end_layout in line "
207 << lex.getLineNo() << "\n"
208 << "Missing \\begin_layout?.\n";
209 } else if (token == "\\end_inset") {
210 lyxerr << BOOST_CURRENT_FUNCTION
211 << ": Solitary \\end_inset in line "
212 << lex.getLineNo() << "\n"
213 << "Missing \\begin_inset?.\n";
214 } else if (token == "\\begin_inset") {
215 InsetBase * inset = readInset(lex, buf);
217 par.insertInset(par.size(), inset, font, change);
220 docstring line = lex.getDocString();
221 errorList.push_back(ErrorItem(_("Unknown Inset"), line,
222 par.id(), 0, par.size()));
224 } else if (token == "\\family") {
226 font.setLyXFamily(lex.getString());
227 } else if (token == "\\series") {
229 font.setLyXSeries(lex.getString());
230 } else if (token == "\\shape") {
232 font.setLyXShape(lex.getString());
233 } else if (token == "\\size") {
235 font.setLyXSize(lex.getString());
236 } else if (token == "\\lang") {
238 string const tok = lex.getString();
239 Language const * lang = languages.getLanguage(tok);
241 font.setLanguage(lang);
243 font.setLanguage(bp.language);
244 lex.printError("Unknown language `$$Token'");
246 } else if (token == "\\numeric") {
248 font.setNumber(font.setLyXMisc(lex.getString()));
249 } else if (token == "\\emph") {
251 font.setEmph(font.setLyXMisc(lex.getString()));
252 } else if (token == "\\bar") {
254 string const tok = lex.getString();
257 font.setUnderbar(LyXFont::ON);
258 else if (tok == "no")
259 font.setUnderbar(LyXFont::OFF);
260 else if (tok == "default")
261 font.setUnderbar(LyXFont::INHERIT);
263 lex.printError("Unknown bar font flag "
265 } else if (token == "\\noun") {
267 font.setNoun(font.setLyXMisc(lex.getString()));
268 } else if (token == "\\color") {
270 font.setLyXColor(lex.getString());
271 } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
273 // Insets don't make sense in a free-spacing context! ---Kayvan
274 if (par.isFreeSpacing()) {
275 if (token == "\\InsetSpace")
276 par.insertChar(par.size(), ' ', font, change);
277 else if (lex.isOK()) {
279 string const next_token = lex.getString();
280 if (next_token == "\\-")
281 par.insertChar(par.size(), '-', font, change);
283 lex.printError("Token `$$Token' "
285 "paragraph layout!");
289 auto_ptr<InsetBase> inset;
290 if (token == "\\SpecialChar" )
291 inset.reset(new InsetSpecialChar);
293 inset.reset(new InsetSpace);
294 inset->read(buf, lex);
295 par.insertInset(par.size(), inset.release(),
298 } else if (token == "\\i") {
299 auto_ptr<InsetBase> inset(new InsetLatexAccent);
300 inset->read(buf, lex);
301 par.insertInset(par.size(), inset.release(), font, change);
302 } else if (token == "\\backslash") {
303 par.insertChar(par.size(), '\\', font, change);
304 } else if (token == "\\newline") {
305 auto_ptr<InsetBase> inset(new InsetNewline);
306 inset->read(buf, lex);
307 par.insertInset(par.size(), inset.release(), font, change);
308 } else if (token == "\\LyXTable") {
309 auto_ptr<InsetBase> inset(new InsetTabular(buf));
310 inset->read(buf, lex);
311 par.insertInset(par.size(), inset.release(), font, change);
312 } else if (token == "\\hfill") {
313 par.insertInset(par.size(), new InsetHFill, font, change);
314 } else if (token == "\\lyxline") {
315 par.insertInset(par.size(), new InsetLine, font, change);
316 } else if (token == "\\newpage") {
317 par.insertInset(par.size(), new InsetPagebreak, font, change);
318 } else if (token == "\\clearpage") {
319 par.insertInset(par.size(), new InsetClearPage, font, change);
320 } else if (token == "\\cleardoublepage") {
321 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
322 } else if (token == "\\change_unchanged") {
323 change = Change(Change::UNCHANGED);
324 } else if (token == "\\change_inserted") {
326 std::istringstream is(lex.getString());
330 if (aid >= bp.author_map.size()) {
331 errorList.push_back(ErrorItem(_("Change tracking error"),
332 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
333 par.id(), 0, par.size()));
334 change = Change(Change::UNCHANGED);
336 change = Change(Change::INSERTED, bp.author_map[aid], ct);
337 } else if (token == "\\change_deleted") {
339 std::istringstream is(lex.getString());
343 if (aid >= bp.author_map.size()) {
344 errorList.push_back(ErrorItem(_("Change tracking error"),
345 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
346 par.id(), 0, par.size()));
347 change = Change(Change::UNCHANGED);
349 change = Change(Change::DELETED, bp.author_map[aid], ct);
352 errorList.push_back(ErrorItem(_("Unknown token"),
353 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
355 par.id(), 0, par.size()));
360 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex,
361 ErrorList & errorList)
364 string token = lex.getString();
366 Change change(Change::UNCHANGED);
369 readParToken(buf, par, lex, token, font, change, errorList);
372 token = lex.getString();
377 if (token == "\\end_layout") {
378 //Ok, paragraph finished
382 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
383 << token << '\'' << endl;
384 if (token == "\\begin_layout" || token == "\\end_document"
385 || token == "\\end_inset" || token == "\\begin_deeper"
386 || token == "\\end_deeper") {
387 lex.pushToken(token);
388 lyxerr << "Paragraph ended in line "
389 << lex.getLineNo() << "\n"
390 << "Missing \\end_layout.\n";
394 // Final change goes to paragraph break:
395 par.setChange(par.size(), change);
397 // Initialize begin_of_body_ on load; redoParagraph maintains
398 par.setBeginOfBody();
406 double LyXText::spacing(Buffer const & buffer,
407 Paragraph const & par) const
409 if (par.params().spacing().isDefault())
410 return buffer.params().spacing().getValue();
411 return par.params().spacing().getValue();
415 int LyXText::singleWidth(Buffer const & buffer, Paragraph const & par,
418 return singleWidth(par, pos, par.getChar(pos),
419 getFont(buffer, par, pos));
423 int LyXText::singleWidth(Paragraph const & par,
424 pos_type pos, char_type c, LyXFont const & font) const
426 // The most common case is handled first (Asger)
427 if (isPrintable(c)) {
428 Language const * language = font.language();
429 if (language->rightToLeft()) {
430 if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
431 lyxrc.font_norm_type == LyXRC::ISO_10646_1)
432 && language->lang() == "arabic") {
433 if (Encodings::isComposeChar_arabic(c))
435 c = par.transformChar(c, pos);
436 } else if (language->lang() == "hebrew" &&
437 Encodings::isComposeChar_hebrew(c))
440 return theFontMetrics(font).width(c);
443 if (c == Paragraph::META_INSET)
444 return par.getInset(pos)->width();
446 return theFontMetrics(font).width(c);
450 int LyXText::leftMargin(Buffer const & buffer, int max_width, pit_type pit) const
452 BOOST_ASSERT(pit >= 0);
453 BOOST_ASSERT(pit < int(pars_.size()));
454 return leftMargin(buffer, max_width, pit, pars_[pit].size());
458 int LyXText::leftMargin(Buffer const & buffer, int max_width,
459 pit_type const pit, pos_type const pos) const
461 BOOST_ASSERT(pit >= 0);
462 BOOST_ASSERT(pit < int(pars_.size()));
463 Paragraph const & par = pars_[pit];
464 BOOST_ASSERT(pos >= 0);
465 BOOST_ASSERT(pos <= par.size());
466 //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
467 LyXTextClass const & tclass = buffer.params().getLyXTextClass();
468 LyXLayout_ptr const & layout = par.layout();
470 string parindent = layout->parindent;
474 if (isMainText(buffer))
475 l_margin += changebarMargin();
478 docstring leftm = from_utf8(tclass.leftmargin());
479 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm);
481 if (par.getDepth() != 0) {
482 // find the next level paragraph
483 pit_type newpar = outerHook(pit, pars_);
484 if (newpar != pit_type(pars_.size())) {
485 if (pars_[newpar].layout()->isEnvironment()) {
486 l_margin = leftMargin(buffer, max_width, newpar);
488 if (par.layout() == tclass.defaultLayout()) {
489 if (pars_[newpar].params().noindent())
492 parindent = pars_[newpar].layout()->parindent;
497 // This happens after sections in standard classes. The 1.3.x
498 // code compared depths too, but it does not seem necessary
500 if (par.layout() == tclass.defaultLayout()
501 && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
504 LyXFont const labelfont = getLabelFont(buffer, par);
505 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
507 switch (layout->margintype) {
509 if (!layout->leftmargin.empty()) {
511 docstring leftm = from_utf8(layout->leftmargin);
512 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm);
514 if (!par.getLabelstring().empty()) {
516 docstring labin = from_utf8(layout->labelindent);
517 l_margin += labelfont_metrics.signedWidth(labin);
518 docstring labstr = par.getLabelstring();
519 l_margin += labelfont_metrics.width(labstr);
520 docstring labsep = from_utf8(layout->labelsep);
521 l_margin += labelfont_metrics.width(labsep);
525 case MARGIN_MANUAL: {
527 docstring labin = from_utf8(layout->labelindent);
528 l_margin += labelfont_metrics.signedWidth(labin);
529 // The width of an empty par, even with manual label, should be 0
530 if (!par.empty() && pos >= par.beginOfBody()) {
531 if (!par.getLabelWidthString().empty()) {
532 docstring labstr = par.getLabelWidthString();
533 l_margin += labelfont_metrics.width(labstr);
534 docstring labsep = from_utf8(layout->labelsep);
535 l_margin += labelfont_metrics.width(labsep);
541 case MARGIN_STATIC: {
543 docstring leftm = from_utf8(layout->leftmargin);
544 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(leftm)
545 * 4 / (par.getDepth() + 4);
549 case MARGIN_FIRST_DYNAMIC:
550 if (layout->labeltype == LABEL_MANUAL) {
551 if (pos >= par.beginOfBody()) {
553 l_margin += labelfont_metrics.signedWidth(
554 from_utf8(layout->leftmargin));
557 l_margin += labelfont_metrics.signedWidth(
558 from_utf8(layout->labelindent));
561 // Special case to fix problems with
563 || (layout->labeltype == LABEL_STATIC
564 && layout->latextype == LATEX_ENVIRONMENT
565 && !isFirstInSequence(pit, pars_))) {
567 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->leftmargin));
568 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
569 && layout->labeltype != LABEL_BIBLIO
570 && layout->labeltype !=
571 LABEL_CENTERED_TOP_ENVIRONMENT) {
572 l_margin += labelfont_metrics.signedWidth(from_utf8(layout->labelindent));
573 l_margin += labelfont_metrics.width(from_utf8(layout->labelsep));
574 l_margin += labelfont_metrics.width(par.getLabelstring());
578 case MARGIN_RIGHT_ADDRESS_BOX: {
580 // ok, a terrible hack. The left margin depends on the widest
581 // row in this paragraph.
582 RowList::iterator rit = par.rows().begin();
583 RowList::iterator end = par.rows().end();
585 #warning This is wrong.
587 int minfill = max_width;
588 for ( ; rit != end; ++rit)
589 if (rit->fill() < minfill)
590 minfill = rit->fill();
591 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
594 // also wrong, but much shorter.
595 l_margin += max_width / 2;
600 if (!par.params().leftIndent().zero())
601 l_margin += par.params().leftIndent().inPixels(max_width);
605 if (par.params().align() == LYX_ALIGN_LAYOUT)
606 align = layout->align;
608 align = par.params().align();
610 // set the correct parindent
612 && (layout->labeltype == LABEL_NO_LABEL
613 || layout->labeltype == LABEL_TOP_ENVIRONMENT
614 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
615 || (layout->labeltype == LABEL_STATIC
616 && layout->latextype == LATEX_ENVIRONMENT
617 && !isFirstInSequence(pit, pars_)))
618 && align == LYX_ALIGN_BLOCK
619 && !par.params().noindent()
620 // in some insets, paragraphs are never indented
621 && !(par.inInset() && par.inInset()->neverIndent(buffer))
622 // display style insets are always centered, omit indentation
625 && par.getInset(pos)->display())
626 && (par.layout() != tclass.defaultLayout()
627 || buffer.params().paragraph_separation ==
628 BufferParams::PARSEP_INDENT))
630 docstring din = from_utf8(parindent);
631 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(din);
638 int LyXText::labelEnd(Buffer const & buffer, int max_width, pit_type const pit) const
640 // labelEnd is only needed if the layout fills a flushleft label.
641 if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
643 // return the beginning of the body
644 return leftMargin(buffer, max_width, pit);
650 // this needs special handling - only newlines count as a break point
651 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
653 pos_type const end = par.size();
656 if (par.isNewline(i))
665 void LyXText::rowBreakPoint(Buffer const & buffer, int right_margin,
666 int max_width, pit_type const pit, Row & row) const
668 Paragraph const & par = pars_[pit];
669 pos_type const end = par.size();
670 pos_type const pos = row.pos();
676 // maximum pixel width of a row
677 int width = max_width - right_margin; // - leftMargin(buffer, max_width, pit, row);
683 LyXLayout_ptr const & layout = par.layout();
685 if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
686 row.endpos(addressBreakPoint(pos, par));
690 pos_type const body_pos = par.beginOfBody();
693 // Now we iterate through until we reach the right margin
694 // or the end of the par, then choose the possible break
697 int label_end = labelEnd(buffer, max_width, pit);
698 int const left = leftMargin(buffer, max_width, pit, pos);
701 // pixel width since last breakpoint
704 FontIterator fi = FontIterator(buffer, *this, par, pos);
705 pos_type point = end;
707 FontMetrics const & fm = theFontMetrics(getLabelFont(buffer, par));
708 for ( ; i < end; ++i, ++fi) {
709 char_type const c = par.getChar(i);
710 int thiswidth = singleWidth(par, i, c, *fi);
712 // add the auto-hfill from label end to the body
713 if (body_pos && i == body_pos) {
714 docstring lsep = from_utf8(layout->labelsep);
715 int add = fm.width(lsep);
716 if (par.isLineSeparator(i - 1))
717 add -= singleWidth(buffer, par, i - 1);
719 add = std::max(add, label_end - x);
724 chunkwidth += thiswidth;
726 // break before a character that will fall off
727 // the right of the row
729 // if no break before, break here
730 if (point == end || chunkwidth >= width - left) {
737 // exit on last registered breakpoint:
741 if (par.isNewline(i)) {
747 if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
752 if (par.isInset(i) && par.getInset(i)->display()) {
758 if (!par.isInset(i) || par.getInset(i)->isChar()) {
759 // some insets are line separators too
760 if (par.isLineSeparator(i)) {
761 // register breakpoint:
768 // maybe found one, but the par is short enough.
769 if (i == end && x < width)
772 // manual labels cannot be broken in LaTeX. But we
773 // want to make our on-screen rendering of footnotes
775 if (body_pos && point < body_pos)
782 void LyXText::setRowWidth(Buffer const & buffer, int right_margin,
783 int max_width, pit_type const pit, Row & row) const
785 // get the pure distance
786 pos_type const end = row.endpos();
788 Paragraph const & par = pars_[pit];
789 docstring const labelsep = from_utf8(par.layout()->labelsep);
790 int w = leftMargin(buffer, max_width, pit, row.pos());
791 int label_end = labelEnd(buffer, max_width, pit);
793 pos_type const body_pos = par.beginOfBody();
794 pos_type i = row.pos();
796 FontMetrics const & fm = theFontMetrics(getLabelFont(buffer, par));
799 FontIterator fi = FontIterator(buffer, *this, par, i);
800 for ( ; i < end; ++i, ++fi) {
801 if (body_pos > 0 && i == body_pos) {
802 w += fm.width(labelsep);
803 if (par.isLineSeparator(i - 1))
804 w -= singleWidth(buffer, par, i - 1);
805 w = max(w, label_end);
807 char_type const c = par.getChar(i);
808 w += singleWidth(par, i, c, *fi);
812 if (body_pos > 0 && body_pos >= end) {
813 w += fm.width(labelsep);
814 if (end > 0 && par.isLineSeparator(end - 1))
815 w -= singleWidth(buffer, par, end - 1);
816 w = max(w, label_end);
819 row.width(w + right_margin);
823 LColor_color LyXText::backgroundColor() const
825 return LColor_color(LColor::color(background_color_));
829 void LyXText::setHeightOfRow(BufferView const & bv, pit_type const pit,
832 Paragraph const & par = pars_[pit];
833 // get the maximum ascent and the maximum descent
834 double layoutasc = 0;
835 double layoutdesc = 0;
836 double const dh = defaultRowHeight();
838 // ok, let us initialize the maxasc and maxdesc value.
839 // Only the fontsize count. The other properties
840 // are taken from the layoutfont. Nicer on the screen :)
841 LyXLayout_ptr const & layout = par.layout();
843 // as max get the first character of this row then it can
844 // increase but not decrease the height. Just some point to
845 // start with so we don't have to do the assignment below too
847 Buffer const & buffer = *bv.buffer();
848 LyXFont font = getFont(buffer, par, row.pos());
849 LyXFont::FONT_SIZE const tmpsize = font.size();
850 font = getLayoutFont(buffer, pit);
851 LyXFont::FONT_SIZE const size = font.size();
852 font.setSize(tmpsize);
854 LyXFont labelfont = getLabelFont(buffer, par);
856 FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
857 FontMetrics const & fontmetrics = theFontMetrics(font);
859 // these are minimum values
860 double const spacing_val = layout->spacing.getValue()
861 * spacing(*bv.buffer(), par);
862 //lyxerr << "spacing_val = " << spacing_val << endl;
863 int maxasc = int(fontmetrics.maxAscent() * spacing_val);
864 int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
866 // insets may be taller
867 InsetList::const_iterator ii = par.insetlist.begin();
868 InsetList::const_iterator iend = par.insetlist.end();
869 for ( ; ii != iend; ++ii) {
870 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
871 maxasc = max(maxasc, ii->inset->ascent());
872 maxdesc = max(maxdesc, ii->inset->descent());
876 // Check if any custom fonts are larger (Asger)
877 // This is not completely correct, but we can live with the small,
878 // cosmetic error for now.
880 pos_type const pos_end = row.endpos();
882 LyXFont::FONT_SIZE maxsize =
883 par.highestFontInRange(row.pos(), pos_end, size);
884 if (maxsize > font.size()) {
885 font.setSize(maxsize);
886 maxasc = max(maxasc, fontmetrics.maxAscent());
887 maxdesc = max(maxdesc, fontmetrics.maxDescent());
890 // This is nicer with box insets:
897 if (row.pos() == 0) {
898 Buffer const & buffer = *bv.buffer();
899 BufferParams const & bufparams = buffer.params();
900 // some parksips VERY EASY IMPLEMENTATION
901 if (bufparams.paragraph_separation
902 == BufferParams::PARSEP_SKIP
904 && ((layout->isParagraph() && par.getDepth() == 0)
905 || (pars_[pit - 1].layout()->isParagraph()
906 && pars_[pit - 1].getDepth() == 0)))
908 maxasc += bufparams.getDefSkip().inPixels(bv);
911 if (par.params().startOfAppendix())
912 maxasc += int(3 * dh);
914 // This is special code for the chapter, since the label of this
915 // layout is printed in an extra row
916 if (layout->counter == "chapter"
917 && !par.params().labelString().empty()) {
918 labeladdon = int(labelfont_metrics.maxHeight()
919 * layout->spacing.getValue()
920 * spacing(buffer, par));
923 // special code for the top label
924 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
925 || layout->labeltype == LABEL_BIBLIO
926 || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
927 && isFirstInSequence(pit, paragraphs())
928 && !par.getLabelstring().empty())
931 labelfont_metrics.maxHeight()
932 * layout->spacing.getValue()
933 * spacing(*bv.buffer(), par)
934 + (layout->topsep + layout->labelbottomsep) * dh);
937 // Add the layout spaces, for example before and after
938 // a section, or between the items of a itemize or enumerate
941 pit_type prev = depthHook(pit, pars_, par.getDepth());
943 && pars_[prev].layout() == layout
944 && pars_[prev].getDepth() == par.getDepth()
945 && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
947 layoutasc = layout->itemsep * dh;
948 } else if (pit != 0 || row.pos() != 0) {
949 if (layout->topsep > 0)
950 layoutasc = layout->topsep * dh;
953 prev = outerHook(pit, pars_);
954 if (prev != pit_type(pars_.size())) {
955 maxasc += int(pars_[prev].layout()->parsep * dh);
956 } else if (pit != 0) {
957 if (pars_[pit - 1].getDepth() != 0 ||
958 pars_[pit - 1].layout() == layout) {
959 maxasc += int(layout->parsep * dh);
964 // is it a bottom line?
965 if (row.endpos() >= par.size()) {
966 // add the layout spaces, for example before and after
967 // a section, or between the items of a itemize or enumerate
969 pit_type nextpit = pit + 1;
970 if (nextpit != pit_type(pars_.size())) {
975 if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
976 usual = pars_[cpit].layout()->bottomsep * dh;
977 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
978 if (pars_[cpit].layout() != pars_[nextpit].layout()
979 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
981 unusual = pars_[cpit].layout()->bottomsep * dh;
983 layoutdesc = max(unusual, usual);
984 } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
985 if (pars_[cpit].layout() != pars_[nextpit].layout()
986 || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
987 layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
992 // incalculate the layout spaces
993 maxasc += int(layoutasc * 2 / (2 + pars_[pit].getDepth()));
994 maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
996 // FIXME: the correct way is to do the following is to move the
997 // following code in another method specially tailored for the
998 // main LyXText. The following test is thus bogus.
999 LyXText const & text = buffer.text();
1000 // Top and bottom margin of the document (only at top-level)
1001 if (&text == this) {
1002 if (pit == 0 && row.pos() == 0)
1004 if (pit + 1 == pit_type(pars_.size()) &&
1005 row.endpos() == par.size())
1009 row.ascent(maxasc + labeladdon);
1010 row.descent(maxdesc);
1014 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1016 BOOST_ASSERT(this == cur.text());
1018 Paragraph & cpar = cur.paragraph();
1019 pit_type cpit = cur.pit();
1021 LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1022 LyXLayout_ptr const & layout = cpar.layout();
1024 // this is only allowed, if the current paragraph is not empty
1025 // or caption and if it has not the keepempty flag active
1026 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
1027 layout->labeltype != LABEL_SENSITIVE)
1030 // a layout change may affect also the following paragraph
1031 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
1033 // Always break behind a space
1034 // It is better to erase the space (Dekel)
1035 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1036 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1038 // What should the layout for the new paragraph be?
1039 int preserve_layout = 0;
1041 preserve_layout = 2;
1043 preserve_layout = layout->isEnvironment();
1045 // We need to remember this before we break the paragraph, because
1046 // that invalidates the layout variable
1047 bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1049 // we need to set this before we insert the paragraph.
1050 bool const isempty = cpar.allowEmpty() && cpar.empty();
1052 lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1053 cur.pos(), preserve_layout);
1055 // After this, neither paragraph contains any rows!
1058 pit_type next_par = cpit + 1;
1060 // well this is the caption hack since one caption is really enough
1063 // set to standard-layout
1064 pars_[cpit].applyLayout(tclass.defaultLayout());
1066 // set to standard-layout
1067 pars_[next_par].applyLayout(tclass.defaultLayout());
1070 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1071 pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges);
1073 ParIterator current_it(cur);
1074 ParIterator last_it(cur);
1078 updateLabels(cur.buffer(), current_it, last_it);
1080 // A singlePar update is not enough in this case.
1081 cur.updateFlags(Update::Force);
1083 // This check is necessary. Otherwise the new empty paragraph will
1084 // be deleted automatically. And it is more friendly for the user!
1085 if (cur.pos() != 0 || isempty)
1086 setCursor(cur.top(), cur.pit() + 1, 0);
1088 setCursor(cur.top(), cur.pit(), 0);
1092 // insert a character, moves all the following breaks in the
1093 // same Paragraph one to the right and make a rebreak
1094 void LyXText::insertChar(LCursor & cur, char_type c)
1096 BOOST_ASSERT(this == cur.text());
1097 BOOST_ASSERT(c != Paragraph::META_INSET);
1099 recordUndo(cur, Undo::INSERT);
1101 Buffer const & buffer = cur.buffer();
1102 Paragraph & par = cur.paragraph();
1103 // try to remove this
1104 pit_type const pit = cur.pit();
1106 bool const freeSpacing = par.layout()->free_spacing ||
1107 par.isFreeSpacing();
1109 if (lyxrc.auto_number) {
1110 static docstring const number_operators = from_ascii("+-/*");
1111 static docstring const number_unary_operators = from_ascii("+-");
1112 static docstring const number_seperators = from_ascii(".,:");
1114 if (current_font.number() == LyXFont::ON) {
1115 if (!isDigit(c) && !contains(number_operators, c) &&
1116 !(contains(number_seperators, c) &&
1118 cur.pos() != cur.lastpos() &&
1119 getFont(buffer, par, cur.pos()).number() == LyXFont::ON &&
1120 getFont(buffer, par, cur.pos() - 1).number() == LyXFont::ON)
1122 number(cur); // Set current_font.number to OFF
1123 } else if (isDigit(c) &&
1124 real_current_font.isVisibleRightToLeft()) {
1125 number(cur); // Set current_font.number to ON
1127 if (cur.pos() != 0) {
1128 char_type const c = par.getChar(cur.pos() - 1);
1129 if (contains(number_unary_operators, c) &&
1131 || par.isSeparator(cur.pos() - 2)
1132 || par.isNewline(cur.pos() - 2))
1134 setCharFont(buffer, pit, cur.pos() - 1, current_font);
1135 } else if (contains(number_seperators, c)
1137 && getFont(buffer, par, cur.pos() - 2).number() == LyXFont::ON) {
1138 setCharFont(buffer, pit, cur.pos() - 1, current_font);
1144 // First check, if there will be two blanks together or a blank at
1145 // the beginning of a paragraph.
1146 // I decided to handle blanks like normal characters, the main
1147 // difference are the special checks when calculating the row.fill
1148 // (blank does not count at the end of a row) and the check here
1150 // When the free-spacing option is set for the current layout,
1151 // disable the double-space checking
1152 if (!freeSpacing && isLineSeparatorChar(c)) {
1153 if (cur.pos() == 0) {
1154 static bool sent_space_message = false;
1155 if (!sent_space_message) {
1156 cur.message(_("You cannot insert a space at the "
1157 "beginning of a paragraph. Please read the Tutorial."));
1158 sent_space_message = true;
1162 BOOST_ASSERT(cur.pos() > 0);
1163 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
1164 && !par.isDeleted(cur.pos() - 1)) {
1165 static bool sent_space_message = false;
1166 if (!sent_space_message) {
1167 cur.message(_("You cannot type two spaces this way. "
1168 "Please read the Tutorial."));
1169 sent_space_message = true;
1175 par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
1177 // cur.updateFlags(Update::Force);
1178 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
1183 void LyXText::charInserted()
1185 // Here we call finishUndo for every 20 characters inserted.
1186 // This is from my experience how emacs does it. (Lgb)
1187 static unsigned int counter;
1197 // the cursor set functions have a special mechanism. When they
1198 // realize, that you left an empty paragraph, they will delete it.
1200 bool LyXText::cursorRightOneWord(LCursor & cur)
1202 BOOST_ASSERT(this == cur.text());
1206 if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1210 // Advance through word.
1211 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1213 // Skip through trailing nonword stuff.
1214 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1217 return setCursor(cur, old.pit(), old.pos());
1221 bool LyXText::cursorLeftOneWord(LCursor & cur)
1223 BOOST_ASSERT(this == cur.text());
1227 if (old.pos() == 0 && old.pit() != 0) {
1229 old.pos() = old.lastpos();
1231 // Skip through initial nonword stuff.
1232 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
1234 // Advance through word.
1235 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
1238 return setCursor(cur, old.pit(), old.pos());
1242 void LyXText::selectWord(LCursor & cur, word_location loc)
1244 BOOST_ASSERT(this == cur.text());
1245 CursorSlice from = cur.top();
1246 CursorSlice to = cur.top();
1247 getWord(from, to, loc);
1248 if (cur.top() != from)
1249 setCursor(cur, from.pit(), from.pos());
1253 setCursor(cur, to.pit(), to.pos());
1258 // Select the word currently under the cursor when no
1259 // selection is currently set
1260 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1262 BOOST_ASSERT(this == cur.text());
1263 if (cur.selection())
1265 selectWord(cur, loc);
1266 return cur.selection();
1270 void LyXText::acceptChange(LCursor & cur)
1272 // FIXME: change tracking (MG)
1274 BOOST_ASSERT(this == cur.text());
1276 if (!cur.selection() && cur.lastpos() != 0)
1279 // FIXME: we must handle start = end = 0
1281 recordUndoSelection(cur, Undo::INSERT);
1283 DocIterator it = cur.selectionBegin();
1284 DocIterator et = cur.selectionEnd();
1285 pit_type pit = it.pit();
1286 for (; pit <= et.pit(); ++pit) {
1287 pos_type left = (pit == it.pit() ? it.pos() : 0);
1288 pos_type right = (pit == et.pit() ? et.pos() : pars_[pit].size());
1289 pars_[pit].acceptChanges(left, right);
1291 // merge paragraph if appropriate:
1292 // if (right >= pars_[pit].size() && pit + 1 < et.pit() &&
1293 // pars_[pit].isDeleted(pars_[pit].size())) {
1294 // setCursorIntern(cur, pit + 1, 0);
1295 // backspacePos0(cur);
1299 cur.clearSelection();
1300 setCursorIntern(cur, it.pit(), 0);
1304 void LyXText::rejectChange(LCursor & cur)
1306 // FIXME: change tracking (MG)
1308 BOOST_ASSERT(this == cur.text());
1310 if (!cur.selection() && cur.lastpos() != 0)
1313 // FIXME: we must handle start = end = 0
1315 recordUndoSelection(cur, Undo::INSERT);
1317 DocIterator it = cur.selectionBegin();
1318 DocIterator et = cur.selectionEnd();
1319 pit_type pit = it.pit();
1320 for (; pit <= et.pit(); ++pit) {
1321 pos_type left = (pit == it.pit() ? it.pos() : 0);
1322 pos_type right = (pit == et.pit() ? et.pos() : pars_[pit].size());
1323 pars_[pit].rejectChanges(left, right);
1325 // merge paragraph if appropriate:
1326 // if (right >= pars_[pit].size() && pit + 1 < et.pit() &&
1327 // pars_[pit].isInserted(pars_[pit].size())) {
1328 // setCursorIntern(cur, pit + 1, 0);
1329 // backspacePos0(cur);
1333 cur.clearSelection();
1334 setCursorIntern(cur, it.pit(), 0);
1338 // Delete from cursor up to the end of the current or next word.
1339 void LyXText::deleteWordForward(LCursor & cur)
1341 BOOST_ASSERT(this == cur.text());
1342 if (cur.lastpos() == 0)
1346 cur.selection() = true;
1347 cursorRightOneWord(cur);
1349 cutSelection(cur, true, false);
1354 // Delete from cursor to start of current or prior word.
1355 void LyXText::deleteWordBackward(LCursor & cur)
1357 BOOST_ASSERT(this == cur.text());
1358 if (cur.lastpos() == 0)
1362 cur.selection() = true;
1363 cursorLeftOneWord(cur);
1365 cutSelection(cur, true, false);
1370 // Kill to end of line.
1371 void LyXText::deleteLineForward(LCursor & cur)
1373 BOOST_ASSERT(this == cur.text());
1374 if (cur.lastpos() == 0) {
1375 // Paragraph is empty, so we just go to the right
1379 cur.selection() = true; // to avoid deletion
1382 // What is this test for ??? (JMarc)
1383 if (!cur.selection())
1384 deleteWordForward(cur);
1386 cutSelection(cur, true, false);
1391 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1393 BOOST_ASSERT(this == cur.text());
1397 if (cur.selection()) {
1398 from = cur.selBegin();
1402 getWord(from, to, PARTIAL_WORD);
1403 cursorRightOneWord(cur);
1406 recordUndoSelection(cur);
1408 pos_type pos = from.pos();
1409 int par = from.pit();
1411 while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1413 if (pos == pars_[pit].size()) {
1418 char_type c = pars_[pit].getChar(pos);
1419 if (c != Paragraph::META_INSET) {
1421 case text_lowercase:
1424 case text_capitalization:
1426 action = text_lowercase;
1428 case text_uppercase:
1434 // FIXME: change tracking (MG)
1435 // sorry but we are no longer allowed to set a single character directly
1436 // we have to rewrite this method in terms of erase&insert operations
1437 //pars_[pit].setChar(pos, c);
1443 bool LyXText::erase(LCursor & cur)
1445 BOOST_ASSERT(this == cur.text());
1446 bool needsUpdate = false;
1447 Paragraph & par = cur.paragraph();
1449 if (cur.pos() != cur.lastpos()) {
1450 // this is the code for a normal delete, not pasting
1452 recordUndo(cur, Undo::DELETE);
1453 par.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1454 if (par.isDeleted(cur.pos()))
1455 cur.forwardPosNoDescend();
1458 if (cur.pit() == cur.lastpit())
1459 return dissolveInset(cur);
1461 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1462 par.setChange(cur.pos(), Change(Change::DELETED));
1466 setCursorIntern(cur, cur.pit() + 1, 0);
1467 needsUpdate = backspacePos0(cur);
1472 // Make sure the cursor is correct. Is this really needed?
1473 // No, not really... at least not here!
1474 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1481 bool LyXText::backspacePos0(LCursor & cur)
1483 BOOST_ASSERT(this == cur.text());
1487 bool needsUpdate = false;
1489 BufferParams const & bufparams = cur.buffer().params();
1490 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1491 ParagraphList & plist = cur.text()->paragraphs();
1492 Paragraph const & par = cur.paragraph();
1493 LCursor prevcur = cur;
1495 prevcur.pos() = prevcur.lastpos();
1496 Paragraph const & prevpar = prevcur.paragraph();
1498 // is it an empty paragraph?
1499 if (cur.lastpos() == 0
1500 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1501 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1502 plist.erase(boost::next(plist.begin(), cur.pit()));
1505 // is previous par empty?
1506 else if (prevcur.lastpos() == 0
1507 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1508 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1509 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1512 // Pasting is not allowed, if the paragraphs have different
1513 // layouts. I think it is a real bug of all other
1514 // word processors to allow it. It confuses the user.
1515 // Correction: Pasting is always allowed with standard-layout
1516 else if (par.layout() == prevpar.layout()
1517 || par.layout() == tclass.defaultLayout()) {
1518 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1519 mergeParagraph(bufparams, plist, prevcur.pit());
1524 updateLabels(cur.buffer());
1525 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1532 bool LyXText::backspace(LCursor & cur)
1534 BOOST_ASSERT(this == cur.text());
1535 bool needsUpdate = false;
1536 if (cur.pos() == 0) {
1538 return dissolveInset(cur);
1540 Paragraph & prev_par = pars_[cur.pit() - 1];
1542 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1543 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1544 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1547 // The cursor is at the beginning of a paragraph, so
1548 // the backspace will collapse two paragraphs into one.
1549 needsUpdate = backspacePos0(cur);
1552 // this is the code for a normal backspace, not pasting
1554 recordUndo(cur, Undo::DELETE);
1555 // We used to do cursorLeftIntern() here, but it is
1556 // not a good idea since it triggers the auto-delete
1557 // mechanism. So we do a cursorLeftIntern()-lite,
1558 // without the dreaded mechanism. (JMarc)
1559 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1560 false, cur.boundary());
1561 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1564 if (cur.pos() == cur.lastpos())
1565 setCurrentFont(cur);
1567 // A singlePar update is not enough in this case.
1568 // cur.updateFlags(Update::Force);
1569 setCursor(cur.top(), cur.pit(), cur.pos());
1575 bool LyXText::dissolveInset(LCursor & cur) {
1576 BOOST_ASSERT(this == cur.text());
1578 if (isMainText(*cur.bv().buffer()) || cur.inset().nargs() != 1)
1581 recordUndoInset(cur);
1582 cur.selHandle(false);
1584 pos_type spos = cur.pos();
1585 pit_type spit = cur.pit();
1586 ParagraphList plist;
1587 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1588 plist = paragraphs();
1590 // store cursor offset
1594 Buffer & b = cur.buffer();
1595 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1596 if (!plist.empty()) {
1597 // ERT paragraphs have the Language latex_language.
1598 // This is invalid outside of ERT, so we need to
1599 // change it to the buffer language.
1600 ParagraphList::iterator it = plist.begin();
1601 ParagraphList::iterator it_end = plist.end();
1602 for (; it != it_end; it++) {
1603 it->changeLanguage(b.params(), latex_language,
1607 pasteParagraphList(cur, plist, b.params().textclass,
1608 b.errorList("Paste"));
1610 cur.pit() = std::min(cur.lastpit(), spit);
1611 cur.pos() = std::min(cur.lastpos(), spos);
1613 cur.clearSelection();
1619 // only used for inset right now. should also be used for main text
1620 void LyXText::draw(PainterInfo & pi, int x, int y) const
1622 paintTextInset(*this, pi, x, y);
1626 // only used for inset right now. should also be used for main text
1627 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
1629 LCursor & cur = pi.base.bv->cursor();
1630 if (!cur.selection())
1632 if (!ptr_cmp(cur.text(), this))
1635 if (lyxerr.debugging(Debug::DEBUG)) {
1636 lyxerr[Debug::DEBUG]
1637 << BOOST_CURRENT_FUNCTION
1638 << "draw selection at " << x
1642 DocIterator beg = cur.selectionBegin();
1643 DocIterator end = cur.selectionEnd();
1645 BufferView & bv = *pi.base.bv;
1646 Buffer const & buffer = *bv.buffer();
1648 // the selection doesn't touch the visible screen
1649 if (bv_funcs::status(&bv, beg) == bv_funcs::CUR_BELOW
1650 || bv_funcs::status(&bv, end) == bv_funcs::CUR_ABOVE)
1653 Paragraph const & par1 = pars_[beg.pit()];
1654 Paragraph const & par2 = pars_[end.pit()];
1655 TextMetrics const & tm = bv.textMetrics(this);
1656 ParagraphMetrics const & pm1 = tm.parMetrics(beg.pit());
1657 ParagraphMetrics const & pm2 = tm.parMetrics(end.pit());
1659 bool const above = (bv_funcs::status(&bv, beg)
1660 == bv_funcs::CUR_ABOVE);
1661 bool const below = (bv_funcs::status(&bv, end)
1662 == bv_funcs::CUR_BELOW);
1670 Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
1671 y1 = bv_funcs::getPos(bv, beg, beg.boundary()).y_ - row1.ascent();
1672 y2 = y1 + row1.height();
1673 int const startx = cursorX(bv, beg.top(), beg.boundary());
1674 if (!isRTL(buffer, par1)) {
1676 x2 = 0 + tm.width();
1686 Y1 = bv.workHeight();
1687 Y2 = bv.workHeight();
1691 Row const & row2 = pm2.getRow(end.pos(), end.boundary());
1692 Y1 = bv_funcs::getPos(bv, end, end.boundary()).y_ - row2.ascent();
1693 Y2 = Y1 + row2.height();
1694 int const endx = cursorX(bv, end.top(), end.boundary());
1695 if (!isRTL(buffer, par2)) {
1701 X2 = 0 + tm.width();
1705 if (!above && !below && &pm1.getRow(beg.pos(), beg.boundary())
1706 == &pm2.getRow(end.pos(), end.boundary()))
1708 // paint only one rectangle
1709 int const b( !isRTL(*bv.buffer(), par1) ? x + x1 : x + X1 );
1710 int const w( !isRTL(*bv.buffer(), par1) ? X2 - x1 : x2 - X1 );
1711 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
1715 if (lyxerr.debugging(Debug::DEBUG)) {
1716 lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
1717 << "X1:" << X1 << " x2: " << X2 << " wid: " << tm.width()
1721 // paint upper rectangle
1722 pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
1724 // paint bottom rectangle
1725 pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
1727 // paint center rectangle
1728 pi.pain.fillRectangle(x, y2, tm.width(),
1729 Y1 - y2, LColor::selection);
1733 bool LyXText::isLastRow(pit_type pit, Row const & row) const
1735 return row.endpos() >= pars_[pit].size()
1736 && pit + 1 == pit_type(paragraphs().size());
1740 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
1742 return row.pos() == 0 && pit == 0;
1746 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1747 word_location const loc)
1749 Paragraph const & from_par = pars_[from.pit()];
1751 case WHOLE_WORD_STRICT:
1752 if (from.pos() == 0 || from.pos() == from_par.size()
1753 || !from_par.isLetter(from.pos())
1754 || !from_par.isLetter(from.pos() - 1)) {
1758 // no break here, we go to the next
1761 // If we are already at the beginning of a word, do nothing
1762 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1764 // no break here, we go to the next
1767 // always move the cursor to the beginning of previous word
1768 while (from.pos() && from_par.isLetter(from.pos() - 1))
1772 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1776 // no need to move the 'from' cursor
1780 Paragraph & to_par = pars_[to.pit()];
1781 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1786 void LyXText::write(Buffer const & buf, std::ostream & os) const
1788 ParagraphList::const_iterator pit = paragraphs().begin();
1789 ParagraphList::const_iterator end = paragraphs().end();
1791 for (; pit != end; ++pit)
1792 pit->write(buf, os, buf.params(), dth);
1796 bool LyXText::read(Buffer const & buf, LyXLex & lex, ErrorList & errorList)
1798 depth_type depth = 0;
1800 while (lex.isOK()) {
1802 string const token = lex.getString();
1807 if (token == "\\end_inset")
1810 if (token == "\\end_body")
1813 if (token == "\\begin_body")
1816 if (token == "\\end_document")
1819 if (token == "\\begin_layout") {
1820 lex.pushToken(token);
1823 par.params().depth(depth);
1824 par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
1825 pars_.push_back(par);
1827 // FIXME: goddamn InsetTabular makes us pass a Buffer
1829 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1831 } else if (token == "\\begin_deeper") {
1833 } else if (token == "\\end_deeper") {
1835 lex.printError("\\end_deeper: " "depth is already null");
1840 lyxerr << "Handling unknown body token: `"
1841 << token << '\'' << endl;
1847 int LyXText::cursorX(BufferView const & bv, CursorSlice const & sl,
1848 bool boundary) const
1850 TextMetrics const & tm = bv.textMetrics(sl.text());
1851 pit_type const pit = sl.pit();
1852 Paragraph const & par = pars_[pit];
1853 ParagraphMetrics const & pm = tm.parMetrics(pit);
1854 if (pm.rows().empty())
1857 int max_width = tm.maxWidth();
1859 pos_type ppos = sl.pos();
1860 // Correct position in front of big insets
1861 bool const boundary_correction = ppos != 0 && boundary;
1862 if (boundary_correction)
1865 Row const & row = pm.getRow(sl.pos(), boundary);
1867 pos_type cursor_vpos = 0;
1869 Buffer const & buffer = *bv.buffer();
1870 int const right_margin = tm.rightMargin(pm);
1871 RowMetrics const m = tm.computeRowMetrics(pit, row);
1874 pos_type const row_pos = row.pos();
1875 pos_type const end = row.endpos();
1878 cursor_vpos = row_pos;
1879 else if (ppos >= end)
1880 cursor_vpos = isRTL(buffer, par) ? row_pos : end;
1881 else if (ppos > row_pos && ppos >= end)
1882 // Place cursor after char at (logical) position pos - 1
1883 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1884 ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1886 // Place cursor before char at (logical) position ppos
1887 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1888 ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1890 pos_type body_pos = par.beginOfBody();
1892 (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1895 // Use font span to speed things up, see below
1898 FontMetrics const & labelfm = theFontMetrics(
1899 getLabelFont(buffer, par));
1901 for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1902 pos_type pos = bidi.vis2log(vpos);
1903 if (body_pos > 0 && pos == body_pos - 1) {
1905 docstring const lsep = from_utf8(par.layout()->labelsep);
1906 x += m.label_hfill + labelfm.width(lsep);
1907 if (par.isLineSeparator(body_pos - 1))
1908 x -= singleWidth(buffer, par, body_pos - 1);
1911 // Use font span to speed things up, see above
1912 if (pos < font_span.first || pos > font_span.last) {
1913 font_span = par.fontSpan(pos);
1914 font = getFont(buffer, par, pos);
1917 x += singleWidth(par, pos, par.getChar(pos), font);
1919 if (par.hfillExpansion(row, pos))
1920 x += (pos >= body_pos) ? m.hfill : m.label_hfill;
1921 else if (par.isSeparator(pos) && pos >= body_pos)
1925 // see correction above
1926 if (boundary_correction)
1927 if (getFont(buffer, par, ppos).isVisibleRightToLeft())
1928 x -= singleWidth(buffer, par, ppos);
1930 x += singleWidth(buffer, par, ppos);
1932 // Make sure inside an inset we always count from the left
1933 // edge (bidi!) -- MV
1934 if (sl.pos() < par.size()) {
1935 font = getFont(buffer, par, sl.pos());
1936 if (!boundary && font.isVisibleRightToLeft()
1937 && par.isInset(sl.pos()))
1938 x -= par.getInset(sl.pos())->width();
1944 int LyXText::cursorY(BufferView const & bv, CursorSlice const & sl, bool boundary) const
1946 //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
1947 ParagraphMetrics const & pm = bv.parMetrics(this, sl.pit());
1948 if (pm.rows().empty())
1952 h -= bv.parMetrics(this, 0).rows()[0].ascent();
1953 for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1954 h += bv.parMetrics(this, pit).height();
1957 if (pos && boundary)
1959 size_t const rend = pm.pos2row(pos);
1960 for (size_t rit = 0; rit != rend; ++rit)
1961 h += pm.rows()[rit].height();
1962 h += pm.rows()[rend].ascent();
1967 // Returns the current font and depth as a message.
1968 docstring LyXText::currentState(LCursor & cur)
1970 BOOST_ASSERT(this == cur.text());
1971 Buffer & buf = cur.buffer();
1972 Paragraph const & par = cur.paragraph();
1973 odocstringstream os;
1975 if (buf.params().trackChanges)
1978 Change change = par.lookupChange(cur.pos());
1980 if (change.type != Change::UNCHANGED) {
1981 Author const & a = buf.params().authors().get(change.author);
1982 os << _("Change: ") << a.name();
1983 if (!a.email().empty())
1984 os << " (" << a.email() << ")";
1985 // FIXME ctime is english, we should translate that
1986 os << _(" at ") << ctime(&change.changetime);
1990 // I think we should only show changes from the default
1992 // No, from the document font (MV)
1993 LyXFont font = real_current_font;
1994 font.reduce(buf.params().getFont());
1996 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1998 // The paragraph depth
1999 int depth = cur.paragraph().getDepth();
2001 os << bformat(_(", Depth: %1$d"), depth);
2003 // The paragraph spacing, but only if different from
2005 Spacing const & spacing = par.params().spacing();
2006 if (!spacing.isDefault()) {
2007 os << _(", Spacing: ");
2008 switch (spacing.getSpace()) {
2009 case Spacing::Single:
2012 case Spacing::Onehalf:
2015 case Spacing::Double:
2018 case Spacing::Other:
2019 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
2021 case Spacing::Default:
2022 // should never happen, do nothing
2027 #ifdef DEVEL_VERSION
2028 os << _(", Inset: ") << &cur.inset();
2029 os << _(", Paragraph: ") << cur.pit();
2030 os << _(", Id: ") << par.id();
2031 os << _(", Position: ") << cur.pos();
2032 os << _(", Boundary: ") << cur.boundary();
2033 // Row & row = cur.textRow();
2034 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2040 docstring LyXText::getPossibleLabel(LCursor & cur) const
2042 pit_type pit = cur.pit();
2044 LyXLayout_ptr layout = pars_[pit].layout();
2046 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2047 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2048 if (layout2->latextype != LATEX_PARAGRAPH) {
2054 docstring name = from_ascii(layout->latexname());
2056 // for captions, we want the abbreviation of the float type
2057 if (layout->labeltype == LABEL_SENSITIVE) {
2058 // Search for the first float or wrap inset in the iterator
2059 for (int i = cur.depth(); --i >= 0; ) {
2060 InsetBase * const in = &cur[i].inset();
2061 if (in->lyxCode() == InsetBase::FLOAT_CODE
2062 || in->lyxCode() == InsetBase::WRAP_CODE) {
2063 name = in->getInsetName();
2069 docstring text = name.substr(0, 3);
2070 if (name == "theorem")
2071 text = from_ascii("thm"); // Create a correct prefix for prettyref
2074 if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2077 docstring par_text = pars_[pit].asString(cur.buffer(), false);
2078 for (int i = 0; i < lyxrc.label_init_length; ++i) {
2079 if (par_text.empty())
2082 par_text = split(par_text, head, ' ');
2083 // Is it legal to use spaces in labels ?
2093 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2097 // Paragraph const & par = pars_[pit];
2098 // Row const & r = par.rows()[row];
2099 // int pos = r.pos();
2100 // for (; currx < x && pos < r.endpos(); ++pos) {
2102 // currx += singleWidth(buffer, par, pos);
2104 // if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2110 pos_type LyXText::x2pos(BufferView const & bv, pit_type pit, int row,
2113 TextMetrics const & tm = bv.textMetrics(this);
2114 ParagraphMetrics const & pm = tm.parMetrics(pit);
2115 BOOST_ASSERT(!pm.rows().empty());
2116 BOOST_ASSERT(row < int(pm.rows().size()));
2118 Row const & r = pm.rows()[row];
2119 Buffer const & buffer = *bv.buffer();
2120 return r.pos() + getColumnNearX(bv, tm.rightMargin(pm), pit, r, x, bound);
2124 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2126 // Paragraph const & par = pars_[pit];
2127 // Row const & r = par.rows()[row];
2133 // x,y are screen coordinates
2134 // sets cursor only within this LyXText
2135 bool LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2137 BOOST_ASSERT(this == cur.text());
2138 pit_type pit = getPitNearY(cur.bv(), y);
2140 TextMetrics const & tm = cur.bv().textMetrics(this);
2141 ParagraphMetrics const & pm = tm.parMetrics(pit);
2143 int yy = cur.bv().coordCache().get(this, pit).y_ - pm.ascent();
2144 lyxerr[Debug::DEBUG]
2145 << BOOST_CURRENT_FUNCTION
2149 << " yy: " << yy << endl;
2152 BOOST_ASSERT(pm.rows().size());
2153 for (; r < int(pm.rows().size()) - 1; ++r) {
2154 Row const & row = pm.rows()[r];
2155 if (int(yy + row.height()) > y)
2160 Row const & row = pm.rows()[r];
2162 lyxerr[Debug::DEBUG]
2163 << BOOST_CURRENT_FUNCTION
2165 << " from pos: " << row.pos()
2170 Buffer const & buffer = cur.buffer();
2171 int right_margin = tm.rightMargin(pm);
2172 pos_type const pos = row.pos() + getColumnNearX(cur.bv(), right_margin,
2173 pit, row, xx, bound);
2175 lyxerr[Debug::DEBUG]
2176 << BOOST_CURRENT_FUNCTION
2177 << ": setting cursor pit: " << pit
2181 return setCursor(cur, pit, pos, true, bound);
2185 void LyXText::charsTranspose(LCursor & cur)
2187 BOOST_ASSERT(this == cur.text());
2189 pos_type pos = cur.pos();
2191 // If cursor is at beginning or end of paragraph, do nothing.
2192 if (pos == cur.lastpos() || pos == 0)
2195 Paragraph & par = cur.paragraph();
2197 // Get the positions of the characters to be transposed.
2198 pos_type pos1 = pos - 1;
2199 pos_type pos2 = pos;
2201 // In change tracking mode, ignore deleted characters.
2202 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2204 if (pos2 == cur.lastpos())
2207 while (pos1 >= 0 && par.isDeleted(pos1))
2212 // Don't do anything if one of the "characters" is not regular text.
2213 if (par.isInset(pos1) || par.isInset(pos2))
2216 // Store the characters to be transposed (including font information).
2217 char_type char1 = par.getChar(pos1);
2218 LyXFont const font1 =
2219 par.getFontSettings(cur.buffer().params(), pos1);
2221 char_type char2 = par.getChar(pos2);
2222 LyXFont const font2 =
2223 par.getFontSettings(cur.buffer().params(), pos2);
2225 // And finally, we are ready to perform the transposition.
2226 // Track the changes if Change Tracking is enabled.
2227 bool const trackChanges = cur.buffer().params().trackChanges;
2231 par.eraseChar(pos2, trackChanges);
2232 par.eraseChar(pos1, trackChanges);
2233 par.insertChar(pos1, char2, font2, trackChanges);
2234 par.insertChar(pos2, char1, font1, trackChanges);
2236 // After the transposition, move cursor to after the transposition.
2237 setCursor(cur, cur.pit(), pos2);