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