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