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