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