]> git.lyx.org Git - features.git/blob - src/Paragraph.cpp
Align \textgreek and \textcyr with font encoding
[features.git] / src / Paragraph.cpp
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.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Richard Heck (XHTML output)
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "Paragraph.h"
22
23 #include "LayoutFile.h"
24 #include "Buffer.h"
25 #include "BufferParams.h"
26 #include "Changes.h"
27 #include "Counters.h"
28 #include "BufferEncodings.h"
29 #include "InsetList.h"
30 #include "Language.h"
31 #include "LaTeXFeatures.h"
32 #include "Layout.h"
33 #include "Length.h"
34 #include "Font.h"
35 #include "FontList.h"
36 #include "LyXRC.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
42 #include "sgml.h"
43 #include "texstream.h"
44 #include "TextClass.h"
45 #include "TexRow.h"
46 #include "Text.h"
47 #include "WordLangTuple.h"
48 #include "WordList.h"
49
50 #include "frontends/alert.h"
51
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55 #include "insets/InsetText.h"
56
57 #include "mathed/InsetMathHull.h"
58
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/textutils.h"
66
67 #include <atomic>
68 #include <sstream>
69 #include <vector>
70
71 using namespace std;
72 using namespace lyx::support;
73
74 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
75 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
76 #define THREAD_LOCAL_STATIC static __thread
77 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
78 #define THREAD_LOCAL_STATIC static __declspec(thread)
79 #else
80 #define THREAD_LOCAL_STATIC thread_local static
81 #endif
82
83 namespace lyx {
84
85 namespace {
86
87 /// Inset identifier (above 0x10ffff, for ucs-4)
88 char_type const META_INSET = 0x200001;
89
90 } // namespace
91
92
93 /////////////////////////////////////////////////////////////////////
94 //
95 // SpellResultRange
96 //
97 /////////////////////////////////////////////////////////////////////
98
99 class SpellResultRange {
100 public:
101         SpellResultRange(FontSpan range, SpellChecker::Result result)
102         : range_(range), result_(result)
103         {}
104         ///
105         FontSpan const & range() const { return range_; }
106         ///
107         void range(FontSpan const & r) { range_ = r; }
108         ///
109         SpellChecker::Result result() const { return result_; }
110         ///
111         void result(SpellChecker::Result r) { result_ = r; }
112         ///
113         bool contains(pos_type pos) const { return range_.contains(pos); }
114         ///
115         bool covered(FontSpan const & r) const
116         {
117                 // 1. first of new range inside current range or
118                 // 2. last of new range inside current range or
119                 // 3. first of current range inside new range or
120                 // 4. last of current range inside new range
121                 //FIXME: is this the same as !range_.intersect(r).empty() ?
122                 return range_.contains(r.first) || range_.contains(r.last) ||
123                         r.contains(range_.first) || r.contains(range_.last);
124         }
125         ///
126         void shift(pos_type pos, int offset)
127         {
128                 if (range_.first > pos) {
129                         range_.first += offset;
130                         range_.last += offset;
131                 } else if (range_.last >= pos) {
132                         range_.last += offset;
133                 }
134         }
135 private:
136         FontSpan range_ ;
137         SpellChecker::Result result_ ;
138 };
139
140
141 /////////////////////////////////////////////////////////////////////
142 //
143 // SpellCheckerState
144 //
145 /////////////////////////////////////////////////////////////////////
146
147 class SpellCheckerState {
148 public:
149         SpellCheckerState()
150         {
151                 needs_refresh_ = true;
152                 current_change_number_ = 0;
153         }
154
155         void setRange(FontSpan const & fp, SpellChecker::Result state)
156         {
157                 Ranges result;
158                 RangesIterator et = ranges_.end();
159                 RangesIterator it = ranges_.begin();
160                 for (; it != et; ++it) {
161                         if (!it->covered(fp))
162                                 result.push_back(SpellResultRange(it->range(), it->result()));
163                         else if (state == SpellChecker::WORD_OK) {
164                                 // trim or split the current misspelled range
165                                 // store misspelled ranges only
166                                 FontSpan range = it->range();
167                                 if (fp.first > range.first) {
168                                         // misspelled area in front of WORD_OK
169                                         range.last = fp.first - 1;
170                                         result.push_back(SpellResultRange(range, it->result()));
171                                         range = it->range();
172                                 }
173                                 if (fp.last < range.last) {
174                                         // misspelled area after WORD_OK range
175                                         range.first = fp.last + 1;
176                                         result.push_back(SpellResultRange(range, it->result()));
177                                 }
178                         }
179                 }
180                 ranges_ = result;
181                 if (state != SpellChecker::WORD_OK)
182                         ranges_.push_back(SpellResultRange(fp, state));
183         }
184
185         void increasePosAfterPos(pos_type pos)
186         {
187                 correctRangesAfterPos(pos, 1);
188                 needsRefresh(pos);
189         }
190
191         void decreasePosAfterPos(pos_type pos)
192         {
193                 correctRangesAfterPos(pos, -1);
194                 needsRefresh(pos);
195         }
196
197         void refreshLast(pos_type pos)
198         {
199                 if (pos < refresh_.last)
200                         refresh_.last = pos;
201         }
202
203         SpellChecker::Result getState(pos_type pos) const
204         {
205                 SpellChecker::Result result = SpellChecker::WORD_OK;
206                 RangesIterator et = ranges_.end();
207                 RangesIterator it = ranges_.begin();
208                 for (; it != et; ++it) {
209                         if(it->contains(pos)) {
210                                 return it->result();
211                         }
212                 }
213                 return result;
214         }
215
216         FontSpan const & getRange(pos_type pos) const
217         {
218                 /// empty span to indicate mismatch
219                 static FontSpan empty_;
220                 RangesIterator et = ranges_.end();
221                 RangesIterator it = ranges_.begin();
222                 for (; it != et; ++it) {
223                         if(it->contains(pos)) {
224                                 return it->range();
225                         }
226                 }
227                 return empty_;
228         }
229
230         bool needsRefresh() const
231         {
232                 return needs_refresh_;
233         }
234
235         SpellChecker::ChangeNumber currentChangeNumber() const
236         {
237                 return current_change_number_;
238         }
239
240         void refreshRange(pos_type & first, pos_type & last) const
241         {
242                 first = refresh_.first;
243                 last = refresh_.last;
244         }
245
246         void needsRefresh(pos_type pos)
247         {
248                 if (needs_refresh_ && pos != -1) {
249                         if (pos < refresh_.first)
250                                 refresh_.first = pos;
251                         if (pos > refresh_.last)
252                                 refresh_.last = pos;
253                 } else if (pos != -1) {
254                         // init request check for neighbour positions too
255                         refresh_.first = pos > 0 ? pos - 1 : 0;
256                         // no need for special end of paragraph check
257                         refresh_.last = pos + 1;
258                 }
259                 needs_refresh_ = pos != -1;
260         }
261
262         void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
263         {
264                 needs_refresh_ = true;
265                 refresh_.first = 0;
266                 refresh_.last = -1;
267                 current_change_number_ = change_number;
268         }
269 private:
270         typedef vector<SpellResultRange> Ranges;
271         typedef Ranges::const_iterator RangesIterator;
272         Ranges ranges_;
273         /// the area of the paragraph with pending spell check
274         FontSpan refresh_;
275         bool needs_refresh_;
276         /// spell state cache version number
277         SpellChecker::ChangeNumber current_change_number_;
278
279
280         void correctRangesAfterPos(pos_type pos, int offset)
281         {
282                 RangesIterator et = ranges_.end();
283                 Ranges::iterator it = ranges_.begin();
284                 for (; it != et; ++it) {
285                         it->shift(pos, offset);
286                 }
287         }
288
289 };
290
291 /////////////////////////////////////////////////////////////////////
292 //
293 // Paragraph::Private
294 //
295 /////////////////////////////////////////////////////////////////////
296
297 class Paragraph::Private
298 {
299         // Enforce our own "copy" constructor
300         Private(Private const &) = delete;
301         Private & operator=(Private const &) = delete;
302         // Unique ID generator
303         static int make_id();
304 public:
305         ///
306         Private(Paragraph * owner, Layout const & layout);
307         /// "Copy constructor"
308         Private(Private const &, Paragraph * owner);
309         /// Copy constructor from \p beg  to \p end
310         Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
311
312         ///
313         void insertChar(pos_type pos, char_type c, Change const & change);
314
315         /// Output the surrogate pair formed by \p c and \p next to \p os.
316         /// \return the number of characters written.
317         int latexSurrogatePair(otexstream & os, char_type c, char_type next,
318                                OutputParams const &);
319
320         /// Output a space in appropriate formatting (or a surrogate pair
321         /// if the next character is a combining character).
322         /// \return whether a surrogate pair was output.
323         bool simpleTeXBlanks(OutputParams const &,
324                              otexstream &,
325                              pos_type i,
326                              unsigned int & column,
327                              Font const & font,
328                              Layout const & style);
329
330         /// Output consecutive unicode chars, belonging to the same script as
331         /// specified by the latex macro \p ltx, to \p os starting from \p i.
332         /// \return the number of characters written.
333         int writeScriptChars(otexstream & os, docstring const & ltx,
334                              Change const &, Encoding const &,
335                              std::string const, pos_type & i);
336
337         /// This could go to ParagraphParameters if we want to.
338         int startTeXParParams(BufferParams const &, otexstream &,
339                               OutputParams const &) const;
340
341         /// This could go to ParagraphParameters if we want to.
342         bool endTeXParParams(BufferParams const &, otexstream &,
343                              OutputParams const &) const;
344
345         ///
346         void latexInset(BufferParams const &,
347                                    otexstream &,
348                                    OutputParams &,
349                                    Font & running_font,
350                                    Font & basefont,
351                                    Font const & outerfont,
352                                    bool & open_font,
353                                    Change & running_change,
354                                    Layout const & style,
355                                    pos_type & i,
356                                    unsigned int & column);
357
358         ///
359         void latexSpecialChar(
360                                    otexstream & os,
361                                    BufferParams const & bparams,
362                                    OutputParams const & runparams,
363                                    Font const & running_font,
364                                    Change const & running_change,
365                                    Layout const & style,
366                                    pos_type & i,
367                                    pos_type end_pos,
368                                    unsigned int & column);
369
370         ///
371         bool latexSpecialT1(
372                 char_type const c,
373                 otexstream & os,
374                 pos_type i,
375                 unsigned int & column);
376         ///
377         bool latexSpecialTU(
378                 char_type const c,
379                 otexstream & os,
380                 pos_type i,
381                 unsigned int & column);
382         ///
383         bool latexSpecialT3(
384                 char_type const c,
385                 otexstream & os,
386                 pos_type i,
387                 unsigned int & column);
388
389         ///
390         void validate(LaTeXFeatures & features) const;
391
392         /// Checks if the paragraph contains only text and no inset or font change.
393         bool onlyText(Buffer const & buf, Font const & outerfont,
394                       pos_type initial) const;
395
396         /// a vector of speller skip positions
397         typedef vector<FontSpan> SkipPositions;
398         typedef SkipPositions::const_iterator SkipPositionsIterator;
399
400         void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
401
402         Language * getSpellLanguage(pos_type const from) const;
403
404         Language * locateSpellRange(pos_type & from, pos_type & to,
405                                     SkipPositions & skips) const;
406
407         bool hasSpellerChange() const
408         {
409                 SpellChecker::ChangeNumber speller_change_number = 0;
410                 if (theSpellChecker())
411                         speller_change_number = theSpellChecker()->changeNumber();
412                 return speller_change_number > speller_state_.currentChangeNumber();
413         }
414
415         bool ignoreWord(docstring const & word) const ;
416
417         void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
418         {
419                 pos_type textsize = owner_->size();
420                 // check for sane arguments
421                 if (to <= from || from >= textsize)
422                         return;
423                 FontSpan fp = FontSpan(from, to - 1);
424                 speller_state_.setRange(fp, state);
425         }
426
427         void requestSpellCheck(pos_type pos)
428         {
429                 if (pos == -1)
430                         speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
431                 else
432                         speller_state_.needsRefresh(pos);
433         }
434
435         void readySpellCheck()
436         {
437                 speller_state_.needsRefresh(-1);
438         }
439
440         bool needsSpellCheck() const
441         {
442                 return speller_state_.needsRefresh();
443         }
444
445         void rangeOfSpellCheck(pos_type & first, pos_type & last) const
446         {
447                 speller_state_.refreshRange(first, last);
448                 if (last == -1) {
449                         last = owner_->size();
450                         return;
451                 }
452                 pos_type endpos = last;
453                 owner_->locateWord(first, endpos, WHOLE_WORD);
454                 if (endpos < last) {
455                         endpos = last;
456                         owner_->locateWord(last, endpos, WHOLE_WORD);
457                 }
458                 last = endpos;
459         }
460
461         int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
462                             int & start) const
463         {
464                 int numskips = 0;
465                 while (it != et && it->first < start) {
466                         int skip = it->last - it->first + 1;
467                         start += skip;
468                         numskips += skip;
469                         ++it;
470                 }
471                 return numskips;
472         }
473
474         void markMisspelledWords(pos_type const & first, pos_type const & last,
475                                                          SpellChecker::Result result,
476                                                          docstring const & word,
477                                                          SkipPositions const & skips);
478
479         InsetCode ownerCode() const
480         {
481                 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
482         }
483
484         /// Which Paragraph owns us?
485         Paragraph * owner_;
486
487         /// In which Inset?
488         Inset const * inset_owner_;
489
490         ///
491         FontList fontlist_;
492
493         ///
494         int id_;
495
496         ///
497         ParagraphParameters params_;
498
499         /// for recording and looking up changes
500         Changes changes_;
501
502         ///
503         InsetList insetlist_;
504
505         /// end of label
506         pos_type begin_of_body_;
507
508         typedef docstring TextContainer;
509         ///
510         TextContainer text_;
511
512         typedef set<docstring> Words;
513         typedef map<string, Words> LangWordsMap;
514         ///
515         LangWordsMap words_;
516         ///
517         Layout const * layout_;
518         ///
519         SpellCheckerState speller_state_;
520 };
521
522
523 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
524         : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
525 {
526         text_.reserve(100);
527 }
528
529
530 //static
531 int Paragraph::Private::make_id()
532 {
533         // The id is unique per session across buffers because it is used in
534         // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
535         // outliner.
536         // (thread-safe)
537         static atomic_uint next_id(0);
538         return next_id++;
539 }
540
541
542 Paragraph::Private::Private(Private const & p, Paragraph * owner)
543         : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
544           id_(make_id()),
545           params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
546           begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
547           layout_(p.layout_)
548 {
549         requestSpellCheck(p.text_.size());
550 }
551
552
553 Paragraph::Private::Private(Private const & p, Paragraph * owner,
554         pos_type beg, pos_type end)
555         : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
556           params_(p.params_), changes_(p.changes_),
557           insetlist_(p.insetlist_, beg, end),
558           begin_of_body_(p.begin_of_body_), words_(p.words_),
559           layout_(p.layout_)
560 {
561         if (beg >= pos_type(p.text_.size()))
562                 return;
563         text_ = p.text_.substr(beg, end - beg);
564
565         FontList::const_iterator fcit = fontlist_.begin();
566         FontList::const_iterator fend = fontlist_.end();
567         for (; fcit != fend; ++fcit) {
568                 if (fcit->pos() < beg)
569                         continue;
570                 if (fcit->pos() >= end) {
571                         // Add last entry in the fontlist_.
572                         fontlist_.set(text_.size() - 1, fcit->font());
573                         break;
574                 }
575                 // Add a new entry in the fontlist_.
576                 fontlist_.set(fcit->pos() - beg, fcit->font());
577         }
578         requestSpellCheck(p.text_.size());
579 }
580
581
582 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
583                                 bool output_active, TocBackend & backend) const
584 {
585         d->changes_.addToToc(cdit, buf, output_active, backend);
586 }
587
588
589 void Paragraph::addChangesToBuffer(Buffer const & buf) const
590 {
591         d->changes_.updateBuffer(buf);
592 }
593
594
595 bool Paragraph::isChangeUpdateRequired() const
596 {
597         return d->changes_.isUpdateRequired();
598 }
599
600
601 bool Paragraph::isDeleted(pos_type start, pos_type end) const
602 {
603         LASSERT(start >= 0 && start <= size(), return false);
604         LASSERT(end > start && end <= size() + 1, return false);
605
606         return d->changes_.isDeleted(start, end);
607 }
608
609
610 bool Paragraph::isChanged(pos_type start, pos_type end) const
611 {
612         LASSERT(start >= 0 && start <= size(), return false);
613         LASSERT(end > start && end <= size() + 1, return false);
614
615         return d->changes_.isChanged(start, end);
616 }
617
618
619 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
620 {
621         // keep the logic here in sync with the logic of eraseChars()
622         if (!trackChanges)
623                 return true;
624
625         Change const & change = d->changes_.lookup(size());
626         return change.inserted() && change.currentAuthor();
627 }
628
629
630 void Paragraph::setChange(Change const & change)
631 {
632         // beware of the imaginary end-of-par character!
633         d->changes_.set(change, 0, size() + 1);
634
635         /*
636          * Propagate the change recursively - but not in case of DELETED!
637          *
638          * Imagine that your co-author makes changes in an existing inset. He
639          * sends your document to you and you come to the conclusion that the
640          * inset should go completely. If you erase it, LyX must not delete all
641          * text within the inset. Otherwise, the change tracked insertions of
642          * your co-author get lost and there is no way to restore them later.
643          *
644          * Conclusion: An inset's content should remain untouched if you delete it
645          */
646
647         if (!change.deleted()) {
648                 for (pos_type pos = 0; pos < size(); ++pos) {
649                         if (Inset * inset = getInset(pos))
650                                 inset->setChange(change);
651                 }
652         }
653 }
654
655
656 void Paragraph::setChange(pos_type pos, Change const & change)
657 {
658         LASSERT(pos >= 0 && pos <= size(), return);
659         d->changes_.set(change, pos);
660
661         // see comment in setChange(Change const &) above
662         if (!change.deleted() && pos < size())
663                         if (Inset * inset = getInset(pos))
664                                 inset->setChange(change);
665 }
666
667
668 Change const & Paragraph::lookupChange(pos_type pos) const
669 {
670         LBUFERR(pos >= 0 && pos <= size());
671         return d->changes_.lookup(pos);
672 }
673
674
675 void Paragraph::acceptChanges(pos_type start, pos_type end)
676 {
677         LASSERT(start >= 0 && start <= size(), return);
678         LASSERT(end > start && end <= size() + 1, return);
679
680         for (pos_type pos = start; pos < end; ++pos) {
681                 switch (lookupChange(pos).type) {
682                         case Change::UNCHANGED:
683                                 // accept changes in nested inset
684                                 if (Inset * inset = getInset(pos))
685                                         inset->acceptChanges();
686                                 break;
687
688                         case Change::INSERTED:
689                                 d->changes_.set(Change(Change::UNCHANGED), pos);
690                                 // also accept changes in nested inset
691                                 if (Inset * inset = getInset(pos))
692                                         inset->acceptChanges();
693                                 break;
694
695                         case Change::DELETED:
696                                 // Suppress access to non-existent
697                                 // "end-of-paragraph char"
698                                 if (pos < size()) {
699                                         eraseChar(pos, false);
700                                         --end;
701                                         --pos;
702                                 }
703                                 break;
704                 }
705
706         }
707 }
708
709
710 void Paragraph::rejectChanges(pos_type start, pos_type end)
711 {
712         LASSERT(start >= 0 && start <= size(), return);
713         LASSERT(end > start && end <= size() + 1, return);
714
715         for (pos_type pos = start; pos < end; ++pos) {
716                 switch (lookupChange(pos).type) {
717                         case Change::UNCHANGED:
718                                 // reject changes in nested inset
719                                 if (Inset * inset = getInset(pos))
720                                                 inset->rejectChanges();
721                                 break;
722
723                         case Change::INSERTED:
724                                 // Suppress access to non-existent
725                                 // "end-of-paragraph char"
726                                 if (pos < size()) {
727                                         eraseChar(pos, false);
728                                         --end;
729                                         --pos;
730                                 }
731                                 break;
732
733                         case Change::DELETED:
734                                 d->changes_.set(Change(Change::UNCHANGED), pos);
735
736                                 // Do NOT reject changes within a deleted inset!
737                                 // There may be insertions of a co-author inside of it!
738
739                                 break;
740                 }
741         }
742 }
743
744
745 void Paragraph::Private::insertChar(pos_type pos, char_type c,
746                 Change const & change)
747 {
748         LASSERT(pos >= 0 && pos <= int(text_.size()), return);
749
750         // track change
751         changes_.insert(change, pos);
752
753         // This is actually very common when parsing buffers (and
754         // maybe inserting ascii text)
755         if (pos == pos_type(text_.size())) {
756                 // when appending characters, no need to update tables
757                 text_.push_back(c);
758                 // but we want spell checking
759                 requestSpellCheck(pos);
760                 return;
761         }
762
763         text_.insert(text_.begin() + pos, c);
764
765         // Update the font table.
766         fontlist_.increasePosAfterPos(pos);
767
768         // Update the insets
769         insetlist_.increasePosAfterPos(pos);
770
771         // Update list of misspelled positions
772         speller_state_.increasePosAfterPos(pos);
773 }
774
775
776 bool Paragraph::insertInset(pos_type pos, Inset * inset,
777                                    Font const & font, Change const & change)
778 {
779         LASSERT(inset, return false);
780         LASSERT(pos >= 0 && pos <= size(), return false);
781
782         // Paragraph::insertInset() can be used in cut/copy/paste operation where
783         // d->inset_owner_ is not set yet.
784         if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
785                 return false;
786
787         d->insertChar(pos, META_INSET, change);
788         LASSERT(d->text_[pos] == META_INSET, return false);
789
790         // Add a new entry in the insetlist_.
791         d->insetlist_.insert(inset, pos);
792
793         // Some insets require run of spell checker
794         requestSpellCheck(pos);
795         setFont(pos, font);
796         return true;
797 }
798
799
800 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
801 {
802         LASSERT(pos >= 0 && pos <= size(), return false);
803
804         // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
805
806         if (trackChanges) {
807                 Change change = d->changes_.lookup(pos);
808
809                 // set the character to DELETED if
810                 //  a) it was previously unchanged or
811                 //  b) it was inserted by a co-author
812
813                 if (!change.changed() ||
814                       (change.inserted() && !change.currentAuthor())) {
815                         setChange(pos, Change(Change::DELETED));
816                         // request run of spell checker
817                         requestSpellCheck(pos);
818                         return false;
819                 }
820
821                 if (change.deleted())
822                         return false;
823         }
824
825         // Don't physically access the imaginary end-of-paragraph character.
826         // eraseChar() can only mark it as DELETED. A physical deletion of
827         // end-of-par must be handled externally.
828         if (pos == size()) {
829                 return false;
830         }
831
832         // track change
833         d->changes_.erase(pos);
834
835         // if it is an inset, delete the inset entry
836         if (d->text_[pos] == META_INSET)
837                 d->insetlist_.erase(pos);
838
839         d->text_.erase(d->text_.begin() + pos);
840
841         // Update the fontlist_
842         d->fontlist_.erase(pos);
843
844         // Update the insetlist_
845         d->insetlist_.decreasePosAfterPos(pos);
846
847         // Update list of misspelled positions
848         d->speller_state_.decreasePosAfterPos(pos);
849         d->speller_state_.refreshLast(size());
850
851         return true;
852 }
853
854
855 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
856 {
857         LASSERT(start >= 0 && start <= size(), return 0);
858         LASSERT(end >= start && end <= size() + 1, return 0);
859
860         pos_type i = start;
861         for (pos_type count = end - start; count; --count) {
862                 if (!eraseChar(i, trackChanges))
863                         ++i;
864         }
865         return end - i;
866 }
867
868
869 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
870                 char_type next, OutputParams const & runparams)
871 {
872         // Writing next here may circumvent a possible font change between
873         // c and next. Since next is only output if it forms a surrogate pair
874         // with c we can ignore this:
875         // A font change inside a surrogate pair does not make sense and is
876         // hopefully impossible to input.
877         // FIXME: change tracking
878         // Is this correct WRT change tracking?
879         Encoding const & encoding = *(runparams.encoding);
880         docstring latex1 = encoding.latexChar(next).first;
881         if (runparams.inIPA) {
882                 string const tipashortcut = Encodings::TIPAShortcut(next);
883                 if (!tipashortcut.empty()) {
884                         latex1 = from_ascii(tipashortcut);
885                 }
886         }
887         docstring latex2 = encoding.latexChar(c).first;
888
889         docstring::size_type const brace1 = latex2.find_first_of(from_ascii("{"));
890         docstring::size_type const brace2 = latex2.find_last_of(from_ascii("}"));
891         string script = to_ascii(latex2.substr(1, brace1 - 1));
892         int pos = 0;
893         int length = brace2;
894         string fontenc;
895         if (runparams.local_font)
896                 fontenc = runparams.local_font->language()->fontenc();
897         else
898                 fontenc = runparams.main_fontenc;
899         if ((script == "textgreek" && fontenc == "LGR")
900             ||(script == "textcyr" && (fontenc == "T2A" || fontenc == "T2B"
901                                        || fontenc == "T2C" || fontenc == "X2"))) {
902                 // Correct font encoding is being used, so we can avoid \text[greek|cyr].
903                 pos = brace1 + 1;
904                 length -= pos;
905                 latex2 = latex2.substr(pos, length);
906         }
907
908         if (docstring(1, next) == latex1) {
909                 // the encoding supports the combination
910                 os << latex2 << latex1;
911                 return latex1.length() + latex2.length();
912         } else if (runparams.local_font &&
913                    runparams.local_font->language()->lang() == "polutonikogreek") {
914                 // polutonikogreek only works without the brackets
915                 os << latex1 << latex2;
916                 return latex1.length() + latex2.length();
917         } else
918                 os << latex1 << '{' << latex2 << '}';
919         return latex1.length() + latex2.length() + 2;
920 }
921
922
923 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
924                                        otexstream & os,
925                                        pos_type i,
926                                        unsigned int & column,
927                                        Font const & font,
928                                        Layout const & style)
929 {
930         if (style.pass_thru || runparams.pass_thru)
931                 return false;
932
933         if (i + 1 < int(text_.size())) {
934                 char_type next = text_[i + 1];
935                 if (Encodings::isCombiningChar(next)) {
936                         // This space has an accent, so we must always output it.
937                         column += latexSurrogatePair(os, ' ', next, runparams) - 1;
938                         return true;
939                 }
940         }
941
942         if (runparams.linelen > 0
943             && column > runparams.linelen
944             && i
945             && text_[i - 1] != ' '
946             && (i + 1 < int(text_.size()))
947             // same in FreeSpacing mode
948             && !owner_->isFreeSpacing()
949             // In typewriter mode, we want to avoid
950             // ! . ? : at the end of a line
951             && !(font.fontInfo().family() == TYPEWRITER_FAMILY
952                  && (text_[i - 1] == '.'
953                      || text_[i - 1] == '?'
954                      || text_[i - 1] == ':'
955                      || text_[i - 1] == '!'))) {
956                 os << '\n';
957                 os.texrow().start(owner_->id(), i + 1);
958                 column = 0;
959         } else if (style.free_spacing) {
960                 os << '~';
961         } else {
962                 os << ' ';
963         }
964         return false;
965 }
966
967
968 int Paragraph::Private::writeScriptChars(otexstream & os,
969                                          docstring const & ltx,
970                                          Change const & runningChange,
971                                          Encoding const & encoding,
972                                          string const fontenc,
973                                          pos_type & i)
974 {
975         // FIXME: modifying i here is not very nice...
976
977         // We only arrive here when character text_[i] could not be translated
978         // into the current latex encoding (or its latex translation has been forced,)
979         // and it belongs to a known script.
980         // Parameter ltx contains the latex translation of text_[i] as specified
981         // in the unicodesymbols file and is something like "\textXXX{<spec>}".
982         // The latex macro name "textXXX" specifies the script to which text_[i]
983         // belongs and we use it in order to check whether characters from the
984         // same script immediately follow, such that we can collect them in a
985         // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
986         // for the first char but only "<spec>" for all subsequent chars.
987         docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
988         docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
989         string script = to_ascii(ltx.substr(1, brace1 - 1));
990         int pos = 0;
991         int length = brace2;
992         bool closing_brace = true;
993         if ((script == "textgreek" && fontenc == "LGR")
994             ||(script == "textcyr" && (fontenc == "T2A" || fontenc == "T2B"
995                                        || fontenc == "T2C" || fontenc == "X2"))) {
996                 // Correct font encoding is being used, so we can avoid \text[greek|cyr].
997                 pos = brace1 + 1;
998                 length -= pos;
999                 closing_brace = false;
1000         }
1001         os << ltx.substr(pos, length);
1002         int size = text_.size();
1003         while (i + 1 < size) {
1004                 char_type const next = text_[i + 1];
1005                 // Stop here if next character belongs to another script
1006                 // or there is a change in change tracking status.
1007                 if (!Encodings::isKnownScriptChar(next, script) ||
1008                     runningChange != owner_->lookupChange(i + 1))
1009                         break;
1010                 Font prev_font;
1011                 bool found = false;
1012                 FontList::const_iterator cit = fontlist_.begin();
1013                 FontList::const_iterator end = fontlist_.end();
1014                 for (; cit != end; ++cit) {
1015                         if (cit->pos() >= i && !found) {
1016                                 prev_font = cit->font();
1017                                 found = true;
1018                         }
1019                         if (cit->pos() >= i + 1)
1020                                 break;
1021                 }
1022                 // Stop here if there is a font attribute or encoding change.
1023                 if (found && cit != end && prev_font != cit->font())
1024                         break;
1025                 docstring const latex = encoding.latexChar(next).first;
1026                 docstring::size_type const b1 =
1027                                         latex.find_first_of(from_ascii("{"));
1028                 docstring::size_type const b2 =
1029                                         latex.find_last_of(from_ascii("}"));
1030                 int const len = b2 - b1 - 1;
1031                 os << latex.substr(b1 + 1, len);
1032                 length += len;
1033                 ++i;
1034         }
1035         if (closing_brace) {
1036                 os << '}';
1037                 ++length;
1038         }
1039         return length;
1040 }
1041
1042
1043 void Paragraph::Private::latexInset(BufferParams const & bparams,
1044                                     otexstream & os,
1045                                     OutputParams & runparams,
1046                                     Font & running_font,
1047                                     Font & basefont,
1048                                     Font const & outerfont,
1049                                     bool & open_font,
1050                                     Change & running_change,
1051                                     Layout const & style,
1052                                     pos_type & i,
1053                                     unsigned int & column)
1054 {
1055         Inset * inset = owner_->getInset(i);
1056         LBUFERR(inset);
1057
1058         if (style.pass_thru) {
1059                 odocstringstream ods;
1060                 inset->plaintext(ods, runparams);
1061                 os << ods.str();
1062                 return;
1063         }
1064
1065         // FIXME: move this to InsetNewline::latex
1066         if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1067                 // newlines are handled differently here than
1068                 // the default in simpleTeXSpecialChars().
1069                 if (!style.newline_allowed) {
1070                         os << '\n';
1071                 } else {
1072                         if (open_font) {
1073                                 bool needPar = false;
1074                                 column += running_font.latexWriteEndChanges(
1075                                         os, bparams, runparams,
1076                                         basefont, basefont, needPar);
1077                                 open_font = false;
1078                         }
1079
1080                         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1081                                 os << '~';
1082
1083                         basefont = owner_->getLayoutFont(bparams, outerfont);
1084                         running_font = basefont;
1085
1086                         if (runparams.moving_arg)
1087                                 os << "\\protect ";
1088
1089                 }
1090                 os.texrow().start(owner_->id(), i + 1);
1091                 column = 0;
1092         }
1093
1094         if (owner_->isDeleted(i)) {
1095                 if( ++runparams.inDeletedInset == 1)
1096                         runparams.changeOfDeletedInset = owner_->lookupChange(i);
1097         }
1098
1099         if (inset->canTrackChanges()) {
1100                 column += Changes::latexMarkChange(os, bparams, running_change,
1101                         Change(Change::UNCHANGED), runparams);
1102                 running_change = Change(Change::UNCHANGED);
1103         }
1104
1105         bool close = false;
1106         odocstream::pos_type const len = os.os().tellp();
1107
1108         if (inset->forceLTR()
1109             && !runparams.use_polyglossia
1110             && running_font.isRightToLeft()
1111             // ERT is an exception, it should be output with no
1112             // decorations at all
1113             && inset->lyxCode() != ERT_CODE) {
1114                 if (running_font.language()->lang() == "farsi")
1115                         os << "\\beginL" << termcmd;
1116                 else
1117                         os << "\\L{";
1118                 close = true;
1119         }
1120
1121         // FIXME: Bug: we can have an empty font change here!
1122         // if there has just been a font change, we are going to close it
1123         // right now, which means stupid latex code like \textsf{}. AFAIK,
1124         // this does not harm dvi output. A minor bug, thus (JMarc)
1125
1126         // Some insets cannot be inside a font change command.
1127         // However, even such insets *can* be placed in \L or \R
1128         // or their equivalents (for RTL language switches), so we don't
1129         // close the language in those cases.
1130         // ArabTeX, though, cannot handle this special behavior, it seems.
1131         bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1132                 || running_font.language()->lang() == "arabic_arabtex";
1133         if (open_font && !inset->inheritFont()) {
1134                 bool needPar = false;
1135                 bool closeLanguage = arabtex
1136                         || basefont.isRightToLeft() == running_font.isRightToLeft();
1137                 unsigned int count = running_font.latexWriteEndChanges(os,
1138                                         bparams, runparams, basefont, basefont,
1139                                         needPar, closeLanguage);
1140                 column += count;
1141                 // if any font properties were closed, update the running_font,
1142                 // making sure, however, to leave the language as it was
1143                 if (count > 0) {
1144                         // FIXME: probably a better way to keep track of the old
1145                         // language, than copying the entire font?
1146                         Font const copy_font(running_font);
1147                         basefont = owner_->getLayoutFont(bparams, outerfont);
1148                         running_font = basefont;
1149                         if (!closeLanguage)
1150                                 running_font.setLanguage(copy_font.language());
1151                         // leave font open if language is still open
1152                         open_font = (running_font.language() == basefont.language());
1153                         if (closeLanguage)
1154                                 runparams.local_font = &basefont;
1155                 }
1156         }
1157
1158         size_t const previous_row_count = os.texrow().rows();
1159
1160         try {
1161                 runparams.lastid = id_;
1162                 runparams.lastpos = i;
1163                 inset->latex(os, runparams);
1164         } catch (EncodingException & e) {
1165                 // add location information and throw again.
1166                 e.par_id = id_;
1167                 e.pos = i;
1168                 throw(e);
1169         }
1170
1171         if (close) {
1172                 if (running_font.language()->lang() == "farsi")
1173                                 os << "\\endL" << termcmd;
1174                         else
1175                                 os << '}';
1176         }
1177
1178         if (os.texrow().rows() > previous_row_count) {
1179                 os.texrow().start(owner_->id(), i + 1);
1180                 column = 0;
1181         } else {
1182                 column += (unsigned int)(os.os().tellp() - len);
1183         }
1184
1185         if (owner_->isDeleted(i))
1186                 --runparams.inDeletedInset;
1187 }
1188
1189
1190 void Paragraph::Private::latexSpecialChar(otexstream & os,
1191                                           BufferParams const & bparams,
1192                                           OutputParams const & runparams,
1193                                           Font const & running_font,
1194                                           Change const & running_change,
1195                                           Layout const & style,
1196                                           pos_type & i,
1197                                           pos_type end_pos,
1198                                           unsigned int & column)
1199 {
1200         // With polyglossia, brackets and stuff need not be reversed
1201         // in RTL scripts (see bug #8251)
1202         char_type const c = (runparams.use_polyglossia) ?
1203                 owner_->getUChar(bparams, i) : text_[i];
1204
1205         if (style.pass_thru || runparams.pass_thru
1206             || contains(style.pass_thru_chars, c)
1207             || contains(runparams.pass_thru_chars, c)) {
1208                 if (c != '\0') {
1209                         Encoding const * const enc = runparams.encoding;
1210                         if (enc && !enc->encodable(c))
1211                                 throw EncodingException(c);
1212                         os.put(c);
1213                 }
1214                 return;
1215         }
1216
1217         // TIPA uses its own T3 encoding
1218         if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1219                 return;
1220         // If T1 font encoding is used, use the special
1221         // characters it provides.
1222         // NOTE: Some languages reset the font encoding internally to a
1223         //       non-standard font encoding. If we are using such a language,
1224         //       we do not output special T1 chars.
1225         if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1226             && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1227             && latexSpecialT1(c, os, i, column))
1228                 return;
1229         // NOTE: XeTeX and LuaTeX use EU1/2 (pre 2017) or TU (as of 2017) encoding
1230         else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1231                  && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1232                      return;
1233
1234         // Otherwise, we use what LaTeX provides us.
1235         switch (c) {
1236         case '\\':
1237                 os << "\\textbackslash" << termcmd;
1238                 column += 15;
1239                 break;
1240         case '<':
1241                 os << "\\textless" << termcmd;
1242                 column += 10;
1243                 break;
1244         case '>':
1245                 os << "\\textgreater" << termcmd;
1246                 column += 13;
1247                 break;
1248         case '|':
1249                 os << "\\textbar" << termcmd;
1250                 column += 9;
1251                 break;
1252         case '-':
1253                 os << '-';
1254                 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1255                     (end_pos == -1 || i + 1 < end_pos) &&
1256                     text_[i+1] == '-') {
1257                         // Prevent "--" becoming an en dash and "---" an em dash.
1258                         // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1259                         os << "{}";
1260                         column += 2;
1261                 }
1262                 break;
1263         case '\"':
1264                 os << "\\textquotedbl" << termcmd;
1265                 column += 14;
1266                 break;
1267
1268         case '$': case '&':
1269         case '%': case '#': case '{':
1270         case '}': case '_':
1271                 os << '\\';
1272                 os.put(c);
1273                 column += 1;
1274                 break;
1275
1276         case '~':
1277                 os << "\\textasciitilde" << termcmd;
1278                 column += 16;
1279                 break;
1280
1281         case '^':
1282                 os << "\\textasciicircum" << termcmd;
1283                 column += 17;
1284                 break;
1285
1286         case '*':
1287         case '[':
1288         case ']':
1289                 // avoid being mistaken for optional arguments
1290                 os << '{';
1291                 os.put(c);
1292                 os << '}';
1293                 column += 2;
1294                 break;
1295
1296         case ' ':
1297                 // Blanks are printed before font switching.
1298                 // Sure? I am not! (try nice-latex)
1299                 // I am sure it's correct. LyX might be smarter
1300                 // in the future, but for now, nothing wrong is
1301                 // written. (Asger)
1302                 break;
1303
1304         case 0x2013:
1305         case 0x2014:
1306                 // XeTeX's dash behaviour is determined via a global setting
1307                 if (bparams.use_dash_ligatures
1308                     && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1309                     && !runparams.inIPA
1310                         // TODO #10961: && not in inset Flex Code
1311                         // TODO #10961: && not in layout LyXCode
1312                     && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1313                         if (c == 0x2013) {
1314                                 // en-dash
1315                                 os << "--";
1316                                 column +=2;
1317                         } else {
1318                                 // em-dash
1319                                 os << "---";
1320                                 column +=3;
1321                         }
1322                         break;
1323                 }
1324                 // fall through
1325         default:
1326                 if (c == '\0')
1327                         return;
1328
1329                 Encoding const & encoding = *(runparams.encoding);
1330                 char_type next = '\0';
1331                 if (i + 1 < int(text_.size())) {
1332                         next = text_[i + 1];
1333                         if (Encodings::isCombiningChar(next)) {
1334                                 column += latexSurrogatePair(os, c, next, runparams) - 1;
1335                                 ++i;
1336                                 break;
1337                         }
1338                 }
1339                 string script;
1340                 pair<docstring, bool> latex = encoding.latexChar(c);
1341                 docstring nextlatex;
1342                 bool nexttipas = false;
1343                 string nexttipashortcut;
1344                 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1345                         nextlatex = encoding.latexChar(next).first;
1346                         if (runparams.inIPA) {
1347                                 nexttipashortcut = Encodings::TIPAShortcut(next);
1348                                 nexttipas = !nexttipashortcut.empty();
1349                         }
1350                 }
1351                 bool tipas = false;
1352                 if (runparams.inIPA) {
1353                         string const tipashortcut = Encodings::TIPAShortcut(c);
1354                         if (!tipashortcut.empty()) {
1355                                 latex.first = from_ascii(tipashortcut);
1356                                 latex.second = false;
1357                                 tipas = true;
1358                         }
1359                 }
1360                 string fontenc;
1361                 if (running_font.language()->lang() == runparams.document_language)
1362                         fontenc = runparams.main_fontenc;
1363                 else
1364                         fontenc = running_font.language()->fontenc();
1365                 if (Encodings::isKnownScriptChar(c, script)
1366                     && prefixIs(latex.first, from_ascii("\\" + script)))
1367                         column += writeScriptChars(os, latex.first,
1368                                                    running_change, encoding,
1369                                                    fontenc, i) - 1;
1370                 else if (latex.second
1371                          && ((!prefixIs(nextlatex, '\\')
1372                                && !prefixIs(nextlatex, '{')
1373                                && !prefixIs(nextlatex, '}'))
1374                              || (nexttipas
1375                                  && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1376                          && !tipas) {
1377                         // Prevent eating of a following
1378                         // space or command corruption by
1379                         // following characters
1380                         if (next == ' ' || next == '\0') {
1381                                 column += latex.first.length() + 1;
1382                                 os << latex.first << "{}";
1383                         } else {
1384                                 column += latex.first.length();
1385                                 os << latex.first << " ";
1386                         }
1387                 } else {
1388                         column += latex.first.length() - 1;
1389                         os << latex.first;
1390                 }
1391                 break;
1392         }
1393 }
1394
1395
1396 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1397         pos_type i, unsigned int & column)
1398 {
1399         switch (c) {
1400         case '>':
1401         case '<':
1402                 os.put(c);
1403                 // In T1 encoding, these characters exist
1404                 // but we should avoid ligatures
1405                 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1406                         return true;
1407                 os << "\\textcompwordmark" << termcmd;
1408                 column += 19;
1409                 return true;
1410         case '|':
1411                 os.put(c);
1412                 return true;
1413         case '\"':
1414                 // soul.sty breaks with \char`\"
1415                 os << "\\textquotedbl" << termcmd;
1416                 column += 14;
1417                 return true;
1418         default:
1419                 return false;
1420         }
1421 }
1422
1423
1424 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1425         pos_type i, unsigned int & column)
1426 {
1427         // TU encoding is currently on par with T1.
1428         return latexSpecialT1(c, os, i, column);
1429 }
1430
1431
1432 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1433         pos_type /*i*/, unsigned int & column)
1434 {
1435         switch (c) {
1436         case '*':
1437         case '[':
1438         case ']':
1439         case '\"':
1440                 os.put(c);
1441                 return true;
1442         case '|':
1443                 os << "\\textvertline" << termcmd;
1444                 column += 14;
1445                 return true;
1446         default:
1447                 return false;
1448         }
1449 }
1450
1451
1452 void Paragraph::Private::validate(LaTeXFeatures & features) const
1453 {
1454         if (layout_->inpreamble && inset_owner_) {
1455                 // FIXME: Using a string stream here circumvents the encoding
1456                 // switching machinery of odocstream. Therefore the
1457                 // output is wrong if this paragraph contains content
1458                 // that needs to switch encoding.
1459                 Buffer const & buf = inset_owner_->buffer();
1460                 otexstringstream os;
1461                 os << layout_->preamble();
1462                 size_t const length = os.length();
1463                 TeXOnePar(buf, buf.text(), buf.getParFromID(owner_->id()).pit(), os,
1464                           features.runparams(), string(), 0, -1, true);
1465                 if (os.length() > length)
1466                         features.addPreambleSnippet(os.release(), true);
1467         }
1468
1469         if (features.runparams().flavor == OutputParams::HTML
1470             && layout_->htmltitle()) {
1471                 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1472         }
1473
1474         // check the params.
1475         if (!params_.spacing().isDefault())
1476                 features.require("setspace");
1477
1478         // then the layouts
1479         features.useLayout(layout_->name());
1480
1481         // then the fonts
1482         fontlist_.validate(features);
1483
1484         // then the indentation
1485         if (!params_.leftIndent().zero())
1486                 features.require("ParagraphLeftIndent");
1487
1488         // then the insets
1489         InsetList::const_iterator icit = insetlist_.begin();
1490         InsetList::const_iterator iend = insetlist_.end();
1491         for (; icit != iend; ++icit) {
1492                 if (icit->inset) {
1493                         features.inDeletedInset(owner_->isDeleted(icit->pos));
1494                         if (icit->inset->lyxCode() == FOOT_CODE) {
1495                                 // FIXME: an item inset would make things much easier.
1496                                 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1497                                      || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1498                                          && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1499                                     && (icit->pos < begin_of_body_
1500                                         || (icit->pos == begin_of_body_
1501                                             && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1502                                         features.saveNoteEnv("description");
1503                         }
1504                         icit->inset->validate(features);
1505                         features.inDeletedInset(false);
1506                         if (layout_->needprotect &&
1507                             icit->inset->lyxCode() == FOOT_CODE)
1508                                 features.require("NeedLyXFootnoteCode");
1509                 }
1510         }
1511
1512         // then the contents
1513         BufferParams const bp = features.runparams().is_child
1514                 ? features.buffer().masterParams() : features.buffer().params();
1515         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1516                 char_type c = text_[i];
1517                 if (c == 0x0022) {
1518                         if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1519                                 features.require("textquotedblp");
1520                         else if (bp.main_font_encoding() != "T1"
1521                                  || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1522                                 features.require("textquotedbl");
1523                 }
1524                 if (!bp.use_dash_ligatures
1525                     && (c == 0x2013 || c == 0x2014)
1526                     && bp.useNonTeXFonts
1527                     && features.runparams().flavor == OutputParams::XETEX)
1528                         // XeTeX's dash behaviour is determined via a global setting
1529                         features.require("xetexdashbreakstate");
1530                 BufferEncodings::validate(c, features);
1531         }
1532 }
1533
1534 /////////////////////////////////////////////////////////////////////
1535 //
1536 // Paragraph
1537 //
1538 /////////////////////////////////////////////////////////////////////
1539
1540 namespace {
1541         Layout const emptyParagraphLayout;
1542 }
1543
1544 Paragraph::Paragraph()
1545         : d(new Paragraph::Private(this, emptyParagraphLayout))
1546 {
1547         itemdepth = 0;
1548         d->params_.clear();
1549 }
1550
1551
1552 Paragraph::Paragraph(Paragraph const & par)
1553         : itemdepth(par.itemdepth),
1554         d(new Paragraph::Private(*par.d, this))
1555 {
1556         registerWords();
1557 }
1558
1559
1560 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1561         : itemdepth(par.itemdepth),
1562         d(new Paragraph::Private(*par.d, this, beg, end))
1563 {
1564         registerWords();
1565 }
1566
1567
1568 Paragraph & Paragraph::operator=(Paragraph const & par)
1569 {
1570         // needed as we will destroy the private part before copying it
1571         if (&par != this) {
1572                 itemdepth = par.itemdepth;
1573
1574                 deregisterWords();
1575                 delete d;
1576                 d = new Private(*par.d, this);
1577                 registerWords();
1578         }
1579         return *this;
1580 }
1581
1582
1583 Paragraph::~Paragraph()
1584 {
1585         deregisterWords();
1586         delete d;
1587 }
1588
1589
1590 namespace {
1591
1592 // this shall be called just before every "os << ..." action.
1593 void flushString(ostream & os, docstring & s)
1594 {
1595         os << to_utf8(s);
1596         s.erase();
1597 }
1598
1599 } // namespace
1600
1601
1602 void Paragraph::write(ostream & os, BufferParams const & bparams,
1603         depth_type & dth) const
1604 {
1605         // The beginning or end of a deeper (i.e. nested) area?
1606         if (dth != d->params_.depth()) {
1607                 if (d->params_.depth() > dth) {
1608                         while (d->params_.depth() > dth) {
1609                                 os << "\n\\begin_deeper";
1610                                 ++dth;
1611                         }
1612                 } else {
1613                         while (d->params_.depth() < dth) {
1614                                 os << "\n\\end_deeper";
1615                                 --dth;
1616                         }
1617                 }
1618         }
1619
1620         // First write the layout
1621         os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1622
1623         d->params_.write(os);
1624
1625         Font font1(inherit_font, bparams.language);
1626
1627         Change running_change = Change(Change::UNCHANGED);
1628
1629         // this string is used as a buffer to avoid repetitive calls
1630         // to to_utf8(), which turn out to be expensive (JMarc)
1631         docstring write_buffer;
1632
1633         int column = 0;
1634         for (pos_type i = 0; i <= size(); ++i) {
1635
1636                 Change const & change = lookupChange(i);
1637                 if (change != running_change)
1638                         flushString(os, write_buffer);
1639                 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1640                 running_change = change;
1641
1642                 if (i == size())
1643                         break;
1644
1645                 // Write font changes
1646                 Font font2 = getFontSettings(bparams, i);
1647                 if (font2 != font1) {
1648                         flushString(os, write_buffer);
1649                         font2.lyxWriteChanges(font1, os);
1650                         column = 0;
1651                         font1 = font2;
1652                 }
1653
1654                 char_type const c = d->text_[i];
1655                 switch (c) {
1656                 case META_INSET:
1657                         if (Inset const * inset = getInset(i)) {
1658                                 flushString(os, write_buffer);
1659                                 if (inset->directWrite()) {
1660                                         // international char, let it write
1661                                         // code directly so it's shorter in
1662                                         // the file
1663                                         inset->write(os);
1664                                 } else {
1665                                         if (i)
1666                                                 os << '\n';
1667                                         os << "\\begin_inset ";
1668                                         inset->write(os);
1669                                         os << "\n\\end_inset\n\n";
1670                                         column = 0;
1671                                 }
1672                                 // FIXME This can be removed again once the mystery
1673                                 // crash has been resolved.
1674                                 os << flush;
1675                         }
1676                         break;
1677                 case '\\':
1678                         flushString(os, write_buffer);
1679                         os << "\n\\backslash\n";
1680                         column = 0;
1681                         break;
1682                 case '.':
1683                         flushString(os, write_buffer);
1684                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1685                                 os << ".\n";
1686                                 column = 0;
1687                         } else
1688                                 os << '.';
1689                         break;
1690                 default:
1691                         if ((column > 70 && c == ' ')
1692                             || column > 79) {
1693                                 flushString(os, write_buffer);
1694                                 os << '\n';
1695                                 column = 0;
1696                         }
1697                         // this check is to amend a bug. LyX sometimes
1698                         // inserts '\0' this could cause problems.
1699                         if (c != '\0')
1700                                 write_buffer.push_back(c);
1701                         else
1702                                 LYXERR0("NUL char in structure.");
1703                         ++column;
1704                         break;
1705                 }
1706         }
1707
1708         flushString(os, write_buffer);
1709         os << "\n\\end_layout\n";
1710         // FIXME This can be removed again once the mystery
1711         // crash has been resolved.
1712         os << flush;
1713 }
1714
1715
1716 void Paragraph::validate(LaTeXFeatures & features) const
1717 {
1718         d->validate(features);
1719         if (needsCProtection())
1720                 features.require("cprotect");
1721 }
1722
1723
1724 void Paragraph::insert(pos_type start, docstring const & str,
1725                        Font const & font, Change const & change)
1726 {
1727         for (size_t i = 0, n = str.size(); i != n ; ++i)
1728                 insertChar(start + i, str[i], font, change);
1729 }
1730
1731
1732 void Paragraph::appendChar(char_type c, Font const & font,
1733                 Change const & change)
1734 {
1735         // track change
1736         d->changes_.insert(change, d->text_.size());
1737         // when appending characters, no need to update tables
1738         d->text_.push_back(c);
1739         setFont(d->text_.size() - 1, font);
1740         d->requestSpellCheck(d->text_.size() - 1);
1741 }
1742
1743
1744 void Paragraph::appendString(docstring const & s, Font const & font,
1745                 Change const & change)
1746 {
1747         pos_type end = s.size();
1748         size_t oldsize = d->text_.size();
1749         size_t newsize = oldsize + end;
1750         size_t capacity = d->text_.capacity();
1751         if (newsize >= capacity)
1752                 d->text_.reserve(max(capacity + 100, newsize));
1753
1754         // when appending characters, no need to update tables
1755         d->text_.append(s);
1756
1757         // FIXME: Optimize this!
1758         for (size_t i = oldsize; i != newsize; ++i) {
1759                 // track change
1760                 d->changes_.insert(change, i);
1761                 d->requestSpellCheck(i);
1762         }
1763         d->fontlist_.set(oldsize, font);
1764         d->fontlist_.set(newsize - 1, font);
1765 }
1766
1767
1768 void Paragraph::insertChar(pos_type pos, char_type c,
1769                            bool trackChanges)
1770 {
1771         d->insertChar(pos, c, Change(trackChanges ?
1772                            Change::INSERTED : Change::UNCHANGED));
1773 }
1774
1775
1776 void Paragraph::insertChar(pos_type pos, char_type c,
1777                            Font const & font, bool trackChanges)
1778 {
1779         d->insertChar(pos, c, Change(trackChanges ?
1780                            Change::INSERTED : Change::UNCHANGED));
1781         setFont(pos, font);
1782 }
1783
1784
1785 void Paragraph::insertChar(pos_type pos, char_type c,
1786                            Font const & font, Change const & change)
1787 {
1788         d->insertChar(pos, c, change);
1789         setFont(pos, font);
1790 }
1791
1792
1793 void Paragraph::resetFonts(Font const & font)
1794 {
1795         d->fontlist_.clear();
1796         d->fontlist_.set(0, font);
1797         d->fontlist_.set(d->text_.size() - 1, font);
1798 }
1799
1800 // Gets uninstantiated font setting at position.
1801 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1802                                          pos_type pos) const
1803 {
1804         if (pos > size()) {
1805                 LYXERR0("pos: " << pos << " size: " << size());
1806                 LBUFERR(false);
1807         }
1808
1809         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1810         if (cit != d->fontlist_.end())
1811                 return cit->font();
1812
1813         if (pos == size() && !empty())
1814                 return getFontSettings(bparams, pos - 1);
1815
1816         // Optimisation: avoid a full font instantiation if there is no
1817         // language change from previous call.
1818         static Font previous_font;
1819         static Language const * previous_lang = 0;
1820         Language const * lang = getParLanguage(bparams);
1821         if (lang != previous_lang) {
1822                 previous_lang = lang;
1823                 previous_font = Font(inherit_font, lang);
1824         }
1825         return previous_font;
1826 }
1827
1828
1829 FontSpan Paragraph::fontSpan(pos_type pos) const
1830 {
1831         LBUFERR(pos <= size());
1832
1833         if (pos == size())
1834                 return FontSpan(pos, pos);
1835
1836         pos_type start = 0;
1837         FontList::const_iterator cit = d->fontlist_.begin();
1838         FontList::const_iterator end = d->fontlist_.end();
1839         for (; cit != end; ++cit) {
1840                 if (cit->pos() >= pos) {
1841                         if (pos >= beginOfBody())
1842                                 return FontSpan(max(start, beginOfBody()),
1843                                                 cit->pos());
1844                         else
1845                                 return FontSpan(start,
1846                                                 min(beginOfBody() - 1,
1847                                                          cit->pos()));
1848                 }
1849                 start = cit->pos() + 1;
1850         }
1851
1852         // This should not happen, but if so, we take no chances.
1853         LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1854         LASSERT(false, return FontSpan(pos, pos));
1855 }
1856
1857
1858 // Gets uninstantiated font setting at position 0
1859 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1860 {
1861         if (!empty() && !d->fontlist_.empty())
1862                 return d->fontlist_.begin()->font();
1863
1864         // Optimisation: avoid a full font instantiation if there is no
1865         // language change from previous call.
1866         static Font previous_font;
1867         static Language const * previous_lang = 0;
1868         if (bparams.language != previous_lang) {
1869                 previous_lang = bparams.language;
1870                 previous_font = Font(inherit_font, bparams.language);
1871         }
1872
1873         return previous_font;
1874 }
1875
1876
1877 // Gets the fully instantiated font at a given position in a paragraph
1878 // This is basically the same function as Text::GetFont() in text2.cpp.
1879 // The difference is that this one is used for generating the LaTeX file,
1880 // and thus cosmetic "improvements" are disallowed: This has to deliver
1881 // the true picture of the buffer. (Asger)
1882 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1883                                  Font const & outerfont) const
1884 {
1885         LBUFERR(pos >= 0);
1886
1887         Font font = getFontSettings(bparams, pos);
1888
1889         pos_type const body_pos = beginOfBody();
1890         FontInfo & fi = font.fontInfo();
1891         if (pos < body_pos)
1892                 fi.realize(d->layout_->labelfont);
1893         else
1894                 fi.realize(d->layout_->font);
1895
1896         fi.realize(outerfont.fontInfo());
1897         fi.realize(bparams.getFont().fontInfo());
1898
1899         return font;
1900 }
1901
1902
1903 Font const Paragraph::getLabelFont
1904         (BufferParams const & bparams, Font const & outerfont) const
1905 {
1906         FontInfo tmpfont = d->layout_->labelfont;
1907         tmpfont.realize(outerfont.fontInfo());
1908         tmpfont.realize(bparams.getFont().fontInfo());
1909         return Font(tmpfont, getParLanguage(bparams));
1910 }
1911
1912
1913 Font const Paragraph::getLayoutFont
1914         (BufferParams const & bparams, Font const & outerfont) const
1915 {
1916         FontInfo tmpfont = d->layout_->font;
1917         tmpfont.realize(outerfont.fontInfo());
1918         tmpfont.realize(bparams.getFont().fontInfo());
1919         return Font(tmpfont, getParLanguage(bparams));
1920 }
1921
1922
1923 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1924 {
1925         char_type c = d->text_[pos];
1926         if (!getFontSettings(bparams, pos).isRightToLeft())
1927                 return c;
1928
1929         // FIXME: The arabic special casing is due to the difference of arabic
1930         // round brackets input introduced in r18599. Check if this should be
1931         // unified with Hebrew or at least if all bracket types should be
1932         // handled the same (file format change in either case).
1933         string const & lang = getFontSettings(bparams, pos).language()->lang();
1934         bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1935                 || lang == "farsi";
1936         char_type uc = c;
1937         switch (c) {
1938         case '(':
1939                 uc = arabic ? c : ')';
1940                 break;
1941         case ')':
1942                 uc = arabic ? c : '(';
1943                 break;
1944         case '[':
1945                 uc = ']';
1946                 break;
1947         case ']':
1948                 uc = '[';
1949                 break;
1950         case '{':
1951                 uc = '}';
1952                 break;
1953         case '}':
1954                 uc = '{';
1955                 break;
1956         case '<':
1957                 uc = '>';
1958                 break;
1959         case '>':
1960                 uc = '<';
1961                 break;
1962         }
1963
1964         return uc;
1965 }
1966
1967
1968 void Paragraph::setFont(pos_type pos, Font const & font)
1969 {
1970         LASSERT(pos <= size(), return);
1971
1972         // First, reduce font against layout/label font
1973         // Update: The setCharFont() routine in text2.cpp already
1974         // reduces font, so we don't need to do that here. (Asger)
1975
1976         d->fontlist_.set(pos, font);
1977 }
1978
1979
1980 void Paragraph::makeSameLayout(Paragraph const & par)
1981 {
1982         d->layout_ = par.d->layout_;
1983         d->params_ = par.d->params_;
1984 }
1985
1986
1987 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1988 {
1989         if (isFreeSpacing())
1990                 return false;
1991
1992         int pos = 0;
1993         int count = 0;
1994
1995         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1996                 if (eraseChar(pos, trackChanges))
1997                         ++count;
1998                 else
1999                         ++pos;
2000         }
2001
2002         return count > 0 || pos > 0;
2003 }
2004
2005
2006 bool Paragraph::hasSameLayout(Paragraph const & par) const
2007 {
2008         return par.d->layout_ == d->layout_
2009                 && d->params_.sameLayout(par.d->params_);
2010 }
2011
2012
2013 depth_type Paragraph::getDepth() const
2014 {
2015         return d->params_.depth();
2016 }
2017
2018
2019 depth_type Paragraph::getMaxDepthAfter() const
2020 {
2021         if (d->layout_->isEnvironment())
2022                 return d->params_.depth() + 1;
2023         else
2024                 return d->params_.depth();
2025 }
2026
2027
2028 LyXAlignment Paragraph::getAlign() const
2029 {
2030         if (d->params_.align() == LYX_ALIGN_LAYOUT)
2031                 return d->layout_->align;
2032         else
2033                 return d->params_.align();
2034 }
2035
2036
2037 docstring const & Paragraph::labelString() const
2038 {
2039         return d->params_.labelString();
2040 }
2041
2042
2043 // the next two functions are for the manual labels
2044 docstring const Paragraph::getLabelWidthString() const
2045 {
2046         if (d->layout_->margintype == MARGIN_MANUAL
2047             || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2048                 return d->params_.labelWidthString();
2049         else
2050                 return _("Senseless with this layout!");
2051 }
2052
2053
2054 void Paragraph::setLabelWidthString(docstring const & s)
2055 {
2056         d->params_.labelWidthString(s);
2057 }
2058
2059
2060 docstring Paragraph::expandLabel(Layout const & layout,
2061                 BufferParams const & bparams) const
2062 {
2063         return expandParagraphLabel(layout, bparams, true);
2064 }
2065
2066
2067 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2068                 BufferParams const & bparams) const
2069 {
2070         return expandParagraphLabel(layout, bparams, false);
2071 }
2072
2073
2074 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2075                 BufferParams const & bparams, bool process_appendix) const
2076 {
2077         DocumentClass const & tclass = bparams.documentClass();
2078         string const & lang = getParLanguage(bparams)->code();
2079         bool const in_appendix = process_appendix && d->params_.appendix();
2080         docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2081
2082         if (fmt.empty() && !layout.counter.empty())
2083                 return tclass.counters().theCounter(layout.counter, lang);
2084
2085         // handle 'inherited level parts' in 'fmt',
2086         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
2087         size_t const i = fmt.find('@', 0);
2088         if (i != docstring::npos) {
2089                 size_t const j = fmt.find('@', i + 1);
2090                 if (j != docstring::npos) {
2091                         docstring parent(fmt, i + 1, j - i - 1);
2092                         docstring label = from_ascii("??");
2093                         if (tclass.hasLayout(parent))
2094                                 label = expandParagraphLabel(tclass[parent], bparams,
2095                                                       process_appendix);
2096                         fmt = docstring(fmt, 0, i) + label
2097                                 + docstring(fmt, j + 1, docstring::npos);
2098                 }
2099         }
2100
2101         return tclass.counters().counterLabel(fmt, lang);
2102 }
2103
2104
2105 void Paragraph::applyLayout(Layout const & new_layout)
2106 {
2107         d->layout_ = &new_layout;
2108         LyXAlignment const oldAlign = d->params_.align();
2109
2110         if (!(oldAlign & d->layout_->alignpossible)) {
2111                 frontend::Alert::warning(_("Alignment not permitted"),
2112                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
2113                 d->params_.align(LYX_ALIGN_LAYOUT);
2114         }
2115 }
2116
2117
2118 pos_type Paragraph::beginOfBody() const
2119 {
2120         return d->begin_of_body_;
2121 }
2122
2123
2124 void Paragraph::setBeginOfBody()
2125 {
2126         if (d->layout_->labeltype != LABEL_MANUAL) {
2127                 d->begin_of_body_ = 0;
2128                 return;
2129         }
2130
2131         // Unroll the first two cycles of the loop
2132         // and remember the previous character to
2133         // remove unnecessary getChar() calls
2134         pos_type i = 0;
2135         pos_type end = size();
2136         if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2137                 ++i;
2138                 if (i < end) {
2139                         char_type previous_char = d->text_[i];
2140                         if (!(isNewline(i) || isEnvSeparator(i))) {
2141                                 ++i;
2142                                 while (i < end && previous_char != ' ') {
2143                                         char_type temp = d->text_[i];
2144                                         if (isNewline(i) || isEnvSeparator(i))
2145                                                 break;
2146                                         ++i;
2147                                         previous_char = temp;
2148                                 }
2149                         }
2150                 }
2151         }
2152
2153         d->begin_of_body_ = i;
2154 }
2155
2156
2157 bool Paragraph::allowParagraphCustomization() const
2158 {
2159         return inInset().allowParagraphCustomization();
2160 }
2161
2162
2163 bool Paragraph::usePlainLayout() const
2164 {
2165         return inInset().usePlainLayout();
2166 }
2167
2168
2169 bool Paragraph::isPassThru() const
2170 {
2171         return inInset().isPassThru() || d->layout_->pass_thru;
2172 }
2173
2174 namespace {
2175
2176 // paragraphs inside floats need different alignment tags to avoid
2177 // unwanted space
2178
2179 bool noTrivlistCentering(InsetCode code)
2180 {
2181         return code == FLOAT_CODE
2182                || code == WRAP_CODE
2183                || code == CELL_CODE;
2184 }
2185
2186
2187 string correction(string const & orig)
2188 {
2189         if (orig == "flushleft")
2190                 return "raggedright";
2191         if (orig == "flushright")
2192                 return "raggedleft";
2193         if (orig == "center")
2194                 return "centering";
2195         return orig;
2196 }
2197
2198
2199 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2200         InsetCode code, bool const lastpar, int & col)
2201 {
2202         string macro = suffix + "{";
2203         if (noTrivlistCentering(code)) {
2204                 if (lastpar) {
2205                         // the last paragraph in non-trivlist-aligned
2206                         // context is special (to avoid unwanted whitespace)
2207                         if (suffix == "\\begin") {
2208                                 macro = "\\" + correction(env) + "{}";
2209                                 os << from_ascii(macro);
2210                                 col += macro.size();
2211                                 return true;
2212                         }
2213                         return false;
2214                 }
2215                 macro += correction(env);
2216         } else
2217                 macro += env;
2218         macro += "}";
2219         if (suffix == "\\par\\end") {
2220                 os << breakln;
2221                 col = 0;
2222         }
2223         os << from_ascii(macro);
2224         col += macro.size();
2225         if (suffix == "\\begin") {
2226                 os << breakln;
2227                 col = 0;
2228         }
2229         return true;
2230 }
2231
2232 } // namespace
2233
2234
2235 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2236                         otexstream & os, OutputParams const & runparams) const
2237 {
2238         int column = 0;
2239
2240         bool canindent =
2241                 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2242                         (layout_->toggle_indent != ITOGGLE_NEVER) :
2243                         (layout_->toggle_indent == ITOGGLE_ALWAYS);
2244
2245         if (canindent && params_.noindent() && !layout_->pass_thru) {
2246                 os << "\\noindent ";
2247                 column += 10;
2248         }
2249
2250         LyXAlignment const curAlign = params_.align();
2251
2252         if (curAlign == layout_->align)
2253                 return column;
2254
2255         switch (curAlign) {
2256         case LYX_ALIGN_NONE:
2257         case LYX_ALIGN_BLOCK:
2258         case LYX_ALIGN_LAYOUT:
2259         case LYX_ALIGN_SPECIAL:
2260         case LYX_ALIGN_DECIMAL:
2261                 break;
2262         case LYX_ALIGN_LEFT:
2263         case LYX_ALIGN_RIGHT:
2264         case LYX_ALIGN_CENTER:
2265                 if (runparams.moving_arg) {
2266                         os << "\\protect";
2267                         column += 8;
2268                 }
2269                 break;
2270         }
2271
2272         string const begin_tag = "\\begin";
2273         InsetCode code = ownerCode();
2274         bool const lastpar = runparams.isLastPar;
2275
2276         switch (curAlign) {
2277         case LYX_ALIGN_NONE:
2278         case LYX_ALIGN_BLOCK:
2279         case LYX_ALIGN_LAYOUT:
2280         case LYX_ALIGN_SPECIAL:
2281         case LYX_ALIGN_DECIMAL:
2282                 break;
2283         case LYX_ALIGN_LEFT: {
2284                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2285                         corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2286                 else
2287                         corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2288                 break;
2289         } case LYX_ALIGN_RIGHT: {
2290                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2291                         corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2292                 else
2293                         corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2294                 break;
2295         } case LYX_ALIGN_CENTER: {
2296                 corrected_env(os, begin_tag, "center", code, lastpar, column);
2297                 break;
2298         }
2299         }
2300
2301         return column;
2302 }
2303
2304
2305 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2306                         otexstream & os, OutputParams const & runparams) const
2307 {
2308         LyXAlignment const curAlign = params_.align();
2309
2310         if (curAlign == layout_->align)
2311                 return false;
2312
2313         switch (curAlign) {
2314         case LYX_ALIGN_NONE:
2315         case LYX_ALIGN_BLOCK:
2316         case LYX_ALIGN_LAYOUT:
2317         case LYX_ALIGN_SPECIAL:
2318         case LYX_ALIGN_DECIMAL:
2319                 break;
2320         case LYX_ALIGN_LEFT:
2321         case LYX_ALIGN_RIGHT:
2322         case LYX_ALIGN_CENTER:
2323                 if (runparams.moving_arg)
2324                         os << "\\protect";
2325                 break;
2326         }
2327
2328         bool output = false;
2329         int col = 0;
2330         string const end_tag = "\\par\\end";
2331         InsetCode code = ownerCode();
2332         bool const lastpar = runparams.isLastPar;
2333
2334         switch (curAlign) {
2335         case LYX_ALIGN_NONE:
2336         case LYX_ALIGN_BLOCK:
2337         case LYX_ALIGN_LAYOUT:
2338         case LYX_ALIGN_SPECIAL:
2339         case LYX_ALIGN_DECIMAL:
2340                 break;
2341         case LYX_ALIGN_LEFT: {
2342                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2343                         output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2344                 else
2345                         output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2346                 break;
2347         } case LYX_ALIGN_RIGHT: {
2348                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2349                         output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2350                 else
2351                         output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2352                 break;
2353         } case LYX_ALIGN_CENTER: {
2354                 corrected_env(os, end_tag, "center", code, lastpar, col);
2355                 break;
2356         }
2357         }
2358
2359         return output || lastpar;
2360 }
2361
2362
2363 // This one spits out the text of the paragraph
2364 void Paragraph::latex(BufferParams const & bparams,
2365         Font const & outerfont,
2366         otexstream & os,
2367         OutputParams const & runparams,
2368         int start_pos, int end_pos, bool force) const
2369 {
2370         LYXERR(Debug::LATEX, "Paragraph::latex...     " << this);
2371
2372         // FIXME This check should not be needed. Perhaps issue an
2373         // error if it triggers.
2374         Layout const & style = inInset().forcePlainLayout() ?
2375                 bparams.documentClass().plainLayout() : *d->layout_;
2376
2377         if (!force && style.inpreamble)
2378                 return;
2379
2380         bool const allowcust = allowParagraphCustomization();
2381
2382         // Current base font for all inherited font changes, without any
2383         // change caused by an individual character, except for the language:
2384         // It is set to the language of the first character.
2385         // As long as we are in the label, this font is the base font of the
2386         // label. Before the first body character it is set to the base font
2387         // of the body.
2388         Font basefont;
2389
2390         // Maybe we have to create a optional argument.
2391         pos_type body_pos = beginOfBody();
2392         unsigned int column = 0;
2393
2394         if (body_pos > 0) {
2395                 // the optional argument is kept in curly brackets in
2396                 // case it contains a ']'
2397                 // This is not strictly needed, but if this is changed it
2398                 // would be a file format change, and tex2lyx would need
2399                 // to be adjusted, since it unconditionally removes the
2400                 // braces when it parses \item.
2401                 os << "[{";
2402                 column += 2;
2403                 basefont = getLabelFont(bparams, outerfont);
2404         } else {
2405                 basefont = getLayoutFont(bparams, outerfont);
2406         }
2407
2408         // Which font is currently active?
2409         Font running_font(basefont);
2410         // Do we have an open font change?
2411         bool open_font = false;
2412
2413         Change runningChange = Change(Change::UNCHANGED);
2414
2415         Encoding const * const prev_encoding = runparams.encoding;
2416
2417         os.texrow().start(id(), 0);
2418
2419         // if the paragraph is empty, the loop will not be entered at all
2420         if (empty()) {
2421                 // For InTitle commands, we have already opened a group
2422                 // in output_latex::TeXOnePar.
2423                 if (style.isCommand() && !style.intitle) {
2424                         os << '{';
2425                         ++column;
2426                 }
2427                 if (!style.leftdelim().empty()) {
2428                         os << style.leftdelim();
2429                         column += style.leftdelim().size();
2430                 }
2431                 if (allowcust)
2432                         column += d->startTeXParParams(bparams, os, runparams);
2433         }
2434
2435         // Whether a \par can be issued for insets typeset inline with text.
2436         // Yes if greater than 0. This has to be static.
2437         THREAD_LOCAL_STATIC int parInline = 0;
2438
2439         for (pos_type i = 0; i < size(); ++i) {
2440                 // First char in paragraph or after label?
2441                 if (i == body_pos) {
2442                         if (body_pos > 0) {
2443                                 if (open_font) {
2444                                         bool needPar = false;
2445                                         column += running_font.latexWriteEndChanges(
2446                                                 os, bparams, runparams,
2447                                                 basefont, basefont, needPar);
2448                                         open_font = false;
2449                                 }
2450                                 basefont = getLayoutFont(bparams, outerfont);
2451                                 running_font = basefont;
2452
2453                                 column += Changes::latexMarkChange(os, bparams,
2454                                                 runningChange, Change(Change::UNCHANGED),
2455                                                 runparams);
2456                                 runningChange = Change(Change::UNCHANGED);
2457
2458                                 os << "}] ";
2459                                 column +=3;
2460                         }
2461                         // For InTitle commands, we have already opened a group
2462                         // in output_latex::TeXOnePar.
2463                         if (style.isCommand() && !style.intitle) {
2464                                 os << '{';
2465                                 ++column;
2466                         }
2467
2468                         if (!style.leftdelim().empty()) {
2469                                 os << style.leftdelim();
2470                                 column += style.leftdelim().size();
2471                         }
2472
2473                         if (allowcust)
2474                                 column += d->startTeXParParams(bparams, os,
2475                                                             runparams);
2476                 }
2477
2478                 runparams.wasDisplayMath = runparams.inDisplayMath;
2479                 runparams.inDisplayMath = false;
2480                 bool deleted_display_math = false;
2481                 Change const & change = runparams.inDeletedInset
2482                         ? runparams.changeOfDeletedInset : lookupChange(i);
2483
2484                 // Check whether a display math inset follows
2485                 if (d->text_[i] == META_INSET
2486                     && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2487                         InsetMath const * im = getInset(i)->asInsetMath();
2488                         if (im && im->asHullInset()
2489                             && im->asHullInset()->outerDisplay()) {
2490                                 runparams.inDisplayMath = true;
2491                                 // runparams.inDeletedInset will be set by
2492                                 // latexInset later, but we need this info
2493                                 // before it is called. On the other hand, we
2494                                 // cannot set it here because it is a counter.
2495                                 deleted_display_math = isDeleted(i);
2496                         }
2497                         if (bparams.output_changes && deleted_display_math
2498                             && runningChange == change
2499                             && change.type == Change::DELETED
2500                             && !os.afterParbreak()) {
2501                                 // A display math in the same paragraph follows.
2502                                 // We have to close and then reopen \lyxdeleted,
2503                                 // otherwise the math will be shifted up.
2504                                 OutputParams rp = runparams;
2505                                 if (open_font) {
2506                                         bool needPar = false;
2507                                         column += running_font.latexWriteEndChanges(
2508                                                 os, bparams, rp, basefont,
2509                                                 basefont, needPar);
2510                                         open_font = false;
2511                                 }
2512                                 basefont = getLayoutFont(bparams, outerfont);
2513                                 running_font = basefont;
2514                                 column += Changes::latexMarkChange(os, bparams,
2515                                         Change(Change::INSERTED), change, rp);
2516                         }
2517                 }
2518
2519                 if (bparams.output_changes && runningChange != change) {
2520                         if (open_font) {
2521                                 bool needPar = false;
2522                                 column += running_font.latexWriteEndChanges(
2523                                                 os, bparams, runparams,
2524                                                 basefont, basefont, needPar);
2525                                 open_font = false;
2526                         }
2527                         basefont = getLayoutFont(bparams, outerfont);
2528                         running_font = basefont;
2529                         column += Changes::latexMarkChange(os, bparams, runningChange,
2530                                                            change, runparams);
2531                         runningChange = change;
2532                 }
2533
2534                 // do not output text which is marked deleted
2535                 // if change tracking output is disabled
2536                 if (!bparams.output_changes && change.deleted()) {
2537                         continue;
2538                 }
2539
2540                 ++column;
2541
2542                 // Fully instantiated font
2543                 Font const current_font = getFont(bparams, i, outerfont);
2544
2545                 Font const last_font = running_font;
2546
2547                 // Do we need to close the previous font?
2548                 if (open_font &&
2549                     (current_font != running_font ||
2550                      current_font.language() != running_font.language()))
2551                 {
2552                         bool needPar = false;
2553                         column += running_font.latexWriteEndChanges(
2554                                     os, bparams, runparams, basefont,
2555                                     (i == body_pos-1) ? basefont : current_font,
2556                                     needPar);
2557                         running_font = basefont;
2558                         open_font = false;
2559                 }
2560
2561                 string const running_lang = runparams.use_polyglossia ?
2562                         running_font.language()->polyglossia() : running_font.language()->babel();
2563                 // close babel's font environment before opening CJK.
2564                 string const lang_end_command = runparams.use_polyglossia ?
2565                         "\\end{$$lang}" : lyxrc.language_command_end;
2566                 bool const using_begin_end = runparams.use_polyglossia ||
2567                                                 !lang_end_command.empty();
2568                 if (!running_lang.empty() &&
2569                     (!using_begin_end || running_lang == openLanguageName()) &&
2570                     current_font.language()->encoding()->package() == Encoding::CJK) {
2571                                 string end_tag = subst(lang_end_command,
2572                                                         "$$lang",
2573                                                         running_lang);
2574                                 os << from_ascii(end_tag);
2575                                 column += end_tag.length();
2576                                 if (using_begin_end)
2577                                         popLanguageName();
2578                 }
2579
2580                 // Switch file encoding if necessary (and allowed)
2581                 if (!runparams.pass_thru && !style.pass_thru &&
2582                     runparams.encoding->package() != Encoding::none &&
2583                     current_font.language()->encoding()->package() != Encoding::none) {
2584                         pair<bool, int> const enc_switch =
2585                                 switchEncoding(os.os(), bparams, runparams,
2586                                         *(current_font.language()->encoding()));
2587                         if (enc_switch.first) {
2588                                 column += enc_switch.second;
2589                                 runparams.encoding = current_font.language()->encoding();
2590                         }
2591                 }
2592
2593                 char_type const c = d->text_[i];
2594
2595                 // A display math inset inside an ulem command will be output
2596                 // as a box of width \linewidth, so we have to either disable
2597                 // indentation if the inset starts a paragraph, or start a new
2598                 // line to accommodate such box. This has to be done before
2599                 // writing any font changing commands.
2600                 if (runparams.inDisplayMath && !deleted_display_math
2601                     && runparams.inulemcmd) {
2602                         if (os.afterParbreak())
2603                                 os << "\\noindent";
2604                         else
2605                                 os << "\\\\\n";
2606                 }
2607
2608                 // Do we need to change font?
2609                 if ((current_font != running_font ||
2610                      current_font.language() != running_font.language()) &&
2611                         i != body_pos - 1)
2612                 {
2613                         odocstringstream ods;
2614                         column += current_font.latexWriteStartChanges(ods, bparams,
2615                                                               runparams, basefont,
2616                                                               last_font);
2617                         // Check again for display math in ulem commands as a
2618                         // font change may also occur just before a math inset.
2619                         if (runparams.inDisplayMath && !deleted_display_math
2620                             && runparams.inulemcmd) {
2621                                 if (os.afterParbreak())
2622                                         os << "\\noindent";
2623                                 else
2624                                         os << "\\\\\n";
2625                         }
2626                         running_font = current_font;
2627                         open_font = true;
2628                         docstring fontchange = ods.str();
2629                         // check whether the fontchange ends with a \\textcolor
2630                         // modifier and the text starts with a space (bug 4473)
2631                         docstring const last_modifier = rsplit(fontchange, '\\');
2632                         if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2633                                 os << fontchange << from_ascii("{}");
2634                         // check if the fontchange ends with a trailing blank
2635                         // (like "\small " (see bug 3382)
2636                         else if (suffixIs(fontchange, ' ') && c == ' ')
2637                                 os << fontchange.substr(0, fontchange.size() - 1)
2638                                    << from_ascii("{}");
2639                         else
2640                                 os << fontchange;
2641                 }
2642
2643                 // FIXME: think about end_pos implementation...
2644                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2645                         // FIXME: integrate this case in latexSpecialChar
2646                         // Do not print the separation of the optional argument
2647                         // if style.pass_thru is false. This works because
2648                         // latexSpecialChar ignores spaces if
2649                         // style.pass_thru is false.
2650                         if (i != body_pos - 1) {
2651                                 if (d->simpleTeXBlanks(runparams, os,
2652                                                 i, column, current_font, style)) {
2653                                         // A surrogate pair was output. We
2654                                         // must not call latexSpecialChar
2655                                         // in this iteration, since it would output
2656                                         // the combining character again.
2657                                         ++i;
2658                                         continue;
2659                                 }
2660                         }
2661                 }
2662
2663                 OutputParams rp = runparams;
2664                 rp.free_spacing = style.free_spacing;
2665                 rp.local_font = &current_font;
2666                 rp.intitle = style.intitle;
2667
2668                 // Two major modes:  LaTeX or plain
2669                 // Handle here those cases common to both modes
2670                 // and then split to handle the two modes separately.
2671                 if (c == META_INSET) {
2672                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2673                                 // Greyedout notes and, in general, all insets
2674                                 // with InsetLayout::isDisplay() == false,
2675                                 // are typeset inline with the text. So, we
2676                                 // can add a \par to the last paragraph of
2677                                 // such insets only if nothing else follows.
2678                                 bool incremented = false;
2679                                 Inset const * inset = getInset(i);
2680                                 InsetText const * textinset = inset
2681                                                         ? inset->asInsetText()
2682                                                         : 0;
2683                                 if (i + 1 == size() && textinset
2684                                     && !inset->getLayout().isDisplay()) {
2685                                         ParagraphList const & pars =
2686                                                 textinset->text().paragraphs();
2687                                         pit_type const pit = pars.size() - 1;
2688                                         Font const lastfont =
2689                                                 pit < 0 || pars[pit].empty()
2690                                                 ? pars[pit].getLayoutFont(
2691                                                                 bparams,
2692                                                                 outerfont)
2693                                                 : pars[pit].getFont(bparams,
2694                                                         pars[pit].size() - 1,
2695                                                         outerfont);
2696                                         if (lastfont.fontInfo().size() !=
2697                                             basefont.fontInfo().size()) {
2698                                                 ++parInline;
2699                                                 incremented = true;
2700                                         }
2701                                 }
2702                                 d->latexInset(bparams, os, rp, running_font,
2703                                                 basefont, outerfont, open_font,
2704                                                 runningChange, style, i, column);
2705                                 if (incremented)
2706                                         --parInline;
2707                         }
2708                 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2709                         try {
2710                                 d->latexSpecialChar(os, bparams, rp,
2711                                                     running_font, runningChange,
2712                                                     style, i, end_pos, column);
2713                         } catch (EncodingException & e) {
2714                                 if (runparams.dryrun) {
2715                                         os << "<" << _("LyX Warning: ")
2716                                            << _("uncodable character") << " '";
2717                                         os.put(c);
2718                                         os << "'>";
2719                                 } else {
2720                                         // add location information and throw again.
2721                                         e.par_id = id();
2722                                         e.pos = i;
2723                                         throw(e);
2724                                 }
2725                         }
2726                 }
2727
2728                 // Set the encoding to that returned from latexSpecialChar (see
2729                 // comment for encoding member in OutputParams.h)
2730                 runparams.encoding = rp.encoding;
2731
2732                 // Also carry on the info on a closed ulem command for insets
2733                 // such as Note that do not produce any output, so that no
2734                 // command is ever executed but its opening was recorded.
2735                 runparams.inulemcmd = rp.inulemcmd;
2736         }
2737
2738         // If we have an open font definition, we have to close it
2739         if (open_font) {
2740                 // Make sure that \\par is done with the font of the last
2741                 // character if this has another size as the default.
2742                 // This is necessary because LaTeX (and LyX on the screen)
2743                 // calculates the space between the baselines according
2744                 // to this font. (Matthias)
2745                 //
2746                 // We must not change the font for the last paragraph
2747                 // of non-multipar insets, tabular cells or commands,
2748                 // since this produces unwanted whitespace.
2749
2750                 Font const font = empty()
2751                         ? getLayoutFont(bparams, outerfont)
2752                         : getFont(bparams, size() - 1, outerfont);
2753
2754                 InsetText const * textinset = inInset().asInsetText();
2755
2756                 bool const maintext = textinset
2757                         ? textinset->text().isMainText()
2758                         : false;
2759
2760                 size_t const numpars = textinset
2761                         ? textinset->text().paragraphs().size()
2762                         : 0;
2763
2764                 bool needPar = false;
2765
2766                 if (style.resfont.size() != font.fontInfo().size()
2767                     && (!runparams.isLastPar || maintext
2768                         || (numpars > 1 && d->ownerCode() != CELL_CODE
2769                             && (inInset().getLayout().isDisplay()
2770                                 || parInline)))
2771                     && !style.isCommand()) {
2772                         needPar = true;
2773                 }
2774 #ifdef FIXED_LANGUAGE_END_DETECTION
2775                 if (next_) {
2776                         running_font.latexWriteEndChanges(os, bparams,
2777                                         runparams, basefont,
2778                                         next_->getFont(bparams, 0, outerfont),
2779                                                        needPar);
2780                 } else {
2781                         running_font.latexWriteEndChanges(os, bparams,
2782                                         runparams, basefont, basefont, needPar);
2783                 }
2784 #else
2785 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2786 //FIXME: there as we start another \selectlanguage with the next paragraph if
2787 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2788                 running_font.latexWriteEndChanges(os, bparams, runparams,
2789                                 basefont, basefont, needPar);
2790 #endif
2791                 if (needPar) {
2792                         // The \par could not be inserted at the same nesting
2793                         // level of the font size change, so do it now.
2794                         os << "{\\" << font.latexSize() << "\\par}";
2795                 }
2796         }
2797
2798         column += Changes::latexMarkChange(os, bparams, runningChange,
2799                                            Change(Change::UNCHANGED), runparams);
2800
2801         // Needed if there is an optional argument but no contents.
2802         if (body_pos > 0 && body_pos == size()) {
2803                 os << "}]~";
2804         }
2805
2806         if (!style.rightdelim().empty()) {
2807                 os << style.rightdelim();
2808                 column += style.rightdelim().size();
2809         }
2810
2811         if (allowcust && d->endTeXParParams(bparams, os, runparams)
2812             && runparams.encoding != prev_encoding) {
2813                 runparams.encoding = prev_encoding;
2814                 os << setEncoding(prev_encoding->iconvName());
2815         }
2816
2817         LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2818 }
2819
2820
2821 bool Paragraph::emptyTag() const
2822 {
2823         for (pos_type i = 0; i < size(); ++i) {
2824                 if (Inset const * inset = getInset(i)) {
2825                         InsetCode lyx_code = inset->lyxCode();
2826                         // FIXME testing like that is wrong. What is
2827                         // the intent?
2828                         if (lyx_code != TOC_CODE &&
2829                             lyx_code != INCLUDE_CODE &&
2830                             lyx_code != GRAPHICS_CODE &&
2831                             lyx_code != ERT_CODE &&
2832                             lyx_code != LISTINGS_CODE &&
2833                             lyx_code != FLOAT_CODE &&
2834                             lyx_code != TABULAR_CODE) {
2835                                 return false;
2836                         }
2837                 } else {
2838                         char_type c = d->text_[i];
2839                         if (c != ' ' && c != '\t')
2840                                 return false;
2841                 }
2842         }
2843         return true;
2844 }
2845
2846
2847 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2848         const
2849 {
2850         for (pos_type i = 0; i < size(); ++i) {
2851                 if (Inset const * inset = getInset(i)) {
2852                         InsetCode lyx_code = inset->lyxCode();
2853                         if (lyx_code == LABEL_CODE) {
2854                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2855                                 docstring const & id = il->getParam("name");
2856                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2857                         }
2858                 }
2859         }
2860         return string();
2861 }
2862
2863
2864 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2865         const
2866 {
2867         pos_type i;
2868         for (i = 0; i < size(); ++i) {
2869                 if (Inset const * inset = getInset(i)) {
2870                         inset->docbook(os, runparams);
2871                 } else {
2872                         char_type c = d->text_[i];
2873                         if (c == ' ')
2874                                 break;
2875                         os << sgml::escapeChar(c);
2876                 }
2877         }
2878         return i;
2879 }
2880
2881
2882 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2883         const
2884 {
2885         pos_type i;
2886         for (i = 0; i < size(); ++i) {
2887                 if (Inset const * inset = getInset(i)) {
2888                         inset->xhtml(xs, runparams);
2889                 } else {
2890                         char_type c = d->text_[i];
2891                         if (c == ' ')
2892                                 break;
2893                         xs << c;
2894                 }
2895         }
2896         return i;
2897 }
2898
2899
2900 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2901 {
2902         Font font_old;
2903         pos_type size = text_.size();
2904         for (pos_type i = initial; i < size; ++i) {
2905                 Font font = owner_->getFont(buf.params(), i, outerfont);
2906                 if (text_[i] == META_INSET)
2907                         return false;
2908                 if (i != initial && font != font_old)
2909                         return false;
2910                 font_old = font;
2911         }
2912
2913         return true;
2914 }
2915
2916
2917 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2918                                     odocstream & os,
2919                                     OutputParams const & runparams,
2920                                     Font const & outerfont,
2921                                     pos_type initial) const
2922 {
2923         bool emph_flag = false;
2924
2925         Layout const & style = *d->layout_;
2926         FontInfo font_old =
2927                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2928
2929         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2930                 os << "]]>";
2931
2932         // parsing main loop
2933         for (pos_type i = initial; i < size(); ++i) {
2934                 Font font = getFont(buf.params(), i, outerfont);
2935
2936                 // handle <emphasis> tag
2937                 if (font_old.emph() != font.fontInfo().emph()) {
2938                         if (font.fontInfo().emph() == FONT_ON) {
2939                                 os << "<emphasis>";
2940                                 emph_flag = true;
2941                         } else if (i != initial) {
2942                                 os << "</emphasis>";
2943                                 emph_flag = false;
2944                         }
2945                 }
2946
2947                 if (Inset const * inset = getInset(i)) {
2948                         inset->docbook(os, runparams);
2949                 } else {
2950                         char_type c = d->text_[i];
2951
2952                         if (style.pass_thru)
2953                                 os.put(c);
2954                         else
2955                                 os << sgml::escapeChar(c);
2956                 }
2957                 font_old = font.fontInfo();
2958         }
2959
2960         if (emph_flag) {
2961                 os << "</emphasis>";
2962         }
2963
2964         if (style.free_spacing)
2965                 os << '\n';
2966         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2967                 os << "<![CDATA[";
2968 }
2969
2970
2971 namespace {
2972 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2973                   vector<html::EndFontTag> & tagsToClose,
2974                   bool & flag, FontState curstate, html::FontTypes type)
2975 {
2976         if (curstate == FONT_ON) {
2977                 tagsToOpen.push_back(html::FontTag(type));
2978                 flag = true;
2979         } else if (flag) {
2980                 tagsToClose.push_back(html::EndFontTag(type));
2981                 flag = false;
2982         }
2983 }
2984 } // namespace
2985
2986
2987 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2988                                     XHTMLStream & xs,
2989                                     OutputParams const & runparams,
2990                                     Font const & outerfont,
2991                                     bool start_paragraph, bool close_paragraph,
2992                                     pos_type initial) const
2993 {
2994         docstring retval;
2995
2996         // track whether we have opened these tags
2997         bool emph_flag = false;
2998         bool bold_flag = false;
2999         bool noun_flag = false;
3000         bool ubar_flag = false;
3001         bool dbar_flag = false;
3002         bool sout_flag = false;
3003         bool xout_flag = false;
3004         bool wave_flag = false;
3005         // shape tags
3006         bool shap_flag = false;
3007         // family tags
3008         bool faml_flag = false;
3009         // size tags
3010         bool size_flag = false;
3011
3012         Layout const & style = *d->layout_;
3013
3014         if (start_paragraph)
3015                 xs.startDivision(allowEmpty());
3016
3017         FontInfo font_old =
3018                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3019
3020         FontShape  curr_fs   = INHERIT_SHAPE;
3021         FontFamily curr_fam  = INHERIT_FAMILY;
3022         FontSize   curr_size = FONT_SIZE_INHERIT;
3023
3024         string const default_family =
3025                 buf.masterBuffer()->params().fonts_default_family;
3026
3027         vector<html::FontTag> tagsToOpen;
3028         vector<html::EndFontTag> tagsToClose;
3029
3030         // parsing main loop
3031         for (pos_type i = initial; i < size(); ++i) {
3032                 // let's not show deleted material in the output
3033                 if (isDeleted(i))
3034                         continue;
3035
3036                 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3037
3038                 // emphasis
3039                 FontState curstate = font.fontInfo().emph();
3040                 if (font_old.emph() != curstate)
3041                         doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
3042
3043                 // noun
3044                 curstate = font.fontInfo().noun();
3045                 if (font_old.noun() != curstate)
3046                         doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
3047
3048                 // underbar
3049                 curstate = font.fontInfo().underbar();
3050                 if (font_old.underbar() != curstate)
3051                         doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
3052
3053                 // strikeout
3054                 curstate = font.fontInfo().strikeout();
3055                 if (font_old.strikeout() != curstate)
3056                         doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
3057
3058                 // xout
3059                 curstate = font.fontInfo().xout();
3060                 if (font_old.xout() != curstate)
3061                         doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
3062
3063                 // double underbar
3064                 curstate = font.fontInfo().uuline();
3065                 if (font_old.uuline() != curstate)
3066                         doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
3067
3068                 // wavy line
3069                 curstate = font.fontInfo().uwave();
3070                 if (font_old.uwave() != curstate)
3071                         doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
3072
3073                 // bold
3074                 // a little hackish, but allows us to reuse what we have.
3075                 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3076                 if (font_old.series() != font.fontInfo().series())
3077                         doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
3078
3079                 // Font shape
3080                 curr_fs = font.fontInfo().shape();
3081                 FontShape old_fs = font_old.shape();
3082                 if (old_fs != curr_fs) {
3083                         if (shap_flag) {
3084                                 switch (old_fs) {
3085                                 case ITALIC_SHAPE:
3086                                         tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
3087                                         break;
3088                                 case SLANTED_SHAPE:
3089                                         tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
3090                                         break;
3091                                 case SMALLCAPS_SHAPE:
3092                                         tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
3093                                         break;
3094                                 case UP_SHAPE:
3095                                 case INHERIT_SHAPE:
3096                                         break;
3097                                 default:
3098                                         // the other tags are for internal use
3099                                         LATTEST(false);
3100                                         break;
3101                                 }
3102                                 shap_flag = false;
3103                         }
3104                         switch (curr_fs) {
3105                         case ITALIC_SHAPE:
3106                                 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
3107                                 shap_flag = true;
3108                                 break;
3109                         case SLANTED_SHAPE:
3110                                 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
3111                                 shap_flag = true;
3112                                 break;
3113                         case SMALLCAPS_SHAPE:
3114                                 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
3115                                 shap_flag = true;
3116                                 break;
3117                         case UP_SHAPE:
3118                         case INHERIT_SHAPE:
3119                                 break;
3120                         default:
3121                                 // the other tags are for internal use
3122                                 LATTEST(false);
3123                                 break;
3124                         }
3125                 }
3126
3127                 // Font family
3128                 curr_fam = font.fontInfo().family();
3129                 FontFamily old_fam = font_old.family();
3130                 if (old_fam != curr_fam) {
3131                         if (faml_flag) {
3132                                 switch (old_fam) {
3133                                 case ROMAN_FAMILY:
3134                                         tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
3135                                         break;
3136                                 case SANS_FAMILY:
3137                                         tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
3138                                         break;
3139                                 case TYPEWRITER_FAMILY:
3140                                         tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3141                                         break;
3142                                 case INHERIT_FAMILY:
3143                                         break;
3144                                 default:
3145                                         // the other tags are for internal use
3146                                         LATTEST(false);
3147                                         break;
3148                                 }
3149                                 faml_flag = false;
3150                         }
3151                         switch (curr_fam) {
3152                         case ROMAN_FAMILY:
3153                                 // we will treat a "default" font family as roman, since we have
3154                                 // no other idea what to do.
3155                                 if (default_family != "rmdefault" && default_family != "default") {
3156                                         tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3157                                         faml_flag = true;
3158                                 }
3159                                 break;
3160                         case SANS_FAMILY:
3161                                 if (default_family != "sfdefault") {
3162                                         tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3163                                         faml_flag = true;
3164                                 }
3165                                 break;
3166                         case TYPEWRITER_FAMILY:
3167                                 if (default_family != "ttdefault") {
3168                                         tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3169                                         faml_flag = true;
3170                                 }
3171                                 break;
3172                         case INHERIT_FAMILY:
3173                                 break;
3174                         default:
3175                                 // the other tags are for internal use
3176                                 LATTEST(false);
3177                                 break;
3178                         }
3179                 }
3180
3181                 // Font size
3182                 curr_size = font.fontInfo().size();
3183                 FontSize old_size = font_old.size();
3184                 if (old_size != curr_size) {
3185                         if (size_flag) {
3186                                 switch (old_size) {
3187                                 case FONT_SIZE_TINY:
3188                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3189                                         break;
3190                                 case FONT_SIZE_SCRIPT:
3191                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3192                                         break;
3193                                 case FONT_SIZE_FOOTNOTE:
3194                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3195                                         break;
3196                                 case FONT_SIZE_SMALL:
3197                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3198                                         break;
3199                                 case FONT_SIZE_LARGE:
3200                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3201                                         break;
3202                                 case FONT_SIZE_LARGER:
3203                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3204                                         break;
3205                                 case FONT_SIZE_LARGEST:
3206                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3207                                         break;
3208                                 case FONT_SIZE_HUGE:
3209                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3210                                         break;
3211                                 case FONT_SIZE_HUGER:
3212                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3213                                         break;
3214                                 case FONT_SIZE_INCREASE:
3215                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3216                                         break;
3217                                 case FONT_SIZE_DECREASE:
3218                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3219                                         break;
3220                                 case FONT_SIZE_INHERIT:
3221                                 case FONT_SIZE_NORMAL:
3222                                         break;
3223                                 default:
3224                                         // the other tags are for internal use
3225                                         LATTEST(false);
3226                                         break;
3227                                 }
3228                                 size_flag = false;
3229                         }
3230                         switch (curr_size) {
3231                         case FONT_SIZE_TINY:
3232                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3233                                 size_flag = true;
3234                                 break;
3235                         case FONT_SIZE_SCRIPT:
3236                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3237                                 size_flag = true;
3238                                 break;
3239                         case FONT_SIZE_FOOTNOTE:
3240                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3241                                 size_flag = true;
3242                                 break;
3243                         case FONT_SIZE_SMALL:
3244                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3245                                 size_flag = true;
3246                                 break;
3247                         case FONT_SIZE_LARGE:
3248                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3249                                 size_flag = true;
3250                                 break;
3251                         case FONT_SIZE_LARGER:
3252                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3253                                 size_flag = true;
3254                                 break;
3255                         case FONT_SIZE_LARGEST:
3256                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3257                                 size_flag = true;
3258                                 break;
3259                         case FONT_SIZE_HUGE:
3260                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3261                                 size_flag = true;
3262                                 break;
3263                         case FONT_SIZE_HUGER:
3264                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3265                                 size_flag = true;
3266                                 break;
3267                         case FONT_SIZE_INCREASE:
3268                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3269                                 size_flag = true;
3270                                 break;
3271                         case FONT_SIZE_DECREASE:
3272                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3273                                 size_flag = true;
3274                                 break;
3275                         case FONT_SIZE_NORMAL:
3276                         case FONT_SIZE_INHERIT:
3277                                 break;
3278                         default:
3279                                 // the other tags are for internal use
3280                                 LATTEST(false);
3281                                 break;
3282                         }
3283                 }
3284
3285                 // FIXME XHTML
3286                 // Other such tags? What about the other text ranges?
3287
3288                 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3289                 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3290                 for (; cit != cen; ++cit)
3291                         xs << *cit;
3292
3293                 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3294                 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3295                 for (; sit != sen; ++sit)
3296                         xs << *sit;
3297
3298                 tagsToClose.clear();
3299                 tagsToOpen.clear();
3300
3301                 Inset const * inset = getInset(i);
3302                 if (inset) {
3303                         if (!runparams.for_toc || inset->isInToc()) {
3304                                 OutputParams np = runparams;
3305                                 np.local_font = &font;
3306                                 // If the paragraph has size 1, then we are in the "special
3307                                 // case" where we do not output the containing paragraph info
3308                                 if (!inset->getLayout().htmlisblock() && size() != 1)
3309                                         np.html_in_par = true;
3310                                 retval += inset->xhtml(xs, np);
3311                         }
3312                 } else {
3313                         char_type c = getUChar(buf.masterBuffer()->params(), i);
3314                         xs << c;
3315                 }
3316                 font_old = font.fontInfo();
3317         }
3318
3319         // FIXME XHTML
3320         // I'm worried about what happens if a branch, say, is itself
3321         // wrapped in some font stuff. I think that will not work.
3322         xs.closeFontTags();
3323         if (close_paragraph)
3324                 xs.endDivision();
3325
3326         return retval;
3327 }
3328
3329
3330 bool Paragraph::isHfill(pos_type pos) const
3331 {
3332         Inset const * inset = getInset(pos);
3333         return inset && inset->isHfill();
3334 }
3335
3336
3337 bool Paragraph::isNewline(pos_type pos) const
3338 {
3339         // U+2028 LINE SEPARATOR
3340         // U+2029 PARAGRAPH SEPARATOR
3341         char_type const c = d->text_[pos];
3342         if (c == 0x2028 || c == 0x2029)
3343                 return true;
3344         Inset const * inset = getInset(pos);
3345         return inset && inset->lyxCode() == NEWLINE_CODE;
3346 }
3347
3348
3349 bool Paragraph::isEnvSeparator(pos_type pos) const
3350 {
3351         Inset const * inset = getInset(pos);
3352         return inset && inset->lyxCode() == SEPARATOR_CODE;
3353 }
3354
3355
3356 bool Paragraph::isLineSeparator(pos_type pos) const
3357 {
3358         char_type const c = d->text_[pos];
3359         if (isLineSeparatorChar(c))
3360                 return true;
3361         Inset const * inset = getInset(pos);
3362         return inset && inset->isLineSeparator();
3363 }
3364
3365
3366 bool Paragraph::isWordSeparator(pos_type pos) const
3367 {
3368         if (pos == size())
3369                 return true;
3370         if (Inset const * inset = getInset(pos))
3371                 return !inset->isLetter();
3372         // if we have a hard hyphen (no en- or emdash) or apostrophe
3373         // we pass this to the spell checker
3374         // FIXME: this method is subject to change, visit
3375         // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3376         // to get an impression how complex this is.
3377         if (isHardHyphenOrApostrophe(pos))
3378                 return false;
3379         char_type const c = d->text_[pos];
3380         // We want to pass the escape chars to the spellchecker
3381         docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3382         return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3383 }
3384
3385
3386 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3387 {
3388         pos_type const psize = size();
3389         if (pos >= psize)
3390                 return false;
3391         char_type const c = d->text_[pos];
3392         if (c != '-' && c != '\'')
3393                 return false;
3394         int nextpos = pos + 1;
3395         int prevpos = pos > 0 ? pos - 1 : 0;
3396         if ((nextpos == psize || isSpace(nextpos))
3397                 && (pos == 0 || isSpace(prevpos)))
3398                 return false;
3399         return true;
3400 }
3401
3402
3403 bool Paragraph::needsCProtection() const
3404 {
3405         // first check the layout of the paragraph
3406         if (layout().needcprotect) {
3407                 // Environments need cprotection regardless the content
3408                 if (layout().latextype == LATEX_ENVIRONMENT)
3409                         return true;
3410
3411                 // Commands need cprotection if they contain specific chars
3412                 int const nchars_escape = 9;
3413                 static char_type const chars_escape[nchars_escape] = {
3414                         '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3415
3416                 docstring const pars = asString();
3417                 for (int k = 0; k < nchars_escape; k++) {
3418                         if (contains(pars, chars_escape[k]))
3419                                 return true;
3420                 }
3421         }
3422
3423         // now check whether we have insets that need cprotection
3424         pos_type size = d->text_.size();
3425         for (pos_type i = 0; i < size; ++i)
3426                 if (isInset(i) && getInset(i)->needsCProtection())
3427                         return true;
3428
3429         return false;
3430 }
3431
3432
3433 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3434 {
3435         return d->speller_state_.getRange(pos);
3436 }
3437
3438
3439 bool Paragraph::isChar(pos_type pos) const
3440 {
3441         if (Inset const * inset = getInset(pos))
3442                 return inset->isChar();
3443         char_type const c = d->text_[pos];
3444         return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3445 }
3446
3447
3448 bool Paragraph::isSpace(pos_type pos) const
3449 {
3450         if (Inset const * inset = getInset(pos))
3451                 return inset->isSpace();
3452         char_type const c = d->text_[pos];
3453         return lyx::isSpace(c);
3454 }
3455
3456
3457 Language const *
3458 Paragraph::getParLanguage(BufferParams const & bparams) const
3459 {
3460         if (!empty())
3461                 return getFirstFontSettings(bparams).language();
3462         // FIXME: we should check the prev par as well (Lgb)
3463         return bparams.language;
3464 }
3465
3466
3467 bool Paragraph::isRTL(BufferParams const & bparams) const
3468 {
3469         return getParLanguage(bparams)->rightToLeft()
3470                 && !inInset().getLayout().forceLTR();
3471 }
3472
3473
3474 void Paragraph::changeLanguage(BufferParams const & bparams,
3475                                Language const * from, Language const * to)
3476 {
3477         // change language including dummy font change at the end
3478         for (pos_type i = 0; i <= size(); ++i) {
3479                 Font font = getFontSettings(bparams, i);
3480                 if (font.language() == from) {
3481                         font.setLanguage(to);
3482                         setFont(i, font);
3483                         d->requestSpellCheck(i);
3484                 }
3485         }
3486 }
3487
3488
3489 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3490 {
3491         Language const * doc_language = bparams.language;
3492         for (auto const & f : d->fontlist_)
3493                 if (f.font().language() != ignore_language &&
3494                     f.font().language() != latex_language &&
3495                     f.font().language() != doc_language)
3496                         return true;
3497         return false;
3498 }
3499
3500
3501 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3502 {
3503         for (auto const & f : d->fontlist_) {
3504                 Language const * lang = f.font().language();
3505                 if (lang != ignore_language &&
3506                     lang != latex_language)
3507                         langs.insert(lang);
3508         }
3509 }
3510
3511
3512 docstring Paragraph::asString(int options) const
3513 {
3514         return asString(0, size(), options);
3515 }
3516
3517
3518 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3519 {
3520         odocstringstream os;
3521
3522         if (beg == 0
3523             && options & AS_STR_LABEL
3524             && !d->params_.labelString().empty())
3525                 os << d->params_.labelString() << ' ';
3526
3527         for (pos_type i = beg; i < end; ++i) {
3528                 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3529                         continue;
3530                 char_type const c = d->text_[i];
3531                 if (isPrintable(c) || c == '\t'
3532                     || (c == '\n' && (options & AS_STR_NEWLINES)))
3533                         os.put(c);
3534                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3535                         if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3536                                 LASSERT(runparams != 0, return docstring());
3537                                 getInset(i)->plaintext(os, *runparams);
3538                         } else {
3539                                 getInset(i)->toString(os);
3540                         }
3541                 }
3542         }
3543
3544         return os.str();
3545 }
3546
3547
3548 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3549                             bool const shorten, bool const label) const
3550 {
3551         size_t tmplen = shorten ? maxlen + 1 : maxlen;
3552         if (label && !labelString().empty())
3553                 os += labelString() + ' ';
3554         if (!layout().isTocCaption())
3555                 return;
3556         for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3557                 if (isDeleted(i))
3558                         continue;
3559                 char_type const c = d->text_[i];
3560                 if (isPrintable(c))
3561                         os += c;
3562                 else if (c == META_INSET)
3563                         getInset(i)->forOutliner(os, tmplen, false);
3564         }
3565         if (shorten)
3566                 Text::shortenForOutliner(os, maxlen);
3567 }
3568
3569
3570 void Paragraph::setInsetOwner(Inset const * inset)
3571 {
3572         d->inset_owner_ = inset;
3573 }
3574
3575
3576 int Paragraph::id() const
3577 {
3578         return d->id_;
3579 }
3580
3581
3582 void Paragraph::setId(int id)
3583 {
3584         d->id_ = id;
3585 }
3586
3587
3588 Layout const & Paragraph::layout() const
3589 {
3590         return *d->layout_;
3591 }
3592
3593
3594 void Paragraph::setLayout(Layout const & layout)
3595 {
3596         d->layout_ = &layout;
3597 }
3598
3599
3600 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3601 {
3602         setLayout(tc.defaultLayout());
3603 }
3604
3605
3606 void Paragraph::setPlainLayout(DocumentClass const & tc)
3607 {
3608         setLayout(tc.plainLayout());
3609 }
3610
3611
3612 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3613 {
3614         if (usePlainLayout())
3615                 setPlainLayout(tclass);
3616         else
3617                 setDefaultLayout(tclass);
3618 }
3619
3620
3621 Inset const & Paragraph::inInset() const
3622 {
3623         LBUFERR(d->inset_owner_);
3624         return *d->inset_owner_;
3625 }
3626
3627
3628 ParagraphParameters & Paragraph::params()
3629 {
3630         return d->params_;
3631 }
3632
3633
3634 ParagraphParameters const & Paragraph::params() const
3635 {
3636         return d->params_;
3637 }
3638
3639
3640 bool Paragraph::isFreeSpacing() const
3641 {
3642         if (d->layout_->free_spacing)
3643                 return true;
3644         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3645 }
3646
3647
3648 bool Paragraph::allowEmpty() const
3649 {
3650         if (d->layout_->keepempty)
3651                 return true;
3652         return d->inset_owner_ && d->inset_owner_->allowEmpty();
3653 }
3654
3655
3656 bool Paragraph::brokenBiblio() const
3657 {
3658         // there is a problem if there is no bibitem at position 0 or
3659         // if there is another bibitem in the paragraph.
3660         return d->layout_->labeltype == LABEL_BIBLIO
3661                 && (d->insetlist_.find(BIBITEM_CODE) != 0
3662                     || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3663 }
3664
3665
3666 int Paragraph::fixBiblio(Buffer const & buffer)
3667 {
3668         // FIXME: What about the case where paragraph is not BIBLIO
3669         // but there is an InsetBibitem?
3670         // FIXME: when there was already an inset at 0, the return value is 1,
3671         // which does not tell whether another inset has been remove; the
3672         // cursor cannot be correctly updated.
3673
3674         if (d->layout_->labeltype != LABEL_BIBLIO)
3675                 return 0;
3676
3677         bool const track_changes = buffer.params().track_changes;
3678         int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3679         bool const hasbibitem0 = bibitem_pos == 0;
3680
3681         if (hasbibitem0) {
3682                 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3683                 // There was an InsetBibitem at pos 0, and no other one => OK
3684                 if (bibitem_pos == -1)
3685                         return 0;
3686                 // there is a bibitem at the 0 position, but since
3687                 // there is a second one, we copy the second on the
3688                 // first. We're assuming there are at most two of
3689                 // these, which there should be.
3690                 // FIXME: why does it make sense to do that rather
3691                 // than keep the first? (JMarc)
3692                 Inset * inset = releaseInset(bibitem_pos);
3693                 d->insetlist_.begin()->inset = inset;
3694                 return -bibitem_pos;
3695         }
3696
3697         // We need to create an inset at the beginning
3698         Inset * inset = 0;
3699         if (bibitem_pos > 0) {
3700                 // there was one somewhere in the paragraph, let's move it
3701                 inset = d->insetlist_.release(bibitem_pos);
3702                 eraseChar(bibitem_pos, track_changes);
3703         } else
3704                 // make a fresh one
3705                 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3706                                          InsetCommandParams(BIBITEM_CODE));
3707
3708         Font font(inherit_font, buffer.params().language);
3709         insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3710                                                    : Change::UNCHANGED));
3711
3712         return 1;
3713 }
3714
3715
3716 void Paragraph::checkAuthors(AuthorList const & authorList)
3717 {
3718         d->changes_.checkAuthors(authorList);
3719 }
3720
3721
3722 bool Paragraph::isChanged(pos_type pos) const
3723 {
3724         return lookupChange(pos).changed();
3725 }
3726
3727
3728 bool Paragraph::isInserted(pos_type pos) const
3729 {
3730         return lookupChange(pos).inserted();
3731 }
3732
3733
3734 bool Paragraph::isDeleted(pos_type pos) const
3735 {
3736         return lookupChange(pos).deleted();
3737 }
3738
3739
3740 InsetList const & Paragraph::insetList() const
3741 {
3742         return d->insetlist_;
3743 }
3744
3745
3746 void Paragraph::setInsetBuffers(Buffer & b)
3747 {
3748         d->insetlist_.setBuffer(b);
3749 }
3750
3751
3752 void Paragraph::resetBuffer()
3753 {
3754         d->insetlist_.resetBuffer();
3755 }
3756
3757
3758 Inset * Paragraph::releaseInset(pos_type pos)
3759 {
3760         Inset * inset = d->insetlist_.release(pos);
3761         /// does not honour change tracking!
3762         eraseChar(pos, false);
3763         return inset;
3764 }
3765
3766
3767 Inset * Paragraph::getInset(pos_type pos)
3768 {
3769         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3770                  ? d->insetlist_.get(pos) : 0;
3771 }
3772
3773
3774 Inset const * Paragraph::getInset(pos_type pos) const
3775 {
3776         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3777                  ? d->insetlist_.get(pos) : 0;
3778 }
3779
3780
3781 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3782                 pos_type & right, TextCase action)
3783 {
3784         // process sequences of modified characters; in change
3785         // tracking mode, this approach results in much better
3786         // usability than changing case on a char-by-char basis
3787         // We also need to track the current font, since font
3788         // changes within sequences can occur.
3789         vector<pair<char_type, Font> > changes;
3790
3791         bool const trackChanges = bparams.track_changes;
3792
3793         bool capitalize = true;
3794
3795         for (; pos < right; ++pos) {
3796                 char_type oldChar = d->text_[pos];
3797                 char_type newChar = oldChar;
3798
3799                 // ignore insets and don't play with deleted text!
3800                 if (oldChar != META_INSET && !isDeleted(pos)) {
3801                         switch (action) {
3802                                 case text_lowercase:
3803                                         newChar = lowercase(oldChar);
3804                                         break;
3805                                 case text_capitalization:
3806                                         if (capitalize) {
3807                                                 newChar = uppercase(oldChar);
3808                                                 capitalize = false;
3809                                         }
3810                                         break;
3811                                 case text_uppercase:
3812                                         newChar = uppercase(oldChar);
3813                                         break;
3814                         }
3815                 }
3816
3817                 if (isWordSeparator(pos) || isDeleted(pos)) {
3818                         // permit capitalization again
3819                         capitalize = true;
3820                 }
3821
3822                 if (oldChar != newChar) {
3823                         changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3824                         if (pos != right - 1)
3825                                 continue;
3826                         // step behind the changing area
3827                         pos++;
3828                 }
3829
3830                 int erasePos = pos - changes.size();
3831                 for (size_t i = 0; i < changes.size(); i++) {
3832                         insertChar(pos, changes[i].first,
3833                                    changes[i].second,
3834                                    trackChanges);
3835                         if (!eraseChar(erasePos, trackChanges)) {
3836                                 ++erasePos;
3837                                 ++pos; // advance
3838                                 ++right; // expand selection
3839                         }
3840                 }
3841                 changes.clear();
3842         }
3843 }
3844
3845
3846 int Paragraph::find(docstring const & str, bool cs, bool mw,
3847                 pos_type start_pos, bool del) const
3848 {
3849         pos_type pos = start_pos;
3850         int const strsize = str.length();
3851         int i = 0;
3852         pos_type const parsize = d->text_.size();
3853         for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3854                 // Ignore "invisible" letters such as ligature breaks
3855                 // and hyphenation chars while searching
3856                 while (pos < parsize - 1 && isInset(pos)) {
3857                         odocstringstream os;
3858                         getInset(pos)->toString(os);
3859                         if (!getInset(pos)->isLetter() || !os.str().empty())
3860                                 break;
3861                         pos++;
3862                 }
3863                 if (cs && str[i] != d->text_[pos])
3864                         break;
3865                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3866                         break;
3867                 if (!del && isDeleted(pos))
3868                         break;
3869         }
3870
3871         if (i != strsize)
3872                 return 0;
3873
3874         // if necessary, check whether string matches word
3875         if (mw) {
3876                 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3877                         return 0;
3878                 if (pos < parsize
3879                         && !isWordSeparator(pos))
3880                         return 0;
3881         }
3882
3883         return pos - start_pos;
3884 }
3885
3886
3887 char_type Paragraph::getChar(pos_type pos) const
3888 {
3889         return d->text_[pos];
3890 }
3891
3892
3893 pos_type Paragraph::size() const
3894 {
3895         return d->text_.size();
3896 }
3897
3898
3899 bool Paragraph::empty() const
3900 {
3901         return d->text_.empty();
3902 }
3903
3904
3905 bool Paragraph::isInset(pos_type pos) const
3906 {
3907         return d->text_[pos] == META_INSET;
3908 }
3909
3910
3911 bool Paragraph::isSeparator(pos_type pos) const
3912 {
3913         //FIXME: Are we sure this can be the only separator?
3914         return d->text_[pos] == ' ';
3915 }
3916
3917
3918 void Paragraph::deregisterWords()
3919 {
3920         Private::LangWordsMap::const_iterator itl = d->words_.begin();
3921         Private::LangWordsMap::const_iterator ite = d->words_.end();
3922         for (; itl != ite; ++itl) {
3923                 WordList & wl = theWordList(itl->first);
3924                 Private::Words::const_iterator it = (itl->second).begin();
3925                 Private::Words::const_iterator et = (itl->second).end();
3926                 for (; it != et; ++it)
3927                         wl.remove(*it);
3928         }
3929         d->words_.clear();
3930 }
3931
3932
3933 void Paragraph::locateWord(pos_type & from, pos_type & to,
3934         word_location const loc) const
3935 {
3936         switch (loc) {
3937         case WHOLE_WORD_STRICT:
3938                 if (from == 0 || from == size()
3939                     || isWordSeparator(from)
3940                     || isWordSeparator(from - 1)) {
3941                         to = from;
3942                         return;
3943                 }
3944                 // fall through
3945
3946         case WHOLE_WORD:
3947                 // If we are already at the beginning of a word, do nothing
3948                 if (!from || isWordSeparator(from - 1))
3949                         break;
3950                 // fall through
3951
3952         case PREVIOUS_WORD:
3953                 // always move the cursor to the beginning of previous word
3954                 while (from && !isWordSeparator(from - 1))
3955                         --from;
3956                 break;
3957         case NEXT_WORD:
3958                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3959                 break;
3960         case PARTIAL_WORD:
3961                 // no need to move the 'from' cursor
3962                 break;
3963         }
3964         to = from;
3965         while (to < size() && !isWordSeparator(to))
3966                 ++to;
3967 }
3968
3969
3970 void Paragraph::collectWords()
3971 {
3972         for (pos_type pos = 0; pos < size(); ++pos) {
3973                 if (isWordSeparator(pos))
3974                         continue;
3975                 pos_type from = pos;
3976                 locateWord(from, pos, WHOLE_WORD);
3977                 // Work around MSVC warning: The statement
3978                 // if (pos < from + lyxrc.completion_minlength)
3979                 // triggers a signed vs. unsigned warning.
3980                 // I don't know why this happens, it could be a MSVC bug, or
3981                 // related to LLP64 (windows) vs. LP64 (unix) programming
3982                 // model, or the C++ standard might be ambigous in the section
3983                 // defining the "usual arithmetic conversions". However, using
3984                 // a temporary variable is safe and works on all compilers.
3985                 pos_type const endpos = from + lyxrc.completion_minlength;
3986                 if (pos < endpos)
3987                         continue;
3988                 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3989                 if (cit == d->fontlist_.end())
3990                         return;
3991                 Language const * lang = cit->font().language();
3992                 docstring const word = asString(from, pos, AS_STR_NONE);
3993                 d->words_[lang->lang()].insert(word);
3994         }
3995 }
3996
3997
3998 void Paragraph::registerWords()
3999 {
4000         Private::LangWordsMap::const_iterator itl = d->words_.begin();
4001         Private::LangWordsMap::const_iterator ite = d->words_.end();
4002         for (; itl != ite; ++itl) {
4003                 WordList & wl = theWordList(itl->first);
4004                 Private::Words::const_iterator it = (itl->second).begin();
4005                 Private::Words::const_iterator et = (itl->second).end();
4006                 for (; it != et; ++it)
4007                         wl.insert(*it);
4008         }
4009 }
4010
4011
4012 void Paragraph::updateWords()
4013 {
4014         deregisterWords();
4015         collectWords();
4016         registerWords();
4017 }
4018
4019
4020 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4021 {
4022         SkipPositionsIterator begin = skips.begin();
4023         SkipPositions::iterator end = skips.end();
4024         if (pos > 0 && begin < end) {
4025                 --end;
4026                 if (end->last == pos - 1) {
4027                         end->last = pos;
4028                         return;
4029                 }
4030         }
4031         skips.insert(end, FontSpan(pos, pos));
4032 }
4033
4034
4035 Language * Paragraph::Private::locateSpellRange(
4036         pos_type & from, pos_type & to,
4037         SkipPositions & skips) const
4038 {
4039         // skip leading white space
4040         while (from < to && owner_->isWordSeparator(from))
4041                 ++from;
4042         // don't check empty range
4043         if (from >= to)
4044                 return 0;
4045         // get current language
4046         Language * lang = getSpellLanguage(from);
4047         pos_type last = from;
4048         bool samelang = true;
4049         bool sameinset = true;
4050         while (last < to && samelang && sameinset) {
4051                 // hop to end of word
4052                 while (last < to && !owner_->isWordSeparator(last)) {
4053                         if (owner_->getInset(last)) {
4054                                 appendSkipPosition(skips, last);
4055                         } else if (owner_->isDeleted(last)) {
4056                                 appendSkipPosition(skips, last);
4057                         }
4058                         ++last;
4059                 }
4060                 // hop to next word while checking for insets
4061                 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4062                         if (Inset const * inset = owner_->getInset(last))
4063                                 sameinset = inset->isChar() && inset->isLetter();
4064                         if (sameinset && owner_->isDeleted(last)) {
4065                                 appendSkipPosition(skips, last);
4066                         }
4067                         if (sameinset)
4068                                 last++;
4069                 }
4070                 if (sameinset && last < to) {
4071                         // now check for language change
4072                         samelang = lang == getSpellLanguage(last);
4073                 }
4074         }
4075         // if language change detected backstep is needed
4076         if (!samelang)
4077                 --last;
4078         to = last;
4079         return lang;
4080 }
4081
4082
4083 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4084 {
4085         Language * lang =
4086                 const_cast<Language *>(owner_->getFontSettings(
4087                         inset_owner_->buffer().params(), from).language());
4088         if (lang == inset_owner_->buffer().params().language
4089                 && !lyxrc.spellchecker_alt_lang.empty()) {
4090                 string lang_code;
4091                 string const lang_variety =
4092                         split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4093                 lang->setCode(lang_code);
4094                 lang->setVariety(lang_variety);
4095         }
4096         return lang;
4097 }
4098
4099
4100 void Paragraph::requestSpellCheck(pos_type pos)
4101 {
4102         d->requestSpellCheck(pos);
4103 }
4104
4105
4106 bool Paragraph::needsSpellCheck() const
4107 {
4108         SpellChecker::ChangeNumber speller_change_number = 0;
4109         if (theSpellChecker())
4110                 speller_change_number = theSpellChecker()->changeNumber();
4111         if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4112                 d->speller_state_.needsCompleteRefresh(speller_change_number);
4113         }
4114         return d->needsSpellCheck();
4115 }
4116
4117
4118 bool Paragraph::Private::ignoreWord(docstring const & word) const
4119 {
4120         // Ignore words with digits
4121         // FIXME: make this customizable
4122         // (note that some checkers ignore words with digits by default)
4123         docstring::const_iterator cit = word.begin();
4124         docstring::const_iterator const end = word.end();
4125         for (; cit != end; ++cit) {
4126                 if (isNumber((*cit)))
4127                         return true;
4128         }
4129         return false;
4130 }
4131
4132
4133 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4134         WordLangTuple & wl, docstring_list & suggestions,
4135         bool do_suggestion, bool check_learned) const
4136 {
4137         SpellChecker::Result result = SpellChecker::WORD_OK;
4138         SpellChecker * speller = theSpellChecker();
4139         if (!speller)
4140                 return result;
4141
4142         if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4143                 return result;
4144
4145         locateWord(from, to, WHOLE_WORD);
4146         if (from == to || from >= size())
4147                 return result;
4148
4149         docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4150         Language * lang = d->getSpellLanguage(from);
4151
4152         wl = WordLangTuple(word, lang);
4153
4154         if (word.empty())
4155                 return result;
4156
4157         if (needsSpellCheck() || check_learned) {
4158                 pos_type end = to;
4159                 if (!d->ignoreWord(word)) {
4160                         bool const trailing_dot = to < size() && d->text_[to] == '.';
4161                         result = speller->check(wl);
4162                         if (SpellChecker::misspelled(result) && trailing_dot) {
4163                                 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4164                                 result = speller->check(wl);
4165                                 if (!SpellChecker::misspelled(result)) {
4166                                         LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4167                                            word << "\" [" <<
4168                                            from << ".." << to << "]");
4169                                 } else {
4170                                         // spell check with dot appended failed too
4171                                         // restore original word/lang value
4172                                         word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4173                                         wl = WordLangTuple(word, lang);
4174                                 }
4175                         }
4176                 }
4177                 if (!SpellChecker::misspelled(result)) {
4178                         // area up to the begin of the next word is not misspelled
4179                         while (end < size() && isWordSeparator(end))
4180                                 ++end;
4181                 }
4182                 d->setMisspelled(from, end, result);
4183         } else {
4184                 result = d->speller_state_.getState(from);
4185         }
4186
4187         if (do_suggestion)
4188                 suggestions.clear();
4189
4190         if (SpellChecker::misspelled(result)) {
4191                 LYXERR(Debug::GUI, "misspelled word: \"" <<
4192                            word << "\" [" <<
4193                            from << ".." << to << "]");
4194                 if (do_suggestion)
4195                         speller->suggest(wl, suggestions);
4196         }
4197         return result;
4198 }
4199
4200
4201 void Paragraph::anonymize()
4202 {
4203         // This is a very crude anonymization for now
4204         for (char_type & c : d->text_)
4205                 if (isLetterChar(c) || isNumber(c))
4206                         c = 'a';
4207 }
4208
4209
4210 void Paragraph::Private::markMisspelledWords(
4211         pos_type const & first, pos_type const & last,
4212         SpellChecker::Result result,
4213         docstring const & word,
4214         SkipPositions const & skips)
4215 {
4216         if (!SpellChecker::misspelled(result)) {
4217                 setMisspelled(first, last, SpellChecker::WORD_OK);
4218                 return;
4219         }
4220         int snext = first;
4221         SpellChecker * speller = theSpellChecker();
4222         // locate and enumerate the error positions
4223         int nerrors = speller->numMisspelledWords();
4224         int numskipped = 0;
4225         SkipPositionsIterator it = skips.begin();
4226         SkipPositionsIterator et = skips.end();
4227         for (int index = 0; index < nerrors; ++index) {
4228                 int wstart;
4229                 int wlen = 0;
4230                 speller->misspelledWord(index, wstart, wlen);
4231                 /// should not happen if speller supports range checks
4232                 if (!wlen) continue;
4233                 docstring const misspelled = word.substr(wstart, wlen);
4234                 wstart += first + numskipped;
4235                 if (snext < wstart) {
4236                         /// mark the range of correct spelling
4237                         numskipped += countSkips(it, et, wstart);
4238                         setMisspelled(snext,
4239                                 wstart - 1, SpellChecker::WORD_OK);
4240                 }
4241                 snext = wstart + wlen;
4242                 numskipped += countSkips(it, et, snext);
4243                 /// mark the range of misspelling
4244                 setMisspelled(wstart, snext, result);
4245                 LYXERR(Debug::GUI, "misspelled word: \"" <<
4246                            misspelled << "\" [" <<
4247                            wstart << ".." << (snext-1) << "]");
4248                 ++snext;
4249         }
4250         if (snext <= last) {
4251                 /// mark the range of correct spelling at end
4252                 setMisspelled(snext, last, SpellChecker::WORD_OK);
4253         }
4254 }
4255
4256
4257 void Paragraph::spellCheck() const
4258 {
4259         SpellChecker * speller = theSpellChecker();
4260         if (!speller || empty() ||!needsSpellCheck())
4261                 return;
4262         pos_type start;
4263         pos_type endpos;
4264         d->rangeOfSpellCheck(start, endpos);
4265         if (speller->canCheckParagraph()) {
4266                 // loop until we leave the range
4267                 for (pos_type first = start; first < endpos; ) {
4268                         pos_type last = endpos;
4269                         Private::SkipPositions skips;
4270                         Language * lang = d->locateSpellRange(first, last, skips);
4271                         if (first >= endpos)
4272                                 break;
4273                         // start the spell checker on the unit of meaning
4274                         docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4275                         WordLangTuple wl = WordLangTuple(word, lang);
4276                         SpellChecker::Result result = word.size() ?
4277                                 speller->check(wl) : SpellChecker::WORD_OK;
4278                         d->markMisspelledWords(first, last, result, word, skips);
4279                         first = ++last;
4280                 }
4281         } else {
4282                 static docstring_list suggestions;
4283                 pos_type to = endpos;
4284                 while (start < endpos) {
4285                         WordLangTuple wl;
4286                         spellCheck(start, to, wl, suggestions, false);
4287                         start = to + 1;
4288                 }
4289         }
4290         d->readySpellCheck();
4291 }
4292
4293
4294 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4295 {
4296         bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4297         if (result || pos <= 0 || pos > size())
4298                 return result;
4299         if (check_boundary && (pos == size() || isWordSeparator(pos)))
4300                 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4301         return result;
4302 }
4303
4304
4305 string Paragraph::magicLabel() const
4306 {
4307         stringstream ss;
4308         ss << "magicparlabel-" << id();
4309         return ss.str();
4310 }
4311
4312
4313 } // namespace lyx