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) and it belongs to a known script.
570 // Parameter ltx contains the latex translation of text_[i] as specified in
571 // the unicodesymbols file and is something like "\textXXX{<spec>}".
572 // The latex macro name "textXXX" specifies the script to which text_[i]
573 // belongs and we use it in order to check whether characters from the
574 // same script immediately follow, such that we can collect them in a
575 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
576 // for the first char but only "<spec>" for all subsequent chars.
577 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
578 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
579 string script = to_ascii(ltx.substr(1, brace1 - 1));
580 int length = ltx.substr(0, brace2).length();
581 os << ltx.substr(0, brace2);
582 int size = text_.size();
583 while (i + 1 < size) {
584 char_type const next = text_[i + 1];
585 // Stop here if next character belongs to another script
586 // or there is a change in change tracking status.
587 if (!Encodings::isKnownScriptChar(next, script) ||
588 runningChange != owner_->lookupChange(i + 1))
592 FontList::const_iterator cit = fontlist_.begin();
593 FontList::const_iterator end = fontlist_.end();
594 for (; cit != end; ++cit) {
595 if (cit->pos() >= i && !found) {
596 prev_font = cit->font();
599 if (cit->pos() >= i + 1)
602 // Stop here if there is a font attribute or encoding change.
603 if (found && cit != end && prev_font != cit->font())
605 docstring const latex = encoding.latexChar(next);
606 docstring::size_type const b1 =
607 latex.find_first_of(from_ascii("{"));
608 docstring::size_type const b2 =
609 latex.find_last_of(from_ascii("}"));
610 int const len = b2 - b1 - 1;
611 os << latex.substr(b1 + 1, len);
621 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
623 pos_type const len = str.length();
625 // is the paragraph large enough?
626 if (pos + len > int(text_.size()))
629 // does the wanted text start at point?
630 for (string::size_type i = 0; i < str.length(); ++i) {
631 // Caution: direct comparison of characters works only
632 // because str is pure ASCII.
633 if (str[i] != text_[pos + i])
637 return fontlist_.hasChangeInRange(pos, len);
641 void Paragraph::Private::latexInset(
642 BufferParams const & bparams,
645 OutputParams & runparams,
648 Font const & outerfont,
650 Change & running_change,
651 Layout const & style,
653 unsigned int & column)
655 Inset * inset = owner_->getInset(i);
656 LASSERT(inset, /**/);
658 if (style.pass_thru) {
659 inset->plaintext(os, runparams);
663 // FIXME: move this to InsetNewline::latex
664 if (inset->lyxCode() == NEWLINE_CODE) {
665 // newlines are handled differently here than
666 // the default in simpleTeXSpecialChars().
667 if (!style.newline_allowed) {
671 column += running_font.latexWriteEndChanges(
672 os, bparams, runparams,
677 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
680 basefont = owner_->getLayoutFont(bparams, outerfont);
681 running_font = basefont;
683 if (runparams.moving_arg)
688 texrow.start(owner_->id(), i + 1);
692 if (owner_->lookupChange(i).type == Change::DELETED) {
693 if( ++runparams.inDeletedInset == 1)
694 runparams.changeOfDeletedInset = owner_->lookupChange(i);
697 if (inset->canTrackChanges()) {
698 column += Changes::latexMarkChange(os, bparams, running_change,
699 Change(Change::UNCHANGED));
700 running_change = Change(Change::UNCHANGED);
704 odocstream::pos_type const len = os.tellp();
706 if (inset->forceLTR()
707 && running_font.isRightToLeft()
708 // ERT is an exception, it should be output with no decorations at all
709 && inset->lyxCode() != ERT_CODE) {
710 if (running_font.language()->lang() == "farsi")
717 // FIXME: Bug: we can have an empty font change here!
718 // if there has just been a font change, we are going to close it
719 // right now, which means stupid latex code like \textsf{}. AFAIK,
720 // this does not harm dvi output. A minor bug, thus (JMarc)
722 // Some insets cannot be inside a font change command.
723 // However, even such insets *can* be placed in \L or \R
724 // or their equivalents (for RTL language switches), so we don't
725 // close the language in those cases.
726 // ArabTeX, though, cannot handle this special behavior, it seems.
727 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
728 || running_font.language()->lang() == "arabic_arabtex";
729 if (open_font && inset->noFontChange()) {
730 bool closeLanguage = arabtex
731 || basefont.isRightToLeft() == running_font.isRightToLeft();
732 unsigned int count = running_font.latexWriteEndChanges(os,
733 bparams, runparams, basefont, basefont, closeLanguage);
735 // if any font properties were closed, update the running_font,
736 // making sure, however, to leave the language as it was
738 // FIXME: probably a better way to keep track of the old
739 // language, than copying the entire font?
740 Font const copy_font(running_font);
741 basefont = owner_->getLayoutFont(bparams, outerfont);
742 running_font = basefont;
744 running_font.setLanguage(copy_font.language());
745 // leave font open if language is still open
746 open_font = (running_font.language() == basefont.language());
748 runparams.local_font = &basefont;
755 tmp = inset->latex(os, runparams);
756 } catch (EncodingException & e) {
757 // add location information and throw again.
764 if (running_font.language()->lang() == "farsi")
771 for (int j = 0; j < tmp; ++j)
774 texrow.start(owner_->id(), i + 1);
777 column += os.tellp() - len;
780 if (owner_->lookupChange(i).type == Change::DELETED)
781 --runparams.inDeletedInset;
785 void Paragraph::Private::latexSpecialChar(
787 OutputParams & runparams,
789 Change & running_change,
790 Layout const & style,
792 unsigned int & column)
794 char_type const c = text_[i];
796 if (style.pass_thru) {
798 // FIXME UNICODE: This can fail if c cannot
799 // be encoded in the current encoding.
804 if (runparams.verbatim) {
809 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
812 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
813 && latexSpecialTypewriter(c, os, i, column))
816 // Otherwise, we use what LaTeX provides us.
819 os << "\\textbackslash{}";
823 os << "\\textless{}";
827 os << "\\textgreater{}";
838 os << "\\char`\\\"{}";
843 case '%': case '#': case '{':
851 os << "\\textasciitilde{}";
856 os << "\\textasciicircum{}";
861 // avoid being mistaken for optional arguments
869 // Blanks are printed before font switching.
870 // Sure? I am not! (try nice-latex)
871 // I am sure it's correct. LyX might be smarter
872 // in the future, but for now, nothing wrong is
879 if (latexSpecialPhrase(os, i, column, runparams))
885 Encoding const & encoding = *(runparams.encoding);
886 if (i + 1 < int(text_.size())) {
887 char_type next = text_[i + 1];
888 if (Encodings::isCombiningChar(next)) {
889 column += latexSurrogatePair(os, c, next, encoding) - 1;
895 docstring const latex = encoding.latexChar(c);
896 if (Encodings::isKnownScriptChar(c, script)
897 && prefixIs(latex, from_ascii("\\" + script)))
898 column += writeScriptChars(os, latex,
899 running_change, encoding, i) - 1;
900 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
901 // Prevent eating of a following
902 // space or command corruption by
903 // following characters
904 column += latex.length() + 1;
907 column += latex.length() - 1;
915 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
916 pos_type & i, unsigned int & column)
922 // In T1 encoding, these characters exist
923 // but we should avoid ligatures
924 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
929 //os << "\\textcompwordmark{}";
941 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
942 pos_type & i, unsigned int & column)
946 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
947 // "--" in Typewriter mode -> "-{}-"
954 // I assume this is hack treating typewriter as verbatim
955 // FIXME UNICODE: This can fail if c cannot be encoded
956 // in the current encoding.
961 // Those characters are not directly supported.
965 case '%': case '#': case '{':
974 // With Typewriter font, these characters exist.
981 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
982 unsigned int & column, OutputParams & runparams)
984 // FIXME: if we have "LaTeX" with a font
985 // change in the middle (before the 'T', then
986 // the "TeX" part is still special cased.
987 // Really we should only operate this on
988 // "words" for some definition of word
990 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
991 if (!isTextAt(special_phrases[pnr].phrase, i))
993 if (runparams.moving_arg)
995 os << special_phrases[pnr].macro;
996 i += special_phrases[pnr].phrase.length() - 1;
997 column += special_phrases[pnr].macro.length() - 1;
1004 void Paragraph::Private::validate(LaTeXFeatures & features,
1005 Layout const & layout) const
1007 // check the params.
1008 if (!params_.spacing().isDefault())
1009 features.require("setspace");
1012 features.useLayout(layout.name());
1015 fontlist_.validate(features);
1017 // then the indentation
1018 if (!params_.leftIndent().zero())
1019 features.require("ParagraphLeftIndent");
1022 InsetList::const_iterator icit = insetlist_.begin();
1023 InsetList::const_iterator iend = insetlist_.end();
1024 for (; icit != iend; ++icit) {
1026 icit->inset->validate(features);
1027 if (layout.needprotect &&
1028 icit->inset->lyxCode() == FOOT_CODE)
1029 features.require("NeedLyXFootnoteCode");
1033 // then the contents
1034 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1035 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1036 if (!special_phrases[pnr].builtin
1037 && isTextAt(special_phrases[pnr].phrase, i)) {
1038 features.require(special_phrases[pnr].phrase);
1042 Encodings::validate(text_[i], features);
1046 /////////////////////////////////////////////////////////////////////
1050 /////////////////////////////////////////////////////////////////////
1053 Layout const emptyParagraphLayout;
1056 Paragraph::Paragraph()
1057 : d(new Paragraph::Private(this, emptyParagraphLayout))
1064 Paragraph::Paragraph(Paragraph const & par)
1065 : itemdepth(par.itemdepth),
1066 d(new Paragraph::Private(*par.d, this))
1072 Paragraph & Paragraph::operator=(Paragraph const & par)
1074 // needed as we will destroy the private part before copying it
1076 itemdepth = par.itemdepth;
1080 d = new Private(*par.d, this);
1087 Paragraph::~Paragraph()
1094 void Paragraph::write(ostream & os, BufferParams const & bparams,
1095 depth_type & dth) const
1097 // The beginning or end of a deeper (i.e. nested) area?
1098 if (dth != d->params_.depth()) {
1099 if (d->params_.depth() > dth) {
1100 while (d->params_.depth() > dth) {
1101 os << "\n\\begin_deeper";
1105 while (d->params_.depth() < dth) {
1106 os << "\n\\end_deeper";
1112 // First write the layout
1113 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1115 d->params_.write(os);
1117 Font font1(inherit_font, bparams.language);
1119 Change running_change = Change(Change::UNCHANGED);
1122 for (pos_type i = 0; i <= size(); ++i) {
1124 Change change = lookupChange(i);
1125 Changes::lyxMarkChange(os, column, running_change, change);
1126 running_change = change;
1131 // Write font changes
1132 Font font2 = getFontSettings(bparams, i);
1133 if (font2 != font1) {
1134 font2.lyxWriteChanges(font1, os);
1139 char_type const c = d->text_[i];
1142 if (Inset const * inset = getInset(i)) {
1143 if (inset->directWrite()) {
1144 // international char, let it write
1145 // code directly so it's shorter in
1151 os << "\\begin_inset ";
1153 os << "\n\\end_inset\n\n";
1159 os << "\n\\backslash\n";
1163 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1170 if ((column > 70 && c == ' ')
1175 // this check is to amend a bug. LyX sometimes
1176 // inserts '\0' this could cause problems.
1178 os << to_utf8(docstring(1, c));
1180 LYXERR0("NUL char in structure.");
1186 os << "\n\\end_layout\n";
1190 void Paragraph::validate(LaTeXFeatures & features) const
1192 d->validate(features, *d->layout_);
1196 void Paragraph::insert(pos_type start, docstring const & str,
1197 Font const & font, Change const & change)
1199 for (size_t i = 0, n = str.size(); i != n ; ++i)
1200 insertChar(start + i, str[i], font, change);
1204 void Paragraph::appendChar(char_type c, Font const & font,
1205 Change const & change)
1208 d->changes_.insert(change, d->text_.size());
1209 // when appending characters, no need to update tables
1210 d->text_.push_back(c);
1211 setFont(d->text_.size() - 1, font);
1215 void Paragraph::appendString(docstring const & s, Font const & font,
1216 Change const & change)
1218 pos_type end = s.size();
1219 size_t oldsize = d->text_.size();
1220 size_t newsize = oldsize + end;
1221 size_t capacity = d->text_.capacity();
1222 if (newsize >= capacity)
1223 d->text_.reserve(max(capacity + 100, newsize));
1225 // when appending characters, no need to update tables
1228 // FIXME: Optimize this!
1229 for (pos_type i = oldsize; i != newsize; ++i) {
1231 d->changes_.insert(change, i);
1233 d->fontlist_.set(oldsize, font);
1234 d->fontlist_.set(newsize - 1, font);
1238 void Paragraph::insertChar(pos_type pos, char_type c,
1241 d->insertChar(pos, c, Change(trackChanges ?
1242 Change::INSERTED : Change::UNCHANGED));
1246 void Paragraph::insertChar(pos_type pos, char_type c,
1247 Font const & font, bool trackChanges)
1249 d->insertChar(pos, c, Change(trackChanges ?
1250 Change::INSERTED : Change::UNCHANGED));
1255 void Paragraph::insertChar(pos_type pos, char_type c,
1256 Font const & font, Change const & change)
1258 d->insertChar(pos, c, change);
1263 void Paragraph::insertInset(pos_type pos, Inset * inset,
1264 Font const & font, Change const & change)
1266 insertInset(pos, inset, change);
1267 // Set the font/language of the inset...
1272 bool Paragraph::insetAllowed(InsetCode code)
1274 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1278 void Paragraph::resetFonts(Font const & font)
1280 d->fontlist_.clear();
1281 d->fontlist_.set(0, font);
1282 d->fontlist_.set(d->text_.size() - 1, font);
1285 // Gets uninstantiated font setting at position.
1286 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1290 LYXERR0("pos: " << pos << " size: " << size());
1291 LASSERT(pos <= size(), /**/);
1294 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1295 if (cit != d->fontlist_.end())
1298 if (pos == size() && !empty())
1299 return getFontSettings(bparams, pos - 1);
1301 return Font(inherit_font, getParLanguage(bparams));
1305 FontSpan Paragraph::fontSpan(pos_type pos) const
1307 LASSERT(pos <= size(), /**/);
1310 FontList::const_iterator cit = d->fontlist_.begin();
1311 FontList::const_iterator end = d->fontlist_.end();
1312 for (; cit != end; ++cit) {
1313 if (cit->pos() >= pos) {
1314 if (pos >= beginOfBody())
1315 return FontSpan(max(start, beginOfBody()),
1318 return FontSpan(start,
1319 min(beginOfBody() - 1,
1322 start = cit->pos() + 1;
1325 // This should not happen, but if so, we take no chances.
1326 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1327 return FontSpan(pos, pos);
1331 // Gets uninstantiated font setting at position 0
1332 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1334 if (!empty() && !d->fontlist_.empty())
1335 return d->fontlist_.begin()->font();
1337 return Font(inherit_font, bparams.language);
1341 // Gets the fully instantiated font at a given position in a paragraph
1342 // This is basically the same function as Text::GetFont() in text2.cpp.
1343 // The difference is that this one is used for generating the LaTeX file,
1344 // and thus cosmetic "improvements" are disallowed: This has to deliver
1345 // the true picture of the buffer. (Asger)
1346 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1347 Font const & outerfont) const
1349 LASSERT(pos >= 0, /**/);
1351 Font font = getFontSettings(bparams, pos);
1353 pos_type const body_pos = beginOfBody();
1355 font.fontInfo().realize(d->layout_->labelfont);
1357 font.fontInfo().realize(d->layout_->font);
1359 font.fontInfo().realize(outerfont.fontInfo());
1360 font.fontInfo().realize(bparams.getFont().fontInfo());
1366 Font const Paragraph::getLabelFont
1367 (BufferParams const & bparams, Font const & outerfont) const
1369 FontInfo tmpfont = d->layout_->labelfont;
1370 tmpfont.realize(outerfont.fontInfo());
1371 tmpfont.realize(bparams.getFont().fontInfo());
1372 return Font(tmpfont, getParLanguage(bparams));
1376 Font const Paragraph::getLayoutFont
1377 (BufferParams const & bparams, Font const & outerfont) const
1379 FontInfo tmpfont = d->layout_->font;
1380 tmpfont.realize(outerfont.fontInfo());
1381 tmpfont.realize(bparams.getFont().fontInfo());
1382 return Font(tmpfont, getParLanguage(bparams));
1386 /// Returns the height of the highest font in range
1387 FontSize Paragraph::highestFontInRange
1388 (pos_type startpos, pos_type endpos, FontSize def_size) const
1390 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1394 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1396 char_type c = d->text_[pos];
1397 if (!lyxrc.rtl_support)
1427 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1433 void Paragraph::setFont(pos_type pos, Font const & font)
1435 LASSERT(pos <= size(), /**/);
1437 // First, reduce font against layout/label font
1438 // Update: The setCharFont() routine in text2.cpp already
1439 // reduces font, so we don't need to do that here. (Asger)
1441 d->fontlist_.set(pos, font);
1445 void Paragraph::makeSameLayout(Paragraph const & par)
1447 d->layout_ = par.d->layout_;
1448 d->params_ = par.d->params_;
1452 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1454 if (isFreeSpacing())
1460 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1461 if (eraseChar(pos, trackChanges))
1467 return count > 0 || pos > 0;
1471 bool Paragraph::hasSameLayout(Paragraph const & par) const
1473 return par.d->layout_ == d->layout_
1474 && d->params_.sameLayout(par.d->params_);
1478 depth_type Paragraph::getDepth() const
1480 return d->params_.depth();
1484 depth_type Paragraph::getMaxDepthAfter() const
1486 if (d->layout_->isEnvironment())
1487 return d->params_.depth() + 1;
1489 return d->params_.depth();
1493 char Paragraph::getAlign() const
1495 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1496 return d->layout_->align;
1498 return d->params_.align();
1502 docstring const & Paragraph::labelString() const
1504 return d->params_.labelString();
1508 // the next two functions are for the manual labels
1509 docstring const Paragraph::getLabelWidthString() const
1511 if (d->layout_->margintype == MARGIN_MANUAL)
1512 return d->params_.labelWidthString();
1514 return _("Senseless with this layout!");
1518 void Paragraph::setLabelWidthString(docstring const & s)
1520 d->params_.labelWidthString(s);
1524 docstring const Paragraph::translateIfPossible(docstring const & s,
1525 BufferParams const & bparams) const
1527 if (!isAscii(s) || s.empty()) {
1528 // This must be a user defined layout. We cannot translate
1529 // this, since gettext accepts only ascii keys.
1532 // Probably standard layout, try to translate
1533 Messages & m = getMessages(getParLanguage(bparams)->code());
1534 return m.get(to_ascii(s));
1538 docstring Paragraph::expandLabel(Layout const & layout,
1539 BufferParams const & bparams, bool process_appendix) const
1541 DocumentClass const & tclass = bparams.documentClass();
1544 if (process_appendix && d->params_.appendix())
1545 fmt = translateIfPossible(layout.labelstring_appendix(),
1548 fmt = translateIfPossible(layout.labelstring(), bparams);
1550 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1551 && !layout.counter.empty())
1552 fmt = "\\the" + layout.counter;
1554 // handle 'inherited level parts' in 'fmt',
1555 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1556 size_t const i = fmt.find('@', 0);
1557 if (i != docstring::npos) {
1558 size_t const j = fmt.find('@', i + 1);
1559 if (j != docstring::npos) {
1560 docstring parent(fmt, i + 1, j - i - 1);
1561 docstring label = from_ascii("??");
1562 if (tclass.hasLayout(parent))
1563 docstring label = expandLabel(tclass[parent], bparams,
1565 fmt = docstring(fmt, 0, i) + label
1566 + docstring(fmt, j + 1, docstring::npos);
1570 return tclass.counters().counterLabel(fmt);
1574 void Paragraph::applyLayout(Layout const & new_layout)
1576 d->layout_ = &new_layout;
1577 LyXAlignment const oldAlign = d->params_.align();
1579 if (!(oldAlign & d->layout_->alignpossible)) {
1580 frontend::Alert::warning(_("Alignment not permitted"),
1581 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1582 d->params_.align(LYX_ALIGN_LAYOUT);
1587 pos_type Paragraph::beginOfBody() const
1589 return d->begin_of_body_;
1593 void Paragraph::setBeginOfBody()
1595 if (d->layout_->labeltype != LABEL_MANUAL) {
1596 d->begin_of_body_ = 0;
1600 // Unroll the first two cycles of the loop
1601 // and remember the previous character to
1602 // remove unnecessary getChar() calls
1604 pos_type end = size();
1605 if (i < end && !isNewline(i)) {
1607 char_type previous_char = 0;
1610 previous_char = d->text_[i];
1611 if (!isNewline(i)) {
1613 while (i < end && previous_char != ' ') {
1618 previous_char = temp;
1624 d->begin_of_body_ = i;
1628 bool Paragraph::forceEmptyLayout() const
1630 Inset const * const inset = inInset();
1633 return inset->forceEmptyLayout();
1637 bool Paragraph::allowParagraphCustomization() const
1639 Inset const * const inset = inInset();
1642 return inset->allowParagraphCustomization();
1646 bool Paragraph::useEmptyLayout() const
1648 Inset const * const inset = inInset();
1651 return inset->useEmptyLayout();
1657 // paragraphs inside floats need different alignment tags to avoid
1660 bool noTrivlistCentering(InsetCode code)
1662 return code == FLOAT_CODE || code == WRAP_CODE;
1666 string correction(string const & orig)
1668 if (orig == "flushleft")
1669 return "raggedright";
1670 if (orig == "flushright")
1671 return "raggedleft";
1672 if (orig == "center")
1678 string const corrected_env(string const & suffix, string const & env,
1681 string output = suffix + "{";
1682 if (noTrivlistCentering(code))
1683 output += correction(env);
1687 if (suffix == "\\begin")
1693 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1695 if (!contains(str, "\n"))
1696 column += str.size();
1700 column = rsplit(str, tmp, '\n').size();
1707 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1708 odocstream & os, TexRow & texrow,
1709 bool moving_arg) const
1713 if (params_.noindent()) {
1714 os << "\\noindent ";
1718 LyXAlignment const curAlign = params_.align();
1720 if (curAlign == layout_->align)
1724 case LYX_ALIGN_NONE:
1725 case LYX_ALIGN_BLOCK:
1726 case LYX_ALIGN_LAYOUT:
1727 case LYX_ALIGN_SPECIAL:
1729 case LYX_ALIGN_LEFT:
1730 case LYX_ALIGN_RIGHT:
1731 case LYX_ALIGN_CENTER:
1740 case LYX_ALIGN_NONE:
1741 case LYX_ALIGN_BLOCK:
1742 case LYX_ALIGN_LAYOUT:
1743 case LYX_ALIGN_SPECIAL:
1745 case LYX_ALIGN_LEFT: {
1747 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1748 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1750 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1751 os << from_ascii(output);
1752 adjust_row_column(output, texrow, column);
1754 } case LYX_ALIGN_RIGHT: {
1756 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1757 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1759 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1760 os << from_ascii(output);
1761 adjust_row_column(output, texrow, column);
1763 } case LYX_ALIGN_CENTER: {
1765 output = corrected_env("\\begin", "center", owner_->ownerCode());
1766 os << from_ascii(output);
1767 adjust_row_column(output, texrow, column);
1776 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1777 odocstream & os, TexRow & texrow,
1778 bool moving_arg) const
1782 switch (params_.align()) {
1783 case LYX_ALIGN_NONE:
1784 case LYX_ALIGN_BLOCK:
1785 case LYX_ALIGN_LAYOUT:
1786 case LYX_ALIGN_SPECIAL:
1788 case LYX_ALIGN_LEFT:
1789 case LYX_ALIGN_RIGHT:
1790 case LYX_ALIGN_CENTER:
1798 switch (params_.align()) {
1799 case LYX_ALIGN_NONE:
1800 case LYX_ALIGN_BLOCK:
1801 case LYX_ALIGN_LAYOUT:
1802 case LYX_ALIGN_SPECIAL:
1804 case LYX_ALIGN_LEFT: {
1806 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1807 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1809 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1810 os << from_ascii(output);
1811 adjust_row_column(output, texrow, column);
1813 } case LYX_ALIGN_RIGHT: {
1815 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1816 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1818 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1819 os << from_ascii(output);
1820 adjust_row_column(output, texrow, column);
1822 } case LYX_ALIGN_CENTER: {
1824 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1825 os << from_ascii(output);
1826 adjust_row_column(output, texrow, column);
1835 // This one spits out the text of the paragraph
1836 bool Paragraph::latex(BufferParams const & bparams,
1837 Font const & outerfont,
1838 odocstream & os, TexRow & texrow,
1839 OutputParams const & runparams) const
1841 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1843 bool return_value = false;
1845 bool asdefault = forceEmptyLayout();
1847 Layout const & style = asdefault ?
1848 bparams.documentClass().emptyLayout() :
1851 // Current base font for all inherited font changes, without any
1852 // change caused by an individual character, except for the language:
1853 // It is set to the language of the first character.
1854 // As long as we are in the label, this font is the base font of the
1855 // label. Before the first body character it is set to the base font
1859 // Maybe we have to create a optional argument.
1860 pos_type body_pos = beginOfBody();
1861 unsigned int column = 0;
1864 // the optional argument is kept in curly brackets in
1865 // case it contains a ']'
1868 basefont = getLabelFont(bparams, outerfont);
1870 basefont = getLayoutFont(bparams, outerfont);
1873 // Which font is currently active?
1874 Font running_font(basefont);
1875 // Do we have an open font change?
1876 bool open_font = false;
1878 Change runningChange = Change(Change::UNCHANGED);
1880 texrow.start(id(), 0);
1882 // if the paragraph is empty, the loop will not be entered at all
1884 if (style.isCommand()) {
1889 column += d->startTeXParParams(bparams, os, texrow,
1890 runparams.moving_arg);
1893 for (pos_type i = 0; i < size(); ++i) {
1894 // First char in paragraph or after label?
1895 if (i == body_pos) {
1898 column += running_font.latexWriteEndChanges(
1899 os, bparams, runparams,
1900 basefont, basefont);
1903 basefont = getLayoutFont(bparams, outerfont);
1904 running_font = basefont;
1906 column += Changes::latexMarkChange(os, bparams,
1907 runningChange, Change(Change::UNCHANGED));
1908 runningChange = Change(Change::UNCHANGED);
1913 if (style.isCommand()) {
1919 column += d->startTeXParParams(bparams, os,
1921 runparams.moving_arg);
1924 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1927 if (bparams.outputChanges && runningChange != change) {
1929 column += running_font.latexWriteEndChanges(
1930 os, bparams, runparams, basefont, basefont);
1933 basefont = getLayoutFont(bparams, outerfont);
1934 running_font = basefont;
1936 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1937 runningChange = change;
1940 // do not output text which is marked deleted
1941 // if change tracking output is disabled
1942 if (!bparams.outputChanges && change.type == Change::DELETED) {
1948 // Fully instantiated font
1949 Font const font = getFont(bparams, i, outerfont);
1951 Font const last_font = running_font;
1953 // Do we need to close the previous font?
1955 (font != running_font ||
1956 font.language() != running_font.language()))
1958 column += running_font.latexWriteEndChanges(
1959 os, bparams, runparams, basefont,
1960 (i == body_pos-1) ? basefont : font);
1961 running_font = basefont;
1965 // close babel's font environment before opening CJK.
1966 if (!running_font.language()->babel().empty() &&
1967 font.language()->encoding()->package() == Encoding::CJK) {
1968 string end_tag = subst(lyxrc.language_command_end,
1970 running_font.language()->babel());
1971 os << from_ascii(end_tag);
1972 column += end_tag.length();
1975 // Switch file encoding if necessary (and allowed)
1976 if (!runparams.verbatim &&
1977 runparams.encoding->package() == Encoding::none &&
1978 font.language()->encoding()->package() == Encoding::none) {
1979 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1980 runparams, *(font.language()->encoding()));
1981 if (enc_switch.first) {
1982 column += enc_switch.second;
1983 runparams.encoding = font.language()->encoding();
1987 char_type const c = d->text_[i];
1989 // Do we need to change font?
1990 if ((font != running_font ||
1991 font.language() != running_font.language()) &&
1994 odocstringstream ods;
1995 column += font.latexWriteStartChanges(ods, bparams,
1996 runparams, basefont,
1998 running_font = font;
2000 docstring fontchange = ods.str();
2001 // check if the fontchange ends with a trailing blank
2002 // (like "\small " (see bug 3382)
2003 if (suffixIs(fontchange, ' ') && c == ' ')
2004 os << fontchange.substr(0, fontchange.size() - 1)
2005 << from_ascii("{}");
2011 // FIXME: integrate this case in latexSpecialChar
2012 // Do not print the separation of the optional argument
2013 // if style.pass_thru is false. This works because
2014 // latexSpecialChar ignores spaces if
2015 // style.pass_thru is false.
2016 if (i != body_pos - 1) {
2017 if (d->simpleTeXBlanks(
2018 runparams, os, texrow,
2019 i, column, font, style)) {
2020 // A surrogate pair was output. We
2021 // must not call latexSpecialChar
2022 // in this iteration, since it would output
2023 // the combining character again.
2030 OutputParams rp = runparams;
2031 rp.free_spacing = style.free_spacing;
2032 rp.local_font = &font;
2033 rp.intitle = style.intitle;
2035 // Two major modes: LaTeX or plain
2036 // Handle here those cases common to both modes
2037 // and then split to handle the two modes separately.
2038 if (c == META_INSET)
2039 d->latexInset(bparams, os,
2040 texrow, rp, running_font,
2041 basefont, outerfont, open_font,
2042 runningChange, style, i, column);
2045 d->latexSpecialChar(os, rp, running_font, runningChange,
2047 } catch (EncodingException & e) {
2048 if (runparams.dryrun) {
2049 os << "<" << _("LyX Warning: ")
2050 << _("uncodable character") << " '";
2054 // add location information and throw again.
2062 // Set the encoding to that returned from simpleTeXSpecialChars (see
2063 // comment for encoding member in OutputParams.h)
2064 runparams.encoding = rp.encoding;
2067 // If we have an open font definition, we have to close it
2069 #ifdef FIXED_LANGUAGE_END_DETECTION
2072 .latexWriteEndChanges(os, bparams, runparams,
2074 next_->getFont(bparams, 0, outerfont));
2076 running_font.latexWriteEndChanges(os, bparams,
2077 runparams, basefont, basefont);
2080 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2081 //FIXME: there as we start another \selectlanguage with the next paragraph if
2082 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2083 running_font.latexWriteEndChanges(os, bparams, runparams,
2084 basefont, basefont);
2088 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2090 // Needed if there is an optional argument but no contents.
2091 if (body_pos > 0 && body_pos == size()) {
2093 return_value = false;
2097 column += d->endTeXParParams(bparams, os, texrow,
2098 runparams.moving_arg);
2101 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2102 return return_value;
2106 bool Paragraph::emptyTag() const
2108 for (pos_type i = 0; i < size(); ++i) {
2109 if (Inset const * inset = getInset(i)) {
2110 InsetCode lyx_code = inset->lyxCode();
2111 if (lyx_code != TOC_CODE &&
2112 lyx_code != INCLUDE_CODE &&
2113 lyx_code != GRAPHICS_CODE &&
2114 lyx_code != ERT_CODE &&
2115 lyx_code != LISTINGS_CODE &&
2116 lyx_code != FLOAT_CODE &&
2117 lyx_code != TABULAR_CODE) {
2121 char_type c = d->text_[i];
2122 if (c != ' ' && c != '\t')
2130 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2133 for (pos_type i = 0; i < size(); ++i) {
2134 if (Inset const * inset = getInset(i)) {
2135 InsetCode lyx_code = inset->lyxCode();
2136 if (lyx_code == LABEL_CODE) {
2137 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2138 docstring const & id = il->getParam("name");
2139 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2147 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2151 for (i = 0; i < size(); ++i) {
2152 if (Inset const * inset = getInset(i)) {
2153 inset->docbook(os, runparams);
2155 char_type c = d->text_[i];
2158 os << sgml::escapeChar(c);
2165 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2168 pos_type size = text_.size();
2169 for (pos_type i = initial; i < size; ++i) {
2170 Font font = owner_->getFont(buf.params(), i, outerfont);
2171 if (text_[i] == META_INSET)
2173 if (i != initial && font != font_old)
2182 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2184 OutputParams const & runparams,
2185 Font const & outerfont,
2186 pos_type initial) const
2188 bool emph_flag = false;
2190 Layout const & style = *d->layout_;
2192 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2194 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2197 // parsing main loop
2198 for (pos_type i = initial; i < size(); ++i) {
2199 Font font = getFont(buf.params(), i, outerfont);
2201 // handle <emphasis> tag
2202 if (font_old.emph() != font.fontInfo().emph()) {
2203 if (font.fontInfo().emph() == FONT_ON) {
2206 } else if (i != initial) {
2207 os << "</emphasis>";
2212 if (Inset const * inset = getInset(i)) {
2213 inset->docbook(os, runparams);
2215 char_type c = d->text_[i];
2217 if (style.pass_thru)
2220 os << sgml::escapeChar(c);
2222 font_old = font.fontInfo();
2226 os << "</emphasis>";
2229 if (style.free_spacing)
2231 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2236 bool Paragraph::isHfill(pos_type pos) const
2238 Inset const * inset = getInset(pos);
2239 return inset && (inset->lyxCode() == SPACE_CODE &&
2240 inset->isStretchableSpace());
2244 bool Paragraph::isNewline(pos_type pos) const
2246 Inset const * inset = getInset(pos);
2247 return inset && inset->lyxCode() == NEWLINE_CODE;
2251 bool Paragraph::isLineSeparator(pos_type pos) const
2253 char_type const c = d->text_[pos];
2254 if (isLineSeparatorChar(c))
2256 Inset const * inset = getInset(pos);
2257 return inset && inset->isLineSeparator();
2261 /// Used by the spellchecker
2262 bool Paragraph::isLetter(pos_type pos) const
2264 if (Inset const * inset = getInset(pos))
2265 return inset->isLetter();
2266 char_type const c = d->text_[pos];
2267 return isLetterChar(c) || isDigit(c);
2271 bool Paragraph::isChar(pos_type pos) const
2273 if (Inset const * inset = getInset(pos))
2274 return inset->isChar();
2275 char_type const c = d->text_[pos];
2276 return !isLetterChar(c) && !isDigit(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::setEmptyOrDefaultLayout(DocumentClass const & tclass)
2381 if (useEmptyLayout())
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, /**/);