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
9 * \author Angus Leeming
11 * \author André Pönitz
13 * \author Jürgen Vigna
15 * Full author contact details are available in file CREDITS.
20 #include "Paragraph.h"
22 #include "LayoutFile.h"
24 #include "BufferParams.h"
28 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "paragraph_funcs.h"
39 #include "ParagraphParameters.h"
41 #include "TextClass.h"
47 #include "frontends/alert.h"
49 #include "insets/InsetBibitem.h"
50 #include "insets/InsetLabel.h"
52 #include "support/lassert.h"
53 #include "support/convert.h"
54 #include "support/debug.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
57 #include "support/Messages.h"
58 #include "support/textutils.h"
64 using namespace lyx::support;
69 /// Inset identifier (above 0x10ffff, for ucs-4)
70 char_type const META_INSET = 0x200001;
73 /////////////////////////////////////////////////////////////////////
77 /////////////////////////////////////////////////////////////////////
79 class Paragraph::Private
83 Private(Paragraph * owner, Layout const & layout);
84 /// "Copy constructor"
85 Private(Private const &, Paragraph * owner);
88 void insertChar(pos_type pos, char_type c, Change const & change);
90 /// Output the surrogate pair formed by \p c and \p next to \p os.
91 /// \return the number of characters written.
92 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
95 /// Output a space in appropriate formatting (or a surrogate pair
96 /// if the next character is a combining character).
97 /// \return whether a surrogate pair was output.
98 bool simpleTeXBlanks(OutputParams const &,
99 odocstream &, TexRow & texrow,
101 unsigned int & column,
103 Layout const & style);
105 /// Output consecutive unicode chars, belonging to the same script as
106 /// specified by the latex macro \p ltx, to \p os starting from \p i.
107 /// \return the number of characters written.
108 int writeScriptChars(odocstream & os, docstring const & ltx,
109 Change &, Encoding const &, pos_type & i);
111 /// This could go to ParagraphParameters if we want to.
112 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
115 /// This could go to ParagraphParameters if we want to.
116 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
120 void latexInset(BufferParams const &,
122 TexRow & texrow, OutputParams &,
125 Font const & outerfont,
127 Change & running_change,
128 Layout const & style,
130 unsigned int & column);
133 void latexSpecialChar(
135 OutputParams & runparams,
137 Change & running_change,
138 Layout const & style,
140 unsigned int & column);
147 unsigned int & column);
149 bool latexSpecialTypewriter(
153 unsigned int & column);
155 bool latexSpecialPhrase(
158 unsigned int & column,
159 OutputParams & runparams);
162 void validate(LaTeXFeatures & features,
163 Layout const & layout) const;
165 /// Checks if the paragraph contains only text and no inset or font change.
166 bool onlyText(Buffer const & buf, Font const & outerfont,
167 pos_type initial) const;
169 /// match a string against a particular point in the paragraph
170 bool isTextAt(string const & str, pos_type pos) const;
172 /// Which Paragraph owns us?
176 Inset * inset_owner_;
184 static unsigned int paragraph_id;
186 ParagraphParameters params_;
188 /// for recording and looking up changes
192 InsetList insetlist_;
195 pos_type begin_of_body_;
197 typedef docstring TextContainer;
201 typedef std::set<docstring> Words;
205 Layout const * layout_;
209 // Initialization of the counter for the paragraph id's,
210 unsigned int Paragraph::Private::paragraph_id = 0;
214 struct special_phrase {
220 special_phrase const special_phrases[] = {
221 { "LyX", from_ascii("\\LyX{}"), false },
222 { "TeX", from_ascii("\\TeX{}"), true },
223 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
224 { "LaTeX", from_ascii("\\LaTeX{}"), true },
227 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
232 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
233 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
235 id_ = paragraph_id++;
240 Paragraph::Private::Private(Private const & p, Paragraph * owner)
241 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
242 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
243 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
246 id_ = paragraph_id++;
250 bool Paragraph::isChanged(pos_type start, pos_type end) const
252 LASSERT(start >= 0 && start <= size(), /**/);
253 LASSERT(end > start && end <= size() + 1, /**/);
255 return d->changes_.isChanged(start, end);
259 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
261 // keep the logic here in sync with the logic of eraseChars()
265 Change const change = d->changes_.lookup(size());
266 return change.type == Change::INSERTED && change.author == 0;
270 void Paragraph::setChange(Change const & change)
272 // beware of the imaginary end-of-par character!
273 d->changes_.set(change, 0, size() + 1);
276 * Propagate the change recursively - but not in case of DELETED!
278 * Imagine that your co-author makes changes in an existing inset. He
279 * sends your document to you and you come to the conclusion that the
280 * inset should go completely. If you erase it, LyX must not delete all
281 * text within the inset. Otherwise, the change tracked insertions of
282 * your co-author get lost and there is no way to restore them later.
284 * Conclusion: An inset's content should remain untouched if you delete it
287 if (change.type != Change::DELETED) {
288 for (pos_type pos = 0; pos < size(); ++pos) {
289 if (Inset * inset = getInset(pos))
290 inset->setChange(change);
296 void Paragraph::setChange(pos_type pos, Change const & change)
298 LASSERT(pos >= 0 && pos <= size(), /**/);
299 d->changes_.set(change, pos);
301 // see comment in setChange(Change const &) above
302 if (change.type != Change::DELETED && pos < size())
303 if (Inset * inset = getInset(pos))
304 inset->setChange(change);
308 Change const & Paragraph::lookupChange(pos_type pos) const
310 LASSERT(pos >= 0 && pos <= size(), /**/);
311 return d->changes_.lookup(pos);
315 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
318 LASSERT(start >= 0 && start <= size(), /**/);
319 LASSERT(end > start && end <= size() + 1, /**/);
321 for (pos_type pos = start; pos < end; ++pos) {
322 switch (lookupChange(pos).type) {
323 case Change::UNCHANGED:
324 // accept changes in nested inset
325 if (Inset * inset = getInset(pos))
326 inset->acceptChanges(bparams);
329 case Change::INSERTED:
330 d->changes_.set(Change(Change::UNCHANGED), pos);
331 // also accept changes in nested inset
332 if (Inset * inset = getInset(pos))
333 inset->acceptChanges(bparams);
336 case Change::DELETED:
337 // Suppress access to non-existent
338 // "end-of-paragraph char"
340 eraseChar(pos, false);
351 void Paragraph::rejectChanges(BufferParams const & bparams,
352 pos_type start, pos_type end)
354 LASSERT(start >= 0 && start <= size(), /**/);
355 LASSERT(end > start && end <= size() + 1, /**/);
357 for (pos_type pos = start; pos < end; ++pos) {
358 switch (lookupChange(pos).type) {
359 case Change::UNCHANGED:
360 // reject changes in nested inset
361 if (Inset * inset = getInset(pos))
362 inset->rejectChanges(bparams);
365 case Change::INSERTED:
366 // Suppress access to non-existent
367 // "end-of-paragraph char"
369 eraseChar(pos, false);
375 case Change::DELETED:
376 d->changes_.set(Change(Change::UNCHANGED), pos);
378 // Do NOT reject changes within a deleted inset!
379 // There may be insertions of a co-author inside of it!
387 void Paragraph::Private::insertChar(pos_type pos, char_type c,
388 Change const & change)
390 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
393 changes_.insert(change, pos);
395 // This is actually very common when parsing buffers (and
396 // maybe inserting ascii text)
397 if (pos == pos_type(text_.size())) {
398 // when appending characters, no need to update tables
403 text_.insert(text_.begin() + pos, c);
405 // Update the font table.
406 fontlist_.increasePosAfterPos(pos);
409 insetlist_.increasePosAfterPos(pos);
413 void Paragraph::insertInset(pos_type pos, Inset * inset,
414 Change const & change)
416 LASSERT(inset, /**/);
417 LASSERT(pos >= 0 && pos <= size(), /**/);
419 d->insertChar(pos, META_INSET, change);
420 LASSERT(d->text_[pos] == META_INSET, /**/);
422 // Add a new entry in the insetlist_.
423 d->insetlist_.insert(inset, pos);
427 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
429 LASSERT(pos >= 0 && pos <= size(), /**/);
431 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
434 Change change = d->changes_.lookup(pos);
436 // set the character to DELETED if
437 // a) it was previously unchanged or
438 // b) it was inserted by a co-author
440 if (change.type == Change::UNCHANGED ||
441 (change.type == Change::INSERTED && change.author != 0)) {
442 setChange(pos, Change(Change::DELETED));
446 if (change.type == Change::DELETED)
450 // Don't physically access the imaginary end-of-paragraph character.
451 // eraseChar() can only mark it as DELETED. A physical deletion of
452 // end-of-par must be handled externally.
458 d->changes_.erase(pos);
460 // if it is an inset, delete the inset entry
461 if (d->text_[pos] == META_INSET)
462 d->insetlist_.erase(pos);
464 d->text_.erase(d->text_.begin() + pos);
466 // Update the fontlist_
467 d->fontlist_.erase(pos);
469 // Update the insetlist_
470 d->insetlist_.decreasePosAfterPos(pos);
476 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
478 LASSERT(start >= 0 && start <= size(), /**/);
479 LASSERT(end >= start && end <= size() + 1, /**/);
482 for (pos_type count = end - start; count; --count) {
483 if (!eraseChar(i, trackChanges))
490 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
491 char_type next, Encoding const & encoding)
493 // Writing next here may circumvent a possible font change between
494 // c and next. Since next is only output if it forms a surrogate pair
495 // with c we can ignore this:
496 // A font change inside a surrogate pair does not make sense and is
497 // hopefully impossible to input.
498 // FIXME: change tracking
499 // Is this correct WRT change tracking?
500 docstring const latex1 = encoding.latexChar(next);
501 docstring const latex2 = encoding.latexChar(c);
502 if (docstring(1, next) == latex1) {
503 // the encoding supports the combination
504 os << latex2 << latex1;
505 return latex1.length() + latex2.length();
507 os << latex1 << '{' << latex2 << '}';
508 return latex1.length() + latex2.length() + 2;
512 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
513 odocstream & os, TexRow & texrow,
515 unsigned int & column,
517 Layout const & style)
519 if (style.pass_thru || runparams.verbatim)
522 if (i + 1 < int(text_.size())) {
523 char_type next = text_[i + 1];
524 if (Encodings::isCombiningChar(next)) {
525 Encoding const & encoding = *(runparams.encoding);
526 // This space has an accent, so we must always output it.
527 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
532 if (lyxrc.plaintext_linelen > 0
533 && column > lyxrc.plaintext_linelen
535 && text_[i - 1] != ' '
536 && (i + 1 < int(text_.size()))
537 // same in FreeSpacing mode
538 && !owner_->isFreeSpacing()
539 // In typewriter mode, we want to avoid
540 // ! . ? : at the end of a line
541 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
542 && (text_[i - 1] == '.'
543 || text_[i - 1] == '?'
544 || text_[i - 1] == ':'
545 || text_[i - 1] == '!'))) {
548 texrow.start(owner_->id(), i + 1);
550 } else if (style.free_spacing) {
559 int Paragraph::Private::writeScriptChars(odocstream & os,
560 docstring const & ltx,
561 Change & runningChange,
562 Encoding const & encoding,
565 // FIXME: modifying i here is not very nice...
567 // We only arrive here when a proper language for character text_[i] has
568 // not been specified (i.e., it could not be translated in the current
569 // latex encoding) or its latex translation has been forced, and it
570 // belongs to a known script.
571 // Parameter ltx contains the latex translation of text_[i] as specified
572 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
573 // The latex macro name "textXXX" specifies the script to which text_[i]
574 // belongs and we use it in order to check whether characters from the
575 // same script immediately follow, such that we can collect them in a
576 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
577 // for the first char but only "<spec>" for all subsequent chars.
578 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
579 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
580 string script = to_ascii(ltx.substr(1, brace1 - 1));
583 bool closing_brace = true;
584 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
585 // Correct encoding is being used, so we can avoid \textgreek.
588 closing_brace = false;
590 os << ltx.substr(pos, length);
591 int size = text_.size();
592 while (i + 1 < size) {
593 char_type const next = text_[i + 1];
594 // Stop here if next character belongs to another script
595 // or there is a change in change tracking status.
596 if (!Encodings::isKnownScriptChar(next, script) ||
597 runningChange != owner_->lookupChange(i + 1))
601 FontList::const_iterator cit = fontlist_.begin();
602 FontList::const_iterator end = fontlist_.end();
603 for (; cit != end; ++cit) {
604 if (cit->pos() >= i && !found) {
605 prev_font = cit->font();
608 if (cit->pos() >= i + 1)
611 // Stop here if there is a font attribute or encoding change.
612 if (found && cit != end && prev_font != cit->font())
614 docstring const latex = encoding.latexChar(next);
615 docstring::size_type const b1 =
616 latex.find_first_of(from_ascii("{"));
617 docstring::size_type const b2 =
618 latex.find_last_of(from_ascii("}"));
619 int const len = b2 - b1 - 1;
620 os << latex.substr(b1 + 1, len);
632 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
634 pos_type const len = str.length();
636 // is the paragraph large enough?
637 if (pos + len > int(text_.size()))
640 // does the wanted text start at point?
641 for (string::size_type i = 0; i < str.length(); ++i) {
642 // Caution: direct comparison of characters works only
643 // because str is pure ASCII.
644 if (str[i] != text_[pos + i])
648 return fontlist_.hasChangeInRange(pos, len);
652 void Paragraph::Private::latexInset(
653 BufferParams const & bparams,
656 OutputParams & runparams,
659 Font const & outerfont,
661 Change & running_change,
662 Layout const & style,
664 unsigned int & column)
666 Inset * inset = owner_->getInset(i);
667 LASSERT(inset, /**/);
669 if (style.pass_thru) {
670 inset->plaintext(os, runparams);
674 // FIXME: move this to InsetNewline::latex
675 if (inset->lyxCode() == NEWLINE_CODE) {
676 // newlines are handled differently here than
677 // the default in simpleTeXSpecialChars().
678 if (!style.newline_allowed) {
682 column += running_font.latexWriteEndChanges(
683 os, bparams, runparams,
688 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
691 basefont = owner_->getLayoutFont(bparams, outerfont);
692 running_font = basefont;
694 if (runparams.moving_arg)
699 texrow.start(owner_->id(), i + 1);
703 if (owner_->lookupChange(i).type == Change::DELETED) {
704 if( ++runparams.inDeletedInset == 1)
705 runparams.changeOfDeletedInset = owner_->lookupChange(i);
708 if (inset->canTrackChanges()) {
709 column += Changes::latexMarkChange(os, bparams, running_change,
710 Change(Change::UNCHANGED));
711 running_change = Change(Change::UNCHANGED);
715 odocstream::pos_type const len = os.tellp();
717 if (inset->forceLTR()
718 && running_font.isRightToLeft()
719 // ERT is an exception, it should be output with no decorations at all
720 && inset->lyxCode() != ERT_CODE) {
721 if (running_font.language()->lang() == "farsi")
728 // FIXME: Bug: we can have an empty font change here!
729 // if there has just been a font change, we are going to close it
730 // right now, which means stupid latex code like \textsf{}. AFAIK,
731 // this does not harm dvi output. A minor bug, thus (JMarc)
733 // Some insets cannot be inside a font change command.
734 // However, even such insets *can* be placed in \L or \R
735 // or their equivalents (for RTL language switches), so we don't
736 // close the language in those cases.
737 // ArabTeX, though, cannot handle this special behavior, it seems.
738 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
739 || running_font.language()->lang() == "arabic_arabtex";
740 if (open_font && inset->noFontChange()) {
741 bool closeLanguage = arabtex
742 || basefont.isRightToLeft() == running_font.isRightToLeft();
743 unsigned int count = running_font.latexWriteEndChanges(os,
744 bparams, runparams, basefont, basefont, closeLanguage);
746 // if any font properties were closed, update the running_font,
747 // making sure, however, to leave the language as it was
749 // FIXME: probably a better way to keep track of the old
750 // language, than copying the entire font?
751 Font const copy_font(running_font);
752 basefont = owner_->getLayoutFont(bparams, outerfont);
753 running_font = basefont;
755 running_font.setLanguage(copy_font.language());
756 // leave font open if language is still open
757 open_font = (running_font.language() == basefont.language());
759 runparams.local_font = &basefont;
766 tmp = inset->latex(os, runparams);
767 } catch (EncodingException & e) {
768 // add location information and throw again.
775 if (running_font.language()->lang() == "farsi")
782 for (int j = 0; j < tmp; ++j)
785 texrow.start(owner_->id(), i + 1);
788 column += os.tellp() - len;
791 if (owner_->lookupChange(i).type == Change::DELETED)
792 --runparams.inDeletedInset;
796 void Paragraph::Private::latexSpecialChar(
798 OutputParams & runparams,
800 Change & running_change,
801 Layout const & style,
803 unsigned int & column)
805 char_type const c = text_[i];
807 if (style.pass_thru) {
809 // FIXME UNICODE: This can fail if c cannot
810 // be encoded in the current encoding.
815 if (runparams.verbatim) {
816 // FIXME UNICODE: This can fail if c cannot
817 // be encoded in the current encoding.
822 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
825 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
826 && latexSpecialTypewriter(c, os, i, column))
829 // Otherwise, we use what LaTeX provides us.
832 os << "\\textbackslash{}";
836 os << "\\textless{}";
840 os << "\\textgreater{}";
851 os << "\\char`\\\"{}";
856 case '%': case '#': case '{':
864 os << "\\textasciitilde{}";
869 os << "\\textasciicircum{}";
874 // avoid being mistaken for optional arguments
882 // Blanks are printed before font switching.
883 // Sure? I am not! (try nice-latex)
884 // I am sure it's correct. LyX might be smarter
885 // in the future, but for now, nothing wrong is
891 if (latexSpecialPhrase(os, i, column, runparams))
897 Encoding const & encoding = *(runparams.encoding);
898 if (i + 1 < int(text_.size())) {
899 char_type next = text_[i + 1];
900 if (Encodings::isCombiningChar(next)) {
901 column += latexSurrogatePair(os, c, next, encoding) - 1;
907 docstring const latex = encoding.latexChar(c);
908 if (Encodings::isKnownScriptChar(c, script)
909 && prefixIs(latex, from_ascii("\\" + script)))
910 column += writeScriptChars(os, latex,
911 running_change, encoding, i) - 1;
912 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
913 // Prevent eating of a following
914 // space or command corruption by
915 // following characters
916 column += latex.length() + 1;
919 column += latex.length() - 1;
927 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
928 pos_type & i, unsigned int & column)
934 // In T1 encoding, these characters exist
935 // but we should avoid ligatures
936 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
938 os << "\\textcompwordmark{}";
950 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
951 pos_type & i, unsigned int & column)
955 // within \ttfamily, "--" is merged to "-" (no endash)
956 // so we avoid this rather irritating ligature
957 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
964 // everything else has to be checked separately
965 // (depending on the encoding)
972 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
973 unsigned int & column, OutputParams & runparams)
975 // FIXME: if we have "LaTeX" with a font
976 // change in the middle (before the 'T', then
977 // the "TeX" part is still special cased.
978 // Really we should only operate this on
979 // "words" for some definition of word
981 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
982 if (!isTextAt(special_phrases[pnr].phrase, i))
984 if (runparams.moving_arg)
986 os << special_phrases[pnr].macro;
987 i += special_phrases[pnr].phrase.length() - 1;
988 column += special_phrases[pnr].macro.length() - 1;
995 void Paragraph::Private::validate(LaTeXFeatures & features,
996 Layout const & layout) const
999 if (!params_.spacing().isDefault())
1000 features.require("setspace");
1003 features.useLayout(layout.name());
1006 fontlist_.validate(features);
1008 // then the indentation
1009 if (!params_.leftIndent().zero())
1010 features.require("ParagraphLeftIndent");
1013 InsetList::const_iterator icit = insetlist_.begin();
1014 InsetList::const_iterator iend = insetlist_.end();
1015 for (; icit != iend; ++icit) {
1017 icit->inset->validate(features);
1018 if (layout.needprotect &&
1019 icit->inset->lyxCode() == FOOT_CODE)
1020 features.require("NeedLyXFootnoteCode");
1024 // then the contents
1025 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1026 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1027 if (!special_phrases[pnr].builtin
1028 && isTextAt(special_phrases[pnr].phrase, i)) {
1029 features.require(special_phrases[pnr].phrase);
1033 Encodings::validate(text_[i], features);
1037 /////////////////////////////////////////////////////////////////////
1041 /////////////////////////////////////////////////////////////////////
1044 Layout const emptyParagraphLayout;
1047 Paragraph::Paragraph()
1048 : d(new Paragraph::Private(this, emptyParagraphLayout))
1055 Paragraph::Paragraph(Paragraph const & par)
1056 : itemdepth(par.itemdepth),
1057 d(new Paragraph::Private(*par.d, this))
1063 Paragraph & Paragraph::operator=(Paragraph const & par)
1065 // needed as we will destroy the private part before copying it
1067 itemdepth = par.itemdepth;
1071 d = new Private(*par.d, this);
1078 Paragraph::~Paragraph()
1085 void Paragraph::write(ostream & os, BufferParams const & bparams,
1086 depth_type & dth) const
1088 // The beginning or end of a deeper (i.e. nested) area?
1089 if (dth != d->params_.depth()) {
1090 if (d->params_.depth() > dth) {
1091 while (d->params_.depth() > dth) {
1092 os << "\n\\begin_deeper";
1096 while (d->params_.depth() < dth) {
1097 os << "\n\\end_deeper";
1103 // First write the layout
1104 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1106 d->params_.write(os);
1108 Font font1(inherit_font, bparams.language);
1110 Change running_change = Change(Change::UNCHANGED);
1113 for (pos_type i = 0; i <= size(); ++i) {
1115 Change change = lookupChange(i);
1116 Changes::lyxMarkChange(os, column, running_change, change);
1117 running_change = change;
1122 // Write font changes
1123 Font font2 = getFontSettings(bparams, i);
1124 if (font2 != font1) {
1125 font2.lyxWriteChanges(font1, os);
1130 char_type const c = d->text_[i];
1133 if (Inset const * inset = getInset(i)) {
1134 if (inset->directWrite()) {
1135 // international char, let it write
1136 // code directly so it's shorter in
1142 os << "\\begin_inset ";
1144 os << "\n\\end_inset\n\n";
1150 os << "\n\\backslash\n";
1154 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1161 if ((column > 70 && c == ' ')
1166 // this check is to amend a bug. LyX sometimes
1167 // inserts '\0' this could cause problems.
1169 os << to_utf8(docstring(1, c));
1171 LYXERR0("NUL char in structure.");
1177 os << "\n\\end_layout\n";
1181 void Paragraph::validate(LaTeXFeatures & features) const
1183 d->validate(features, *d->layout_);
1187 void Paragraph::insert(pos_type start, docstring const & str,
1188 Font const & font, Change const & change)
1190 for (size_t i = 0, n = str.size(); i != n ; ++i)
1191 insertChar(start + i, str[i], font, change);
1195 void Paragraph::appendChar(char_type c, Font const & font,
1196 Change const & change)
1199 d->changes_.insert(change, d->text_.size());
1200 // when appending characters, no need to update tables
1201 d->text_.push_back(c);
1202 setFont(d->text_.size() - 1, font);
1206 void Paragraph::appendString(docstring const & s, Font const & font,
1207 Change const & change)
1209 pos_type end = s.size();
1210 size_t oldsize = d->text_.size();
1211 size_t newsize = oldsize + end;
1212 size_t capacity = d->text_.capacity();
1213 if (newsize >= capacity)
1214 d->text_.reserve(max(capacity + 100, newsize));
1216 // when appending characters, no need to update tables
1219 // FIXME: Optimize this!
1220 for (pos_type i = oldsize; i != newsize; ++i) {
1222 d->changes_.insert(change, i);
1224 d->fontlist_.set(oldsize, font);
1225 d->fontlist_.set(newsize - 1, font);
1229 void Paragraph::insertChar(pos_type pos, char_type c,
1232 d->insertChar(pos, c, Change(trackChanges ?
1233 Change::INSERTED : Change::UNCHANGED));
1237 void Paragraph::insertChar(pos_type pos, char_type c,
1238 Font const & font, bool trackChanges)
1240 d->insertChar(pos, c, Change(trackChanges ?
1241 Change::INSERTED : Change::UNCHANGED));
1246 void Paragraph::insertChar(pos_type pos, char_type c,
1247 Font const & font, Change const & change)
1249 d->insertChar(pos, c, change);
1254 void Paragraph::insertInset(pos_type pos, Inset * inset,
1255 Font const & font, Change const & change)
1257 insertInset(pos, inset, change);
1258 // Set the font/language of the inset...
1263 bool Paragraph::insetAllowed(InsetCode code)
1265 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1269 void Paragraph::resetFonts(Font const & font)
1271 d->fontlist_.clear();
1272 d->fontlist_.set(0, font);
1273 d->fontlist_.set(d->text_.size() - 1, font);
1276 // Gets uninstantiated font setting at position.
1277 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1281 LYXERR0("pos: " << pos << " size: " << size());
1282 LASSERT(pos <= size(), /**/);
1285 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1286 if (cit != d->fontlist_.end())
1289 if (pos == size() && !empty())
1290 return getFontSettings(bparams, pos - 1);
1292 return Font(inherit_font, getParLanguage(bparams));
1296 FontSpan Paragraph::fontSpan(pos_type pos) const
1298 LASSERT(pos <= size(), /**/);
1301 FontList::const_iterator cit = d->fontlist_.begin();
1302 FontList::const_iterator end = d->fontlist_.end();
1303 for (; cit != end; ++cit) {
1304 if (cit->pos() >= pos) {
1305 if (pos >= beginOfBody())
1306 return FontSpan(max(start, beginOfBody()),
1309 return FontSpan(start,
1310 min(beginOfBody() - 1,
1313 start = cit->pos() + 1;
1316 // This should not happen, but if so, we take no chances.
1317 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1318 return FontSpan(pos, pos);
1322 // Gets uninstantiated font setting at position 0
1323 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1325 if (!empty() && !d->fontlist_.empty())
1326 return d->fontlist_.begin()->font();
1328 return Font(inherit_font, bparams.language);
1332 // Gets the fully instantiated font at a given position in a paragraph
1333 // This is basically the same function as Text::GetFont() in text2.cpp.
1334 // The difference is that this one is used for generating the LaTeX file,
1335 // and thus cosmetic "improvements" are disallowed: This has to deliver
1336 // the true picture of the buffer. (Asger)
1337 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1338 Font const & outerfont) const
1340 LASSERT(pos >= 0, /**/);
1342 Font font = getFontSettings(bparams, pos);
1344 pos_type const body_pos = beginOfBody();
1346 font.fontInfo().realize(d->layout_->labelfont);
1348 font.fontInfo().realize(d->layout_->font);
1350 font.fontInfo().realize(outerfont.fontInfo());
1351 font.fontInfo().realize(bparams.getFont().fontInfo());
1357 Font const Paragraph::getLabelFont
1358 (BufferParams const & bparams, Font const & outerfont) const
1360 FontInfo tmpfont = d->layout_->labelfont;
1361 tmpfont.realize(outerfont.fontInfo());
1362 tmpfont.realize(bparams.getFont().fontInfo());
1363 return Font(tmpfont, getParLanguage(bparams));
1367 Font const Paragraph::getLayoutFont
1368 (BufferParams const & bparams, Font const & outerfont) const
1370 FontInfo tmpfont = d->layout_->font;
1371 tmpfont.realize(outerfont.fontInfo());
1372 tmpfont.realize(bparams.getFont().fontInfo());
1373 return Font(tmpfont, getParLanguage(bparams));
1377 /// Returns the height of the highest font in range
1378 FontSize Paragraph::highestFontInRange
1379 (pos_type startpos, pos_type endpos, FontSize def_size) const
1381 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1385 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1387 char_type c = d->text_[pos];
1388 if (!lyxrc.rtl_support)
1418 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1424 void Paragraph::setFont(pos_type pos, Font const & font)
1426 LASSERT(pos <= size(), /**/);
1428 // First, reduce font against layout/label font
1429 // Update: The setCharFont() routine in text2.cpp already
1430 // reduces font, so we don't need to do that here. (Asger)
1432 d->fontlist_.set(pos, font);
1436 void Paragraph::makeSameLayout(Paragraph const & par)
1438 d->layout_ = par.d->layout_;
1439 d->params_ = par.d->params_;
1443 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1445 if (isFreeSpacing())
1451 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1452 if (eraseChar(pos, trackChanges))
1458 return count > 0 || pos > 0;
1462 bool Paragraph::hasSameLayout(Paragraph const & par) const
1464 return par.d->layout_ == d->layout_
1465 && d->params_.sameLayout(par.d->params_);
1469 depth_type Paragraph::getDepth() const
1471 return d->params_.depth();
1475 depth_type Paragraph::getMaxDepthAfter() const
1477 if (d->layout_->isEnvironment())
1478 return d->params_.depth() + 1;
1480 return d->params_.depth();
1484 char Paragraph::getAlign() const
1486 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1487 return d->layout_->align;
1489 return d->params_.align();
1493 docstring const & Paragraph::labelString() const
1495 return d->params_.labelString();
1499 // the next two functions are for the manual labels
1500 docstring const Paragraph::getLabelWidthString() const
1502 if (d->layout_->margintype == MARGIN_MANUAL)
1503 return d->params_.labelWidthString();
1505 return _("Senseless with this layout!");
1509 void Paragraph::setLabelWidthString(docstring const & s)
1511 d->params_.labelWidthString(s);
1515 docstring const Paragraph::translateIfPossible(docstring const & s,
1516 BufferParams const & bparams) const
1518 if (!isAscii(s) || s.empty()) {
1519 // This must be a user defined layout. We cannot translate
1520 // this, since gettext accepts only ascii keys.
1523 // Probably standard layout, try to translate
1524 Messages & m = getMessages(getParLanguage(bparams)->code());
1525 return m.get(to_ascii(s));
1529 docstring Paragraph::expandLabel(Layout const & layout,
1530 BufferParams const & bparams, bool process_appendix) const
1532 DocumentClass const & tclass = bparams.documentClass();
1535 if (process_appendix && d->params_.appendix())
1536 fmt = translateIfPossible(layout.labelstring_appendix(),
1539 fmt = translateIfPossible(layout.labelstring(), bparams);
1541 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1542 && !layout.counter.empty())
1543 fmt = "\\the" + layout.counter;
1545 // handle 'inherited level parts' in 'fmt',
1546 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1547 size_t const i = fmt.find('@', 0);
1548 if (i != docstring::npos) {
1549 size_t const j = fmt.find('@', i + 1);
1550 if (j != docstring::npos) {
1551 docstring parent(fmt, i + 1, j - i - 1);
1552 docstring label = from_ascii("??");
1553 if (tclass.hasLayout(parent))
1554 docstring label = expandLabel(tclass[parent], bparams,
1556 fmt = docstring(fmt, 0, i) + label
1557 + docstring(fmt, j + 1, docstring::npos);
1561 return tclass.counters().counterLabel(fmt);
1565 void Paragraph::applyLayout(Layout const & new_layout)
1567 d->layout_ = &new_layout;
1568 LyXAlignment const oldAlign = d->params_.align();
1570 if (!(oldAlign & d->layout_->alignpossible)) {
1571 frontend::Alert::warning(_("Alignment not permitted"),
1572 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1573 d->params_.align(LYX_ALIGN_LAYOUT);
1578 pos_type Paragraph::beginOfBody() const
1580 return d->begin_of_body_;
1584 void Paragraph::setBeginOfBody()
1586 if (d->layout_->labeltype != LABEL_MANUAL) {
1587 d->begin_of_body_ = 0;
1591 // Unroll the first two cycles of the loop
1592 // and remember the previous character to
1593 // remove unnecessary getChar() calls
1595 pos_type end = size();
1596 if (i < end && !isNewline(i)) {
1598 char_type previous_char = 0;
1601 previous_char = d->text_[i];
1602 if (!isNewline(i)) {
1604 while (i < end && previous_char != ' ') {
1609 previous_char = temp;
1615 d->begin_of_body_ = i;
1619 bool Paragraph::forcePlainLayout() const
1621 Inset const * const inset = inInset();
1624 return inset->forcePlainLayout();
1628 bool Paragraph::allowParagraphCustomization() const
1630 Inset const * const inset = inInset();
1633 return inset->allowParagraphCustomization();
1637 bool Paragraph::usePlainLayout() const
1639 Inset const * const inset = inInset();
1642 return inset->usePlainLayout();
1648 // paragraphs inside floats need different alignment tags to avoid
1651 bool noTrivlistCentering(InsetCode code)
1653 return code == FLOAT_CODE || code == WRAP_CODE;
1657 string correction(string const & orig)
1659 if (orig == "flushleft")
1660 return "raggedright";
1661 if (orig == "flushright")
1662 return "raggedleft";
1663 if (orig == "center")
1669 string const corrected_env(string const & suffix, string const & env,
1672 string output = suffix + "{";
1673 if (noTrivlistCentering(code))
1674 output += correction(env);
1678 if (suffix == "\\begin")
1684 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1686 if (!contains(str, "\n"))
1687 column += str.size();
1691 column = rsplit(str, tmp, '\n').size();
1698 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1699 odocstream & os, TexRow & texrow,
1700 bool moving_arg) const
1704 if (params_.noindent()) {
1705 os << "\\noindent ";
1709 LyXAlignment const curAlign = params_.align();
1711 if (curAlign == layout_->align)
1715 case LYX_ALIGN_NONE:
1716 case LYX_ALIGN_BLOCK:
1717 case LYX_ALIGN_LAYOUT:
1718 case LYX_ALIGN_SPECIAL:
1720 case LYX_ALIGN_LEFT:
1721 case LYX_ALIGN_RIGHT:
1722 case LYX_ALIGN_CENTER:
1731 case LYX_ALIGN_NONE:
1732 case LYX_ALIGN_BLOCK:
1733 case LYX_ALIGN_LAYOUT:
1734 case LYX_ALIGN_SPECIAL:
1736 case LYX_ALIGN_LEFT: {
1738 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1739 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1741 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1742 os << from_ascii(output);
1743 adjust_row_column(output, texrow, column);
1745 } case LYX_ALIGN_RIGHT: {
1747 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1748 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1750 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1751 os << from_ascii(output);
1752 adjust_row_column(output, texrow, column);
1754 } case LYX_ALIGN_CENTER: {
1756 output = corrected_env("\\begin", "center", owner_->ownerCode());
1757 os << from_ascii(output);
1758 adjust_row_column(output, texrow, column);
1767 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1768 odocstream & os, TexRow & texrow,
1769 bool moving_arg) const
1773 switch (params_.align()) {
1774 case LYX_ALIGN_NONE:
1775 case LYX_ALIGN_BLOCK:
1776 case LYX_ALIGN_LAYOUT:
1777 case LYX_ALIGN_SPECIAL:
1779 case LYX_ALIGN_LEFT:
1780 case LYX_ALIGN_RIGHT:
1781 case LYX_ALIGN_CENTER:
1789 switch (params_.align()) {
1790 case LYX_ALIGN_NONE:
1791 case LYX_ALIGN_BLOCK:
1792 case LYX_ALIGN_LAYOUT:
1793 case LYX_ALIGN_SPECIAL:
1795 case LYX_ALIGN_LEFT: {
1797 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1798 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1800 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1801 os << from_ascii(output);
1802 adjust_row_column(output, texrow, column);
1804 } case LYX_ALIGN_RIGHT: {
1806 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1807 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1809 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1810 os << from_ascii(output);
1811 adjust_row_column(output, texrow, column);
1813 } case LYX_ALIGN_CENTER: {
1815 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1816 os << from_ascii(output);
1817 adjust_row_column(output, texrow, column);
1826 // This one spits out the text of the paragraph
1827 bool Paragraph::latex(BufferParams const & bparams,
1828 Font const & outerfont,
1829 odocstream & os, TexRow & texrow,
1830 OutputParams const & runparams) const
1832 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1834 bool return_value = false;
1836 bool asdefault = forcePlainLayout();
1838 Layout const & style = asdefault ?
1839 bparams.documentClass().emptyLayout() :
1842 // Current base font for all inherited font changes, without any
1843 // change caused by an individual character, except for the language:
1844 // It is set to the language of the first character.
1845 // As long as we are in the label, this font is the base font of the
1846 // label. Before the first body character it is set to the base font
1850 // Maybe we have to create a optional argument.
1851 pos_type body_pos = beginOfBody();
1852 unsigned int column = 0;
1855 // the optional argument is kept in curly brackets in
1856 // case it contains a ']'
1859 basefont = getLabelFont(bparams, outerfont);
1861 basefont = getLayoutFont(bparams, outerfont);
1864 // Which font is currently active?
1865 Font running_font(basefont);
1866 // Do we have an open font change?
1867 bool open_font = false;
1869 Change runningChange = Change(Change::UNCHANGED);
1871 texrow.start(id(), 0);
1873 // if the paragraph is empty, the loop will not be entered at all
1875 if (style.isCommand()) {
1880 column += d->startTeXParParams(bparams, os, texrow,
1881 runparams.moving_arg);
1884 for (pos_type i = 0; i < size(); ++i) {
1885 // First char in paragraph or after label?
1886 if (i == body_pos) {
1889 column += running_font.latexWriteEndChanges(
1890 os, bparams, runparams,
1891 basefont, basefont);
1894 basefont = getLayoutFont(bparams, outerfont);
1895 running_font = basefont;
1897 column += Changes::latexMarkChange(os, bparams,
1898 runningChange, Change(Change::UNCHANGED));
1899 runningChange = Change(Change::UNCHANGED);
1904 if (style.isCommand()) {
1910 column += d->startTeXParParams(bparams, os,
1912 runparams.moving_arg);
1915 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1918 if (bparams.outputChanges && runningChange != change) {
1920 column += running_font.latexWriteEndChanges(
1921 os, bparams, runparams, basefont, basefont);
1924 basefont = getLayoutFont(bparams, outerfont);
1925 running_font = basefont;
1927 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1928 runningChange = change;
1931 // do not output text which is marked deleted
1932 // if change tracking output is disabled
1933 if (!bparams.outputChanges && change.type == Change::DELETED) {
1939 // Fully instantiated font
1940 Font const font = getFont(bparams, i, outerfont);
1942 Font const last_font = running_font;
1944 // Do we need to close the previous font?
1946 (font != running_font ||
1947 font.language() != running_font.language()))
1949 column += running_font.latexWriteEndChanges(
1950 os, bparams, runparams, basefont,
1951 (i == body_pos-1) ? basefont : font);
1952 running_font = basefont;
1956 // close babel's font environment before opening CJK.
1957 if (!running_font.language()->babel().empty() &&
1958 font.language()->encoding()->package() == Encoding::CJK) {
1959 string end_tag = subst(lyxrc.language_command_end,
1961 running_font.language()->babel());
1962 os << from_ascii(end_tag);
1963 column += end_tag.length();
1966 // Switch file encoding if necessary (and allowed)
1967 if (!runparams.verbatim &&
1968 runparams.encoding->package() != Encoding::none &&
1969 font.language()->encoding()->package() != Encoding::none) {
1970 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1971 runparams, *(font.language()->encoding()));
1972 if (enc_switch.first) {
1973 column += enc_switch.second;
1974 runparams.encoding = font.language()->encoding();
1978 char_type const c = d->text_[i];
1980 // Do we need to change font?
1981 if ((font != running_font ||
1982 font.language() != running_font.language()) &&
1985 odocstringstream ods;
1986 column += font.latexWriteStartChanges(ods, bparams,
1987 runparams, basefont,
1989 running_font = font;
1991 docstring fontchange = ods.str();
1992 // check if the fontchange ends with a trailing blank
1993 // (like "\small " (see bug 3382)
1994 if (suffixIs(fontchange, ' ') && c == ' ')
1995 os << fontchange.substr(0, fontchange.size() - 1)
1996 << from_ascii("{}");
2002 // FIXME: integrate this case in latexSpecialChar
2003 // Do not print the separation of the optional argument
2004 // if style.pass_thru is false. This works because
2005 // latexSpecialChar ignores spaces if
2006 // style.pass_thru is false.
2007 if (i != body_pos - 1) {
2008 if (d->simpleTeXBlanks(
2009 runparams, os, texrow,
2010 i, column, font, style)) {
2011 // A surrogate pair was output. We
2012 // must not call latexSpecialChar
2013 // in this iteration, since it would output
2014 // the combining character again.
2021 OutputParams rp = runparams;
2022 rp.free_spacing = style.free_spacing;
2023 rp.local_font = &font;
2024 rp.intitle = style.intitle;
2026 // Two major modes: LaTeX or plain
2027 // Handle here those cases common to both modes
2028 // and then split to handle the two modes separately.
2029 if (c == META_INSET)
2030 d->latexInset(bparams, os,
2031 texrow, rp, running_font,
2032 basefont, outerfont, open_font,
2033 runningChange, style, i, column);
2036 d->latexSpecialChar(os, rp, running_font, runningChange,
2038 } catch (EncodingException & e) {
2039 if (runparams.dryrun) {
2040 os << "<" << _("LyX Warning: ")
2041 << _("uncodable character") << " '";
2045 // add location information and throw again.
2053 // Set the encoding to that returned from latexSpecialChar (see
2054 // comment for encoding member in OutputParams.h)
2055 runparams.encoding = rp.encoding;
2058 // If we have an open font definition, we have to close it
2060 #ifdef FIXED_LANGUAGE_END_DETECTION
2063 .latexWriteEndChanges(os, bparams, runparams,
2065 next_->getFont(bparams, 0, outerfont));
2067 running_font.latexWriteEndChanges(os, bparams,
2068 runparams, basefont, basefont);
2071 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2072 //FIXME: there as we start another \selectlanguage with the next paragraph if
2073 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2074 running_font.latexWriteEndChanges(os, bparams, runparams,
2075 basefont, basefont);
2079 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2081 // Needed if there is an optional argument but no contents.
2082 if (body_pos > 0 && body_pos == size()) {
2084 return_value = false;
2088 column += d->endTeXParParams(bparams, os, texrow,
2089 runparams.moving_arg);
2092 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2093 return return_value;
2097 bool Paragraph::emptyTag() const
2099 for (pos_type i = 0; i < size(); ++i) {
2100 if (Inset const * inset = getInset(i)) {
2101 InsetCode lyx_code = inset->lyxCode();
2102 if (lyx_code != TOC_CODE &&
2103 lyx_code != INCLUDE_CODE &&
2104 lyx_code != GRAPHICS_CODE &&
2105 lyx_code != ERT_CODE &&
2106 lyx_code != LISTINGS_CODE &&
2107 lyx_code != FLOAT_CODE &&
2108 lyx_code != TABULAR_CODE) {
2112 char_type c = d->text_[i];
2113 if (c != ' ' && c != '\t')
2121 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2124 for (pos_type i = 0; i < size(); ++i) {
2125 if (Inset const * inset = getInset(i)) {
2126 InsetCode lyx_code = inset->lyxCode();
2127 if (lyx_code == LABEL_CODE) {
2128 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2129 docstring const & id = il->getParam("name");
2130 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2138 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2142 for (i = 0; i < size(); ++i) {
2143 if (Inset const * inset = getInset(i)) {
2144 inset->docbook(os, runparams);
2146 char_type c = d->text_[i];
2149 os << sgml::escapeChar(c);
2156 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2159 pos_type size = text_.size();
2160 for (pos_type i = initial; i < size; ++i) {
2161 Font font = owner_->getFont(buf.params(), i, outerfont);
2162 if (text_[i] == META_INSET)
2164 if (i != initial && font != font_old)
2173 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2175 OutputParams const & runparams,
2176 Font const & outerfont,
2177 pos_type initial) const
2179 bool emph_flag = false;
2181 Layout const & style = *d->layout_;
2183 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2185 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2188 // parsing main loop
2189 for (pos_type i = initial; i < size(); ++i) {
2190 Font font = getFont(buf.params(), i, outerfont);
2192 // handle <emphasis> tag
2193 if (font_old.emph() != font.fontInfo().emph()) {
2194 if (font.fontInfo().emph() == FONT_ON) {
2197 } else if (i != initial) {
2198 os << "</emphasis>";
2203 if (Inset const * inset = getInset(i)) {
2204 inset->docbook(os, runparams);
2206 char_type c = d->text_[i];
2208 if (style.pass_thru)
2211 os << sgml::escapeChar(c);
2213 font_old = font.fontInfo();
2217 os << "</emphasis>";
2220 if (style.free_spacing)
2222 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2227 bool Paragraph::isHfill(pos_type pos) const
2229 Inset const * inset = getInset(pos);
2230 return inset && (inset->lyxCode() == SPACE_CODE &&
2231 inset->isStretchableSpace());
2235 bool Paragraph::isNewline(pos_type pos) const
2237 Inset const * inset = getInset(pos);
2238 return inset && inset->lyxCode() == NEWLINE_CODE;
2242 bool Paragraph::isLineSeparator(pos_type pos) const
2244 char_type const c = d->text_[pos];
2245 if (isLineSeparatorChar(c))
2247 Inset const * inset = getInset(pos);
2248 return inset && inset->isLineSeparator();
2252 /// Used by the spellchecker
2253 bool Paragraph::isLetter(pos_type pos) const
2255 if (Inset const * inset = getInset(pos))
2256 return inset->isLetter();
2257 char_type const c = d->text_[pos];
2258 return isLetterChar(c) || isDigit(c);
2262 bool Paragraph::isChar(pos_type pos) const
2264 if (Inset const * inset = getInset(pos))
2265 return inset->isChar();
2266 char_type const c = d->text_[pos];
2267 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2271 bool Paragraph::isSpace(pos_type pos) const
2273 if (Inset const * inset = getInset(pos))
2274 return inset->isSpace();
2275 char_type const c = d->text_[pos];
2276 return lyx::isSpace(c);
2281 Paragraph::getParLanguage(BufferParams const & bparams) const
2284 return getFirstFontSettings(bparams).language();
2285 // FIXME: we should check the prev par as well (Lgb)
2286 return bparams.language;
2290 bool Paragraph::isRTL(BufferParams const & bparams) const
2292 return lyxrc.rtl_support
2293 && getParLanguage(bparams)->rightToLeft()
2294 && ownerCode() != ERT_CODE
2295 && ownerCode() != LISTINGS_CODE;
2299 void Paragraph::changeLanguage(BufferParams const & bparams,
2300 Language const * from, Language const * to)
2302 // change language including dummy font change at the end
2303 for (pos_type i = 0; i <= size(); ++i) {
2304 Font font = getFontSettings(bparams, i);
2305 if (font.language() == from) {
2306 font.setLanguage(to);
2313 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2315 Language const * doc_language = bparams.language;
2316 FontList::const_iterator cit = d->fontlist_.begin();
2317 FontList::const_iterator end = d->fontlist_.end();
2319 for (; cit != end; ++cit)
2320 if (cit->font().language() != ignore_language &&
2321 cit->font().language() != latex_language &&
2322 cit->font().language() != doc_language)
2328 docstring Paragraph::asString(int options) const
2330 return asString(0, size(), options);
2334 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2336 odocstringstream os;
2339 && options & AS_STR_LABEL
2340 && !d->params_.labelString().empty())
2341 os << d->params_.labelString() << ' ';
2343 for (pos_type i = beg; i < end; ++i) {
2344 char_type const c = d->text_[i];
2347 else if (c == META_INSET && options & AS_STR_INSETS)
2348 getInset(i)->textString(os);
2355 void Paragraph::setInsetOwner(Inset * inset)
2357 d->inset_owner_ = inset;
2361 int Paragraph::id() const
2367 Layout const & Paragraph::layout() const
2373 void Paragraph::setLayout(Layout const & layout)
2375 d->layout_ = &layout;
2379 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2381 if (usePlainLayout())
2382 setLayout(tclass.emptyLayout());
2384 setLayout(tclass.defaultLayout());
2388 Inset * Paragraph::inInset() const
2390 return d->inset_owner_;
2394 InsetCode Paragraph::ownerCode() const
2396 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2400 ParagraphParameters & Paragraph::params()
2406 ParagraphParameters const & Paragraph::params() const
2412 bool Paragraph::isFreeSpacing() const
2414 if (d->layout_->free_spacing)
2416 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2420 bool Paragraph::allowEmpty() const
2422 if (d->layout_->keepempty)
2424 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2428 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2430 if (!Encodings::isArabicChar(c))
2433 char_type prev_char = ' ';
2434 char_type next_char = ' ';
2436 for (pos_type i = pos - 1; i >= 0; --i) {
2437 char_type const par_char = d->text_[i];
2438 if (!Encodings::isArabicComposeChar(par_char)) {
2439 prev_char = par_char;
2444 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2445 char_type const par_char = d->text_[i];
2446 if (!Encodings::isArabicComposeChar(par_char)) {
2447 next_char = par_char;
2452 if (Encodings::isArabicChar(next_char)) {
2453 if (Encodings::isArabicChar(prev_char) &&
2454 !Encodings::isArabicSpecialChar(prev_char))
2455 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2457 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2459 if (Encodings::isArabicChar(prev_char) &&
2460 !Encodings::isArabicSpecialChar(prev_char))
2461 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2463 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2468 int Paragraph::checkBiblio(Buffer const & buffer)
2471 // This is getting more and more a mess. ...We really should clean
2472 // up this bibitem issue for 1.6. See also bug 2743.
2474 // Add bibitem insets if necessary
2475 if (d->layout_->labeltype != LABEL_BIBLIO)
2478 bool hasbibitem = !d->insetlist_.empty()
2479 // Insist on it being in pos 0
2480 && d->text_[0] == META_INSET
2481 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2483 bool track_changes = buffer.params().trackChanges;
2488 // remove a bibitem in pos != 0
2489 // restore it later in pos 0 if necessary
2490 // (e.g. if a user inserts contents _before_ the item)
2491 // we're assuming there's only one of these, which there
2493 int erasedInsetPosition = -1;
2494 InsetList::iterator it = d->insetlist_.begin();
2495 InsetList::iterator end = d->insetlist_.end();
2496 for (; it != end; ++it)
2497 if (it->inset->lyxCode() == BIBITEM_CODE
2499 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2500 oldkey = olditem->getParam("key");
2501 oldlabel = olditem->getParam("label");
2502 erasedInsetPosition = it->pos;
2503 eraseChar(erasedInsetPosition, track_changes);
2507 // There was an InsetBibitem at the beginning, and we didn't
2508 // have to erase one.
2509 if (hasbibitem && erasedInsetPosition < 0)
2512 // There was an InsetBibitem at the beginning and we did have to
2513 // erase one. So we give its properties to the beginning inset.
2515 InsetBibitem * inset =
2516 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2517 if (!oldkey.empty())
2518 inset->setParam("key", oldkey);
2519 inset->setParam("label", oldlabel);
2520 return -erasedInsetPosition;
2523 // There was no inset at the beginning, so we need to create one with
2524 // the key and label of the one we erased.
2525 InsetBibitem * inset =
2526 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2527 // restore values of previously deleted item in this par.
2528 if (!oldkey.empty())
2529 inset->setParam("key", oldkey);
2530 inset->setParam("label", oldlabel);
2531 insertInset(0, static_cast<Inset *>(inset),
2532 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2538 void Paragraph::checkAuthors(AuthorList const & authorList)
2540 d->changes_.checkAuthors(authorList);
2544 bool Paragraph::isUnchanged(pos_type pos) const
2546 return lookupChange(pos).type == Change::UNCHANGED;
2550 bool Paragraph::isInserted(pos_type pos) const
2552 return lookupChange(pos).type == Change::INSERTED;
2556 bool Paragraph::isDeleted(pos_type pos) const
2558 return lookupChange(pos).type == Change::DELETED;
2562 InsetList const & Paragraph::insetList() const
2564 return d->insetlist_;
2568 Inset * Paragraph::releaseInset(pos_type pos)
2570 Inset * inset = d->insetlist_.release(pos);
2571 /// does not honour change tracking!
2572 eraseChar(pos, false);
2577 Inset * Paragraph::getInset(pos_type pos)
2579 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2580 ? d->insetlist_.get(pos) : 0;
2584 Inset const * Paragraph::getInset(pos_type pos) const
2586 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2587 ? d->insetlist_.get(pos) : 0;
2591 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2592 pos_type & right, TextCase action)
2594 // process sequences of modified characters; in change
2595 // tracking mode, this approach results in much better
2596 // usability than changing case on a char-by-char basis
2599 bool const trackChanges = bparams.trackChanges;
2601 bool capitalize = true;
2603 for (; pos < right; ++pos) {
2604 char_type oldChar = d->text_[pos];
2605 char_type newChar = oldChar;
2607 // ignore insets and don't play with deleted text!
2608 if (oldChar != META_INSET && !isDeleted(pos)) {
2610 case text_lowercase:
2611 newChar = lowercase(oldChar);
2613 case text_capitalization:
2615 newChar = uppercase(oldChar);
2619 case text_uppercase:
2620 newChar = uppercase(oldChar);
2625 if (!isLetter(pos) || isDeleted(pos)) {
2626 // permit capitalization again
2630 if (oldChar != newChar)
2633 if (oldChar == newChar || pos == right - 1) {
2634 if (oldChar != newChar) {
2635 // step behind the changing area
2638 int erasePos = pos - changes.size();
2639 for (size_t i = 0; i < changes.size(); i++) {
2640 insertChar(pos, changes[i],
2641 getFontSettings(bparams,
2644 if (!eraseChar(erasePos, trackChanges)) {
2647 ++right; // expand selection
2656 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2657 pos_type pos, bool del) const
2659 int const strsize = str.length();
2661 pos_type const parsize = d->text_.size();
2662 for (i = 0; pos + i < parsize; ++i) {
2665 if (cs && str[i] != d->text_[pos + i])
2667 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2669 if (!del && isDeleted(pos + i))
2676 // if necessary, check whether string matches word
2678 if (pos > 0 && isLetter(pos - 1))
2680 if (pos + strsize < parsize
2681 && isLetter(pos + strsize))
2689 char_type Paragraph::getChar(pos_type pos) const
2691 return d->text_[pos];
2695 pos_type Paragraph::size() const
2697 return d->text_.size();
2701 bool Paragraph::empty() const
2703 return d->text_.empty();
2707 bool Paragraph::isInset(pos_type pos) const
2709 return d->text_[pos] == META_INSET;
2713 bool Paragraph::isSeparator(pos_type pos) const
2715 //FIXME: Are we sure this can be the only separator?
2716 return d->text_[pos] == ' ';
2720 void Paragraph::deregisterWords()
2722 Private::Words::const_iterator it;
2723 WordList & wl = theWordList();
2724 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2730 void Paragraph::collectWords(CursorSlice const & sl)
2733 bool inword = false;
2735 //lyxerr << "Words: ";
2736 pos_type n = size();
2737 for (pos_type pos = 0; pos != n; ++pos) {
2741 if (!isLetter(pos)) {
2750 CursorSlice from = sl;
2751 CursorSlice to = sl;
2754 from.text()->getWord(from, to, WHOLE_WORD);
2755 if (to.pos() - from.pos() < 6)
2757 docstring word = asString(from.pos(), to.pos(), false);
2758 d->words_.insert(word);
2759 //lyxerr << word << " ";
2761 //lyxerr << std::endl;
2765 void Paragraph::registerWords()
2767 Private::Words::const_iterator it;
2768 WordList & wl = theWordList();
2769 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2774 void Paragraph::updateWords(CursorSlice const & sl)
2776 LASSERT(&sl.paragraph() == this, /**/);