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