]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
9dfd0938f437e26c84c692aea22e93981a6577ca
[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 en dash and "---" an em dash.
1242                         // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1243                         os << "{}";
1244                         column += 2;
1245                 }
1246                 break;
1247         case '\"':
1248                 os << "\\textquotedbl" << termcmd;
1249                 column += 14;
1250                 break;
1251
1252         case '$': case '&':
1253         case '%': case '#': case '{':
1254         case '}': case '_':
1255                 os << '\\';
1256                 os.put(c);
1257                 column += 1;
1258                 break;
1259
1260         case '~':
1261                 os << "\\textasciitilde" << termcmd;
1262                 column += 16;
1263                 break;
1264
1265         case '^':
1266                 os << "\\textasciicircum" << termcmd;
1267                 column += 17;
1268                 break;
1269
1270         case '*':
1271         case '[':
1272         case ']':
1273                 // avoid being mistaken for optional arguments
1274                 os << '{';
1275                 os.put(c);
1276                 os << '}';
1277                 column += 2;
1278                 break;
1279
1280         case ' ':
1281                 // Blanks are printed before font switching.
1282                 // Sure? I am not! (try nice-latex)
1283                 // I am sure it's correct. LyX might be smarter
1284                 // in the future, but for now, nothing wrong is
1285                 // written. (Asger)
1286                 break;
1287
1288         case 0x2013:
1289         case 0x2014:
1290                 // XeTeX's dash behaviour is determined via a global setting
1291                 if (bparams.use_dash_ligatures
1292                     && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1293                     && !runparams.inIPA
1294                         // TODO #10961: && not in inset Flex Code
1295                         // TODO #10961: && not in layout LyXCode
1296                     && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1297                         if (c == 0x2013) {
1298                                 // en-dash
1299                                 os << "--";
1300                                 column +=2;
1301                         } else {
1302                                 // em-dash
1303                                 os << "---";
1304                                 column +=3;
1305                         }
1306                         break;
1307                 }
1308                 // fall through
1309         default:
1310                 if (c == '\0')
1311                         return;
1312
1313                 Encoding const & encoding = *(runparams.encoding);
1314                 char_type next = '\0';
1315                 if (i + 1 < int(text_.size())) {
1316                         next = text_[i + 1];
1317                         if (Encodings::isCombiningChar(next)) {
1318                                 column += latexSurrogatePair(os, c, next, runparams) - 1;
1319                                 ++i;
1320                                 break;
1321                         }
1322                 }
1323                 string script;
1324                 pair<docstring, bool> latex = encoding.latexChar(c);
1325                 docstring nextlatex;
1326                 bool nexttipas = false;
1327                 string nexttipashortcut;
1328                 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1329                         nextlatex = encoding.latexChar(next).first;
1330                         if (runparams.inIPA) {
1331                                 nexttipashortcut = Encodings::TIPAShortcut(next);
1332                                 nexttipas = !nexttipashortcut.empty();
1333                         }
1334                 }
1335                 bool tipas = false;
1336                 if (runparams.inIPA) {
1337                         string const tipashortcut = Encodings::TIPAShortcut(c);
1338                         if (!tipashortcut.empty()) {
1339                                 latex.first = from_ascii(tipashortcut);
1340                                 latex.second = false;
1341                                 tipas = true;
1342                         }
1343                 }
1344                 if (Encodings::isKnownScriptChar(c, script)
1345                     && prefixIs(latex.first, from_ascii("\\" + script)))
1346                         column += writeScriptChars(os, latex.first,
1347                                         running_change, encoding, i) - 1;
1348                 else if (latex.second
1349                          && ((!prefixIs(nextlatex, '\\')
1350                                && !prefixIs(nextlatex, '{')
1351                                && !prefixIs(nextlatex, '}'))
1352                              || (nexttipas
1353                                  && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1354                          && !tipas) {
1355                         // Prevent eating of a following
1356                         // space or command corruption by
1357                         // following characters
1358                         if (next == ' ' || next == '\0') {
1359                                 column += latex.first.length() + 1;
1360                                 os << latex.first << "{}";
1361                         } else {
1362                                 column += latex.first.length();
1363                                 os << latex.first << " ";
1364                         }
1365                 } else {
1366                         column += latex.first.length() - 1;
1367                         os << latex.first;
1368                 }
1369                 break;
1370         }
1371 }
1372
1373
1374 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1375         pos_type i, unsigned int & column)
1376 {
1377         switch (c) {
1378         case '>':
1379         case '<':
1380                 os.put(c);
1381                 // In T1 encoding, these characters exist
1382                 // but we should avoid ligatures
1383                 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1384                         return true;
1385                 os << "\\textcompwordmark" << termcmd;
1386                 column += 19;
1387                 return true;
1388         case '|':
1389                 os.put(c);
1390                 return true;
1391         case '\"':
1392                 // soul.sty breaks with \char`\"
1393                 os << "\\textquotedbl" << termcmd;
1394                 column += 14;
1395                 return true;
1396         default:
1397                 return false;
1398         }
1399 }
1400
1401
1402 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1403         pos_type i, unsigned int & column)
1404 {
1405         // TU encoding is currently on par with T1.
1406         return latexSpecialT1(c, os, i, column);
1407 }
1408
1409
1410 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1411         pos_type /*i*/, unsigned int & column)
1412 {
1413         switch (c) {
1414         case '*':
1415         case '[':
1416         case ']':
1417         case '\"':
1418                 os.put(c);
1419                 return true;
1420         case '|':
1421                 os << "\\textvertline" << termcmd;
1422                 column += 14;
1423                 return true;
1424         default:
1425                 return false;
1426         }
1427 }
1428
1429
1430 void Paragraph::Private::validate(LaTeXFeatures & features) const
1431 {
1432         if (layout_->inpreamble && inset_owner_) {
1433                 // FIXME: Using a string stream here circumvents the encoding
1434                 // switching machinery of odocstream. Therefore the
1435                 // output is wrong if this paragraph contains content
1436                 // that needs to switch encoding.
1437                 Buffer const & buf = inset_owner_->buffer();
1438                 otexstringstream os;
1439                 os << layout_->preamble();
1440                 size_t const length = os.length();
1441                 TeXOnePar(buf, buf.text(), buf.getParFromID(owner_->id()).pit(), os,
1442                           features.runparams(), string(), 0, -1, true);
1443                 if (os.length() > length)
1444                         features.addPreambleSnippet(os.release(), true);
1445         }
1446
1447         if (features.runparams().flavor == OutputParams::HTML
1448             && layout_->htmltitle()) {
1449                 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1450         }
1451
1452         // check the params.
1453         if (!params_.spacing().isDefault())
1454                 features.require("setspace");
1455
1456         // then the layouts
1457         features.useLayout(layout_->name());
1458
1459         // then the fonts
1460         fontlist_.validate(features);
1461
1462         // then the indentation
1463         if (!params_.leftIndent().zero())
1464                 features.require("ParagraphLeftIndent");
1465
1466         // then the insets
1467         InsetList::const_iterator icit = insetlist_.begin();
1468         InsetList::const_iterator iend = insetlist_.end();
1469         for (; icit != iend; ++icit) {
1470                 if (icit->inset) {
1471                         features.inDeletedInset(owner_->isDeleted(icit->pos));
1472                         if (icit->inset->lyxCode() == FOOT_CODE) {
1473                                 // FIXME: an item inset would make things much easier.
1474                                 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1475                                      || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1476                                          && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1477                                     && (icit->pos < begin_of_body_
1478                                         || (icit->pos == begin_of_body_
1479                                             && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1480                                         features.saveNoteEnv("description");
1481                         }
1482                         icit->inset->validate(features);
1483                         features.inDeletedInset(false);
1484                         if (layout_->needprotect &&
1485                             icit->inset->lyxCode() == FOOT_CODE)
1486                                 features.require("NeedLyXFootnoteCode");
1487                 }
1488         }
1489
1490         // then the contents
1491         BufferParams const bp = features.runparams().is_child
1492                 ? features.buffer().masterParams() : features.buffer().params();
1493         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1494                 char_type c = text_[i];
1495                 if (c == 0x0022) {
1496                         if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1497                                 features.require("textquotedblp");
1498                         else if (bp.main_font_encoding() != "T1"
1499                                  || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1500                                 features.require("textquotedbl");
1501                 }
1502                 if (!bp.use_dash_ligatures
1503                     && (c == 0x2013 || c == 0x2014)
1504                     && bp.useNonTeXFonts
1505                     && features.runparams().flavor == OutputParams::XETEX)
1506                         // XeTeX's dash behaviour is determined via a global setting
1507                         features.require("xetexdashbreakstate");
1508                 BufferEncodings::validate(c, features);
1509         }
1510 }
1511
1512 /////////////////////////////////////////////////////////////////////
1513 //
1514 // Paragraph
1515 //
1516 /////////////////////////////////////////////////////////////////////
1517
1518 namespace {
1519         Layout const emptyParagraphLayout;
1520 }
1521
1522 Paragraph::Paragraph()
1523         : d(new Paragraph::Private(this, emptyParagraphLayout))
1524 {
1525         itemdepth = 0;
1526         d->params_.clear();
1527 }
1528
1529
1530 Paragraph::Paragraph(Paragraph const & par)
1531         : itemdepth(par.itemdepth),
1532         d(new Paragraph::Private(*par.d, this))
1533 {
1534         registerWords();
1535 }
1536
1537
1538 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1539         : itemdepth(par.itemdepth),
1540         d(new Paragraph::Private(*par.d, this, beg, end))
1541 {
1542         registerWords();
1543 }
1544
1545
1546 Paragraph & Paragraph::operator=(Paragraph const & par)
1547 {
1548         // needed as we will destroy the private part before copying it
1549         if (&par != this) {
1550                 itemdepth = par.itemdepth;
1551
1552                 deregisterWords();
1553                 delete d;
1554                 d = new Private(*par.d, this);
1555                 registerWords();
1556         }
1557         return *this;
1558 }
1559
1560
1561 Paragraph::~Paragraph()
1562 {
1563         deregisterWords();
1564         delete d;
1565 }
1566
1567
1568 namespace {
1569
1570 // this shall be called just before every "os << ..." action.
1571 void flushString(ostream & os, docstring & s)
1572 {
1573         os << to_utf8(s);
1574         s.erase();
1575 }
1576
1577 } // namespace
1578
1579
1580 void Paragraph::write(ostream & os, BufferParams const & bparams,
1581         depth_type & dth) const
1582 {
1583         // The beginning or end of a deeper (i.e. nested) area?
1584         if (dth != d->params_.depth()) {
1585                 if (d->params_.depth() > dth) {
1586                         while (d->params_.depth() > dth) {
1587                                 os << "\n\\begin_deeper";
1588                                 ++dth;
1589                         }
1590                 } else {
1591                         while (d->params_.depth() < dth) {
1592                                 os << "\n\\end_deeper";
1593                                 --dth;
1594                         }
1595                 }
1596         }
1597
1598         // First write the layout
1599         os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1600
1601         d->params_.write(os);
1602
1603         Font font1(inherit_font, bparams.language);
1604
1605         Change running_change = Change(Change::UNCHANGED);
1606
1607         // this string is used as a buffer to avoid repetitive calls
1608         // to to_utf8(), which turn out to be expensive (JMarc)
1609         docstring write_buffer;
1610
1611         int column = 0;
1612         for (pos_type i = 0; i <= size(); ++i) {
1613
1614                 Change const & change = lookupChange(i);
1615                 if (change != running_change)
1616                         flushString(os, write_buffer);
1617                 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1618                 running_change = change;
1619
1620                 if (i == size())
1621                         break;
1622
1623                 // Write font changes
1624                 Font font2 = getFontSettings(bparams, i);
1625                 if (font2 != font1) {
1626                         flushString(os, write_buffer);
1627                         font2.lyxWriteChanges(font1, os);
1628                         column = 0;
1629                         font1 = font2;
1630                 }
1631
1632                 char_type const c = d->text_[i];
1633                 switch (c) {
1634                 case META_INSET:
1635                         if (Inset const * inset = getInset(i)) {
1636                                 flushString(os, write_buffer);
1637                                 if (inset->directWrite()) {
1638                                         // international char, let it write
1639                                         // code directly so it's shorter in
1640                                         // the file
1641                                         inset->write(os);
1642                                 } else {
1643                                         if (i)
1644                                                 os << '\n';
1645                                         os << "\\begin_inset ";
1646                                         inset->write(os);
1647                                         os << "\n\\end_inset\n\n";
1648                                         column = 0;
1649                                 }
1650                                 // FIXME This can be removed again once the mystery
1651                                 // crash has been resolved.
1652                                 os << flush;
1653                         }
1654                         break;
1655                 case '\\':
1656                         flushString(os, write_buffer);
1657                         os << "\n\\backslash\n";
1658                         column = 0;
1659                         break;
1660                 case '.':
1661                         flushString(os, write_buffer);
1662                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1663                                 os << ".\n";
1664                                 column = 0;
1665                         } else
1666                                 os << '.';
1667                         break;
1668                 default:
1669                         if ((column > 70 && c == ' ')
1670                             || column > 79) {
1671                                 flushString(os, write_buffer);
1672                                 os << '\n';
1673                                 column = 0;
1674                         }
1675                         // this check is to amend a bug. LyX sometimes
1676                         // inserts '\0' this could cause problems.
1677                         if (c != '\0')
1678                                 write_buffer.push_back(c);
1679                         else
1680                                 LYXERR0("NUL char in structure.");
1681                         ++column;
1682                         break;
1683                 }
1684         }
1685
1686         flushString(os, write_buffer);
1687         os << "\n\\end_layout\n";
1688         // FIXME This can be removed again once the mystery
1689         // crash has been resolved.
1690         os << flush;
1691 }
1692
1693
1694 void Paragraph::validate(LaTeXFeatures & features) const
1695 {
1696         d->validate(features);
1697         if (needsCProtection())
1698                 features.require("cprotect");
1699 }
1700
1701
1702 void Paragraph::insert(pos_type start, docstring const & str,
1703                        Font const & font, Change const & change)
1704 {
1705         for (size_t i = 0, n = str.size(); i != n ; ++i)
1706                 insertChar(start + i, str[i], font, change);
1707 }
1708
1709
1710 void Paragraph::appendChar(char_type c, Font const & font,
1711                 Change const & change)
1712 {
1713         // track change
1714         d->changes_.insert(change, d->text_.size());
1715         // when appending characters, no need to update tables
1716         d->text_.push_back(c);
1717         setFont(d->text_.size() - 1, font);
1718         d->requestSpellCheck(d->text_.size() - 1);
1719 }
1720
1721
1722 void Paragraph::appendString(docstring const & s, Font const & font,
1723                 Change const & change)
1724 {
1725         pos_type end = s.size();
1726         size_t oldsize = d->text_.size();
1727         size_t newsize = oldsize + end;
1728         size_t capacity = d->text_.capacity();
1729         if (newsize >= capacity)
1730                 d->text_.reserve(max(capacity + 100, newsize));
1731
1732         // when appending characters, no need to update tables
1733         d->text_.append(s);
1734
1735         // FIXME: Optimize this!
1736         for (size_t i = oldsize; i != newsize; ++i) {
1737                 // track change
1738                 d->changes_.insert(change, i);
1739                 d->requestSpellCheck(i);
1740         }
1741         d->fontlist_.set(oldsize, font);
1742         d->fontlist_.set(newsize - 1, font);
1743 }
1744
1745
1746 void Paragraph::insertChar(pos_type pos, char_type c,
1747                            bool trackChanges)
1748 {
1749         d->insertChar(pos, c, Change(trackChanges ?
1750                            Change::INSERTED : Change::UNCHANGED));
1751 }
1752
1753
1754 void Paragraph::insertChar(pos_type pos, char_type c,
1755                            Font const & font, bool trackChanges)
1756 {
1757         d->insertChar(pos, c, Change(trackChanges ?
1758                            Change::INSERTED : Change::UNCHANGED));
1759         setFont(pos, font);
1760 }
1761
1762
1763 void Paragraph::insertChar(pos_type pos, char_type c,
1764                            Font const & font, Change const & change)
1765 {
1766         d->insertChar(pos, c, change);
1767         setFont(pos, font);
1768 }
1769
1770
1771 void Paragraph::resetFonts(Font const & font)
1772 {
1773         d->fontlist_.clear();
1774         d->fontlist_.set(0, font);
1775         d->fontlist_.set(d->text_.size() - 1, font);
1776 }
1777
1778 // Gets uninstantiated font setting at position.
1779 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1780                                          pos_type pos) const
1781 {
1782         if (pos > size()) {
1783                 LYXERR0("pos: " << pos << " size: " << size());
1784                 LBUFERR(false);
1785         }
1786
1787         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1788         if (cit != d->fontlist_.end())
1789                 return cit->font();
1790
1791         if (pos == size() && !empty())
1792                 return getFontSettings(bparams, pos - 1);
1793
1794         // Optimisation: avoid a full font instantiation if there is no
1795         // language change from previous call.
1796         static Font previous_font;
1797         static Language const * previous_lang = 0;
1798         Language const * lang = getParLanguage(bparams);
1799         if (lang != previous_lang) {
1800                 previous_lang = lang;
1801                 previous_font = Font(inherit_font, lang);
1802         }
1803         return previous_font;
1804 }
1805
1806
1807 FontSpan Paragraph::fontSpan(pos_type pos) const
1808 {
1809         LBUFERR(pos <= size());
1810
1811         if (pos == size())
1812                 return FontSpan(pos, pos);
1813
1814         pos_type start = 0;
1815         FontList::const_iterator cit = d->fontlist_.begin();
1816         FontList::const_iterator end = d->fontlist_.end();
1817         for (; cit != end; ++cit) {
1818                 if (cit->pos() >= pos) {
1819                         if (pos >= beginOfBody())
1820                                 return FontSpan(max(start, beginOfBody()),
1821                                                 cit->pos());
1822                         else
1823                                 return FontSpan(start,
1824                                                 min(beginOfBody() - 1,
1825                                                          cit->pos()));
1826                 }
1827                 start = cit->pos() + 1;
1828         }
1829
1830         // This should not happen, but if so, we take no chances.
1831         LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1832         LASSERT(false, return FontSpan(pos, pos));
1833 }
1834
1835
1836 // Gets uninstantiated font setting at position 0
1837 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1838 {
1839         if (!empty() && !d->fontlist_.empty())
1840                 return d->fontlist_.begin()->font();
1841
1842         // Optimisation: avoid a full font instantiation if there is no
1843         // language change from previous call.
1844         static Font previous_font;
1845         static Language const * previous_lang = 0;
1846         if (bparams.language != previous_lang) {
1847                 previous_lang = bparams.language;
1848                 previous_font = Font(inherit_font, bparams.language);
1849         }
1850
1851         return previous_font;
1852 }
1853
1854
1855 // Gets the fully instantiated font at a given position in a paragraph
1856 // This is basically the same function as Text::GetFont() in text2.cpp.
1857 // The difference is that this one is used for generating the LaTeX file,
1858 // and thus cosmetic "improvements" are disallowed: This has to deliver
1859 // the true picture of the buffer. (Asger)
1860 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1861                                  Font const & outerfont) const
1862 {
1863         LBUFERR(pos >= 0);
1864
1865         Font font = getFontSettings(bparams, pos);
1866
1867         pos_type const body_pos = beginOfBody();
1868         FontInfo & fi = font.fontInfo();
1869         if (pos < body_pos)
1870                 fi.realize(d->layout_->labelfont);
1871         else
1872                 fi.realize(d->layout_->font);
1873
1874         fi.realize(outerfont.fontInfo());
1875         fi.realize(bparams.getFont().fontInfo());
1876
1877         return font;
1878 }
1879
1880
1881 Font const Paragraph::getLabelFont
1882         (BufferParams const & bparams, Font const & outerfont) const
1883 {
1884         FontInfo tmpfont = d->layout_->labelfont;
1885         tmpfont.realize(outerfont.fontInfo());
1886         tmpfont.realize(bparams.getFont().fontInfo());
1887         return Font(tmpfont, getParLanguage(bparams));
1888 }
1889
1890
1891 Font const Paragraph::getLayoutFont
1892         (BufferParams const & bparams, Font const & outerfont) const
1893 {
1894         FontInfo tmpfont = d->layout_->font;
1895         tmpfont.realize(outerfont.fontInfo());
1896         tmpfont.realize(bparams.getFont().fontInfo());
1897         return Font(tmpfont, getParLanguage(bparams));
1898 }
1899
1900
1901 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1902 {
1903         char_type c = d->text_[pos];
1904         if (!getFontSettings(bparams, pos).isRightToLeft())
1905                 return c;
1906
1907         // FIXME: The arabic special casing is due to the difference of arabic
1908         // round brackets input introduced in r18599. Check if this should be
1909         // unified with Hebrew or at least if all bracket types should be
1910         // handled the same (file format change in either case).
1911         string const & lang = getFontSettings(bparams, pos).language()->lang();
1912         bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1913                 || lang == "farsi";
1914         char_type uc = c;
1915         switch (c) {
1916         case '(':
1917                 uc = arabic ? c : ')';
1918                 break;
1919         case ')':
1920                 uc = arabic ? c : '(';
1921                 break;
1922         case '[':
1923                 uc = ']';
1924                 break;
1925         case ']':
1926                 uc = '[';
1927                 break;
1928         case '{':
1929                 uc = '}';
1930                 break;
1931         case '}':
1932                 uc = '{';
1933                 break;
1934         case '<':
1935                 uc = '>';
1936                 break;
1937         case '>':
1938                 uc = '<';
1939                 break;
1940         }
1941
1942         return uc;
1943 }
1944
1945
1946 void Paragraph::setFont(pos_type pos, Font const & font)
1947 {
1948         LASSERT(pos <= size(), return);
1949
1950         // First, reduce font against layout/label font
1951         // Update: The setCharFont() routine in text2.cpp already
1952         // reduces font, so we don't need to do that here. (Asger)
1953
1954         d->fontlist_.set(pos, font);
1955 }
1956
1957
1958 void Paragraph::makeSameLayout(Paragraph const & par)
1959 {
1960         d->layout_ = par.d->layout_;
1961         d->params_ = par.d->params_;
1962 }
1963
1964
1965 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1966 {
1967         if (isFreeSpacing())
1968                 return false;
1969
1970         int pos = 0;
1971         int count = 0;
1972
1973         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1974                 if (eraseChar(pos, trackChanges))
1975                         ++count;
1976                 else
1977                         ++pos;
1978         }
1979
1980         return count > 0 || pos > 0;
1981 }
1982
1983
1984 bool Paragraph::hasSameLayout(Paragraph const & par) const
1985 {
1986         return par.d->layout_ == d->layout_
1987                 && d->params_.sameLayout(par.d->params_);
1988 }
1989
1990
1991 depth_type Paragraph::getDepth() const
1992 {
1993         return d->params_.depth();
1994 }
1995
1996
1997 depth_type Paragraph::getMaxDepthAfter() const
1998 {
1999         if (d->layout_->isEnvironment())
2000                 return d->params_.depth() + 1;
2001         else
2002                 return d->params_.depth();
2003 }
2004
2005
2006 LyXAlignment Paragraph::getAlign() const
2007 {
2008         if (d->params_.align() == LYX_ALIGN_LAYOUT)
2009                 return d->layout_->align;
2010         else
2011                 return d->params_.align();
2012 }
2013
2014
2015 docstring const & Paragraph::labelString() const
2016 {
2017         return d->params_.labelString();
2018 }
2019
2020
2021 // the next two functions are for the manual labels
2022 docstring const Paragraph::getLabelWidthString() const
2023 {
2024         if (d->layout_->margintype == MARGIN_MANUAL
2025             || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2026                 return d->params_.labelWidthString();
2027         else
2028                 return _("Senseless with this layout!");
2029 }
2030
2031
2032 void Paragraph::setLabelWidthString(docstring const & s)
2033 {
2034         d->params_.labelWidthString(s);
2035 }
2036
2037
2038 docstring Paragraph::expandLabel(Layout const & layout,
2039                 BufferParams const & bparams) const
2040 {
2041         return expandParagraphLabel(layout, bparams, true);
2042 }
2043
2044
2045 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2046                 BufferParams const & bparams) const
2047 {
2048         return expandParagraphLabel(layout, bparams, false);
2049 }
2050
2051
2052 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2053                 BufferParams const & bparams, bool process_appendix) const
2054 {
2055         DocumentClass const & tclass = bparams.documentClass();
2056         string const & lang = getParLanguage(bparams)->code();
2057         bool const in_appendix = process_appendix && d->params_.appendix();
2058         docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2059
2060         if (fmt.empty() && !layout.counter.empty())
2061                 return tclass.counters().theCounter(layout.counter, lang);
2062
2063         // handle 'inherited level parts' in 'fmt',
2064         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
2065         size_t const i = fmt.find('@', 0);
2066         if (i != docstring::npos) {
2067                 size_t const j = fmt.find('@', i + 1);
2068                 if (j != docstring::npos) {
2069                         docstring parent(fmt, i + 1, j - i - 1);
2070                         docstring label = from_ascii("??");
2071                         if (tclass.hasLayout(parent))
2072                                 label = expandParagraphLabel(tclass[parent], bparams,
2073                                                       process_appendix);
2074                         fmt = docstring(fmt, 0, i) + label
2075                                 + docstring(fmt, j + 1, docstring::npos);
2076                 }
2077         }
2078
2079         return tclass.counters().counterLabel(fmt, lang);
2080 }
2081
2082
2083 void Paragraph::applyLayout(Layout const & new_layout)
2084 {
2085         d->layout_ = &new_layout;
2086         LyXAlignment const oldAlign = d->params_.align();
2087
2088         if (!(oldAlign & d->layout_->alignpossible)) {
2089                 frontend::Alert::warning(_("Alignment not permitted"),
2090                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
2091                 d->params_.align(LYX_ALIGN_LAYOUT);
2092         }
2093 }
2094
2095
2096 pos_type Paragraph::beginOfBody() const
2097 {
2098         return d->begin_of_body_;
2099 }
2100
2101
2102 void Paragraph::setBeginOfBody()
2103 {
2104         if (d->layout_->labeltype != LABEL_MANUAL) {
2105                 d->begin_of_body_ = 0;
2106                 return;
2107         }
2108
2109         // Unroll the first two cycles of the loop
2110         // and remember the previous character to
2111         // remove unnecessary getChar() calls
2112         pos_type i = 0;
2113         pos_type end = size();
2114         if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2115                 ++i;
2116                 if (i < end) {
2117                         char_type previous_char = d->text_[i];
2118                         if (!(isNewline(i) || isEnvSeparator(i))) {
2119                                 ++i;
2120                                 while (i < end && previous_char != ' ') {
2121                                         char_type temp = d->text_[i];
2122                                         if (isNewline(i) || isEnvSeparator(i))
2123                                                 break;
2124                                         ++i;
2125                                         previous_char = temp;
2126                                 }
2127                         }
2128                 }
2129         }
2130
2131         d->begin_of_body_ = i;
2132 }
2133
2134
2135 bool Paragraph::allowParagraphCustomization() const
2136 {
2137         return inInset().allowParagraphCustomization();
2138 }
2139
2140
2141 bool Paragraph::usePlainLayout() const
2142 {
2143         return inInset().usePlainLayout();
2144 }
2145
2146
2147 bool Paragraph::isPassThru() const
2148 {
2149         return inInset().isPassThru() || d->layout_->pass_thru;
2150 }
2151
2152 namespace {
2153
2154 // paragraphs inside floats need different alignment tags to avoid
2155 // unwanted space
2156
2157 bool noTrivlistCentering(InsetCode code)
2158 {
2159         return code == FLOAT_CODE
2160                || code == WRAP_CODE
2161                || code == CELL_CODE;
2162 }
2163
2164
2165 string correction(string const & orig)
2166 {
2167         if (orig == "flushleft")
2168                 return "raggedright";
2169         if (orig == "flushright")
2170                 return "raggedleft";
2171         if (orig == "center")
2172                 return "centering";
2173         return orig;
2174 }
2175
2176
2177 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2178         InsetCode code, bool const lastpar, int & col)
2179 {
2180         string macro = suffix + "{";
2181         if (noTrivlistCentering(code)) {
2182                 if (lastpar) {
2183                         // the last paragraph in non-trivlist-aligned
2184                         // context is special (to avoid unwanted whitespace)
2185                         if (suffix == "\\begin") {
2186                                 macro = "\\" + correction(env) + "{}";
2187                                 os << from_ascii(macro);
2188                                 col += macro.size();
2189                                 return true;
2190                         }
2191                         return false;
2192                 }
2193                 macro += correction(env);
2194         } else
2195                 macro += env;
2196         macro += "}";
2197         if (suffix == "\\par\\end") {
2198                 os << breakln;
2199                 col = 0;
2200         }
2201         os << from_ascii(macro);
2202         col += macro.size();
2203         if (suffix == "\\begin") {
2204                 os << breakln;
2205                 col = 0;
2206         }
2207         return true;
2208 }
2209
2210 } // namespace
2211
2212
2213 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2214                         otexstream & os, OutputParams const & runparams) const
2215 {
2216         int column = 0;
2217
2218         bool canindent =
2219                 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2220                         (layout_->toggle_indent != ITOGGLE_NEVER) :
2221                         (layout_->toggle_indent == ITOGGLE_ALWAYS);
2222
2223         if (canindent && params_.noindent() && !layout_->pass_thru) {
2224                 os << "\\noindent ";
2225                 column += 10;
2226         }
2227
2228         LyXAlignment const curAlign = params_.align();
2229
2230         if (curAlign == layout_->align)
2231                 return column;
2232
2233         switch (curAlign) {
2234         case LYX_ALIGN_NONE:
2235         case LYX_ALIGN_BLOCK:
2236         case LYX_ALIGN_LAYOUT:
2237         case LYX_ALIGN_SPECIAL:
2238         case LYX_ALIGN_DECIMAL:
2239                 break;
2240         case LYX_ALIGN_LEFT:
2241         case LYX_ALIGN_RIGHT:
2242         case LYX_ALIGN_CENTER:
2243                 if (runparams.moving_arg) {
2244                         os << "\\protect";
2245                         column += 8;
2246                 }
2247                 break;
2248         }
2249
2250         string const begin_tag = "\\begin";
2251         InsetCode code = ownerCode();
2252         bool const lastpar = runparams.isLastPar;
2253
2254         switch (curAlign) {
2255         case LYX_ALIGN_NONE:
2256         case LYX_ALIGN_BLOCK:
2257         case LYX_ALIGN_LAYOUT:
2258         case LYX_ALIGN_SPECIAL:
2259         case LYX_ALIGN_DECIMAL:
2260                 break;
2261         case LYX_ALIGN_LEFT: {
2262                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2263                         corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2264                 else
2265                         corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2266                 break;
2267         } case LYX_ALIGN_RIGHT: {
2268                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2269                         corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2270                 else
2271                         corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2272                 break;
2273         } case LYX_ALIGN_CENTER: {
2274                 corrected_env(os, begin_tag, "center", code, lastpar, column);
2275                 break;
2276         }
2277         }
2278
2279         return column;
2280 }
2281
2282
2283 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2284                         otexstream & os, OutputParams const & runparams) const
2285 {
2286         LyXAlignment const curAlign = params_.align();
2287
2288         if (curAlign == layout_->align)
2289                 return false;
2290
2291         switch (curAlign) {
2292         case LYX_ALIGN_NONE:
2293         case LYX_ALIGN_BLOCK:
2294         case LYX_ALIGN_LAYOUT:
2295         case LYX_ALIGN_SPECIAL:
2296         case LYX_ALIGN_DECIMAL:
2297                 break;
2298         case LYX_ALIGN_LEFT:
2299         case LYX_ALIGN_RIGHT:
2300         case LYX_ALIGN_CENTER:
2301                 if (runparams.moving_arg)
2302                         os << "\\protect";
2303                 break;
2304         }
2305
2306         bool output = false;
2307         int col = 0;
2308         string const end_tag = "\\par\\end";
2309         InsetCode code = ownerCode();
2310         bool const lastpar = runparams.isLastPar;
2311
2312         switch (curAlign) {
2313         case LYX_ALIGN_NONE:
2314         case LYX_ALIGN_BLOCK:
2315         case LYX_ALIGN_LAYOUT:
2316         case LYX_ALIGN_SPECIAL:
2317         case LYX_ALIGN_DECIMAL:
2318                 break;
2319         case LYX_ALIGN_LEFT: {
2320                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2321                         output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2322                 else
2323                         output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2324                 break;
2325         } case LYX_ALIGN_RIGHT: {
2326                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2327                         output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2328                 else
2329                         output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2330                 break;
2331         } case LYX_ALIGN_CENTER: {
2332                 corrected_env(os, end_tag, "center", code, lastpar, col);
2333                 break;
2334         }
2335         }
2336
2337         return output || lastpar;
2338 }
2339
2340
2341 // This one spits out the text of the paragraph
2342 void Paragraph::latex(BufferParams const & bparams,
2343         Font const & outerfont,
2344         otexstream & os,
2345         OutputParams const & runparams,
2346         int start_pos, int end_pos, bool force) const
2347 {
2348         LYXERR(Debug::LATEX, "Paragraph::latex...     " << this);
2349
2350         // FIXME This check should not be needed. Perhaps issue an
2351         // error if it triggers.
2352         Layout const & style = inInset().forcePlainLayout() ?
2353                 bparams.documentClass().plainLayout() : *d->layout_;
2354
2355         if (!force && style.inpreamble)
2356                 return;
2357
2358         bool const allowcust = allowParagraphCustomization();
2359
2360         // Current base font for all inherited font changes, without any
2361         // change caused by an individual character, except for the language:
2362         // It is set to the language of the first character.
2363         // As long as we are in the label, this font is the base font of the
2364         // label. Before the first body character it is set to the base font
2365         // of the body.
2366         Font basefont;
2367
2368         // Maybe we have to create a optional argument.
2369         pos_type body_pos = beginOfBody();
2370         unsigned int column = 0;
2371
2372         if (body_pos > 0) {
2373                 // the optional argument is kept in curly brackets in
2374                 // case it contains a ']'
2375                 // This is not strictly needed, but if this is changed it
2376                 // would be a file format change, and tex2lyx would need
2377                 // to be adjusted, since it unconditionally removes the
2378                 // braces when it parses \item.
2379                 os << "[{";
2380                 column += 2;
2381                 basefont = getLabelFont(bparams, outerfont);
2382         } else {
2383                 basefont = getLayoutFont(bparams, outerfont);
2384         }
2385
2386         // Which font is currently active?
2387         Font running_font(basefont);
2388         // Do we have an open font change?
2389         bool open_font = false;
2390
2391         Change runningChange = Change(Change::UNCHANGED);
2392
2393         Encoding const * const prev_encoding = runparams.encoding;
2394
2395         os.texrow().start(id(), 0);
2396
2397         // if the paragraph is empty, the loop will not be entered at all
2398         if (empty()) {
2399                 // For InTitle commands, we have already opened a group
2400                 // in output_latex::TeXOnePar.
2401                 if (style.isCommand() && !style.intitle) {
2402                         os << '{';
2403                         ++column;
2404                 }
2405                 if (!style.leftdelim().empty()) {
2406                         os << style.leftdelim();
2407                         column += style.leftdelim().size();
2408                 }
2409                 if (allowcust)
2410                         column += d->startTeXParParams(bparams, os, runparams);
2411         }
2412
2413         // Whether a \par can be issued for insets typeset inline with text.
2414         // Yes if greater than 0. This has to be static.
2415         THREAD_LOCAL_STATIC int parInline = 0;
2416
2417         for (pos_type i = 0; i < size(); ++i) {
2418                 // First char in paragraph or after label?
2419                 if (i == body_pos) {
2420                         if (body_pos > 0) {
2421                                 if (open_font) {
2422                                         bool needPar = false;
2423                                         column += running_font.latexWriteEndChanges(
2424                                                 os, bparams, runparams,
2425                                                 basefont, basefont, needPar);
2426                                         open_font = false;
2427                                 }
2428                                 basefont = getLayoutFont(bparams, outerfont);
2429                                 running_font = basefont;
2430
2431                                 column += Changes::latexMarkChange(os, bparams,
2432                                                 runningChange, Change(Change::UNCHANGED),
2433                                                 runparams);
2434                                 runningChange = Change(Change::UNCHANGED);
2435
2436                                 os << "}] ";
2437                                 column +=3;
2438                         }
2439                         // For InTitle commands, we have already opened a group
2440                         // in output_latex::TeXOnePar.
2441                         if (style.isCommand() && !style.intitle) {
2442                                 os << '{';
2443                                 ++column;
2444                         }
2445
2446                         if (!style.leftdelim().empty()) {
2447                                 os << style.leftdelim();
2448                                 column += style.leftdelim().size();
2449                         }
2450
2451                         if (allowcust)
2452                                 column += d->startTeXParParams(bparams, os,
2453                                                             runparams);
2454                 }
2455
2456                 runparams.wasDisplayMath = runparams.inDisplayMath;
2457                 runparams.inDisplayMath = false;
2458                 bool deleted_display_math = false;
2459                 Change const & change = runparams.inDeletedInset
2460                         ? runparams.changeOfDeletedInset : lookupChange(i);
2461
2462                 // Check whether a display math inset follows
2463                 if (d->text_[i] == META_INSET
2464                     && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2465                         InsetMath const * im = getInset(i)->asInsetMath();
2466                         if (im && im->asHullInset()
2467                             && im->asHullInset()->outerDisplay()) {
2468                                 runparams.inDisplayMath = true;
2469                                 // runparams.inDeletedInset will be set by
2470                                 // latexInset later, but we need this info
2471                                 // before it is called. On the other hand, we
2472                                 // cannot set it here because it is a counter.
2473                                 deleted_display_math = isDeleted(i);
2474                         }
2475                         if (bparams.output_changes && deleted_display_math
2476                             && runningChange == change
2477                             && change.type == Change::DELETED
2478                             && !os.afterParbreak()) {
2479                                 // A display math in the same paragraph follows.
2480                                 // We have to close and then reopen \lyxdeleted,
2481                                 // otherwise the math will be shifted up.
2482                                 OutputParams rp = runparams;
2483                                 if (open_font) {
2484                                         bool needPar = false;
2485                                         column += running_font.latexWriteEndChanges(
2486                                                 os, bparams, rp, basefont,
2487                                                 basefont, needPar);
2488                                         open_font = false;
2489                                 }
2490                                 basefont = getLayoutFont(bparams, outerfont);
2491                                 running_font = basefont;
2492                                 column += Changes::latexMarkChange(os, bparams,
2493                                         Change(Change::INSERTED), change, rp);
2494                         }
2495                 }
2496
2497                 if (bparams.output_changes && runningChange != change) {
2498                         if (open_font) {
2499                                 bool needPar = false;
2500                                 column += running_font.latexWriteEndChanges(
2501                                                 os, bparams, runparams,
2502                                                 basefont, basefont, needPar);
2503                                 open_font = false;
2504                         }
2505                         basefont = getLayoutFont(bparams, outerfont);
2506                         running_font = basefont;
2507                         column += Changes::latexMarkChange(os, bparams, runningChange,
2508                                                            change, runparams);
2509                         runningChange = change;
2510                 }
2511
2512                 // do not output text which is marked deleted
2513                 // if change tracking output is disabled
2514                 if (!bparams.output_changes && change.deleted()) {
2515                         continue;
2516                 }
2517
2518                 ++column;
2519
2520                 // Fully instantiated font
2521                 Font const current_font = getFont(bparams, i, outerfont);
2522
2523                 Font const last_font = running_font;
2524
2525                 // Do we need to close the previous font?
2526                 if (open_font &&
2527                     (current_font != running_font ||
2528                      current_font.language() != running_font.language()))
2529                 {
2530                         bool needPar = false;
2531                         column += running_font.latexWriteEndChanges(
2532                                     os, bparams, runparams, basefont,
2533                                     (i == body_pos-1) ? basefont : current_font,
2534                                     needPar);
2535                         running_font = basefont;
2536                         open_font = false;
2537                 }
2538
2539                 string const running_lang = runparams.use_polyglossia ?
2540                         running_font.language()->polyglossia() : running_font.language()->babel();
2541                 // close babel's font environment before opening CJK.
2542                 string const lang_end_command = runparams.use_polyglossia ?
2543                         "\\end{$$lang}" : lyxrc.language_command_end;
2544                 bool const using_begin_end = runparams.use_polyglossia ||
2545                                                 !lang_end_command.empty();
2546                 if (!running_lang.empty() &&
2547                     (!using_begin_end || running_lang == openLanguageName()) &&
2548                     current_font.language()->encoding()->package() == Encoding::CJK) {
2549                                 string end_tag = subst(lang_end_command,
2550                                                         "$$lang",
2551                                                         running_lang);
2552                                 os << from_ascii(end_tag);
2553                                 column += end_tag.length();
2554                                 if (using_begin_end)
2555                                         popLanguageName();
2556                 }
2557
2558                 // Switch file encoding if necessary (and allowed)
2559                 if (!runparams.pass_thru && !style.pass_thru &&
2560                     runparams.encoding->package() != Encoding::none &&
2561                     current_font.language()->encoding()->package() != Encoding::none) {
2562                         pair<bool, int> const enc_switch =
2563                                 switchEncoding(os.os(), bparams, runparams,
2564                                         *(current_font.language()->encoding()));
2565                         if (enc_switch.first) {
2566                                 column += enc_switch.second;
2567                                 runparams.encoding = current_font.language()->encoding();
2568                         }
2569                 }
2570
2571                 char_type const c = d->text_[i];
2572
2573                 // A display math inset inside an ulem command will be output
2574                 // as a box of width \linewidth, so we have to either disable
2575                 // indentation if the inset starts a paragraph, or start a new
2576                 // line to accommodate such box. This has to be done before
2577                 // writing any font changing commands.
2578                 if (runparams.inDisplayMath && !deleted_display_math
2579                     && runparams.inulemcmd) {
2580                         if (os.afterParbreak())
2581                                 os << "\\noindent";
2582                         else
2583                                 os << "\\\\\n";
2584                 }
2585
2586                 // Do we need to change font?
2587                 if ((current_font != running_font ||
2588                      current_font.language() != running_font.language()) &&
2589                         i != body_pos - 1)
2590                 {
2591                         odocstringstream ods;
2592                         column += current_font.latexWriteStartChanges(ods, bparams,
2593                                                               runparams, basefont,
2594                                                               last_font);
2595                         // Check again for display math in ulem commands as a
2596                         // font change may also occur just before a math inset.
2597                         if (runparams.inDisplayMath && !deleted_display_math
2598                             && runparams.inulemcmd) {
2599                                 if (os.afterParbreak())
2600                                         os << "\\noindent";
2601                                 else
2602                                         os << "\\\\\n";
2603                         }
2604                         running_font = current_font;
2605                         open_font = true;
2606                         docstring fontchange = ods.str();
2607                         // check whether the fontchange ends with a \\textcolor
2608                         // modifier and the text starts with a space (bug 4473)
2609                         docstring const last_modifier = rsplit(fontchange, '\\');
2610                         if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2611                                 os << fontchange << from_ascii("{}");
2612                         // check if the fontchange ends with a trailing blank
2613                         // (like "\small " (see bug 3382)
2614                         else if (suffixIs(fontchange, ' ') && c == ' ')
2615                                 os << fontchange.substr(0, fontchange.size() - 1)
2616                                    << from_ascii("{}");
2617                         else
2618                                 os << fontchange;
2619                 }
2620
2621                 // FIXME: think about end_pos implementation...
2622                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2623                         // FIXME: integrate this case in latexSpecialChar
2624                         // Do not print the separation of the optional argument
2625                         // if style.pass_thru is false. This works because
2626                         // latexSpecialChar ignores spaces if
2627                         // style.pass_thru is false.
2628                         if (i != body_pos - 1) {
2629                                 if (d->simpleTeXBlanks(runparams, os,
2630                                                 i, column, current_font, style)) {
2631                                         // A surrogate pair was output. We
2632                                         // must not call latexSpecialChar
2633                                         // in this iteration, since it would output
2634                                         // the combining character again.
2635                                         ++i;
2636                                         continue;
2637                                 }
2638                         }
2639                 }
2640
2641                 OutputParams rp = runparams;
2642                 rp.free_spacing = style.free_spacing;
2643                 rp.local_font = &current_font;
2644                 rp.intitle = style.intitle;
2645
2646                 // Two major modes:  LaTeX or plain
2647                 // Handle here those cases common to both modes
2648                 // and then split to handle the two modes separately.
2649                 if (c == META_INSET) {
2650                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2651                                 // Greyedout notes and, in general, all insets
2652                                 // with InsetLayout::isDisplay() == false,
2653                                 // are typeset inline with the text. So, we
2654                                 // can add a \par to the last paragraph of
2655                                 // such insets only if nothing else follows.
2656                                 bool incremented = false;
2657                                 Inset const * inset = getInset(i);
2658                                 InsetText const * textinset = inset
2659                                                         ? inset->asInsetText()
2660                                                         : 0;
2661                                 if (i + 1 == size() && textinset
2662                                     && !inset->getLayout().isDisplay()) {
2663                                         ParagraphList const & pars =
2664                                                 textinset->text().paragraphs();
2665                                         pit_type const pit = pars.size() - 1;
2666                                         Font const lastfont =
2667                                                 pit < 0 || pars[pit].empty()
2668                                                 ? pars[pit].getLayoutFont(
2669                                                                 bparams,
2670                                                                 outerfont)
2671                                                 : pars[pit].getFont(bparams,
2672                                                         pars[pit].size() - 1,
2673                                                         outerfont);
2674                                         if (lastfont.fontInfo().size() !=
2675                                             basefont.fontInfo().size()) {
2676                                                 ++parInline;
2677                                                 incremented = true;
2678                                         }
2679                                 }
2680                                 d->latexInset(bparams, os, rp, running_font,
2681                                                 basefont, outerfont, open_font,
2682                                                 runningChange, style, i, column);
2683                                 if (incremented)
2684                                         --parInline;
2685                         }
2686                 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2687                         try {
2688                                 d->latexSpecialChar(os, bparams, rp,
2689                                                     running_font, runningChange,
2690                                                     style, i, end_pos, column);
2691                         } catch (EncodingException & e) {
2692                                 if (runparams.dryrun) {
2693                                         os << "<" << _("LyX Warning: ")
2694                                            << _("uncodable character") << " '";
2695                                         os.put(c);
2696                                         os << "'>";
2697                                 } else {
2698                                         // add location information and throw again.
2699                                         e.par_id = id();
2700                                         e.pos = i;
2701                                         throw(e);
2702                                 }
2703                         }
2704                 }
2705
2706                 // Set the encoding to that returned from latexSpecialChar (see
2707                 // comment for encoding member in OutputParams.h)
2708                 runparams.encoding = rp.encoding;
2709
2710                 // Also carry on the info on a closed ulem command for insets
2711                 // such as Note that do not produce any output, so that no
2712                 // command is ever executed but its opening was recorded.
2713                 runparams.inulemcmd = rp.inulemcmd;
2714         }
2715
2716         // If we have an open font definition, we have to close it
2717         if (open_font) {
2718                 // Make sure that \\par is done with the font of the last
2719                 // character if this has another size as the default.
2720                 // This is necessary because LaTeX (and LyX on the screen)
2721                 // calculates the space between the baselines according
2722                 // to this font. (Matthias)
2723                 //
2724                 // We must not change the font for the last paragraph
2725                 // of non-multipar insets, tabular cells or commands,
2726                 // since this produces unwanted whitespace.
2727
2728                 Font const font = empty()
2729                         ? getLayoutFont(bparams, outerfont)
2730                         : getFont(bparams, size() - 1, outerfont);
2731
2732                 InsetText const * textinset = inInset().asInsetText();
2733
2734                 bool const maintext = textinset
2735                         ? textinset->text().isMainText()
2736                         : false;
2737
2738                 size_t const numpars = textinset
2739                         ? textinset->text().paragraphs().size()
2740                         : 0;
2741
2742                 bool needPar = false;
2743
2744                 if (style.resfont.size() != font.fontInfo().size()
2745                     && (!runparams.isLastPar || maintext
2746                         || (numpars > 1 && d->ownerCode() != CELL_CODE
2747                             && (inInset().getLayout().isDisplay()
2748                                 || parInline)))
2749                     && !style.isCommand()) {
2750                         needPar = true;
2751                 }
2752 #ifdef FIXED_LANGUAGE_END_DETECTION
2753                 if (next_) {
2754                         running_font.latexWriteEndChanges(os, bparams,
2755                                         runparams, basefont,
2756                                         next_->getFont(bparams, 0, outerfont),
2757                                                        needPar);
2758                 } else {
2759                         running_font.latexWriteEndChanges(os, bparams,
2760                                         runparams, basefont, basefont, needPar);
2761                 }
2762 #else
2763 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2764 //FIXME: there as we start another \selectlanguage with the next paragraph if
2765 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2766                 running_font.latexWriteEndChanges(os, bparams, runparams,
2767                                 basefont, basefont, needPar);
2768 #endif
2769                 if (needPar) {
2770                         // The \par could not be inserted at the same nesting
2771                         // level of the font size change, so do it now.
2772                         os << "{\\" << font.latexSize() << "\\par}";
2773                 }
2774         }
2775
2776         column += Changes::latexMarkChange(os, bparams, runningChange,
2777                                            Change(Change::UNCHANGED), runparams);
2778
2779         // Needed if there is an optional argument but no contents.
2780         if (body_pos > 0 && body_pos == size()) {
2781                 os << "}]~";
2782         }
2783
2784         if (!style.rightdelim().empty()) {
2785                 os << style.rightdelim();
2786                 column += style.rightdelim().size();
2787         }
2788
2789         if (allowcust && d->endTeXParParams(bparams, os, runparams)
2790             && runparams.encoding != prev_encoding) {
2791                 runparams.encoding = prev_encoding;
2792                 os << setEncoding(prev_encoding->iconvName());
2793         }
2794
2795         LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2796 }
2797
2798
2799 bool Paragraph::emptyTag() const
2800 {
2801         for (pos_type i = 0; i < size(); ++i) {
2802                 if (Inset const * inset = getInset(i)) {
2803                         InsetCode lyx_code = inset->lyxCode();
2804                         // FIXME testing like that is wrong. What is
2805                         // the intent?
2806                         if (lyx_code != TOC_CODE &&
2807                             lyx_code != INCLUDE_CODE &&
2808                             lyx_code != GRAPHICS_CODE &&
2809                             lyx_code != ERT_CODE &&
2810                             lyx_code != LISTINGS_CODE &&
2811                             lyx_code != FLOAT_CODE &&
2812                             lyx_code != TABULAR_CODE) {
2813                                 return false;
2814                         }
2815                 } else {
2816                         char_type c = d->text_[i];
2817                         if (c != ' ' && c != '\t')
2818                                 return false;
2819                 }
2820         }
2821         return true;
2822 }
2823
2824
2825 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2826         const
2827 {
2828         for (pos_type i = 0; i < size(); ++i) {
2829                 if (Inset const * inset = getInset(i)) {
2830                         InsetCode lyx_code = inset->lyxCode();
2831                         if (lyx_code == LABEL_CODE) {
2832                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2833                                 docstring const & id = il->getParam("name");
2834                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2835                         }
2836                 }
2837         }
2838         return string();
2839 }
2840
2841
2842 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2843         const
2844 {
2845         pos_type i;
2846         for (i = 0; i < size(); ++i) {
2847                 if (Inset const * inset = getInset(i)) {
2848                         inset->docbook(os, runparams);
2849                 } else {
2850                         char_type c = d->text_[i];
2851                         if (c == ' ')
2852                                 break;
2853                         os << sgml::escapeChar(c);
2854                 }
2855         }
2856         return i;
2857 }
2858
2859
2860 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2861         const
2862 {
2863         pos_type i;
2864         for (i = 0; i < size(); ++i) {
2865                 if (Inset const * inset = getInset(i)) {
2866                         inset->xhtml(xs, runparams);
2867                 } else {
2868                         char_type c = d->text_[i];
2869                         if (c == ' ')
2870                                 break;
2871                         xs << c;
2872                 }
2873         }
2874         return i;
2875 }
2876
2877
2878 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2879 {
2880         Font font_old;
2881         pos_type size = text_.size();
2882         for (pos_type i = initial; i < size; ++i) {
2883                 Font font = owner_->getFont(buf.params(), i, outerfont);
2884                 if (text_[i] == META_INSET)
2885                         return false;
2886                 if (i != initial && font != font_old)
2887                         return false;
2888                 font_old = font;
2889         }
2890
2891         return true;
2892 }
2893
2894
2895 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2896                                     odocstream & os,
2897                                     OutputParams const & runparams,
2898                                     Font const & outerfont,
2899                                     pos_type initial) const
2900 {
2901         bool emph_flag = false;
2902
2903         Layout const & style = *d->layout_;
2904         FontInfo font_old =
2905                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2906
2907         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2908                 os << "]]>";
2909
2910         // parsing main loop
2911         for (pos_type i = initial; i < size(); ++i) {
2912                 Font font = getFont(buf.params(), i, outerfont);
2913
2914                 // handle <emphasis> tag
2915                 if (font_old.emph() != font.fontInfo().emph()) {
2916                         if (font.fontInfo().emph() == FONT_ON) {
2917                                 os << "<emphasis>";
2918                                 emph_flag = true;
2919                         } else if (i != initial) {
2920                                 os << "</emphasis>";
2921                                 emph_flag = false;
2922                         }
2923                 }
2924
2925                 if (Inset const * inset = getInset(i)) {
2926                         inset->docbook(os, runparams);
2927                 } else {
2928                         char_type c = d->text_[i];
2929
2930                         if (style.pass_thru)
2931                                 os.put(c);
2932                         else
2933                                 os << sgml::escapeChar(c);
2934                 }
2935                 font_old = font.fontInfo();
2936         }
2937
2938         if (emph_flag) {
2939                 os << "</emphasis>";
2940         }
2941
2942         if (style.free_spacing)
2943                 os << '\n';
2944         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2945                 os << "<![CDATA[";
2946 }
2947
2948
2949 namespace {
2950 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2951                   vector<html::EndFontTag> & tagsToClose,
2952                   bool & flag, FontState curstate, html::FontTypes type)
2953 {
2954         if (curstate == FONT_ON) {
2955                 tagsToOpen.push_back(html::FontTag(type));
2956                 flag = true;
2957         } else if (flag) {
2958                 tagsToClose.push_back(html::EndFontTag(type));
2959                 flag = false;
2960         }
2961 }
2962 } // namespace
2963
2964
2965 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2966                                     XHTMLStream & xs,
2967                                     OutputParams const & runparams,
2968                                     Font const & outerfont,
2969                                     bool start_paragraph, bool close_paragraph,
2970                                     pos_type initial) const
2971 {
2972         docstring retval;
2973
2974         // track whether we have opened these tags
2975         bool emph_flag = false;
2976         bool bold_flag = false;
2977         bool noun_flag = false;
2978         bool ubar_flag = false;
2979         bool dbar_flag = false;
2980         bool sout_flag = false;
2981         bool xout_flag = false;
2982         bool wave_flag = false;
2983         // shape tags
2984         bool shap_flag = false;
2985         // family tags
2986         bool faml_flag = false;
2987         // size tags
2988         bool size_flag = false;
2989
2990         Layout const & style = *d->layout_;
2991
2992         if (start_paragraph)
2993                 xs.startDivision(allowEmpty());
2994
2995         FontInfo font_old =
2996                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2997
2998         FontShape  curr_fs   = INHERIT_SHAPE;
2999         FontFamily curr_fam  = INHERIT_FAMILY;
3000         FontSize   curr_size = FONT_SIZE_INHERIT;
3001
3002         string const default_family =
3003                 buf.masterBuffer()->params().fonts_default_family;
3004
3005         vector<html::FontTag> tagsToOpen;
3006         vector<html::EndFontTag> tagsToClose;
3007
3008         // parsing main loop
3009         for (pos_type i = initial; i < size(); ++i) {
3010                 // let's not show deleted material in the output
3011                 if (isDeleted(i))
3012                         continue;
3013
3014                 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3015
3016                 // emphasis
3017                 FontState curstate = font.fontInfo().emph();
3018                 if (font_old.emph() != curstate)
3019                         doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
3020
3021                 // noun
3022                 curstate = font.fontInfo().noun();
3023                 if (font_old.noun() != curstate)
3024                         doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
3025
3026                 // underbar
3027                 curstate = font.fontInfo().underbar();
3028                 if (font_old.underbar() != curstate)
3029                         doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
3030
3031                 // strikeout
3032                 curstate = font.fontInfo().strikeout();
3033                 if (font_old.strikeout() != curstate)
3034                         doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
3035
3036                 // xout
3037                 curstate = font.fontInfo().xout();
3038                 if (font_old.xout() != curstate)
3039                         doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
3040
3041                 // double underbar
3042                 curstate = font.fontInfo().uuline();
3043                 if (font_old.uuline() != curstate)
3044                         doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
3045
3046                 // wavy line
3047                 curstate = font.fontInfo().uwave();
3048                 if (font_old.uwave() != curstate)
3049                         doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
3050
3051                 // bold
3052                 // a little hackish, but allows us to reuse what we have.
3053                 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3054                 if (font_old.series() != font.fontInfo().series())
3055                         doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
3056
3057                 // Font shape
3058                 curr_fs = font.fontInfo().shape();
3059                 FontShape old_fs = font_old.shape();
3060                 if (old_fs != curr_fs) {
3061                         if (shap_flag) {
3062                                 switch (old_fs) {
3063                                 case ITALIC_SHAPE:
3064                                         tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
3065                                         break;
3066                                 case SLANTED_SHAPE:
3067                                         tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
3068                                         break;
3069                                 case SMALLCAPS_SHAPE:
3070                                         tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
3071                                         break;
3072                                 case UP_SHAPE:
3073                                 case INHERIT_SHAPE:
3074                                         break;
3075                                 default:
3076                                         // the other tags are for internal use
3077                                         LATTEST(false);
3078                                         break;
3079                                 }
3080                                 shap_flag = false;
3081                         }
3082                         switch (curr_fs) {
3083                         case ITALIC_SHAPE:
3084                                 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
3085                                 shap_flag = true;
3086                                 break;
3087                         case SLANTED_SHAPE:
3088                                 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
3089                                 shap_flag = true;
3090                                 break;
3091                         case SMALLCAPS_SHAPE:
3092                                 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
3093                                 shap_flag = true;
3094                                 break;
3095                         case UP_SHAPE:
3096                         case INHERIT_SHAPE:
3097                                 break;
3098                         default:
3099                                 // the other tags are for internal use
3100                                 LATTEST(false);
3101                                 break;
3102                         }
3103                 }
3104
3105                 // Font family
3106                 curr_fam = font.fontInfo().family();
3107                 FontFamily old_fam = font_old.family();
3108                 if (old_fam != curr_fam) {
3109                         if (faml_flag) {
3110                                 switch (old_fam) {
3111                                 case ROMAN_FAMILY:
3112                                         tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
3113                                         break;
3114                                 case SANS_FAMILY:
3115                                         tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
3116                                         break;
3117                                 case TYPEWRITER_FAMILY:
3118                                         tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3119                                         break;
3120                                 case INHERIT_FAMILY:
3121                                         break;
3122                                 default:
3123                                         // the other tags are for internal use
3124                                         LATTEST(false);
3125                                         break;
3126                                 }
3127                                 faml_flag = false;
3128                         }
3129                         switch (curr_fam) {
3130                         case ROMAN_FAMILY:
3131                                 // we will treat a "default" font family as roman, since we have
3132                                 // no other idea what to do.
3133                                 if (default_family != "rmdefault" && default_family != "default") {
3134                                         tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3135                                         faml_flag = true;
3136                                 }
3137                                 break;
3138                         case SANS_FAMILY:
3139                                 if (default_family != "sfdefault") {
3140                                         tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3141                                         faml_flag = true;
3142                                 }
3143                                 break;
3144                         case TYPEWRITER_FAMILY:
3145                                 if (default_family != "ttdefault") {
3146                                         tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3147                                         faml_flag = true;
3148                                 }
3149                                 break;
3150                         case INHERIT_FAMILY:
3151                                 break;
3152                         default:
3153                                 // the other tags are for internal use
3154                                 LATTEST(false);
3155                                 break;
3156                         }
3157                 }
3158
3159                 // Font size
3160                 curr_size = font.fontInfo().size();
3161                 FontSize old_size = font_old.size();
3162                 if (old_size != curr_size) {
3163                         if (size_flag) {
3164                                 switch (old_size) {
3165                                 case FONT_SIZE_TINY:
3166                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3167                                         break;
3168                                 case FONT_SIZE_SCRIPT:
3169                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3170                                         break;
3171                                 case FONT_SIZE_FOOTNOTE:
3172                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3173                                         break;
3174                                 case FONT_SIZE_SMALL:
3175                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3176                                         break;
3177                                 case FONT_SIZE_LARGE:
3178                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3179                                         break;
3180                                 case FONT_SIZE_LARGER:
3181                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3182                                         break;
3183                                 case FONT_SIZE_LARGEST:
3184                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3185                                         break;
3186                                 case FONT_SIZE_HUGE:
3187                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3188                                         break;
3189                                 case FONT_SIZE_HUGER:
3190                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3191                                         break;
3192                                 case FONT_SIZE_INCREASE:
3193                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3194                                         break;
3195                                 case FONT_SIZE_DECREASE:
3196                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3197                                         break;
3198                                 case FONT_SIZE_INHERIT:
3199                                 case FONT_SIZE_NORMAL:
3200                                         break;
3201                                 default:
3202                                         // the other tags are for internal use
3203                                         LATTEST(false);
3204                                         break;
3205                                 }
3206                                 size_flag = false;
3207                         }
3208                         switch (curr_size) {
3209                         case FONT_SIZE_TINY:
3210                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3211                                 size_flag = true;
3212                                 break;
3213                         case FONT_SIZE_SCRIPT:
3214                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3215                                 size_flag = true;
3216                                 break;
3217                         case FONT_SIZE_FOOTNOTE:
3218                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3219                                 size_flag = true;
3220                                 break;
3221                         case FONT_SIZE_SMALL:
3222                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3223                                 size_flag = true;
3224                                 break;
3225                         case FONT_SIZE_LARGE:
3226                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3227                                 size_flag = true;
3228                                 break;
3229                         case FONT_SIZE_LARGER:
3230                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3231                                 size_flag = true;
3232                                 break;
3233                         case FONT_SIZE_LARGEST:
3234                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3235                                 size_flag = true;
3236                                 break;
3237                         case FONT_SIZE_HUGE:
3238                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3239                                 size_flag = true;
3240                                 break;
3241                         case FONT_SIZE_HUGER:
3242                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3243                                 size_flag = true;
3244                                 break;
3245                         case FONT_SIZE_INCREASE:
3246                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3247                                 size_flag = true;
3248                                 break;
3249                         case FONT_SIZE_DECREASE:
3250                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3251                                 size_flag = true;
3252                                 break;
3253                         case FONT_SIZE_NORMAL:
3254                         case FONT_SIZE_INHERIT:
3255                                 break;
3256                         default:
3257                                 // the other tags are for internal use
3258                                 LATTEST(false);
3259                                 break;
3260                         }
3261                 }
3262
3263                 // FIXME XHTML
3264                 // Other such tags? What about the other text ranges?
3265
3266                 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3267                 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3268                 for (; cit != cen; ++cit)
3269                         xs << *cit;
3270
3271                 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3272                 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3273                 for (; sit != sen; ++sit)
3274                         xs << *sit;
3275
3276                 tagsToClose.clear();
3277                 tagsToOpen.clear();
3278
3279                 Inset const * inset = getInset(i);
3280                 if (inset) {
3281                         if (!runparams.for_toc || inset->isInToc()) {
3282                                 OutputParams np = runparams;
3283                                 np.local_font = &font;
3284                                 // If the paragraph has size 1, then we are in the "special
3285                                 // case" where we do not output the containing paragraph info
3286                                 if (!inset->getLayout().htmlisblock() && size() != 1)
3287                                         np.html_in_par = true;
3288                                 retval += inset->xhtml(xs, np);
3289                         }
3290                 } else {
3291                         char_type c = getUChar(buf.masterBuffer()->params(), i);
3292                         xs << c;
3293                 }
3294                 font_old = font.fontInfo();
3295         }
3296
3297         // FIXME XHTML
3298         // I'm worried about what happens if a branch, say, is itself
3299         // wrapped in some font stuff. I think that will not work.
3300         xs.closeFontTags();
3301         if (close_paragraph)
3302                 xs.endDivision();
3303
3304         return retval;
3305 }
3306
3307
3308 bool Paragraph::isHfill(pos_type pos) const
3309 {
3310         Inset const * inset = getInset(pos);
3311         return inset && inset->isHfill();
3312 }
3313
3314
3315 bool Paragraph::isNewline(pos_type pos) const
3316 {
3317         // U+2028 LINE SEPARATOR
3318         // U+2029 PARAGRAPH SEPARATOR
3319         char_type const c = d->text_[pos];
3320         if (c == 0x2028 || c == 0x2029)
3321                 return true;
3322         Inset const * inset = getInset(pos);
3323         return inset && inset->lyxCode() == NEWLINE_CODE;
3324 }
3325
3326
3327 bool Paragraph::isEnvSeparator(pos_type pos) const
3328 {
3329         Inset const * inset = getInset(pos);
3330         return inset && inset->lyxCode() == SEPARATOR_CODE;
3331 }
3332
3333
3334 bool Paragraph::isLineSeparator(pos_type pos) const
3335 {
3336         char_type const c = d->text_[pos];
3337         if (isLineSeparatorChar(c))
3338                 return true;
3339         Inset const * inset = getInset(pos);
3340         return inset && inset->isLineSeparator();
3341 }
3342
3343
3344 bool Paragraph::isWordSeparator(pos_type pos) const
3345 {
3346         if (pos == size())
3347                 return true;
3348         if (Inset const * inset = getInset(pos))
3349                 return !inset->isLetter();
3350         // if we have a hard hyphen (no en- or emdash) or apostrophe
3351         // we pass this to the spell checker
3352         // FIXME: this method is subject to change, visit
3353         // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3354         // to get an impression how complex this is.
3355         if (isHardHyphenOrApostrophe(pos))
3356                 return false;
3357         char_type const c = d->text_[pos];
3358         // We want to pass the escape chars to the spellchecker
3359         docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3360         return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3361 }
3362
3363
3364 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3365 {
3366         pos_type const psize = size();
3367         if (pos >= psize)
3368                 return false;
3369         char_type const c = d->text_[pos];
3370         if (c != '-' && c != '\'')
3371                 return false;
3372         int nextpos = pos + 1;
3373         int prevpos = pos > 0 ? pos - 1 : 0;
3374         if ((nextpos == psize || isSpace(nextpos))
3375                 && (pos == 0 || isSpace(prevpos)))
3376                 return false;
3377         return true;
3378 }
3379
3380
3381 bool Paragraph::needsCProtection() const
3382 {
3383         // first check the layout of the paragraph
3384         if (layout().needcprotect) {
3385                 // Environments need cprotection regardless the content
3386                 if (layout().latextype == LATEX_ENVIRONMENT)
3387                         return true;
3388
3389                 // Commands need cprotection if they contain specific chars
3390                 int const nchars_escape = 9;
3391                 static char_type const chars_escape[nchars_escape] = {
3392                         '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3393
3394                 docstring const pars = asString();
3395                 for (int k = 0; k < nchars_escape; k++) {
3396                         if (contains(pars, chars_escape[k]))
3397                                 return true;
3398                 }
3399         }
3400
3401         // now check whether we have insets that need cprotection
3402         pos_type size = d->text_.size();
3403         for (pos_type i = 0; i < size; ++i)
3404                 if (isInset(i))
3405                         if (getInset(i)->needsCProtection())
3406                                 return true;
3407
3408         return false;
3409 }
3410
3411
3412 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3413 {
3414         return d->speller_state_.getRange(pos);
3415 }
3416
3417
3418 bool Paragraph::isChar(pos_type pos) const
3419 {
3420         if (Inset const * inset = getInset(pos))
3421                 return inset->isChar();
3422         char_type const c = d->text_[pos];
3423         return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3424 }
3425
3426
3427 bool Paragraph::isSpace(pos_type pos) const
3428 {
3429         if (Inset const * inset = getInset(pos))
3430                 return inset->isSpace();
3431         char_type const c = d->text_[pos];
3432         return lyx::isSpace(c);
3433 }
3434
3435
3436 Language const *
3437 Paragraph::getParLanguage(BufferParams const & bparams) const
3438 {
3439         if (!empty())
3440                 return getFirstFontSettings(bparams).language();
3441         // FIXME: we should check the prev par as well (Lgb)
3442         return bparams.language;
3443 }
3444
3445
3446 bool Paragraph::isRTL(BufferParams const & bparams) const
3447 {
3448         return getParLanguage(bparams)->rightToLeft()
3449                 && !inInset().getLayout().forceLTR();
3450 }
3451
3452
3453 void Paragraph::changeLanguage(BufferParams const & bparams,
3454                                Language const * from, Language const * to)
3455 {
3456         // change language including dummy font change at the end
3457         for (pos_type i = 0; i <= size(); ++i) {
3458                 Font font = getFontSettings(bparams, i);
3459                 if (font.language() == from) {
3460                         font.setLanguage(to);
3461                         setFont(i, font);
3462                         d->requestSpellCheck(i);
3463                 }
3464         }
3465 }
3466
3467
3468 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3469 {
3470         Language const * doc_language = bparams.language;
3471         for (auto const & f : d->fontlist_)
3472                 if (f.font().language() != ignore_language &&
3473                     f.font().language() != latex_language &&
3474                     f.font().language() != doc_language)
3475                         return true;
3476         return false;
3477 }
3478
3479
3480 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3481 {
3482         for (auto const & f : d->fontlist_) {
3483                 Language const * lang = f.font().language();
3484                 if (lang != ignore_language &&
3485                     lang != latex_language)
3486                         langs.insert(lang);
3487         }
3488 }
3489
3490
3491 docstring Paragraph::asString(int options) const
3492 {
3493         return asString(0, size(), options);
3494 }
3495
3496
3497 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3498 {
3499         odocstringstream os;
3500
3501         if (beg == 0
3502             && options & AS_STR_LABEL
3503             && !d->params_.labelString().empty())
3504                 os << d->params_.labelString() << ' ';
3505
3506         for (pos_type i = beg; i < end; ++i) {
3507                 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3508                         continue;
3509                 char_type const c = d->text_[i];
3510                 if (isPrintable(c) || c == '\t'
3511                     || (c == '\n' && (options & AS_STR_NEWLINES)))
3512                         os.put(c);
3513                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3514                         if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3515                                 LASSERT(runparams != 0, return docstring());
3516                                 getInset(i)->plaintext(os, *runparams);
3517                         } else {
3518                                 getInset(i)->toString(os);
3519                         }
3520                 }
3521         }
3522
3523         return os.str();
3524 }
3525
3526
3527 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3528                             bool const shorten, bool const label) const
3529 {
3530         size_t tmplen = shorten ? maxlen + 1 : maxlen;
3531         if (label && !labelString().empty())
3532                 os += labelString() + ' ';
3533         if (!layout().isTocCaption())
3534                 return;
3535         for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3536                 if (isDeleted(i))
3537                         continue;
3538                 char_type const c = d->text_[i];
3539                 if (isPrintable(c))
3540                         os += c;
3541                 else if (c == META_INSET)
3542                         getInset(i)->forOutliner(os, tmplen, false);
3543         }
3544         if (shorten)
3545                 Text::shortenForOutliner(os, maxlen);
3546 }
3547
3548
3549 void Paragraph::setInsetOwner(Inset const * inset)
3550 {
3551         d->inset_owner_ = inset;
3552 }
3553
3554
3555 int Paragraph::id() const
3556 {
3557         return d->id_;
3558 }
3559
3560
3561 void Paragraph::setId(int id)
3562 {
3563         d->id_ = id;
3564 }
3565
3566
3567 Layout const & Paragraph::layout() const
3568 {
3569         return *d->layout_;
3570 }
3571
3572
3573 void Paragraph::setLayout(Layout const & layout)
3574 {
3575         d->layout_ = &layout;
3576 }
3577
3578
3579 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3580 {
3581         setLayout(tc.defaultLayout());
3582 }
3583
3584
3585 void Paragraph::setPlainLayout(DocumentClass const & tc)
3586 {
3587         setLayout(tc.plainLayout());
3588 }
3589
3590
3591 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3592 {
3593         if (usePlainLayout())
3594                 setPlainLayout(tclass);
3595         else
3596                 setDefaultLayout(tclass);
3597 }
3598
3599
3600 Inset const & Paragraph::inInset() const
3601 {
3602         LBUFERR(d->inset_owner_);
3603         return *d->inset_owner_;
3604 }
3605
3606
3607 ParagraphParameters & Paragraph::params()
3608 {
3609         return d->params_;
3610 }
3611
3612
3613 ParagraphParameters const & Paragraph::params() const
3614 {
3615         return d->params_;
3616 }
3617
3618
3619 bool Paragraph::isFreeSpacing() const
3620 {
3621         if (d->layout_->free_spacing)
3622                 return true;
3623         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3624 }
3625
3626
3627 bool Paragraph::allowEmpty() const
3628 {
3629         if (d->layout_->keepempty)
3630                 return true;
3631         return d->inset_owner_ && d->inset_owner_->allowEmpty();
3632 }
3633
3634
3635 bool Paragraph::brokenBiblio() const
3636 {
3637         // there is a problem if there is no bibitem at position 0 or
3638         // if there is another bibitem in the paragraph.
3639         return d->layout_->labeltype == LABEL_BIBLIO
3640                 && (d->insetlist_.find(BIBITEM_CODE) != 0
3641                     || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3642 }
3643
3644
3645 int Paragraph::fixBiblio(Buffer const & buffer)
3646 {
3647         // FIXME: What about the case where paragraph is not BIBLIO
3648         // but there is an InsetBibitem?
3649         // FIXME: when there was already an inset at 0, the return value is 1,
3650         // which does not tell whether another inset has been remove; the
3651         // cursor cannot be correctly updated.
3652
3653         if (d->layout_->labeltype != LABEL_BIBLIO)
3654                 return 0;
3655
3656         bool const track_changes = buffer.params().track_changes;
3657         int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3658         bool const hasbibitem0 = bibitem_pos == 0;
3659
3660         if (hasbibitem0) {
3661                 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3662                 // There was an InsetBibitem at pos 0, and no other one => OK
3663                 if (bibitem_pos == -1)
3664                         return 0;
3665                 // there is a bibitem at the 0 position, but since
3666                 // there is a second one, we copy the second on the
3667                 // first. We're assuming there are at most two of
3668                 // these, which there should be.
3669                 // FIXME: why does it make sense to do that rather
3670                 // than keep the first? (JMarc)
3671                 Inset * inset = releaseInset(bibitem_pos);
3672                 d->insetlist_.begin()->inset = inset;
3673                 return -bibitem_pos;
3674         }
3675
3676         // We need to create an inset at the beginning
3677         Inset * inset = 0;
3678         if (bibitem_pos > 0) {
3679                 // there was one somewhere in the paragraph, let's move it
3680                 inset = d->insetlist_.release(bibitem_pos);
3681                 eraseChar(bibitem_pos, track_changes);
3682         } else
3683                 // make a fresh one
3684                 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3685                                          InsetCommandParams(BIBITEM_CODE));
3686
3687         Font font(inherit_font, buffer.params().language);
3688         insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3689                                                    : Change::UNCHANGED));
3690
3691         return 1;
3692 }
3693
3694
3695 void Paragraph::checkAuthors(AuthorList const & authorList)
3696 {
3697         d->changes_.checkAuthors(authorList);
3698 }
3699
3700
3701 bool Paragraph::isChanged(pos_type pos) const
3702 {
3703         return lookupChange(pos).changed();
3704 }
3705
3706
3707 bool Paragraph::isInserted(pos_type pos) const
3708 {
3709         return lookupChange(pos).inserted();
3710 }
3711
3712
3713 bool Paragraph::isDeleted(pos_type pos) const
3714 {
3715         return lookupChange(pos).deleted();
3716 }
3717
3718
3719 InsetList const & Paragraph::insetList() const
3720 {
3721         return d->insetlist_;
3722 }
3723
3724
3725 void Paragraph::setInsetBuffers(Buffer & b)
3726 {
3727         d->insetlist_.setBuffer(b);
3728 }
3729
3730
3731 void Paragraph::resetBuffer()
3732 {
3733         d->insetlist_.resetBuffer();
3734 }
3735
3736
3737 Inset * Paragraph::releaseInset(pos_type pos)
3738 {
3739         Inset * inset = d->insetlist_.release(pos);
3740         /// does not honour change tracking!
3741         eraseChar(pos, false);
3742         return inset;
3743 }
3744
3745
3746 Inset * Paragraph::getInset(pos_type pos)
3747 {
3748         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3749                  ? d->insetlist_.get(pos) : 0;
3750 }
3751
3752
3753 Inset const * Paragraph::getInset(pos_type pos) const
3754 {
3755         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3756                  ? d->insetlist_.get(pos) : 0;
3757 }
3758
3759
3760 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3761                 pos_type & right, TextCase action)
3762 {
3763         // process sequences of modified characters; in change
3764         // tracking mode, this approach results in much better
3765         // usability than changing case on a char-by-char basis
3766         // We also need to track the current font, since font
3767         // changes within sequences can occur.
3768         vector<pair<char_type, Font> > changes;
3769
3770         bool const trackChanges = bparams.track_changes;
3771
3772         bool capitalize = true;
3773
3774         for (; pos < right; ++pos) {
3775                 char_type oldChar = d->text_[pos];
3776                 char_type newChar = oldChar;
3777
3778                 // ignore insets and don't play with deleted text!
3779                 if (oldChar != META_INSET && !isDeleted(pos)) {
3780                         switch (action) {
3781                                 case text_lowercase:
3782                                         newChar = lowercase(oldChar);
3783                                         break;
3784                                 case text_capitalization:
3785                                         if (capitalize) {
3786                                                 newChar = uppercase(oldChar);
3787                                                 capitalize = false;
3788                                         }
3789                                         break;
3790                                 case text_uppercase:
3791                                         newChar = uppercase(oldChar);
3792                                         break;
3793                         }
3794                 }
3795
3796                 if (isWordSeparator(pos) || isDeleted(pos)) {
3797                         // permit capitalization again
3798                         capitalize = true;
3799                 }
3800
3801                 if (oldChar != newChar) {
3802                         changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3803                         if (pos != right - 1)
3804                                 continue;
3805                         // step behind the changing area
3806                         pos++;
3807                 }
3808
3809                 int erasePos = pos - changes.size();
3810                 for (size_t i = 0; i < changes.size(); i++) {
3811                         insertChar(pos, changes[i].first,
3812                                    changes[i].second,
3813                                    trackChanges);
3814                         if (!eraseChar(erasePos, trackChanges)) {
3815                                 ++erasePos;
3816                                 ++pos; // advance
3817                                 ++right; // expand selection
3818                         }
3819                 }
3820                 changes.clear();
3821         }
3822 }
3823
3824
3825 int Paragraph::find(docstring const & str, bool cs, bool mw,
3826                 pos_type start_pos, bool del) const
3827 {
3828         pos_type pos = start_pos;
3829         int const strsize = str.length();
3830         int i = 0;
3831         pos_type const parsize = d->text_.size();
3832         for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3833                 // Ignore "invisible" letters such as ligature breaks
3834                 // and hyphenation chars while searching
3835                 while (pos < parsize - 1 && isInset(pos)) {
3836                         odocstringstream os;
3837                         getInset(pos)->toString(os);
3838                         if (!getInset(pos)->isLetter() || !os.str().empty())
3839                                 break;
3840                         pos++;
3841                 }
3842                 if (cs && str[i] != d->text_[pos])
3843                         break;
3844                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3845                         break;
3846                 if (!del && isDeleted(pos))
3847                         break;
3848         }
3849
3850         if (i != strsize)
3851                 return 0;
3852
3853         // if necessary, check whether string matches word
3854         if (mw) {
3855                 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3856                         return 0;
3857                 if (pos < parsize
3858                         && !isWordSeparator(pos))
3859                         return 0;
3860         }
3861
3862         return pos - start_pos;
3863 }
3864
3865
3866 char_type Paragraph::getChar(pos_type pos) const
3867 {
3868         return d->text_[pos];
3869 }
3870
3871
3872 pos_type Paragraph::size() const
3873 {
3874         return d->text_.size();
3875 }
3876
3877
3878 bool Paragraph::empty() const
3879 {
3880         return d->text_.empty();
3881 }
3882
3883
3884 bool Paragraph::isInset(pos_type pos) const
3885 {
3886         return d->text_[pos] == META_INSET;
3887 }
3888
3889
3890 bool Paragraph::isSeparator(pos_type pos) const
3891 {
3892         //FIXME: Are we sure this can be the only separator?
3893         return d->text_[pos] == ' ';
3894 }
3895
3896
3897 void Paragraph::deregisterWords()
3898 {
3899         Private::LangWordsMap::const_iterator itl = d->words_.begin();
3900         Private::LangWordsMap::const_iterator ite = d->words_.end();
3901         for (; itl != ite; ++itl) {
3902                 WordList & wl = theWordList(itl->first);
3903                 Private::Words::const_iterator it = (itl->second).begin();
3904                 Private::Words::const_iterator et = (itl->second).end();
3905                 for (; it != et; ++it)
3906                         wl.remove(*it);
3907         }
3908         d->words_.clear();
3909 }
3910
3911
3912 void Paragraph::locateWord(pos_type & from, pos_type & to,
3913         word_location const loc) const
3914 {
3915         switch (loc) {
3916         case WHOLE_WORD_STRICT:
3917                 if (from == 0 || from == size()
3918                     || isWordSeparator(from)
3919                     || isWordSeparator(from - 1)) {
3920                         to = from;
3921                         return;
3922                 }
3923                 // fall through
3924
3925         case WHOLE_WORD:
3926                 // If we are already at the beginning of a word, do nothing
3927                 if (!from || isWordSeparator(from - 1))
3928                         break;
3929                 // fall through
3930
3931         case PREVIOUS_WORD:
3932                 // always move the cursor to the beginning of previous word
3933                 while (from && !isWordSeparator(from - 1))
3934                         --from;
3935                 break;
3936         case NEXT_WORD:
3937                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3938                 break;
3939         case PARTIAL_WORD:
3940                 // no need to move the 'from' cursor
3941                 break;
3942         }
3943         to = from;
3944         while (to < size() && !isWordSeparator(to))
3945                 ++to;
3946 }
3947
3948
3949 void Paragraph::collectWords()
3950 {
3951         for (pos_type pos = 0; pos < size(); ++pos) {
3952                 if (isWordSeparator(pos))
3953                         continue;
3954                 pos_type from = pos;
3955                 locateWord(from, pos, WHOLE_WORD);
3956                 // Work around MSVC warning: The statement
3957                 // if (pos < from + lyxrc.completion_minlength)
3958                 // triggers a signed vs. unsigned warning.
3959                 // I don't know why this happens, it could be a MSVC bug, or
3960                 // related to LLP64 (windows) vs. LP64 (unix) programming
3961                 // model, or the C++ standard might be ambigous in the section
3962                 // defining the "usual arithmetic conversions". However, using
3963                 // a temporary variable is safe and works on all compilers.
3964                 pos_type const endpos = from + lyxrc.completion_minlength;
3965                 if (pos < endpos)
3966                         continue;
3967                 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3968                 if (cit == d->fontlist_.end())
3969                         return;
3970                 Language const * lang = cit->font().language();
3971                 docstring const word = asString(from, pos, AS_STR_NONE);
3972                 d->words_[lang->lang()].insert(word);
3973         }
3974 }
3975
3976
3977 void Paragraph::registerWords()
3978 {
3979         Private::LangWordsMap::const_iterator itl = d->words_.begin();
3980         Private::LangWordsMap::const_iterator ite = d->words_.end();
3981         for (; itl != ite; ++itl) {
3982                 WordList & wl = theWordList(itl->first);
3983                 Private::Words::const_iterator it = (itl->second).begin();
3984                 Private::Words::const_iterator et = (itl->second).end();
3985                 for (; it != et; ++it)
3986                         wl.insert(*it);
3987         }
3988 }
3989
3990
3991 void Paragraph::updateWords()
3992 {
3993         deregisterWords();
3994         collectWords();
3995         registerWords();
3996 }
3997
3998
3999 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4000 {
4001         SkipPositionsIterator begin = skips.begin();
4002         SkipPositions::iterator end = skips.end();
4003         if (pos > 0 && begin < end) {
4004                 --end;
4005                 if (end->last == pos - 1) {
4006                         end->last = pos;
4007                         return;
4008                 }
4009         }
4010         skips.insert(end, FontSpan(pos, pos));
4011 }
4012
4013
4014 Language * Paragraph::Private::locateSpellRange(
4015         pos_type & from, pos_type & to,
4016         SkipPositions & skips) const
4017 {
4018         // skip leading white space
4019         while (from < to && owner_->isWordSeparator(from))
4020                 ++from;
4021         // don't check empty range
4022         if (from >= to)
4023                 return 0;
4024         // get current language
4025         Language * lang = getSpellLanguage(from);
4026         pos_type last = from;
4027         bool samelang = true;
4028         bool sameinset = true;
4029         while (last < to && samelang && sameinset) {
4030                 // hop to end of word
4031                 while (last < to && !owner_->isWordSeparator(last)) {
4032                         if (owner_->getInset(last)) {
4033                                 appendSkipPosition(skips, last);
4034                         } else if (owner_->isDeleted(last)) {
4035                                 appendSkipPosition(skips, last);
4036                         }
4037                         ++last;
4038                 }
4039                 // hop to next word while checking for insets
4040                 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4041                         if (Inset const * inset = owner_->getInset(last))
4042                                 sameinset = inset->isChar() && inset->isLetter();
4043                         if (sameinset && owner_->isDeleted(last)) {
4044                                 appendSkipPosition(skips, last);
4045                         }
4046                         if (sameinset)
4047                                 last++;
4048                 }
4049                 if (sameinset && last < to) {
4050                         // now check for language change
4051                         samelang = lang == getSpellLanguage(last);
4052                 }
4053         }
4054         // if language change detected backstep is needed
4055         if (!samelang)
4056                 --last;
4057         to = last;
4058         return lang;
4059 }
4060
4061
4062 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4063 {
4064         Language * lang =
4065                 const_cast<Language *>(owner_->getFontSettings(
4066                         inset_owner_->buffer().params(), from).language());
4067         if (lang == inset_owner_->buffer().params().language
4068                 && !lyxrc.spellchecker_alt_lang.empty()) {
4069                 string lang_code;
4070                 string const lang_variety =
4071                         split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4072                 lang->setCode(lang_code);
4073                 lang->setVariety(lang_variety);
4074         }
4075         return lang;
4076 }
4077
4078
4079 void Paragraph::requestSpellCheck(pos_type pos)
4080 {
4081         d->requestSpellCheck(pos);
4082 }
4083
4084
4085 bool Paragraph::needsSpellCheck() const
4086 {
4087         SpellChecker::ChangeNumber speller_change_number = 0;
4088         if (theSpellChecker())
4089                 speller_change_number = theSpellChecker()->changeNumber();
4090         if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4091                 d->speller_state_.needsCompleteRefresh(speller_change_number);
4092         }
4093         return d->needsSpellCheck();
4094 }
4095
4096
4097 bool Paragraph::Private::ignoreWord(docstring const & word) const
4098 {
4099         // Ignore words with digits
4100         // FIXME: make this customizable
4101         // (note that some checkers ignore words with digits by default)
4102         docstring::const_iterator cit = word.begin();
4103         docstring::const_iterator const end = word.end();
4104         for (; cit != end; ++cit) {
4105                 if (isNumber((*cit)))
4106                         return true;
4107         }
4108         return false;
4109 }
4110
4111
4112 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4113         WordLangTuple & wl, docstring_list & suggestions,
4114         bool do_suggestion, bool check_learned) const
4115 {
4116         SpellChecker::Result result = SpellChecker::WORD_OK;
4117         SpellChecker * speller = theSpellChecker();
4118         if (!speller)
4119                 return result;
4120
4121         if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4122                 return result;
4123
4124         locateWord(from, to, WHOLE_WORD);
4125         if (from == to || from >= size())
4126                 return result;
4127
4128         docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4129         Language * lang = d->getSpellLanguage(from);
4130
4131         wl = WordLangTuple(word, lang);
4132
4133         if (word.empty())
4134                 return result;
4135
4136         if (needsSpellCheck() || check_learned) {
4137                 pos_type end = to;
4138                 if (!d->ignoreWord(word)) {
4139                         bool const trailing_dot = to < size() && d->text_[to] == '.';
4140                         result = speller->check(wl);
4141                         if (SpellChecker::misspelled(result) && trailing_dot) {
4142                                 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4143                                 result = speller->check(wl);
4144                                 if (!SpellChecker::misspelled(result)) {
4145                                         LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4146                                            word << "\" [" <<
4147                                            from << ".." << to << "]");
4148                                 } else {
4149                                         // spell check with dot appended failed too
4150                                         // restore original word/lang value
4151                                         word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4152                                         wl = WordLangTuple(word, lang);
4153                                 }
4154                         }
4155                 }
4156                 if (!SpellChecker::misspelled(result)) {
4157                         // area up to the begin of the next word is not misspelled
4158                         while (end < size() && isWordSeparator(end))
4159                                 ++end;
4160                 }
4161                 d->setMisspelled(from, end, result);
4162         } else {
4163                 result = d->speller_state_.getState(from);
4164         }
4165
4166         if (do_suggestion)
4167                 suggestions.clear();
4168
4169         if (SpellChecker::misspelled(result)) {
4170                 LYXERR(Debug::GUI, "misspelled word: \"" <<
4171                            word << "\" [" <<
4172                            from << ".." << to << "]");
4173                 if (do_suggestion)
4174                         speller->suggest(wl, suggestions);
4175         }
4176         return result;
4177 }
4178
4179
4180 void Paragraph::anonymize()
4181 {
4182         // This is a very crude anonymization for now
4183         for (char_type & c : d->text_)
4184                 if (isLetterChar(c) || isNumber(c))
4185                         c = 'a';
4186 }
4187
4188
4189 void Paragraph::Private::markMisspelledWords(
4190         pos_type const & first, pos_type const & last,
4191         SpellChecker::Result result,
4192         docstring const & word,
4193         SkipPositions const & skips)
4194 {
4195         if (!SpellChecker::misspelled(result)) {
4196                 setMisspelled(first, last, SpellChecker::WORD_OK);
4197                 return;
4198         }
4199         int snext = first;
4200         SpellChecker * speller = theSpellChecker();
4201         // locate and enumerate the error positions
4202         int nerrors = speller->numMisspelledWords();
4203         int numskipped = 0;
4204         SkipPositionsIterator it = skips.begin();
4205         SkipPositionsIterator et = skips.end();
4206         for (int index = 0; index < nerrors; ++index) {
4207                 int wstart;
4208                 int wlen = 0;
4209                 speller->misspelledWord(index, wstart, wlen);
4210                 /// should not happen if speller supports range checks
4211                 if (!wlen) continue;
4212                 docstring const misspelled = word.substr(wstart, wlen);
4213                 wstart += first + numskipped;
4214                 if (snext < wstart) {
4215                         /// mark the range of correct spelling
4216                         numskipped += countSkips(it, et, wstart);
4217                         setMisspelled(snext,
4218                                 wstart - 1, SpellChecker::WORD_OK);
4219                 }
4220                 snext = wstart + wlen;
4221                 numskipped += countSkips(it, et, snext);
4222                 /// mark the range of misspelling
4223                 setMisspelled(wstart, snext, result);
4224                 LYXERR(Debug::GUI, "misspelled word: \"" <<
4225                            misspelled << "\" [" <<
4226                            wstart << ".." << (snext-1) << "]");
4227                 ++snext;
4228         }
4229         if (snext <= last) {
4230                 /// mark the range of correct spelling at end
4231                 setMisspelled(snext, last, SpellChecker::WORD_OK);
4232         }
4233 }
4234
4235
4236 void Paragraph::spellCheck() const
4237 {
4238         SpellChecker * speller = theSpellChecker();
4239         if (!speller || empty() ||!needsSpellCheck())
4240                 return;
4241         pos_type start;
4242         pos_type endpos;
4243         d->rangeOfSpellCheck(start, endpos);
4244         if (speller->canCheckParagraph()) {
4245                 // loop until we leave the range
4246                 for (pos_type first = start; first < endpos; ) {
4247                         pos_type last = endpos;
4248                         Private::SkipPositions skips;
4249                         Language * lang = d->locateSpellRange(first, last, skips);
4250                         if (first >= endpos)
4251                                 break;
4252                         // start the spell checker on the unit of meaning
4253                         docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4254                         WordLangTuple wl = WordLangTuple(word, lang);
4255                         SpellChecker::Result result = word.size() ?
4256                                 speller->check(wl) : SpellChecker::WORD_OK;
4257                         d->markMisspelledWords(first, last, result, word, skips);
4258                         first = ++last;
4259                 }
4260         } else {
4261                 static docstring_list suggestions;
4262                 pos_type to = endpos;
4263                 while (start < endpos) {
4264                         WordLangTuple wl;
4265                         spellCheck(start, to, wl, suggestions, false);
4266                         start = to + 1;
4267                 }
4268         }
4269         d->readySpellCheck();
4270 }
4271
4272
4273 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4274 {
4275         bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4276         if (result || pos <= 0 || pos > size())
4277                 return result;
4278         if (check_boundary && (pos == size() || isWordSeparator(pos)))
4279                 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4280         return result;
4281 }
4282
4283
4284 string Paragraph::magicLabel() const
4285 {
4286         stringstream ss;
4287         ss << "magicparlabel-" << id();
4288         return ss.str();
4289 }
4290
4291
4292 } // namespace lyx