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