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