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