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