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