Fix the output of a single dash in xhtml.
[lyx.git] / src / Paragraph.cpp
blob13335530401d4690c9cc3ab9a24d3171af8005ae
1 /**
2 * \file Paragraph.cpp
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
10 * \author John Levon
11 * \author André Pönitz
12 * \author Dekel Tsur
13 * \author Jürgen Vigna
15 * Full author contact details are available in file CREDITS.
18 #include <config.h>
20 #include "Paragraph.h"
22 #include "LayoutFile.h"
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "Changes.h"
26 #include "Counters.h"
27 #include "Encoding.h"
28 #include "InsetList.h"
29 #include "Language.h"
30 #include "LaTeXFeatures.h"
31 #include "Layout.h"
32 #include "Length.h"
33 #include "Font.h"
34 #include "FontList.h"
35 #include "LyXRC.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "output_xhtml.h"
39 #include "paragraph_funcs.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
42 #include "sgml.h"
43 #include "TextClass.h"
44 #include "TexRow.h"
45 #include "Text.h"
46 #include "VSpace.h"
47 #include "WordLangTuple.h"
48 #include "WordList.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
55 #include "support/lassert.h"
56 #include "support/debug.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
60 #include "support/Messages.h"
61 #include "support/textutils.h"
63 #include <sstream>
64 #include <vector>
66 using namespace std;
67 using namespace lyx::support;
69 namespace lyx {
71 namespace {
72 /// Inset identifier (above 0x10ffff, for ucs-4)
73 char_type const META_INSET = 0x200001;
76 /////////////////////////////////////////////////////////////////////
78 // Paragraph::Private
80 /////////////////////////////////////////////////////////////////////
82 class Paragraph::Private
84 public:
85 ///
86 Private(Paragraph * owner, Layout const & layout);
87 /// "Copy constructor"
88 Private(Private const &, Paragraph * owner);
89 /// Copy constructor from \p beg to \p end
90 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
92 ///
93 void insertChar(pos_type pos, char_type c, Change const & change);
95 /// Output the surrogate pair formed by \p c and \p next to \p os.
96 /// \return the number of characters written.
97 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
98 Encoding const &);
100 /// Output a space in appropriate formatting (or a surrogate pair
101 /// if the next character is a combining character).
102 /// \return whether a surrogate pair was output.
103 bool simpleTeXBlanks(OutputParams const &,
104 odocstream &, TexRow & texrow,
105 pos_type i,
106 unsigned int & column,
107 Font const & font,
108 Layout const & style);
110 /// Output consecutive unicode chars, belonging to the same script as
111 /// specified by the latex macro \p ltx, to \p os starting from \p i.
112 /// \return the number of characters written.
113 int writeScriptChars(odocstream & os, docstring const & ltx,
114 Change const &, Encoding const &, pos_type & i);
116 /// This could go to ParagraphParameters if we want to.
117 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
118 OutputParams const &) const;
120 /// This could go to ParagraphParameters if we want to.
121 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
122 OutputParams const &) const;
125 void latexInset(BufferParams const &,
126 odocstream &,
127 TexRow & texrow, OutputParams &,
128 Font & running_font,
129 Font & basefont,
130 Font const & outerfont,
131 bool & open_font,
132 Change & running_change,
133 Layout const & style,
134 pos_type & i,
135 unsigned int & column);
138 void latexSpecialChar(
139 odocstream & os,
140 OutputParams const & runparams,
141 Font const & running_font,
142 Change const & running_change,
143 Layout const & style,
144 pos_type & i,
145 unsigned int & column);
148 bool latexSpecialT1(
149 char_type const c,
150 odocstream & os,
151 pos_type i,
152 unsigned int & column);
154 bool latexSpecialTypewriter(
155 char_type const c,
156 odocstream & os,
157 pos_type i,
158 unsigned int & column);
160 bool latexSpecialPhrase(
161 odocstream & os,
162 pos_type & i,
163 unsigned int & column,
164 OutputParams const & runparams);
167 void validate(LaTeXFeatures & features,
168 Layout const & layout) const;
170 /// Checks if the paragraph contains only text and no inset or font change.
171 bool onlyText(Buffer const & buf, Font const & outerfont,
172 pos_type initial) const;
174 /// match a string against a particular point in the paragraph
175 bool isTextAt(string const & str, pos_type pos) const;
177 /// Which Paragraph owns us?
178 Paragraph * owner_;
180 /// In which Inset?
181 Inset const * inset_owner_;
184 FontList fontlist_;
187 unsigned int id_;
189 static unsigned int paragraph_id;
191 ParagraphParameters params_;
193 /// for recording and looking up changes
194 Changes changes_;
197 InsetList insetlist_;
199 /// end of label
200 pos_type begin_of_body_;
202 typedef docstring TextContainer;
204 TextContainer text_;
206 typedef std::set<docstring> Words;
208 Words words_;
210 Layout const * layout_;
214 // Initialization of the counter for the paragraph id's,
215 unsigned int Paragraph::Private::paragraph_id = 0;
217 namespace {
219 struct special_phrase {
220 string phrase;
221 docstring macro;
222 bool builtin;
225 special_phrase const special_phrases[] = {
226 { "LyX", from_ascii("\\LyX{}"), false },
227 { "TeX", from_ascii("\\TeX{}"), true },
228 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
229 { "LaTeX", from_ascii("\\LaTeX{}"), true },
232 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
234 } // namespace anon
237 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
238 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
240 id_ = paragraph_id++;
241 text_.reserve(100);
245 Paragraph::Private::Private(Private const & p, Paragraph * owner)
246 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
247 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
248 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
249 layout_(p.layout_)
251 id_ = paragraph_id++;
255 Paragraph::Private::Private(Private const & p, Paragraph * owner,
256 pos_type beg, pos_type end)
257 : owner_(owner), inset_owner_(p.inset_owner_),
258 params_(p.params_), changes_(p.changes_),
259 insetlist_(p.insetlist_, beg, end),
260 begin_of_body_(p.begin_of_body_), words_(p.words_),
261 layout_(p.layout_)
263 id_ = paragraph_id++;
264 if (beg >= pos_type(p.text_.size()))
265 return;
266 text_ = p.text_.substr(beg, end - beg);
268 FontList::const_iterator fcit = fontlist_.begin();
269 FontList::const_iterator fend = fontlist_.end();
270 for (; fcit != fend; ++fcit) {
271 if (fcit->pos() < beg)
272 continue;
273 if (fcit->pos() >= end) {
274 // Add last entry in the fontlist_.
275 fontlist_.set(text_.size() - 1, fcit->font());
276 break;
278 // Add a new entry in the fontlist_.
279 fontlist_.set(fcit->pos() - beg, fcit->font());
284 void Paragraph::addChangesToToc(DocIterator const & cdit,
285 Buffer const & buf) const
287 d->changes_.addToToc(cdit, buf);
291 bool Paragraph::isFullyDeleted(pos_type start, pos_type end) const
293 LASSERT(start >= 0 && start <= size(), /**/);
294 LASSERT(end > start && end <= size() + 1, /**/);
296 return d->changes_.isFullyDeleted(start, end);
300 bool Paragraph::isChanged(pos_type start, pos_type end) const
302 LASSERT(start >= 0 && start <= size(), /**/);
303 LASSERT(end > start && end <= size() + 1, /**/);
305 return d->changes_.isChanged(start, end);
309 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
311 // keep the logic here in sync with the logic of eraseChars()
312 if (!trackChanges)
313 return true;
315 Change const change = d->changes_.lookup(size());
316 return change.type == Change::INSERTED && change.author == 0;
320 void Paragraph::setChange(Change const & change)
322 // beware of the imaginary end-of-par character!
323 d->changes_.set(change, 0, size() + 1);
326 * Propagate the change recursively - but not in case of DELETED!
328 * Imagine that your co-author makes changes in an existing inset. He
329 * sends your document to you and you come to the conclusion that the
330 * inset should go completely. If you erase it, LyX must not delete all
331 * text within the inset. Otherwise, the change tracked insertions of
332 * your co-author get lost and there is no way to restore them later.
334 * Conclusion: An inset's content should remain untouched if you delete it
337 if (change.type != Change::DELETED) {
338 for (pos_type pos = 0; pos < size(); ++pos) {
339 if (Inset * inset = getInset(pos))
340 inset->setChange(change);
346 void Paragraph::setChange(pos_type pos, Change const & change)
348 LASSERT(pos >= 0 && pos <= size(), /**/);
349 d->changes_.set(change, pos);
351 // see comment in setChange(Change const &) above
352 if (change.type != Change::DELETED && pos < size())
353 if (Inset * inset = getInset(pos))
354 inset->setChange(change);
358 Change const & Paragraph::lookupChange(pos_type pos) const
360 LASSERT(pos >= 0 && pos <= size(), /**/);
361 return d->changes_.lookup(pos);
365 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
366 pos_type end)
368 LASSERT(start >= 0 && start <= size(), /**/);
369 LASSERT(end > start && end <= size() + 1, /**/);
371 for (pos_type pos = start; pos < end; ++pos) {
372 switch (lookupChange(pos).type) {
373 case Change::UNCHANGED:
374 // accept changes in nested inset
375 if (Inset * inset = getInset(pos))
376 inset->acceptChanges(bparams);
377 break;
379 case Change::INSERTED:
380 d->changes_.set(Change(Change::UNCHANGED), pos);
381 // also accept changes in nested inset
382 if (Inset * inset = getInset(pos))
383 inset->acceptChanges(bparams);
384 break;
386 case Change::DELETED:
387 // Suppress access to non-existent
388 // "end-of-paragraph char"
389 if (pos < size()) {
390 eraseChar(pos, false);
391 --end;
392 --pos;
394 break;
401 void Paragraph::rejectChanges(BufferParams const & bparams,
402 pos_type start, pos_type end)
404 LASSERT(start >= 0 && start <= size(), /**/);
405 LASSERT(end > start && end <= size() + 1, /**/);
407 for (pos_type pos = start; pos < end; ++pos) {
408 switch (lookupChange(pos).type) {
409 case Change::UNCHANGED:
410 // reject changes in nested inset
411 if (Inset * inset = getInset(pos))
412 inset->rejectChanges(bparams);
413 break;
415 case Change::INSERTED:
416 // Suppress access to non-existent
417 // "end-of-paragraph char"
418 if (pos < size()) {
419 eraseChar(pos, false);
420 --end;
421 --pos;
423 break;
425 case Change::DELETED:
426 d->changes_.set(Change(Change::UNCHANGED), pos);
428 // Do NOT reject changes within a deleted inset!
429 // There may be insertions of a co-author inside of it!
431 break;
437 void Paragraph::Private::insertChar(pos_type pos, char_type c,
438 Change const & change)
440 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
442 // track change
443 changes_.insert(change, pos);
445 // This is actually very common when parsing buffers (and
446 // maybe inserting ascii text)
447 if (pos == pos_type(text_.size())) {
448 // when appending characters, no need to update tables
449 text_.push_back(c);
450 return;
453 text_.insert(text_.begin() + pos, c);
455 // Update the font table.
456 fontlist_.increasePosAfterPos(pos);
458 // Update the insets
459 insetlist_.increasePosAfterPos(pos);
463 bool Paragraph::insertInset(pos_type pos, Inset * inset,
464 Change const & change)
466 LASSERT(inset, /**/);
467 LASSERT(pos >= 0 && pos <= size(), /**/);
469 // Paragraph::insertInset() can be used in cut/copy/paste operation where
470 // d->inset_owner_ is not set yet.
471 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
472 return false;
474 d->insertChar(pos, META_INSET, change);
475 LASSERT(d->text_[pos] == META_INSET, /**/);
477 // Add a new entry in the insetlist_.
478 d->insetlist_.insert(inset, pos);
479 return true;
483 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
485 LASSERT(pos >= 0 && pos <= size(), return false);
487 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
489 if (trackChanges) {
490 Change change = d->changes_.lookup(pos);
492 // set the character to DELETED if
493 // a) it was previously unchanged or
494 // b) it was inserted by a co-author
496 if (change.type == Change::UNCHANGED ||
497 (change.type == Change::INSERTED && change.author != 0)) {
498 setChange(pos, Change(Change::DELETED));
499 return false;
502 if (change.type == Change::DELETED)
503 return false;
506 // Don't physically access the imaginary end-of-paragraph character.
507 // eraseChar() can only mark it as DELETED. A physical deletion of
508 // end-of-par must be handled externally.
509 if (pos == size()) {
510 return false;
513 // track change
514 d->changes_.erase(pos);
516 // if it is an inset, delete the inset entry
517 if (d->text_[pos] == META_INSET)
518 d->insetlist_.erase(pos);
520 d->text_.erase(d->text_.begin() + pos);
522 // Update the fontlist_
523 d->fontlist_.erase(pos);
525 // Update the insetlist_
526 d->insetlist_.decreasePosAfterPos(pos);
528 return true;
532 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
534 LASSERT(start >= 0 && start <= size(), /**/);
535 LASSERT(end >= start && end <= size() + 1, /**/);
537 pos_type i = start;
538 for (pos_type count = end - start; count; --count) {
539 if (!eraseChar(i, trackChanges))
540 ++i;
542 return end - i;
546 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
547 char_type next, Encoding const & encoding)
549 // Writing next here may circumvent a possible font change between
550 // c and next. Since next is only output if it forms a surrogate pair
551 // with c we can ignore this:
552 // A font change inside a surrogate pair does not make sense and is
553 // hopefully impossible to input.
554 // FIXME: change tracking
555 // Is this correct WRT change tracking?
556 docstring const latex1 = encoding.latexChar(next);
557 docstring const latex2 = encoding.latexChar(c);
558 if (docstring(1, next) == latex1) {
559 // the encoding supports the combination
560 os << latex2 << latex1;
561 return latex1.length() + latex2.length();
562 } else
563 os << latex1 << '{' << latex2 << '}';
564 return latex1.length() + latex2.length() + 2;
568 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
569 odocstream & os, TexRow & texrow,
570 pos_type i,
571 unsigned int & column,
572 Font const & font,
573 Layout const & style)
575 if (style.pass_thru || runparams.verbatim)
576 return false;
578 if (i + 1 < int(text_.size())) {
579 char_type next = text_[i + 1];
580 if (Encodings::isCombiningChar(next)) {
581 Encoding const & encoding = *(runparams.encoding);
582 // This space has an accent, so we must always output it.
583 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
584 return true;
588 if (lyxrc.plaintext_linelen > 0
589 && column > lyxrc.plaintext_linelen
590 && i
591 && text_[i - 1] != ' '
592 && (i + 1 < int(text_.size()))
593 // same in FreeSpacing mode
594 && !owner_->isFreeSpacing()
595 // In typewriter mode, we want to avoid
596 // ! . ? : at the end of a line
597 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
598 && (text_[i - 1] == '.'
599 || text_[i - 1] == '?'
600 || text_[i - 1] == ':'
601 || text_[i - 1] == '!'))) {
602 os << '\n';
603 texrow.newline();
604 texrow.start(owner_->id(), i + 1);
605 column = 0;
606 } else if (style.free_spacing) {
607 os << '~';
608 } else {
609 os << ' ';
611 return false;
615 int Paragraph::Private::writeScriptChars(odocstream & os,
616 docstring const & ltx,
617 Change const & runningChange,
618 Encoding const & encoding,
619 pos_type & i)
621 // FIXME: modifying i here is not very nice...
623 // We only arrive here when a proper language for character text_[i] has
624 // not been specified (i.e., it could not be translated in the current
625 // latex encoding) or its latex translation has been forced, and it
626 // belongs to a known script.
627 // Parameter ltx contains the latex translation of text_[i] as specified
628 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
629 // The latex macro name "textXXX" specifies the script to which text_[i]
630 // belongs and we use it in order to check whether characters from the
631 // same script immediately follow, such that we can collect them in a
632 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
633 // for the first char but only "<spec>" for all subsequent chars.
634 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
635 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
636 string script = to_ascii(ltx.substr(1, brace1 - 1));
637 int pos = 0;
638 int length = brace2;
639 bool closing_brace = true;
640 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
641 // Correct encoding is being used, so we can avoid \textgreek.
642 pos = brace1 + 1;
643 length -= pos;
644 closing_brace = false;
646 os << ltx.substr(pos, length);
647 int size = text_.size();
648 while (i + 1 < size) {
649 char_type const next = text_[i + 1];
650 // Stop here if next character belongs to another script
651 // or there is a change in change tracking status.
652 if (!Encodings::isKnownScriptChar(next, script) ||
653 runningChange != owner_->lookupChange(i + 1))
654 break;
655 Font prev_font;
656 bool found = false;
657 FontList::const_iterator cit = fontlist_.begin();
658 FontList::const_iterator end = fontlist_.end();
659 for (; cit != end; ++cit) {
660 if (cit->pos() >= i && !found) {
661 prev_font = cit->font();
662 found = true;
664 if (cit->pos() >= i + 1)
665 break;
667 // Stop here if there is a font attribute or encoding change.
668 if (found && cit != end && prev_font != cit->font())
669 break;
670 docstring const latex = encoding.latexChar(next);
671 docstring::size_type const b1 =
672 latex.find_first_of(from_ascii("{"));
673 docstring::size_type const b2 =
674 latex.find_last_of(from_ascii("}"));
675 int const len = b2 - b1 - 1;
676 os << latex.substr(b1 + 1, len);
677 length += len;
678 ++i;
680 if (closing_brace) {
681 os << '}';
682 ++length;
684 return length;
688 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
690 pos_type const len = str.length();
692 // is the paragraph large enough?
693 if (pos + len > int(text_.size()))
694 return false;
696 // does the wanted text start at point?
697 for (string::size_type i = 0; i < str.length(); ++i) {
698 // Caution: direct comparison of characters works only
699 // because str is pure ASCII.
700 if (str[i] != text_[pos + i])
701 return false;
704 return fontlist_.hasChangeInRange(pos, len);
708 void Paragraph::Private::latexInset(
709 BufferParams const & bparams,
710 odocstream & os,
711 TexRow & texrow,
712 OutputParams & runparams,
713 Font & running_font,
714 Font & basefont,
715 Font const & outerfont,
716 bool & open_font,
717 Change & running_change,
718 Layout const & style,
719 pos_type & i,
720 unsigned int & column)
722 Inset * inset = owner_->getInset(i);
723 LASSERT(inset, /**/);
725 if (style.pass_thru) {
726 inset->plaintext(os, runparams);
727 return;
730 // FIXME: move this to InsetNewline::latex
731 if (inset->lyxCode() == NEWLINE_CODE) {
732 // newlines are handled differently here than
733 // the default in simpleTeXSpecialChars().
734 if (!style.newline_allowed) {
735 os << '\n';
736 } else {
737 if (open_font) {
738 column += running_font.latexWriteEndChanges(
739 os, bparams, runparams,
740 basefont, basefont);
741 open_font = false;
744 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
745 os << '~';
747 basefont = owner_->getLayoutFont(bparams, outerfont);
748 running_font = basefont;
750 if (runparams.moving_arg)
751 os << "\\protect ";
754 texrow.newline();
755 texrow.start(owner_->id(), i + 1);
756 column = 0;
759 if (owner_->lookupChange(i).type == Change::DELETED) {
760 if( ++runparams.inDeletedInset == 1)
761 runparams.changeOfDeletedInset = owner_->lookupChange(i);
764 if (inset->canTrackChanges()) {
765 column += Changes::latexMarkChange(os, bparams, running_change,
766 Change(Change::UNCHANGED));
767 running_change = Change(Change::UNCHANGED);
770 bool close = false;
771 odocstream::pos_type const len = os.tellp();
773 if (inset->forceLTR()
774 && running_font.isRightToLeft()
775 // ERT is an exception, it should be output with no decorations at all
776 && inset->lyxCode() != ERT_CODE) {
777 if (running_font.language()->lang() == "farsi")
778 os << "\\beginL{}";
779 else
780 os << "\\L{";
781 close = true;
784 // FIXME: Bug: we can have an empty font change here!
785 // if there has just been a font change, we are going to close it
786 // right now, which means stupid latex code like \textsf{}. AFAIK,
787 // this does not harm dvi output. A minor bug, thus (JMarc)
789 // Some insets cannot be inside a font change command.
790 // However, even such insets *can* be placed in \L or \R
791 // or their equivalents (for RTL language switches), so we don't
792 // close the language in those cases.
793 // ArabTeX, though, cannot handle this special behavior, it seems.
794 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
795 || running_font.language()->lang() == "arabic_arabtex";
796 if (open_font && inset->noFontChange()) {
797 bool closeLanguage = arabtex
798 || basefont.isRightToLeft() == running_font.isRightToLeft();
799 unsigned int count = running_font.latexWriteEndChanges(os,
800 bparams, runparams, basefont, basefont, closeLanguage);
801 column += count;
802 // if any font properties were closed, update the running_font,
803 // making sure, however, to leave the language as it was
804 if (count > 0) {
805 // FIXME: probably a better way to keep track of the old
806 // language, than copying the entire font?
807 Font const copy_font(running_font);
808 basefont = owner_->getLayoutFont(bparams, outerfont);
809 running_font = basefont;
810 if (!closeLanguage)
811 running_font.setLanguage(copy_font.language());
812 // leave font open if language is still open
813 open_font = (running_font.language() == basefont.language());
814 if (closeLanguage)
815 runparams.local_font = &basefont;
819 int tmp;
821 try {
822 tmp = inset->latex(os, runparams);
823 } catch (EncodingException & e) {
824 // add location information and throw again.
825 e.par_id = id_;
826 e.pos = i;
827 throw(e);
830 if (close) {
831 if (running_font.language()->lang() == "farsi")
832 os << "\\endL{}";
833 else
834 os << '}';
837 if (tmp) {
838 for (int j = 0; j < tmp; ++j)
839 texrow.newline();
841 texrow.start(owner_->id(), i + 1);
842 column = 0;
843 } else {
844 column += os.tellp() - len;
847 if (owner_->lookupChange(i).type == Change::DELETED)
848 --runparams.inDeletedInset;
852 void Paragraph::Private::latexSpecialChar(
853 odocstream & os,
854 OutputParams const & runparams,
855 Font const & running_font,
856 Change const & running_change,
857 Layout const & style,
858 pos_type & i,
859 unsigned int & column)
861 char_type const c = text_[i];
863 if (style.pass_thru) {
864 if (c != '\0')
865 // FIXME UNICODE: This can fail if c cannot
866 // be encoded in the current encoding.
867 os.put(c);
868 return;
871 if (runparams.verbatim) {
872 // FIXME UNICODE: This can fail if c cannot
873 // be encoded in the current encoding.
874 os.put(c);
875 return;
878 // If T1 font encoding is used, use the special
879 // characters it provides.
880 // NOTE: some languages reset the font encoding
881 // internally
882 if (!running_font.language()->internalFontEncoding()
883 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
884 return;
886 // \tt font needs special treatment
887 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
888 && latexSpecialTypewriter(c, os, i, column))
889 return;
891 // Otherwise, we use what LaTeX provides us.
892 switch (c) {
893 case '\\':
894 os << "\\textbackslash{}";
895 column += 15;
896 break;
897 case '<':
898 os << "\\textless{}";
899 column += 10;
900 break;
901 case '>':
902 os << "\\textgreater{}";
903 column += 13;
904 break;
905 case '|':
906 os << "\\textbar{}";
907 column += 9;
908 break;
909 case '-':
910 os << '-';
911 break;
912 case '\"':
913 os << "\\char`\\\"{}";
914 column += 9;
915 break;
917 case '$': case '&':
918 case '%': case '#': case '{':
919 case '}': case '_':
920 os << '\\';
921 os.put(c);
922 column += 1;
923 break;
925 case '~':
926 os << "\\textasciitilde{}";
927 column += 16;
928 break;
930 case '^':
931 os << "\\textasciicircum{}";
932 column += 17;
933 break;
935 case '*':
936 case '[':
937 case ']':
938 // avoid being mistaken for optional arguments
939 os << '{';
940 os.put(c);
941 os << '}';
942 column += 2;
943 break;
945 case ' ':
946 // Blanks are printed before font switching.
947 // Sure? I am not! (try nice-latex)
948 // I am sure it's correct. LyX might be smarter
949 // in the future, but for now, nothing wrong is
950 // written. (Asger)
951 break;
953 default:
954 // LyX, LaTeX etc.
955 if (latexSpecialPhrase(os, i, column, runparams))
956 return;
958 if (c == '\0')
959 return;
961 Encoding const & encoding = *(runparams.encoding);
962 if (i + 1 < int(text_.size())) {
963 char_type next = text_[i + 1];
964 if (Encodings::isCombiningChar(next)) {
965 column += latexSurrogatePair(os, c, next, encoding) - 1;
966 ++i;
967 break;
970 string script;
971 docstring const latex = encoding.latexChar(c);
972 if (Encodings::isKnownScriptChar(c, script)
973 && prefixIs(latex, from_ascii("\\" + script)))
974 column += writeScriptChars(os, latex,
975 running_change, encoding, i) - 1;
976 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
977 // Prevent eating of a following
978 // space or command corruption by
979 // following characters
980 column += latex.length() + 1;
981 os << latex << "{}";
982 } else {
983 column += latex.length() - 1;
984 os << latex;
986 break;
991 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
992 pos_type i, unsigned int & column)
994 switch (c) {
995 case '>':
996 case '<':
997 os.put(c);
998 // In T1 encoding, these characters exist
999 // but we should avoid ligatures
1000 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1001 return true;
1002 os << "\\textcompwordmark{}";
1003 column += 19;
1004 return true;
1005 case '|':
1006 os.put(c);
1007 return true;
1008 case '\"':
1009 // soul.sty breaks with \char`\"
1010 os << "\\textquotedbl{}";
1011 column += 14;
1012 return true;
1013 default:
1014 return false;
1019 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1020 pos_type i, unsigned int & column)
1022 switch (c) {
1023 case '-':
1024 // within \ttfamily, "--" is merged to "-" (no endash)
1025 // so we avoid this rather irritating ligature
1026 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1027 os << "-{}";
1028 column += 2;
1029 } else
1030 os << '-';
1031 return true;
1033 // everything else has to be checked separately
1034 // (depending on the encoding)
1035 default:
1036 return false;
1041 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1042 unsigned int & column, OutputParams const & runparams)
1044 // FIXME: if we have "LaTeX" with a font
1045 // change in the middle (before the 'T', then
1046 // the "TeX" part is still special cased.
1047 // Really we should only operate this on
1048 // "words" for some definition of word
1050 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1051 if (!isTextAt(special_phrases[pnr].phrase, i))
1052 continue;
1053 if (runparams.moving_arg)
1054 os << "\\protect";
1055 os << special_phrases[pnr].macro;
1056 i += special_phrases[pnr].phrase.length() - 1;
1057 column += special_phrases[pnr].macro.length() - 1;
1058 return true;
1060 return false;
1064 void Paragraph::Private::validate(LaTeXFeatures & features,
1065 Layout const & layout) const
1067 // check the params.
1068 if (!params_.spacing().isDefault())
1069 features.require("setspace");
1071 // then the layouts
1072 features.useLayout(layout.name());
1074 // then the fonts
1075 fontlist_.validate(features);
1077 // then the indentation
1078 if (!params_.leftIndent().zero())
1079 features.require("ParagraphLeftIndent");
1081 // then the insets
1082 InsetList::const_iterator icit = insetlist_.begin();
1083 InsetList::const_iterator iend = insetlist_.end();
1084 for (; icit != iend; ++icit) {
1085 if (icit->inset) {
1086 icit->inset->validate(features);
1087 if (layout.needprotect &&
1088 icit->inset->lyxCode() == FOOT_CODE)
1089 features.require("NeedLyXFootnoteCode");
1093 // then the contents
1094 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1095 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1096 if (!special_phrases[pnr].builtin
1097 && isTextAt(special_phrases[pnr].phrase, i)) {
1098 features.require(special_phrases[pnr].phrase);
1099 break;
1102 Encodings::validate(text_[i], features);
1106 /////////////////////////////////////////////////////////////////////
1108 // Paragraph
1110 /////////////////////////////////////////////////////////////////////
1112 namespace {
1113 Layout const emptyParagraphLayout;
1116 Paragraph::Paragraph()
1117 : d(new Paragraph::Private(this, emptyParagraphLayout))
1119 itemdepth = 0;
1120 d->params_.clear();
1124 Paragraph::Paragraph(Paragraph const & par)
1125 : itemdepth(par.itemdepth),
1126 d(new Paragraph::Private(*par.d, this))
1128 registerWords();
1132 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1133 : itemdepth(par.itemdepth),
1134 d(new Paragraph::Private(*par.d, this, beg, end))
1136 registerWords();
1140 Paragraph & Paragraph::operator=(Paragraph const & par)
1142 // needed as we will destroy the private part before copying it
1143 if (&par != this) {
1144 itemdepth = par.itemdepth;
1146 deregisterWords();
1147 delete d;
1148 d = new Private(*par.d, this);
1149 registerWords();
1151 return *this;
1155 Paragraph::~Paragraph()
1157 deregisterWords();
1158 delete d;
1162 void Paragraph::write(ostream & os, BufferParams const & bparams,
1163 depth_type & dth) const
1165 // The beginning or end of a deeper (i.e. nested) area?
1166 if (dth != d->params_.depth()) {
1167 if (d->params_.depth() > dth) {
1168 while (d->params_.depth() > dth) {
1169 os << "\n\\begin_deeper";
1170 ++dth;
1172 } else {
1173 while (d->params_.depth() < dth) {
1174 os << "\n\\end_deeper";
1175 --dth;
1180 // First write the layout
1181 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1183 d->params_.write(os);
1185 Font font1(inherit_font, bparams.language);
1187 Change running_change = Change(Change::UNCHANGED);
1189 int column = 0;
1190 for (pos_type i = 0; i <= size(); ++i) {
1192 Change change = lookupChange(i);
1193 Changes::lyxMarkChange(os, column, running_change, change);
1194 running_change = change;
1196 if (i == size())
1197 break;
1199 // Write font changes
1200 Font const & font2 = getFontSettings(bparams, i);
1201 if (font2 != font1) {
1202 font2.lyxWriteChanges(font1, os);
1203 column = 0;
1204 font1 = font2;
1207 char_type const c = d->text_[i];
1208 switch (c) {
1209 case META_INSET:
1210 if (Inset const * inset = getInset(i)) {
1211 if (inset->directWrite()) {
1212 // international char, let it write
1213 // code directly so it's shorter in
1214 // the file
1215 inset->write(os);
1216 } else {
1217 if (i)
1218 os << '\n';
1219 os << "\\begin_inset ";
1220 inset->write(os);
1221 os << "\n\\end_inset\n\n";
1222 column = 0;
1225 break;
1226 case '\\':
1227 os << "\n\\backslash\n";
1228 column = 0;
1229 break;
1230 case '.':
1231 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1232 os << ".\n";
1233 column = 0;
1234 } else
1235 os << '.';
1236 break;
1237 default:
1238 if ((column > 70 && c == ' ')
1239 || column > 79) {
1240 os << '\n';
1241 column = 0;
1243 // this check is to amend a bug. LyX sometimes
1244 // inserts '\0' this could cause problems.
1245 if (c != '\0')
1246 os << to_utf8(docstring(1, c));
1247 else
1248 LYXERR0("NUL char in structure.");
1249 ++column;
1250 break;
1254 os << "\n\\end_layout\n";
1258 void Paragraph::validate(LaTeXFeatures & features) const
1260 d->validate(features, *d->layout_);
1264 void Paragraph::insert(pos_type start, docstring const & str,
1265 Font const & font, Change const & change)
1267 for (size_t i = 0, n = str.size(); i != n ; ++i)
1268 insertChar(start + i, str[i], font, change);
1272 void Paragraph::appendChar(char_type c, Font const & font,
1273 Change const & change)
1275 // track change
1276 d->changes_.insert(change, d->text_.size());
1277 // when appending characters, no need to update tables
1278 d->text_.push_back(c);
1279 setFont(d->text_.size() - 1, font);
1283 void Paragraph::appendString(docstring const & s, Font const & font,
1284 Change const & change)
1286 pos_type end = s.size();
1287 size_t oldsize = d->text_.size();
1288 size_t newsize = oldsize + end;
1289 size_t capacity = d->text_.capacity();
1290 if (newsize >= capacity)
1291 d->text_.reserve(max(capacity + 100, newsize));
1293 // when appending characters, no need to update tables
1294 d->text_.append(s);
1296 // FIXME: Optimize this!
1297 for (size_t i = oldsize; i != newsize; ++i) {
1298 // track change
1299 d->changes_.insert(change, i);
1301 d->fontlist_.set(oldsize, font);
1302 d->fontlist_.set(newsize - 1, font);
1306 void Paragraph::insertChar(pos_type pos, char_type c,
1307 bool trackChanges)
1309 d->insertChar(pos, c, Change(trackChanges ?
1310 Change::INSERTED : Change::UNCHANGED));
1314 void Paragraph::insertChar(pos_type pos, char_type c,
1315 Font const & font, bool trackChanges)
1317 d->insertChar(pos, c, Change(trackChanges ?
1318 Change::INSERTED : Change::UNCHANGED));
1319 setFont(pos, font);
1323 void Paragraph::insertChar(pos_type pos, char_type c,
1324 Font const & font, Change const & change)
1326 d->insertChar(pos, c, change);
1327 setFont(pos, font);
1331 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1332 Font const & font, Change const & change)
1334 bool const success = insertInset(pos, inset, change);
1335 // Set the font/language of the inset...
1336 setFont(pos, font);
1337 return success;
1341 void Paragraph::resetFonts(Font const & font)
1343 d->fontlist_.clear();
1344 d->fontlist_.set(0, font);
1345 d->fontlist_.set(d->text_.size() - 1, font);
1348 // Gets uninstantiated font setting at position.
1349 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1350 pos_type pos) const
1352 if (pos > size()) {
1353 LYXERR0("pos: " << pos << " size: " << size());
1354 LASSERT(pos <= size(), /**/);
1357 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1358 if (cit != d->fontlist_.end())
1359 return cit->font();
1361 if (pos == size() && !empty())
1362 return getFontSettings(bparams, pos - 1);
1364 // Optimisation: avoid a full font instantiation if there is no
1365 // language change from previous call.
1366 static Font previous_font;
1367 static Language const * previous_lang = 0;
1368 Language const * lang = getParLanguage(bparams);
1369 if (lang != previous_lang) {
1370 previous_lang = lang;
1371 previous_font = Font(inherit_font, lang);
1373 return previous_font;
1377 FontSpan Paragraph::fontSpan(pos_type pos) const
1379 LASSERT(pos <= size(), /**/);
1380 pos_type start = 0;
1382 FontList::const_iterator cit = d->fontlist_.begin();
1383 FontList::const_iterator end = d->fontlist_.end();
1384 for (; cit != end; ++cit) {
1385 if (cit->pos() >= pos) {
1386 if (pos >= beginOfBody())
1387 return FontSpan(max(start, beginOfBody()),
1388 cit->pos());
1389 else
1390 return FontSpan(start,
1391 min(beginOfBody() - 1,
1392 cit->pos()));
1394 start = cit->pos() + 1;
1397 // This should not happen, but if so, we take no chances.
1398 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1399 return FontSpan(pos, pos);
1403 // Gets uninstantiated font setting at position 0
1404 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1406 if (!empty() && !d->fontlist_.empty())
1407 return d->fontlist_.begin()->font();
1409 // Optimisation: avoid a full font instantiation if there is no
1410 // language change from previous call.
1411 static Font previous_font;
1412 static Language const * previous_lang = 0;
1413 if (bparams.language != previous_lang) {
1414 previous_lang = bparams.language;
1415 previous_font = Font(inherit_font, bparams.language);
1418 return previous_font;
1422 // Gets the fully instantiated font at a given position in a paragraph
1423 // This is basically the same function as Text::GetFont() in text2.cpp.
1424 // The difference is that this one is used for generating the LaTeX file,
1425 // and thus cosmetic "improvements" are disallowed: This has to deliver
1426 // the true picture of the buffer. (Asger)
1427 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1428 Font const & outerfont) const
1430 LASSERT(pos >= 0, /**/);
1432 Font font = getFontSettings(bparams, pos);
1434 pos_type const body_pos = beginOfBody();
1435 FontInfo & fi = font.fontInfo();
1436 if (pos < body_pos)
1437 fi.realize(d->layout_->labelfont);
1438 else
1439 fi.realize(d->layout_->font);
1441 fi.realize(outerfont.fontInfo());
1442 fi.realize(bparams.getFont().fontInfo());
1444 return font;
1448 Font const Paragraph::getLabelFont
1449 (BufferParams const & bparams, Font const & outerfont) const
1451 FontInfo tmpfont = d->layout_->labelfont;
1452 tmpfont.realize(outerfont.fontInfo());
1453 tmpfont.realize(bparams.getFont().fontInfo());
1454 return Font(tmpfont, getParLanguage(bparams));
1458 Font const Paragraph::getLayoutFont
1459 (BufferParams const & bparams, Font const & outerfont) const
1461 FontInfo tmpfont = d->layout_->font;
1462 tmpfont.realize(outerfont.fontInfo());
1463 tmpfont.realize(bparams.getFont().fontInfo());
1464 return Font(tmpfont, getParLanguage(bparams));
1468 /// Returns the height of the highest font in range
1469 FontSize Paragraph::highestFontInRange
1470 (pos_type startpos, pos_type endpos, FontSize def_size) const
1472 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1476 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1478 char_type c = d->text_[pos];
1479 if (!lyxrc.rtl_support)
1480 return c;
1482 char_type uc = c;
1483 switch (c) {
1484 case '(':
1485 uc = ')';
1486 break;
1487 case ')':
1488 uc = '(';
1489 break;
1490 case '[':
1491 uc = ']';
1492 break;
1493 case ']':
1494 uc = '[';
1495 break;
1496 case '{':
1497 uc = '}';
1498 break;
1499 case '}':
1500 uc = '{';
1501 break;
1502 case '<':
1503 uc = '>';
1504 break;
1505 case '>':
1506 uc = '<';
1507 break;
1509 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1510 return uc;
1511 return c;
1515 void Paragraph::setFont(pos_type pos, Font const & font)
1517 LASSERT(pos <= size(), /**/);
1519 // First, reduce font against layout/label font
1520 // Update: The setCharFont() routine in text2.cpp already
1521 // reduces font, so we don't need to do that here. (Asger)
1523 d->fontlist_.set(pos, font);
1527 void Paragraph::makeSameLayout(Paragraph const & par)
1529 d->layout_ = par.d->layout_;
1530 d->params_ = par.d->params_;
1534 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1536 if (isFreeSpacing())
1537 return false;
1539 int pos = 0;
1540 int count = 0;
1542 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1543 if (eraseChar(pos, trackChanges))
1544 ++count;
1545 else
1546 ++pos;
1549 return count > 0 || pos > 0;
1553 bool Paragraph::hasSameLayout(Paragraph const & par) const
1555 return par.d->layout_ == d->layout_
1556 && d->params_.sameLayout(par.d->params_);
1560 depth_type Paragraph::getDepth() const
1562 return d->params_.depth();
1566 depth_type Paragraph::getMaxDepthAfter() const
1568 if (d->layout_->isEnvironment())
1569 return d->params_.depth() + 1;
1570 else
1571 return d->params_.depth();
1575 char Paragraph::getAlign() const
1577 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1578 return d->layout_->align;
1579 else
1580 return d->params_.align();
1584 docstring const & Paragraph::labelString() const
1586 return d->params_.labelString();
1590 // the next two functions are for the manual labels
1591 docstring const Paragraph::getLabelWidthString() const
1593 if (d->layout_->margintype == MARGIN_MANUAL
1594 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1595 return d->params_.labelWidthString();
1596 else
1597 return _("Senseless with this layout!");
1601 void Paragraph::setLabelWidthString(docstring const & s)
1603 d->params_.labelWidthString(s);
1607 docstring const Paragraph::translateIfPossible(docstring const & s,
1608 BufferParams const & bparams) const
1610 if (!isAscii(s) || s.empty()) {
1611 // This must be a user defined layout. We cannot translate
1612 // this, since gettext accepts only ascii keys.
1613 return s;
1615 // Probably standard layout, try to translate
1616 Messages & m = getMessages(getParLanguage(bparams)->code());
1617 return m.get(to_ascii(s));
1621 docstring Paragraph::expandLabel(Layout const & layout,
1622 BufferParams const & bparams, bool process_appendix) const
1624 DocumentClass const & tclass = bparams.documentClass();
1626 docstring fmt;
1627 if (process_appendix && d->params_.appendix())
1628 fmt = translateIfPossible(layout.labelstring_appendix(),
1629 bparams);
1630 else
1631 fmt = translateIfPossible(layout.labelstring(), bparams);
1633 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1634 && !layout.counter.empty())
1635 return tclass.counters().theCounter(layout.counter);
1637 // handle 'inherited level parts' in 'fmt',
1638 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1639 size_t const i = fmt.find('@', 0);
1640 if (i != docstring::npos) {
1641 size_t const j = fmt.find('@', i + 1);
1642 if (j != docstring::npos) {
1643 docstring parent(fmt, i + 1, j - i - 1);
1644 docstring label = from_ascii("??");
1645 if (tclass.hasLayout(parent))
1646 docstring label = expandLabel(tclass[parent], bparams,
1647 process_appendix);
1648 fmt = docstring(fmt, 0, i) + label
1649 + docstring(fmt, j + 1, docstring::npos);
1653 return tclass.counters().counterLabel(fmt);
1657 void Paragraph::applyLayout(Layout const & new_layout)
1659 d->layout_ = &new_layout;
1660 LyXAlignment const oldAlign = d->params_.align();
1662 if (!(oldAlign & d->layout_->alignpossible)) {
1663 frontend::Alert::warning(_("Alignment not permitted"),
1664 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1665 d->params_.align(LYX_ALIGN_LAYOUT);
1670 pos_type Paragraph::beginOfBody() const
1672 return d->begin_of_body_;
1676 void Paragraph::setBeginOfBody()
1678 if (d->layout_->labeltype != LABEL_MANUAL) {
1679 d->begin_of_body_ = 0;
1680 return;
1683 // Unroll the first two cycles of the loop
1684 // and remember the previous character to
1685 // remove unnecessary getChar() calls
1686 pos_type i = 0;
1687 pos_type end = size();
1688 if (i < end && !isNewline(i)) {
1689 ++i;
1690 char_type previous_char = 0;
1691 char_type temp = 0;
1692 if (i < end) {
1693 previous_char = d->text_[i];
1694 if (!isNewline(i)) {
1695 ++i;
1696 while (i < end && previous_char != ' ') {
1697 temp = d->text_[i];
1698 if (isNewline(i))
1699 break;
1700 ++i;
1701 previous_char = temp;
1707 d->begin_of_body_ = i;
1711 bool Paragraph::forcePlainLayout() const
1713 return inInset().forcePlainLayout();
1717 bool Paragraph::allowParagraphCustomization() const
1719 return inInset().allowParagraphCustomization();
1723 bool Paragraph::usePlainLayout() const
1725 return inInset().usePlainLayout();
1729 namespace {
1731 // paragraphs inside floats need different alignment tags to avoid
1732 // unwanted space
1734 bool noTrivlistCentering(InsetCode code)
1736 return code == FLOAT_CODE
1737 || code == WRAP_CODE
1738 || code == CELL_CODE;
1742 string correction(string const & orig)
1744 if (orig == "flushleft")
1745 return "raggedright";
1746 if (orig == "flushright")
1747 return "raggedleft";
1748 if (orig == "center")
1749 return "centering";
1750 return orig;
1754 string const corrected_env(string const & suffix, string const & env,
1755 InsetCode code, bool const lastpar)
1757 string output = suffix + "{";
1758 if (noTrivlistCentering(code)) {
1759 if (lastpar) {
1760 // the last paragraph in non-trivlist-aligned
1761 // context is special (to avoid unwanted whitespace)
1762 if (suffix == "\\begin")
1763 return "\\" + correction(env) + "{}";
1764 return string();
1766 output += correction(env);
1767 } else
1768 output += env;
1769 output += "}";
1770 if (suffix == "\\begin")
1771 output += "\n";
1772 return output;
1776 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1778 if (!contains(str, "\n"))
1779 column += str.size();
1780 else {
1781 string tmp;
1782 texrow.newline();
1783 column = rsplit(str, tmp, '\n').size();
1787 } // namespace anon
1790 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1791 odocstream & os, TexRow & texrow,
1792 OutputParams const & runparams) const
1794 int column = 0;
1796 if (params_.noindent()) {
1797 os << "\\noindent ";
1798 column += 10;
1801 LyXAlignment const curAlign = params_.align();
1803 if (curAlign == layout_->align)
1804 return column;
1806 switch (curAlign) {
1807 case LYX_ALIGN_NONE:
1808 case LYX_ALIGN_BLOCK:
1809 case LYX_ALIGN_LAYOUT:
1810 case LYX_ALIGN_SPECIAL:
1811 break;
1812 case LYX_ALIGN_LEFT:
1813 case LYX_ALIGN_RIGHT:
1814 case LYX_ALIGN_CENTER:
1815 if (runparams.moving_arg) {
1816 os << "\\protect";
1817 column += 8;
1819 break;
1822 string const begin_tag = "\\begin";
1823 InsetCode code = owner_->ownerCode();
1824 bool const lastpar = runparams.isLastPar;
1826 switch (curAlign) {
1827 case LYX_ALIGN_NONE:
1828 case LYX_ALIGN_BLOCK:
1829 case LYX_ALIGN_LAYOUT:
1830 case LYX_ALIGN_SPECIAL:
1831 break;
1832 case LYX_ALIGN_LEFT: {
1833 string output;
1834 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1835 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1836 else
1837 output = corrected_env(begin_tag, "flushright", code, lastpar);
1838 os << from_ascii(output);
1839 adjust_row_column(output, texrow, column);
1840 break;
1841 } case LYX_ALIGN_RIGHT: {
1842 string output;
1843 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1844 output = corrected_env(begin_tag, "flushright", code, lastpar);
1845 else
1846 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1847 os << from_ascii(output);
1848 adjust_row_column(output, texrow, column);
1849 break;
1850 } case LYX_ALIGN_CENTER: {
1851 string output;
1852 output = corrected_env(begin_tag, "center", code, lastpar);
1853 os << from_ascii(output);
1854 adjust_row_column(output, texrow, column);
1855 break;
1859 return column;
1863 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1864 odocstream & os, TexRow & texrow,
1865 OutputParams const & runparams) const
1867 int column = 0;
1869 switch (params_.align()) {
1870 case LYX_ALIGN_NONE:
1871 case LYX_ALIGN_BLOCK:
1872 case LYX_ALIGN_LAYOUT:
1873 case LYX_ALIGN_SPECIAL:
1874 break;
1875 case LYX_ALIGN_LEFT:
1876 case LYX_ALIGN_RIGHT:
1877 case LYX_ALIGN_CENTER:
1878 if (runparams.moving_arg) {
1879 os << "\\protect";
1880 column = 8;
1882 break;
1885 string const end_tag = "\n\\par\\end";
1886 InsetCode code = owner_->ownerCode();
1887 bool const lastpar = runparams.isLastPar;
1889 switch (params_.align()) {
1890 case LYX_ALIGN_NONE:
1891 case LYX_ALIGN_BLOCK:
1892 case LYX_ALIGN_LAYOUT:
1893 case LYX_ALIGN_SPECIAL:
1894 break;
1895 case LYX_ALIGN_LEFT: {
1896 string output;
1897 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1898 output = corrected_env(end_tag, "flushleft", code, lastpar);
1899 else
1900 output = corrected_env(end_tag, "flushright", code, lastpar);
1901 os << from_ascii(output);
1902 adjust_row_column(output, texrow, column);
1903 break;
1904 } case LYX_ALIGN_RIGHT: {
1905 string output;
1906 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1907 output = corrected_env(end_tag, "flushright", code, lastpar);
1908 else
1909 output = corrected_env(end_tag, "flushleft", code, lastpar);
1910 os << from_ascii(output);
1911 adjust_row_column(output, texrow, column);
1912 break;
1913 } case LYX_ALIGN_CENTER: {
1914 string output;
1915 output = corrected_env(end_tag, "center", code, lastpar);
1916 os << from_ascii(output);
1917 adjust_row_column(output, texrow, column);
1918 break;
1922 return column;
1926 // This one spits out the text of the paragraph
1927 bool Paragraph::latex(BufferParams const & bparams,
1928 Font const & outerfont,
1929 odocstream & os, TexRow & texrow,
1930 OutputParams const & runparams,
1931 int start_pos, int end_pos) const
1933 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1935 bool return_value = false;
1937 bool const allowcust = allowParagraphCustomization();
1939 // FIXME This check should not be needed. Perhaps issue an
1940 // error if it triggers.
1941 Layout const & style = forcePlainLayout() ?
1942 bparams.documentClass().plainLayout() : *d->layout_;
1944 // Current base font for all inherited font changes, without any
1945 // change caused by an individual character, except for the language:
1946 // It is set to the language of the first character.
1947 // As long as we are in the label, this font is the base font of the
1948 // label. Before the first body character it is set to the base font
1949 // of the body.
1950 Font basefont;
1952 // Maybe we have to create a optional argument.
1953 pos_type body_pos = beginOfBody();
1954 unsigned int column = 0;
1956 if (body_pos > 0) {
1957 // the optional argument is kept in curly brackets in
1958 // case it contains a ']'
1959 os << "[{";
1960 column += 2;
1961 basefont = getLabelFont(bparams, outerfont);
1962 } else {
1963 basefont = getLayoutFont(bparams, outerfont);
1966 // Which font is currently active?
1967 Font running_font(basefont);
1968 // Do we have an open font change?
1969 bool open_font = false;
1971 Change runningChange = Change(Change::UNCHANGED);
1973 texrow.start(id(), 0);
1975 // if the paragraph is empty, the loop will not be entered at all
1976 if (empty()) {
1977 if (style.isCommand()) {
1978 os << '{';
1979 ++column;
1981 if (allowcust)
1982 column += d->startTeXParParams(bparams, os, texrow,
1983 runparams);
1986 for (pos_type i = 0; i < size(); ++i) {
1987 // First char in paragraph or after label?
1988 if (i == body_pos) {
1989 if (body_pos > 0) {
1990 if (open_font) {
1991 column += running_font.latexWriteEndChanges(
1992 os, bparams, runparams,
1993 basefont, basefont);
1994 open_font = false;
1996 basefont = getLayoutFont(bparams, outerfont);
1997 running_font = basefont;
1999 column += Changes::latexMarkChange(os, bparams,
2000 runningChange, Change(Change::UNCHANGED));
2001 runningChange = Change(Change::UNCHANGED);
2003 os << "}] ";
2004 column +=3;
2006 if (style.isCommand()) {
2007 os << '{';
2008 ++column;
2011 if (allowcust)
2012 column += d->startTeXParParams(bparams, os,
2013 texrow,
2014 runparams);
2017 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2018 : lookupChange(i);
2020 if (bparams.outputChanges && runningChange != change) {
2021 if (open_font) {
2022 column += running_font.latexWriteEndChanges(
2023 os, bparams, runparams, basefont, basefont);
2024 open_font = false;
2026 basefont = getLayoutFont(bparams, outerfont);
2027 running_font = basefont;
2029 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2030 runningChange = change;
2033 // do not output text which is marked deleted
2034 // if change tracking output is disabled
2035 if (!bparams.outputChanges && change.type == Change::DELETED) {
2036 continue;
2039 ++column;
2041 // Fully instantiated font
2042 Font const font = getFont(bparams, i, outerfont);
2044 Font const last_font = running_font;
2046 // Do we need to close the previous font?
2047 if (open_font &&
2048 (font != running_font ||
2049 font.language() != running_font.language()))
2051 column += running_font.latexWriteEndChanges(
2052 os, bparams, runparams, basefont,
2053 (i == body_pos-1) ? basefont : font);
2054 running_font = basefont;
2055 open_font = false;
2058 // close babel's font environment before opening CJK.
2059 if (!running_font.language()->babel().empty() &&
2060 font.language()->encoding()->package() == Encoding::CJK) {
2061 string end_tag = subst(lyxrc.language_command_end,
2062 "$$lang",
2063 running_font.language()->babel());
2064 os << from_ascii(end_tag);
2065 column += end_tag.length();
2068 // Switch file encoding if necessary (and allowed)
2069 if (!runparams.verbatim &&
2070 runparams.encoding->package() != Encoding::none &&
2071 font.language()->encoding()->package() != Encoding::none) {
2072 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2073 runparams, *(font.language()->encoding()));
2074 if (enc_switch.first) {
2075 column += enc_switch.second;
2076 runparams.encoding = font.language()->encoding();
2080 char_type const c = d->text_[i];
2082 // Do we need to change font?
2083 if ((font != running_font ||
2084 font.language() != running_font.language()) &&
2085 i != body_pos - 1)
2087 odocstringstream ods;
2088 column += font.latexWriteStartChanges(ods, bparams,
2089 runparams, basefont,
2090 last_font);
2091 running_font = font;
2092 open_font = true;
2093 docstring fontchange = ods.str();
2094 // check if the fontchange ends with a trailing blank
2095 // (like "\small " (see bug 3382)
2096 if (suffixIs(fontchange, ' ') && c == ' ')
2097 os << fontchange.substr(0, fontchange.size() - 1)
2098 << from_ascii("{}");
2099 else
2100 os << fontchange;
2103 // FIXME: think about end_pos implementation...
2104 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2105 // FIXME: integrate this case in latexSpecialChar
2106 // Do not print the separation of the optional argument
2107 // if style.pass_thru is false. This works because
2108 // latexSpecialChar ignores spaces if
2109 // style.pass_thru is false.
2110 if (i != body_pos - 1) {
2111 if (d->simpleTeXBlanks(
2112 runparams, os, texrow,
2113 i, column, font, style)) {
2114 // A surrogate pair was output. We
2115 // must not call latexSpecialChar
2116 // in this iteration, since it would output
2117 // the combining character again.
2118 ++i;
2119 continue;
2124 OutputParams rp = runparams;
2125 rp.free_spacing = style.free_spacing;
2126 rp.local_font = &font;
2127 rp.intitle = style.intitle;
2129 // Two major modes: LaTeX or plain
2130 // Handle here those cases common to both modes
2131 // and then split to handle the two modes separately.
2132 if (c == META_INSET) {
2133 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2134 d->latexInset(bparams, os,
2135 texrow, rp, running_font,
2136 basefont, outerfont, open_font,
2137 runningChange, style, i, column);
2139 } else {
2140 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2141 try {
2142 d->latexSpecialChar(os, rp, running_font, runningChange,
2143 style, i, column);
2144 } catch (EncodingException & e) {
2145 if (runparams.dryrun) {
2146 os << "<" << _("LyX Warning: ")
2147 << _("uncodable character") << " '";
2148 os.put(c);
2149 os << "'>";
2150 } else {
2151 // add location information and throw again.
2152 e.par_id = id();
2153 e.pos = i;
2154 throw(e);
2160 // Set the encoding to that returned from latexSpecialChar (see
2161 // comment for encoding member in OutputParams.h)
2162 runparams.encoding = rp.encoding;
2165 // If we have an open font definition, we have to close it
2166 if (open_font) {
2167 #ifdef FIXED_LANGUAGE_END_DETECTION
2168 if (next_) {
2169 running_font
2170 .latexWriteEndChanges(os, bparams, runparams,
2171 basefont,
2172 next_->getFont(bparams, 0, outerfont));
2173 } else {
2174 running_font.latexWriteEndChanges(os, bparams,
2175 runparams, basefont, basefont);
2177 #else
2178 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2179 //FIXME: there as we start another \selectlanguage with the next paragraph if
2180 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2181 running_font.latexWriteEndChanges(os, bparams, runparams,
2182 basefont, basefont);
2183 #endif
2186 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2188 // Needed if there is an optional argument but no contents.
2189 if (body_pos > 0 && body_pos == size()) {
2190 os << "}]~";
2191 return_value = false;
2194 if (allowcust) {
2195 column += d->endTeXParParams(bparams, os, texrow,
2196 runparams);
2199 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2200 return return_value;
2204 bool Paragraph::emptyTag() const
2206 for (pos_type i = 0; i < size(); ++i) {
2207 if (Inset const * inset = getInset(i)) {
2208 InsetCode lyx_code = inset->lyxCode();
2209 if (lyx_code != TOC_CODE &&
2210 lyx_code != INCLUDE_CODE &&
2211 lyx_code != GRAPHICS_CODE &&
2212 lyx_code != ERT_CODE &&
2213 lyx_code != LISTINGS_CODE &&
2214 lyx_code != FLOAT_CODE &&
2215 lyx_code != TABULAR_CODE) {
2216 return false;
2218 } else {
2219 char_type c = d->text_[i];
2220 if (c != ' ' && c != '\t')
2221 return false;
2224 return true;
2228 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2229 const
2231 for (pos_type i = 0; i < size(); ++i) {
2232 if (Inset const * inset = getInset(i)) {
2233 InsetCode lyx_code = inset->lyxCode();
2234 if (lyx_code == LABEL_CODE) {
2235 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2236 docstring const & id = il->getParam("name");
2237 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2241 return string();
2245 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2246 const
2248 pos_type i;
2249 for (i = 0; i < size(); ++i) {
2250 if (Inset const * inset = getInset(i)) {
2251 inset->docbook(os, runparams);
2252 } else {
2253 char_type c = d->text_[i];
2254 if (c == ' ')
2255 break;
2256 os << sgml::escapeChar(c);
2259 return i;
2263 pos_type Paragraph::firstWordLyXHTML(odocstream & os, OutputParams const & runparams)
2264 const
2266 pos_type i;
2267 for (i = 0; i < size(); ++i) {
2268 if (Inset const * inset = getInset(i)) {
2269 inset->xhtml(os, runparams);
2270 } else {
2271 char_type c = d->text_[i];
2272 if (c == ' ')
2273 break;
2274 os << html::escapeChar(c);
2277 return i;
2281 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2283 Font font_old;
2284 pos_type size = text_.size();
2285 for (pos_type i = initial; i < size; ++i) {
2286 Font font = owner_->getFont(buf.params(), i, outerfont);
2287 if (text_[i] == META_INSET)
2288 return false;
2289 if (i != initial && font != font_old)
2290 return false;
2291 font_old = font;
2294 return true;
2298 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2299 odocstream & os,
2300 OutputParams const & runparams,
2301 Font const & outerfont,
2302 pos_type initial) const
2304 bool emph_flag = false;
2306 Layout const & style = *d->layout_;
2307 FontInfo font_old =
2308 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2310 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2311 os << "]]>";
2313 // parsing main loop
2314 for (pos_type i = initial; i < size(); ++i) {
2315 Font font = getFont(buf.params(), i, outerfont);
2317 // handle <emphasis> tag
2318 if (font_old.emph() != font.fontInfo().emph()) {
2319 if (font.fontInfo().emph() == FONT_ON) {
2320 os << "<emphasis>";
2321 emph_flag = true;
2322 } else if (i != initial) {
2323 os << "</emphasis>";
2324 emph_flag = false;
2328 if (Inset const * inset = getInset(i)) {
2329 inset->docbook(os, runparams);
2330 } else {
2331 char_type c = d->text_[i];
2333 if (style.pass_thru)
2334 os.put(c);
2335 else
2336 os << sgml::escapeChar(c);
2338 font_old = font.fontInfo();
2341 if (emph_flag) {
2342 os << "</emphasis>";
2345 if (style.free_spacing)
2346 os << '\n';
2347 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2348 os << "<![CDATA[";
2352 void Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2353 odocstream & os,
2354 OutputParams const & runparams,
2355 Font const & outerfont,
2356 pos_type initial) const
2358 // FIXME We really need to manage the tag nesting here.
2359 // Probably in the same sort of way as in output_xhtml.
2360 bool emph_flag = false;
2361 bool bold_flag = false;
2362 std::string closing_tag;
2364 Layout const & style = *d->layout_;
2365 FontInfo font_old =
2366 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2368 //if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2369 // os << "]]>";
2371 // parsing main loop
2372 for (pos_type i = initial; i < size(); ++i) {
2373 Font font = getFont(buf.params(), i, outerfont);
2375 // emphasis
2376 if (font_old.emph() != font.fontInfo().emph()) {
2377 if (font.fontInfo().emph() == FONT_ON) {
2378 os << "<em>";
2379 emph_flag = true;
2380 } else if (emph_flag && i != initial) {
2381 os << "</em>";
2382 emph_flag = false;
2385 // bold
2386 if (font_old.series() != font.fontInfo().series()) {
2387 if (font.fontInfo().series() == BOLD_SERIES) {
2388 os << "<strong>";
2389 bold_flag = true;
2390 } else if (bold_flag && i != initial) {
2391 os << "</strong>";
2392 bold_flag = false;
2395 // FIXME Other such tags?
2397 if (Inset const * inset = getInset(i)) {
2398 inset->xhtml(os, runparams);
2399 } else {
2400 char_type c = d->text_[i];
2402 if (style.pass_thru)
2403 os.put(c);
2404 else if (c == '-') {
2405 docstring str;
2406 int j = i + 1;
2407 if (j < size() && d->text_[j] == '-') {
2408 j += 1;
2409 if (j < size() && d->text_[j] == '-') {
2410 str += from_ascii("&mdash;");
2411 i += 2;
2412 } else {
2413 str += from_ascii("&ndash;");
2414 i += 1;
2417 else
2418 str += c;
2419 os << str;
2420 } else
2421 os << html::escapeChar(c);
2423 font_old = font.fontInfo();
2426 // FIXME This could be out of order. See above.
2427 if (emph_flag)
2428 os << "</em>";
2429 if (bold_flag)
2430 os << "</strong>";
2432 // if (style.free_spacing)
2433 // os << '\n';
2434 // if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2435 // os << "<![CDATA[";
2439 bool Paragraph::isHfill(pos_type pos) const
2441 Inset const * inset = getInset(pos);
2442 return inset && (inset->lyxCode() == SPACE_CODE &&
2443 inset->isStretchableSpace());
2447 bool Paragraph::isNewline(pos_type pos) const
2449 Inset const * inset = getInset(pos);
2450 return inset && inset->lyxCode() == NEWLINE_CODE;
2454 bool Paragraph::isLineSeparator(pos_type pos) const
2456 char_type const c = d->text_[pos];
2457 if (isLineSeparatorChar(c))
2458 return true;
2459 Inset const * inset = getInset(pos);
2460 return inset && inset->isLineSeparator();
2464 /// Used by the spellchecker
2465 bool Paragraph::isLetter(pos_type pos) const
2467 if (Inset const * inset = getInset(pos))
2468 return inset->isLetter();
2469 char_type const c = d->text_[pos];
2470 // We want to pass the ' and escape chars to the spellchecker
2471 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2472 return (isLetterChar(c) || isDigit(c) || contains(quote, c))
2473 && (!d->inset_owner_ || d->inset_owner_->allowSpellCheck())
2474 && pos != size()
2475 && !isDeleted(pos);
2479 bool Paragraph::isChar(pos_type pos) const
2481 if (Inset const * inset = getInset(pos))
2482 return inset->isChar();
2483 char_type const c = d->text_[pos];
2484 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2488 bool Paragraph::isSpace(pos_type pos) const
2490 if (Inset const * inset = getInset(pos))
2491 return inset->isSpace();
2492 char_type const c = d->text_[pos];
2493 return lyx::isSpace(c);
2497 Language const *
2498 Paragraph::getParLanguage(BufferParams const & bparams) const
2500 if (!empty())
2501 return getFirstFontSettings(bparams).language();
2502 // FIXME: we should check the prev par as well (Lgb)
2503 return bparams.language;
2507 bool Paragraph::isRTL(BufferParams const & bparams) const
2509 return lyxrc.rtl_support
2510 && getParLanguage(bparams)->rightToLeft()
2511 && ownerCode() != ERT_CODE
2512 && ownerCode() != LISTINGS_CODE;
2516 void Paragraph::changeLanguage(BufferParams const & bparams,
2517 Language const * from, Language const * to)
2519 // change language including dummy font change at the end
2520 for (pos_type i = 0; i <= size(); ++i) {
2521 Font font = getFontSettings(bparams, i);
2522 if (font.language() == from) {
2523 font.setLanguage(to);
2524 setFont(i, font);
2530 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2532 Language const * doc_language = bparams.language;
2533 FontList::const_iterator cit = d->fontlist_.begin();
2534 FontList::const_iterator end = d->fontlist_.end();
2536 for (; cit != end; ++cit)
2537 if (cit->font().language() != ignore_language &&
2538 cit->font().language() != latex_language &&
2539 cit->font().language() != doc_language)
2540 return true;
2541 return false;
2545 docstring Paragraph::asString(int options) const
2547 return asString(0, size(), options);
2551 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2553 odocstringstream os;
2555 if (beg == 0
2556 && options & AS_STR_LABEL
2557 && !d->params_.labelString().empty())
2558 os << d->params_.labelString() << ' ';
2560 for (pos_type i = beg; i < end; ++i) {
2561 char_type const c = d->text_[i];
2562 if (isPrintable(c) || c == '\t'
2563 || (c == '\n' && options & AS_STR_NEWLINES))
2564 os.put(c);
2565 else if (c == META_INSET && options & AS_STR_INSETS)
2566 getInset(i)->tocString(os);
2569 return os.str();
2573 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2575 odocstringstream os;
2577 if (beg == 0
2578 && options & AS_STR_LABEL
2579 && !d->params_.labelString().empty())
2580 os << d->params_.labelString() << ' ';
2582 for (pos_type i = beg; i < end; ++i) {
2583 char_type const c = d->text_[i];
2584 if (isPrintable(c) || c == '\t'
2585 || (c == '\n' && options & AS_STR_NEWLINES))
2586 os.put(c);
2587 else if (c == META_INSET && options & AS_STR_INSETS) {
2588 getInset(i)->plaintext(os, runparams);
2592 return os.str();
2596 void Paragraph::setInsetOwner(Inset const * inset)
2598 d->inset_owner_ = inset;
2602 int Paragraph::id() const
2604 return d->id_;
2608 Layout const & Paragraph::layout() const
2610 return *d->layout_;
2614 void Paragraph::setLayout(Layout const & layout)
2616 d->layout_ = &layout;
2620 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2622 setLayout(tc.defaultLayout());
2626 void Paragraph::setPlainLayout(DocumentClass const & tc)
2628 setLayout(tc.plainLayout());
2632 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2634 if (usePlainLayout())
2635 setPlainLayout(tclass);
2636 else
2637 setDefaultLayout(tclass);
2641 Inset const & Paragraph::inInset() const
2643 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2644 _("Memory problem"), _("Paragraph not properly initialized")));
2645 return *d->inset_owner_;
2649 InsetCode Paragraph::ownerCode() const
2651 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2655 ParagraphParameters & Paragraph::params()
2657 return d->params_;
2661 ParagraphParameters const & Paragraph::params() const
2663 return d->params_;
2667 bool Paragraph::isFreeSpacing() const
2669 if (d->layout_->free_spacing)
2670 return true;
2671 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2675 bool Paragraph::allowEmpty() const
2677 if (d->layout_->keepempty)
2678 return true;
2679 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2683 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2685 if (!Encodings::isArabicChar(c))
2686 return c;
2688 char_type prev_char = ' ';
2689 char_type next_char = ' ';
2691 for (pos_type i = pos - 1; i >= 0; --i) {
2692 char_type const par_char = d->text_[i];
2693 if (!Encodings::isArabicComposeChar(par_char)) {
2694 prev_char = par_char;
2695 break;
2699 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2700 char_type const par_char = d->text_[i];
2701 if (!Encodings::isArabicComposeChar(par_char)) {
2702 next_char = par_char;
2703 break;
2707 if (Encodings::isArabicChar(next_char)) {
2708 if (Encodings::isArabicChar(prev_char) &&
2709 !Encodings::isArabicSpecialChar(prev_char))
2710 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2711 else
2712 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2713 } else {
2714 if (Encodings::isArabicChar(prev_char) &&
2715 !Encodings::isArabicSpecialChar(prev_char))
2716 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2717 else
2718 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2723 int Paragraph::checkBiblio(Buffer const & buffer)
2725 // FIXME From JS:
2726 // This is getting more and more a mess. ...We really should clean
2727 // up this bibitem issue for 1.6. See also bug 2743.
2729 // Add bibitem insets if necessary
2730 if (d->layout_->labeltype != LABEL_BIBLIO)
2731 return 0;
2733 bool hasbibitem = !d->insetlist_.empty()
2734 // Insist on it being in pos 0
2735 && d->text_[0] == META_INSET
2736 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2738 bool track_changes = buffer.params().trackChanges;
2740 docstring oldkey;
2741 docstring oldlabel;
2743 // remove a bibitem in pos != 0
2744 // restore it later in pos 0 if necessary
2745 // (e.g. if a user inserts contents _before_ the item)
2746 // we're assuming there's only one of these, which there
2747 // should be.
2748 int erasedInsetPosition = -1;
2749 InsetList::iterator it = d->insetlist_.begin();
2750 InsetList::iterator end = d->insetlist_.end();
2751 for (; it != end; ++it)
2752 if (it->inset->lyxCode() == BIBITEM_CODE
2753 && it->pos > 0) {
2754 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2755 oldkey = olditem->getParam("key");
2756 oldlabel = olditem->getParam("label");
2757 erasedInsetPosition = it->pos;
2758 eraseChar(erasedInsetPosition, track_changes);
2759 break;
2762 // There was an InsetBibitem at the beginning, and we didn't
2763 // have to erase one.
2764 if (hasbibitem && erasedInsetPosition < 0)
2765 return 0;
2767 // There was an InsetBibitem at the beginning and we did have to
2768 // erase one. So we give its properties to the beginning inset.
2769 if (hasbibitem) {
2770 InsetBibitem * inset =
2771 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2772 if (!oldkey.empty())
2773 inset->setParam("key", oldkey);
2774 inset->setParam("label", oldlabel);
2775 return -erasedInsetPosition;
2778 // There was no inset at the beginning, so we need to create one with
2779 // the key and label of the one we erased.
2780 InsetBibitem * inset =
2781 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2782 // restore values of previously deleted item in this par.
2783 if (!oldkey.empty())
2784 inset->setParam("key", oldkey);
2785 inset->setParam("label", oldlabel);
2786 insertInset(0, static_cast<Inset *>(inset),
2787 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2789 return 1;
2793 void Paragraph::checkAuthors(AuthorList const & authorList)
2795 d->changes_.checkAuthors(authorList);
2799 bool Paragraph::isUnchanged(pos_type pos) const
2801 return lookupChange(pos).type == Change::UNCHANGED;
2805 bool Paragraph::isInserted(pos_type pos) const
2807 return lookupChange(pos).type == Change::INSERTED;
2811 bool Paragraph::isDeleted(pos_type pos) const
2813 return lookupChange(pos).type == Change::DELETED;
2817 InsetList const & Paragraph::insetList() const
2819 return d->insetlist_;
2823 void Paragraph::setBuffer(Buffer & b)
2825 d->insetlist_.setBuffer(b);
2829 Inset * Paragraph::releaseInset(pos_type pos)
2831 Inset * inset = d->insetlist_.release(pos);
2832 /// does not honour change tracking!
2833 eraseChar(pos, false);
2834 return inset;
2838 Inset * Paragraph::getInset(pos_type pos)
2840 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2841 ? d->insetlist_.get(pos) : 0;
2845 Inset const * Paragraph::getInset(pos_type pos) const
2847 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2848 ? d->insetlist_.get(pos) : 0;
2852 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2853 pos_type & right, TextCase action)
2855 // process sequences of modified characters; in change
2856 // tracking mode, this approach results in much better
2857 // usability than changing case on a char-by-char basis
2858 docstring changes;
2860 bool const trackChanges = bparams.trackChanges;
2862 bool capitalize = true;
2864 for (; pos < right; ++pos) {
2865 char_type oldChar = d->text_[pos];
2866 char_type newChar = oldChar;
2868 // ignore insets and don't play with deleted text!
2869 if (oldChar != META_INSET && !isDeleted(pos)) {
2870 switch (action) {
2871 case text_lowercase:
2872 newChar = lowercase(oldChar);
2873 break;
2874 case text_capitalization:
2875 if (capitalize) {
2876 newChar = uppercase(oldChar);
2877 capitalize = false;
2879 break;
2880 case text_uppercase:
2881 newChar = uppercase(oldChar);
2882 break;
2886 if (!isLetter(pos) || isDeleted(pos)) {
2887 // permit capitalization again
2888 capitalize = true;
2891 if (oldChar != newChar)
2892 changes += newChar;
2894 if (oldChar == newChar || pos == right - 1) {
2895 if (oldChar != newChar) {
2896 // step behind the changing area
2897 pos++;
2899 int erasePos = pos - changes.size();
2900 for (size_t i = 0; i < changes.size(); i++) {
2901 insertChar(pos, changes[i],
2902 getFontSettings(bparams,
2903 erasePos),
2904 trackChanges);
2905 if (!eraseChar(erasePos, trackChanges)) {
2906 ++erasePos;
2907 ++pos; // advance
2908 ++right; // expand selection
2911 changes.clear();
2917 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2918 pos_type pos, bool del) const
2920 int const strsize = str.length();
2921 int i = 0;
2922 pos_type const parsize = d->text_.size();
2923 for (i = 0; pos + i < parsize; ++i) {
2924 if (i >= strsize)
2925 break;
2926 if (cs && str[i] != d->text_[pos + i])
2927 break;
2928 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2929 break;
2930 if (!del && isDeleted(pos + i))
2931 break;
2934 if (i != strsize)
2935 return false;
2937 // if necessary, check whether string matches word
2938 if (mw) {
2939 if (pos > 0 && isLetter(pos - 1))
2940 return false;
2941 if (pos + strsize < parsize
2942 && isLetter(pos + strsize))
2943 return false;
2946 return true;
2950 char_type Paragraph::getChar(pos_type pos) const
2952 return d->text_[pos];
2956 pos_type Paragraph::size() const
2958 return d->text_.size();
2962 bool Paragraph::empty() const
2964 return d->text_.empty();
2968 bool Paragraph::isInset(pos_type pos) const
2970 return d->text_[pos] == META_INSET;
2974 bool Paragraph::isSeparator(pos_type pos) const
2976 //FIXME: Are we sure this can be the only separator?
2977 return d->text_[pos] == ' ';
2981 void Paragraph::deregisterWords()
2983 Private::Words::const_iterator it;
2984 WordList & wl = theWordList();
2985 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2986 wl.remove(*it);
2987 d->words_.clear();
2991 void Paragraph::locateWord(pos_type & from, pos_type & to,
2992 word_location const loc) const
2994 switch (loc) {
2995 case WHOLE_WORD_STRICT:
2996 if (from == 0 || from == size()
2997 || !isLetter(from)
2998 || !isLetter(from - 1)) {
2999 to = from;
3000 return;
3002 // no break here, we go to the next
3004 case WHOLE_WORD:
3005 // If we are already at the beginning of a word, do nothing
3006 if (!from || !isLetter(from - 1))
3007 break;
3008 // no break here, we go to the next
3010 case PREVIOUS_WORD:
3011 // always move the cursor to the beginning of previous word
3012 while (from && isLetter(from - 1))
3013 --from;
3014 break;
3015 case NEXT_WORD:
3016 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3017 break;
3018 case PARTIAL_WORD:
3019 // no need to move the 'from' cursor
3020 break;
3022 to = from;
3023 while (to < size() && isLetter(to))
3024 ++to;
3028 void Paragraph::collectWords()
3030 SpellChecker * speller = theSpellChecker();
3032 //lyxerr << "Words: ";
3033 pos_type n = size();
3034 for (pos_type pos = 0; pos < n; ++pos) {
3035 if (!isLetter(pos))
3036 continue;
3037 pos_type from = pos;
3038 locateWord(from, pos, WHOLE_WORD);
3039 if (!lyxrc.spellcheck_continuously && pos - from < 6)
3040 continue;
3042 docstring word = asString(from, pos, false);
3043 if (pos - from >= 6)
3044 d->words_.insert(word);
3046 if (!lyxrc.spellcheck_continuously || !speller)
3047 continue;
3049 string lang_code = lyxrc.spellchecker_use_alt_lang
3050 ? lyxrc.spellchecker_alt_lang
3051 : getFontSettings(d->inset_owner_->buffer().params(), from).language()->code();
3052 WordLangTuple wl(word, lang_code);
3053 SpellChecker::Result res = speller->check(wl);
3054 // ... just ignore any error that the spellchecker reports.
3055 if (!speller->error().empty())
3056 continue;
3057 bool const misspelled = res != SpellChecker::OK
3058 && res != SpellChecker::IGNORED_WORD;
3059 d->fontlist_.setMisspelled(from, pos, misspelled);
3061 //lyxerr << word << " ";
3063 //lyxerr << std::endl;
3067 void Paragraph::registerWords()
3069 Private::Words::const_iterator it;
3070 WordList & wl = theWordList();
3071 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3072 wl.insert(*it);
3076 void Paragraph::updateWords()
3078 deregisterWords();
3079 collectWords();
3080 registerWords();
3084 bool Paragraph::isMisspelled(pos_type pos) const
3086 SpellChecker * speller = theSpellChecker();
3087 pos_type from = pos;
3088 pos_type to = pos;
3089 locateWord(from, to, WHOLE_WORD);
3090 docstring word = asString(from, to, false);
3091 if (!speller)
3092 return false;
3094 string lang_code = lyxrc.spellchecker_use_alt_lang
3095 ? lyxrc.spellchecker_alt_lang
3096 : getFontSettings(d->inset_owner_->buffer().params(), from).language()->code();
3097 WordLangTuple wl(word, lang_code);
3098 SpellChecker::Result res = speller->check(wl);
3099 // ... just ignore any error that the spellchecker reports.
3100 if (!speller->error().empty())
3101 return false;
3103 bool const misspelled = res != SpellChecker::OK
3104 && res != SpellChecker::IGNORED_WORD;
3105 if (lyxrc.spellcheck_continuously)
3106 d->fontlist_.setMisspelled(from, pos, misspelled);
3107 return misspelled;
3111 } // namespace lyx