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