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