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