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