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