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