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