]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
LYX_CXX_GLOBAL_CSTD is not really useful anymore
[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 Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  * \author Dekel Tsur
13  * \author Jürgen Vigna
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "Paragraph.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "Changes.h"
25 #include "Counters.h"
26 #include "Encoding.h"
27 #include "InsetList.h"
28 #include "Language.h"
29 #include "LaTeXFeatures.h"
30 #include "Layout.h"
31 #include "Length.h"
32 #include "Font.h"
33 #include "FontList.h"
34 #include "LyXRC.h"
35 #include "OutputParams.h"
36 #include "output_latex.h"
37 #include "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
39 #include "sgml.h"
40 #include "TextClass.h"
41 #include "TexRow.h"
42 #include "VSpace.h"
43
44 #include "frontends/alert.h"
45 #include "frontends/FontMetrics.h"
46
47 #include "insets/InsetBibitem.h"
48 #include "insets/InsetLabel.h"
49
50 #include "support/convert.h"
51 #include "support/debug.h"
52 #include "support/gettext.h"
53 #include "support/lstrings.h"
54 #include "support/Messages.h"
55 #include "support/textutils.h"
56 #include "support/unicode.h"
57
58 #include <sstream>
59 #include <vector>
60
61 using namespace std;
62 using namespace lyx::support;
63
64 namespace lyx {
65
66 namespace {
67 /// Inset identifier (above 0x10ffff, for ucs-4)
68 char_type const META_INSET = 0x200001;
69 };
70
71 /////////////////////////////////////////////////////////////////////
72 //
73 // Paragraph::Private
74 //
75 /////////////////////////////////////////////////////////////////////
76
77 class Paragraph::Private
78 {
79 public:
80         ///
81         Private(Paragraph * owner);
82         /// "Copy constructor"
83         Private(Private const &, Paragraph * owner);
84
85         ///
86         void insertChar(pos_type pos, char_type c, Change const & change);
87
88         /// Output the surrogate pair formed by \p c and \p next to \p os.
89         /// \return the number of characters written.
90         int latexSurrogatePair(odocstream & os, char_type c, char_type next,
91                                Encoding const &);
92
93         /// Output a space in appropriate formatting (or a surrogate pair
94         /// if the next character is a combining character).
95         /// \return whether a surrogate pair was output.
96         bool simpleTeXBlanks(OutputParams const &,
97                              odocstream &, TexRow & texrow,
98                              pos_type i,
99                              unsigned int & column,
100                              Font const & font,
101                              Layout const & style);
102
103         /// Output consecutive unicode chars, belonging to the same script as
104         /// specified by the latex macro \p ltx, to \p os starting from \p i.
105         /// \return the number of characters written.
106         int writeScriptChars(odocstream & os, docstring const & ltx,
107                            Change &, Encoding const &, pos_type & i);
108
109         /// This could go to ParagraphParameters if we want to.
110         int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
111                               bool) const;
112
113         /// This could go to ParagraphParameters if we want to.
114         int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
115                             bool) const;
116
117         ///
118         void latexInset(Buffer const &, BufferParams const &,
119                                    odocstream &,
120                                    TexRow & texrow, OutputParams &,
121                                    Font & running_font,
122                                    Font & basefont,
123                                    Font const & outerfont,
124                                    bool & open_font,
125                                    Change & running_change,
126                                    Layout const & style,
127                                    pos_type & i,
128                                    unsigned int & column);
129
130         ///
131         void latexSpecialChar(
132                                    odocstream & os,
133                                    OutputParams & runparams,
134                                    Font & running_font,
135                                    Change & running_change,
136                                    Layout const & style,
137                                    pos_type & i,
138                                    unsigned int & column);
139
140         ///
141         bool latexSpecialT1(
142                 char_type const c,
143                 odocstream & os,
144                 pos_type & i,
145                 unsigned int & column);
146         ///
147         bool latexSpecialTypewriter(
148                 char_type const c,
149                 odocstream & os,
150                 pos_type & i,
151                 unsigned int & column);
152         ///
153         bool latexSpecialPhrase(
154                 odocstream & os,
155                 pos_type & i,
156                 unsigned int & column,
157                 OutputParams & runparams);
158
159         ///
160         void validate(LaTeXFeatures & features,
161                       Layout const & layout) const;
162
163         /// Checks if the paragraph contains only text and no inset or font change.
164         bool onlyText(Buffer const & buf, Font const & outerfont,
165                       pos_type initial) const;
166
167         /// match a string against a particular point in the paragraph
168         bool isTextAt(string const & str, pos_type pos) const;
169         
170         /// Which Paragraph owns us?
171         Paragraph * owner_;
172
173         /// In which Inset?
174         Inset * inset_owner_;
175
176         ///
177         FontList fontlist_;
178
179         ///
180         unsigned int id_;
181         ///
182         static unsigned int paragraph_id;
183         ///
184         ParagraphParameters params_;
185
186         /// position of the paragraph in the buffer. Only macros from
187         /// paragraphs strictly smaller are visible in this paragraph
188         unsigned int macrocontext_position_;
189         
190         /// for recording and looking up changes
191         Changes changes_;
192
193         ///
194         InsetList insetlist_;
195
196         ///
197         LayoutPtr layout_;
198
199         /// end of label
200         pos_type begin_of_body_;
201
202         typedef docstring TextContainer;
203         ///
204         TextContainer text_;
205 };
206
207
208 // Initialization of the counter for the paragraph id's,
209 unsigned int Paragraph::Private::paragraph_id = 0;
210
211 namespace {
212
213 struct special_phrase {
214         string phrase;
215         docstring macro;
216         bool builtin;
217 };
218
219 special_phrase const special_phrases[] = {
220         { "LyX", from_ascii("\\LyX{}"), false },
221         { "TeX", from_ascii("\\TeX{}"), true },
222         { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
223         { "LaTeX", from_ascii("\\LaTeX{}"), true },
224 };
225
226 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
227
228 } // namespace anon
229
230
231 Paragraph::Private::Private(Paragraph * owner)
232         : owner_(owner), inset_owner_(0), begin_of_body_(0)
233 {
234         id_ = paragraph_id++;
235         macrocontext_position_ = 0;
236         text_.reserve(100);
237 }
238
239
240 Paragraph::Private::Private(Private const & p, Paragraph * owner)
241         : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_), 
242           params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
243           layout_(p.layout_), begin_of_body_(p.begin_of_body_), text_(p.text_)
244 {
245         id_ = paragraph_id++;
246 }
247
248
249 bool Paragraph::isChanged(pos_type start, pos_type end) const
250 {
251         BOOST_ASSERT(start >= 0 && start <= size());
252         BOOST_ASSERT(end > start && end <= size() + 1);
253
254         return d->changes_.isChanged(start, end);
255 }
256
257
258 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const {
259         // keep the logic here in sync with the logic of eraseChars()
260
261         if (!trackChanges) {
262                 return true;
263         }
264
265         Change change = d->changes_.lookup(size());
266
267         return change.type == Change::INSERTED && change.author == 0;
268 }
269
270
271 void Paragraph::setChange(Change const & change)
272 {
273         // beware of the imaginary end-of-par character!
274         d->changes_.set(change, 0, size() + 1);
275
276         /*
277          * Propagate the change recursively - but not in case of DELETED!
278          *
279          * Imagine that your co-author makes changes in an existing inset. He
280          * sends your document to you and you come to the conclusion that the
281          * inset should go completely. If you erase it, LyX must not delete all
282          * text within the inset. Otherwise, the change tracked insertions of
283          * your co-author get lost and there is no way to restore them later.
284          *
285          * Conclusion: An inset's content should remain untouched if you delete it
286          */
287
288         if (change.type != Change::DELETED) {
289                 for (pos_type pos = 0; pos < size(); ++pos) {
290                         if (isInset(pos))
291                                 getInset(pos)->setChange(change);
292                 }
293         }
294 }
295
296
297 void Paragraph::setChange(pos_type pos, Change const & change)
298 {
299         BOOST_ASSERT(pos >= 0 && pos <= size());
300
301         d->changes_.set(change, pos);
302
303         // see comment in setChange(Change const &) above
304
305         if (change.type != Change::DELETED &&
306             pos < size() && isInset(pos)) {
307                 getInset(pos)->setChange(change);
308         }
309 }
310
311
312 Change const & Paragraph::lookupChange(pos_type pos) const
313 {
314         BOOST_ASSERT(pos >= 0 && pos <= size());
315
316         return d->changes_.lookup(pos);
317 }
318
319
320 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
321                 pos_type end)
322 {
323         BOOST_ASSERT(start >= 0 && start <= size());
324         BOOST_ASSERT(end > start && end <= size() + 1);
325
326         for (pos_type pos = start; pos < end; ++pos) {
327                 switch (lookupChange(pos).type) {
328                         case Change::UNCHANGED:
329                                 // accept changes in nested inset
330                                 if (pos < size() && isInset(pos))
331                                         getInset(pos)->acceptChanges(bparams);
332
333                                 break;
334
335                         case Change::INSERTED:
336                                 d->changes_.set(Change(Change::UNCHANGED), pos);
337                                 // also accept changes in nested inset
338                                 if (pos < size() && isInset(pos)) {
339                                         getInset(pos)->acceptChanges(bparams);
340                                 }
341                                 break;
342
343                         case Change::DELETED:
344                                 // Suppress access to non-existent
345                                 // "end-of-paragraph char"
346                                 if (pos < size()) {
347                                         eraseChar(pos, false);
348                                         --end;
349                                         --pos;
350                                 }
351                                 break;
352                 }
353
354         }
355 }
356
357
358 void Paragraph::rejectChanges(BufferParams const & bparams,
359                 pos_type start, pos_type end)
360 {
361         BOOST_ASSERT(start >= 0 && start <= size());
362         BOOST_ASSERT(end > start && end <= size() + 1);
363
364         for (pos_type pos = start; pos < end; ++pos) {
365                 switch (lookupChange(pos).type) {
366                         case Change::UNCHANGED:
367                                 // reject changes in nested inset
368                                 if (pos < size() && isInset(pos)) {
369                                         getInset(pos)->rejectChanges(bparams);
370                                 }
371                                 break;
372
373                         case Change::INSERTED:
374                                 // Suppress access to non-existent
375                                 // "end-of-paragraph char"
376                                 if (pos < size()) {
377                                         eraseChar(pos, false);
378                                         --end;
379                                         --pos;
380                                 }
381                                 break;
382
383                         case Change::DELETED:
384                                 d->changes_.set(Change(Change::UNCHANGED), pos);
385
386                                 // Do NOT reject changes within a deleted inset!
387                                 // There may be insertions of a co-author inside of it!
388
389                                 break;
390                 }
391         }
392 }
393
394
395 void Paragraph::Private::insertChar(pos_type pos, char_type c,
396                 Change const & change)
397 {
398         BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
399
400         // track change
401         changes_.insert(change, pos);
402
403         // This is actually very common when parsing buffers (and
404         // maybe inserting ascii text)
405         if (pos == pos_type(text_.size())) {
406                 // when appending characters, no need to update tables
407                 text_.push_back(c);
408                 return;
409         }
410
411         text_.insert(text_.begin() + pos, c);
412
413         // Update the font table.
414         fontlist_.increasePosAfterPos(pos);
415
416         // Update the insets
417         insetlist_.increasePosAfterPos(pos);
418 }
419
420
421 void Paragraph::insertInset(pos_type pos, Inset * inset,
422                                    Change const & change)
423 {
424         BOOST_ASSERT(inset);
425         BOOST_ASSERT(pos >= 0 && pos <= size());
426
427         d->insertChar(pos, META_INSET, change);
428         BOOST_ASSERT(d->text_[pos] == META_INSET);
429
430         // Add a new entry in the insetlist_.
431         d->insetlist_.insert(inset, pos);
432 }
433
434
435 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
436 {
437         BOOST_ASSERT(pos >= 0 && pos <= size());
438
439         // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
440
441         if (trackChanges) {
442                 Change change = d->changes_.lookup(pos);
443
444                 // set the character to DELETED if
445                 //  a) it was previously unchanged or
446                 //  b) it was inserted by a co-author
447
448                 if (change.type == Change::UNCHANGED ||
449                     (change.type == Change::INSERTED && change.author != 0)) {
450                         setChange(pos, Change(Change::DELETED));
451                         return false;
452                 }
453
454                 if (change.type == Change::DELETED)
455                         return false;
456         }
457
458         // Don't physically access the imaginary end-of-paragraph character.
459         // eraseChar() can only mark it as DELETED. A physical deletion of
460         // end-of-par must be handled externally.
461         if (pos == size()) {
462                 return false;
463         }
464
465         // track change
466         d->changes_.erase(pos);
467
468         // if it is an inset, delete the inset entry
469         if (d->text_[pos] == META_INSET)
470                 d->insetlist_.erase(pos);
471
472         d->text_.erase(d->text_.begin() + pos);
473
474         // Update the fontlist_
475         d->fontlist_.erase(pos);
476
477         // Update the insetlist_
478         d->insetlist_.decreasePosAfterPos(pos);
479
480         return true;
481 }
482
483
484 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
485 {
486         BOOST_ASSERT(start >= 0 && start <= size());
487         BOOST_ASSERT(end >= start && end <= size() + 1);
488
489         pos_type i = start;
490         for (pos_type count = end - start; count; --count) {
491                 if (!eraseChar(i, trackChanges))
492                         ++i;
493         }
494         return end - i;
495 }
496
497
498 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
499                 char_type next, Encoding const & encoding)
500 {
501         // Writing next here may circumvent a possible font change between
502         // c and next. Since next is only output if it forms a surrogate pair
503         // with c we can ignore this:
504         // A font change inside a surrogate pair does not make sense and is
505         // hopefully impossible to input.
506         // FIXME: change tracking
507         // Is this correct WRT change tracking?
508         docstring const latex1 = encoding.latexChar(next);
509         docstring const latex2 = encoding.latexChar(c);
510         os << latex1 << '{' << latex2 << '}';
511         return latex1.length() + latex2.length() + 2;
512 }
513
514
515 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
516                                        odocstream & os, TexRow & texrow,
517                                        pos_type i,
518                                        unsigned int & column,
519                                        Font const & font,
520                                        Layout const & style)
521 {
522         if (style.pass_thru || runparams.verbatim)
523                 return false;
524
525         if (i + 1 < int(text_.size())) {
526                 char_type next = text_[i + 1];
527                 if (Encodings::isCombiningChar(next)) {
528                         Encoding const & encoding = *(runparams.encoding);
529                         // This space has an accent, so we must always output it.
530                         column += latexSurrogatePair(os, ' ', next, encoding) - 1;
531                         return true;
532                 }
533         }
534
535         if (lyxrc.plaintext_linelen > 0
536             && column > lyxrc.plaintext_linelen
537             && i
538             && text_[i - 1] != ' '
539             && (i + 1 < int(text_.size()))
540             // same in FreeSpacing mode
541             && !owner_->isFreeSpacing()
542             // In typewriter mode, we want to avoid
543             // ! . ? : at the end of a line
544             && !(font.fontInfo().family() == TYPEWRITER_FAMILY
545                  && (text_[i - 1] == '.'
546                      || text_[i - 1] == '?'
547                      || text_[i - 1] == ':'
548                      || text_[i - 1] == '!'))) {
549                 os << '\n';
550                 texrow.newline();
551                 texrow.start(owner_->id(), i + 1);
552                 column = 0;
553         } else if (style.free_spacing) {
554                 os << '~';
555         } else {
556                 os << ' ';
557         }
558         return false;
559 }
560
561
562 int Paragraph::Private::writeScriptChars(odocstream & os,
563                                          docstring const & ltx,
564                                          Change & runningChange,
565                                          Encoding const & encoding,
566                                          pos_type & i)
567 {
568         // FIXME: modifying i here is not very nice...
569
570         // We only arrive here when a proper language for character text_[i] has
571         // not been specified (i.e., it could not be translated in the current
572         // latex encoding) and it belongs to a known script.
573         // Parameter ltx contains the latex translation of text_[i] as specified in
574         // the unicodesymbols file and is something like "\textXXX{<spec>}".
575         // The latex macro name "textXXX" specifies the script to which text_[i]
576         // belongs and we use it in order to check whether characters from the
577         // same script immediately follow, such that we can collect them in a
578         // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
579         // for the first char but only "<spec>" for all subsequent chars.
580         docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
581         docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
582         string script = to_ascii(ltx.substr(1, brace1 - 1));
583         int length = ltx.substr(0, brace2).length();
584         os << ltx.substr(0, brace2);
585         int size = text_.size();
586         while (i + 1 < size) {
587                 char_type const next = text_[i + 1];
588                 // Stop here if next character belongs to another script
589                 // or there is a change in change tracking status.
590                 if (!Encodings::isKnownScriptChar(next, script) ||
591                     runningChange != owner_->lookupChange(i + 1))
592                         break;
593                 Font prev_font;
594                 bool found = false;
595                 FontList::const_iterator cit = fontlist_.begin();
596                 FontList::const_iterator end = fontlist_.end();
597                 for (; cit != end; ++cit) {
598                         if (cit->pos() >= i && !found) {
599                                 prev_font = cit->font();
600                                 found = true;
601                         }
602                         if (cit->pos() >= i + 1)
603                                 break;
604                 }
605                 // Stop here if there is a font attribute or encoding change.
606                 if (found && cit != end && prev_font != cit->font())
607                         break;
608                 docstring const latex = encoding.latexChar(next);
609                 docstring::size_type const b1 =
610                                         latex.find_first_of(from_ascii("{"));
611                 docstring::size_type const b2 =
612                                         latex.find_last_of(from_ascii("}"));
613                 int const len = b2 - b1 - 1;
614                 os << latex.substr(b1 + 1, len);
615                 length += len;
616                 ++i;
617         }
618         os << '}';
619         ++length;
620         return length;
621 }
622
623
624 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
625 {
626         pos_type const len = str.length();
627
628         // is the paragraph large enough?
629         if (pos + len > int(text_.size()))
630                 return false;
631
632         // does the wanted text start at point?
633         for (string::size_type i = 0; i < str.length(); ++i) {
634                 // Caution: direct comparison of characters works only
635                 // because str is pure ASCII.
636                 if (str[i] != text_[pos + i])
637                         return false;
638         }
639
640         return fontlist_.hasChangeInRange(pos, len);
641 }
642
643
644 void Paragraph::Private::latexInset(Buffer const & buf,
645                                              BufferParams const & bparams,
646                                              odocstream & os,
647                                              TexRow & texrow,
648                                              OutputParams & runparams,
649                                              Font & running_font,
650                                              Font & basefont,
651                                              Font const & outerfont,
652                                              bool & open_font,
653                                              Change & running_change,
654                                              Layout const & style,
655                                              pos_type & i,
656                                              unsigned int & column)
657 {
658         Inset * inset = owner_->getInset(i);
659         BOOST_ASSERT(inset);
660
661         if (style.pass_thru) {
662                 inset->plaintext(buf, os, runparams);
663                 return;
664         }
665
666         // FIXME: move this to InsetNewline::latex
667         if (inset->lyxCode() == NEWLINE_CODE) {
668                 // newlines are handled differently here than
669                 // the default in simpleTeXSpecialChars().
670                 if (!style.newline_allowed) {
671                         os << '\n';
672                 } else {
673                         if (open_font) {
674                                 column += running_font.latexWriteEndChanges(
675                                         os, bparams, runparams,
676                                         basefont, basefont);
677                                 open_font = false;
678                         }
679
680                         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
681                                 os << '~';
682
683                         basefont = owner_->getLayoutFont(bparams, outerfont);
684                         running_font = basefont;
685
686                         if (runparams.moving_arg)
687                                 os << "\\protect ";
688
689                 }
690                 texrow.newline();
691                 texrow.start(owner_->id(), i + 1);
692                 column = 0;
693         }
694
695         if (owner_->lookupChange(i).type == Change::DELETED) {
696                 if( ++runparams.inDeletedInset == 1)
697                         runparams.changeOfDeletedInset = owner_->lookupChange(i);
698         }
699
700         if (inset->canTrackChanges()) {
701                 column += Changes::latexMarkChange(os, bparams, running_change,
702                         Change(Change::UNCHANGED));
703                 running_change = Change(Change::UNCHANGED);
704         }
705
706         bool close = false;
707         odocstream::pos_type const len = os.tellp();
708
709         if (inset->forceLTR() 
710             && running_font.isRightToLeft()
711                 // ERT is an exception, it should be output with no decorations at all
712                 && inset->lyxCode() != ERT_CODE) {
713                 if (running_font.language()->lang() == "farsi")
714                         os << "\\beginL{}";
715                 else
716                         os << "\\L{";
717                 close = true;
718         }
719
720         // FIXME: Bug: we can have an empty font change here!
721         // if there has just been a font change, we are going to close it
722         // right now, which means stupid latex code like \textsf{}. AFAIK,
723         // this does not harm dvi output. A minor bug, thus (JMarc)
724
725         // Some insets cannot be inside a font change command.
726         // However, even such insets *can* be placed in \L or \R
727         // or their equivalents (for RTL language switches), so we don't
728         // close the language in those cases.
729         // ArabTeX, though, cannot handle this special behavior, it seems.
730         bool arabtex = basefont.language()->lang() == "arabic_arabtex"
731                 || running_font.language()->lang() == "arabic_arabtex";
732         if (open_font && inset->noFontChange()) {
733                 bool closeLanguage = arabtex
734                         || basefont.isRightToLeft() == running_font.isRightToLeft();
735                 unsigned int count = running_font.latexWriteEndChanges(os,
736                         bparams, runparams, basefont, basefont, closeLanguage);
737                 column += count;
738                 // if any font properties were closed, update the running_font, 
739                 // making sure, however, to leave the language as it was
740                 if (count > 0) {
741                         // FIXME: probably a better way to keep track of the old 
742                         // language, than copying the entire font?
743                         Font const copy_font(running_font);
744                         basefont = owner_->getLayoutFont(bparams, outerfont);
745                         running_font = basefont;
746                         if (!closeLanguage)
747                                 running_font.setLanguage(copy_font.language());
748                         // leave font open if language is still open
749                         open_font = (running_font.language() == basefont.language());
750                         if (closeLanguage)
751                                 runparams.local_font = &basefont;
752                 }
753         }
754
755         int tmp = inset->latex(buf, os, runparams);
756
757         if (close) {
758         if (running_font.language()->lang() == "farsi")
759                         os << "\\endL{}";
760                 else
761                         os << '}';
762         }
763
764         if (tmp) {
765                 for (int j = 0; j < tmp; ++j)
766                         texrow.newline();
767
768                 texrow.start(owner_->id(), i + 1);
769                 column = 0;
770         } else {
771                 column += os.tellp() - len;
772         }
773
774         if (owner_->lookupChange(i).type == Change::DELETED)
775                 --runparams.inDeletedInset;
776 }
777
778
779 void Paragraph::Private::latexSpecialChar(
780                                              odocstream & os,
781                                              OutputParams & runparams,
782                                              Font & running_font,
783                                              Change & running_change,
784                                              Layout const & style,
785                                              pos_type & i,
786                                              unsigned int & column)
787 {
788         char_type const c = text_[i];
789
790         if (style.pass_thru) {
791                 if (c != '\0')
792                         // FIXME UNICODE: This can fail if c cannot
793                         // be encoded in the current encoding.
794                         os.put(c);
795                 return;
796         }
797
798         if (runparams.verbatim) {
799                 os.put(c);
800                 return;
801         }
802
803         if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
804                 return;
805
806         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
807                 && latexSpecialTypewriter(c, os, i, column))
808                 return;
809
810         // Otherwise, we use what LaTeX provides us.
811         switch (c) {
812         case '\\':
813                 os << "\\textbackslash{}";
814                 column += 15;
815                 break;
816         case '<':
817                 os << "\\textless{}";
818                 column += 10;
819                 break;
820         case '>':
821                 os << "\\textgreater{}";
822                 column += 13;
823                 break;
824         case '|':
825                 os << "\\textbar{}";
826                 column += 9;
827                 break;
828         case '-':
829                 os << '-';
830                 break;
831         case '\"':
832                 os << "\\char`\\\"{}";
833                 column += 9;
834                 break;
835
836         case '$': case '&':
837         case '%': case '#': case '{':
838         case '}': case '_':
839                 os << '\\';
840                 os.put(c);
841                 column += 1;
842                 break;
843
844         case '~':
845                 os << "\\textasciitilde{}";
846                 column += 16;
847                 break;
848
849         case '^':
850                 os << "\\textasciicircum{}";
851                 column += 17;
852                 break;
853
854         case '*': case '[':
855                 // avoid being mistaken for optional arguments
856                 os << '{';
857                 os.put(c);
858                 os << '}';
859                 column += 2;
860                 break;
861
862         case ' ':
863                 // Blanks are printed before font switching.
864                 // Sure? I am not! (try nice-latex)
865                 // I am sure it's correct. LyX might be smarter
866                 // in the future, but for now, nothing wrong is
867                 // written. (Asger)
868                 break;
869
870         default:
871
872                 // LyX, LaTeX etc.
873                 if (latexSpecialPhrase(os, i, column, runparams))
874                         return;
875
876                 if (c == '\0')
877                         return;
878
879                 Encoding const & encoding = *(runparams.encoding);
880                 if (i + 1 < int(text_.size())) {
881                         char_type next = text_[i + 1];
882                         if (Encodings::isCombiningChar(next)) {
883                                 column += latexSurrogatePair(os, c, next, encoding) - 1;
884                                 ++i;
885                                 break;
886                         }
887                 }
888                 string script;
889                 docstring const latex = encoding.latexChar(c);
890                 if (Encodings::isKnownScriptChar(c, script)
891                     && prefixIs(latex, from_ascii("\\" + script)))
892                         column += writeScriptChars(os, latex,
893                                         running_change, encoding, i) - 1;
894                 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
895                         // Prevent eating of a following
896                         // space or command corruption by
897                         // following characters
898                         column += latex.length() + 1;
899                         os << latex << "{}";
900                 } else {
901                         column += latex.length() - 1;
902                         os << latex;
903                 }
904                 break;
905         }
906 }
907
908
909 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
910         pos_type & i, unsigned int & column)
911 {
912         switch (c) {
913         case '>':
914         case '<':
915                 os.put(c);
916                 // In T1 encoding, these characters exist
917                 // but we should avoid ligatures
918                 if (i + 1 > int(text_.size()) || text_[i + 1] != c)
919                         return true;
920                 os << "\\,{}";
921                 column += 3;
922                 // Alternative code:
923                 //os << "\\textcompwordmark{}";
924                 //column += 19;
925                 return true;
926         case '|':
927                 os.put(c);
928                 return true;
929         default:
930                 return false;
931         }
932 }
933
934
935 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
936         pos_type & i, unsigned int & column)
937 {
938         switch (c) {
939         case '-':
940                 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
941                         // "--" in Typewriter mode -> "-{}-"
942                         os << "-{}";
943                         column += 2;
944                 } else
945                         os << '-';
946                 return true;
947
948         // I assume this is hack treating typewriter as verbatim
949         // FIXME UNICODE: This can fail if c cannot be encoded
950         // in the current encoding.
951
952         case '\0':
953                 return true;
954
955         // Those characters are not directly supported.
956         case '\\':
957         case '\"':
958         case '$': case '&':
959         case '%': case '#': case '{':
960         case '}': case '_':
961         case '~':
962         case '^':
963         case '*': case '[':
964         case ' ':
965                 return false;
966
967         default:
968                 // With Typewriter font, these characters exist.
969                 os.put(c);
970                 return true;
971         }
972 }
973
974
975 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
976         unsigned int & column, OutputParams & runparams)
977 {
978         // FIXME: if we have "LaTeX" with a font
979         // change in the middle (before the 'T', then
980         // the "TeX" part is still special cased.
981         // Really we should only operate this on
982         // "words" for some definition of word
983
984         for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
985                 if (!isTextAt(special_phrases[pnr].phrase, i))
986                         continue;
987                 if (runparams.moving_arg)
988                         os << "\\protect";
989                 os << special_phrases[pnr].macro;
990                 i += special_phrases[pnr].phrase.length() - 1;
991                 column += special_phrases[pnr].macro.length() - 1;
992                 return true;
993         }
994         return false;
995 }
996
997
998 void Paragraph::Private::validate(LaTeXFeatures & features,
999                                 Layout const & layout) const
1000 {
1001         // check the params.
1002         if (!params_.spacing().isDefault())
1003                 features.require("setspace");
1004
1005         // then the layouts
1006         features.useLayout(layout.name());
1007
1008         // then the fonts
1009         fontlist_.validate(features);
1010
1011         // then the indentation
1012         if (!params_.leftIndent().zero())
1013                 features.require("ParagraphLeftIndent");
1014
1015         // then the insets
1016         InsetList::const_iterator icit = insetlist_.begin();
1017         InsetList::const_iterator iend = insetlist_.end();
1018         for (; icit != iend; ++icit) {
1019                 if (icit->inset) {
1020                         icit->inset->validate(features);
1021                         if (layout.needprotect &&
1022                             icit->inset->lyxCode() == FOOT_CODE)
1023                                 features.require("NeedLyXFootnoteCode");
1024                 }
1025         }
1026
1027         // then the contents
1028         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1029                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1030                         if (!special_phrases[pnr].builtin
1031                             && isTextAt(special_phrases[pnr].phrase, i)) {
1032                                 features.require(special_phrases[pnr].phrase);
1033                                 break;
1034                         }
1035                 }
1036                 Encodings::validate(text_[i], features);
1037         }
1038 }
1039
1040 /////////////////////////////////////////////////////////////////////
1041 //
1042 // Paragraph
1043 //
1044 /////////////////////////////////////////////////////////////////////
1045
1046 Paragraph::Paragraph()
1047         : d(new Paragraph::Private(this))
1048 {
1049         itemdepth = 0;
1050         d->params_.clear();
1051 }
1052
1053
1054 Paragraph::Paragraph(Paragraph const & par)
1055         : itemdepth(par.itemdepth),
1056         d(new Paragraph::Private(*par.d, this))
1057 {
1058 }
1059
1060
1061 Paragraph & Paragraph::operator=(Paragraph const & par)
1062 {
1063         // needed as we will destroy the private part before copying it
1064         if (&par != this) {
1065                 itemdepth = par.itemdepth;
1066
1067                 delete d;
1068                 d = new Private(*par.d, this);
1069         }
1070         return *this;
1071 }
1072
1073
1074 Paragraph::~Paragraph()
1075 {
1076         delete d;
1077 }
1078
1079
1080 void Paragraph::write(Buffer const & buf, ostream & os,
1081                           BufferParams const & bparams,
1082                           depth_type & dth) const
1083 {
1084         // The beginning or end of a deeper (i.e. nested) area?
1085         if (dth != params().depth()) {
1086                 if (params().depth() > dth) {
1087                         while (params().depth() > dth) {
1088                                 os << "\n\\begin_deeper";
1089                                 ++dth;
1090                         }
1091                 } else {
1092                         while (params().depth() < dth) {
1093                                 os << "\n\\end_deeper";
1094                                 --dth;
1095                         }
1096                 }
1097         }
1098
1099         // First write the layout
1100         os << "\n\\begin_layout " << to_utf8(layout()->name()) << '\n';
1101
1102         params().write(os);
1103
1104         Font font1(inherit_font, bparams.language);
1105
1106         Change running_change = Change(Change::UNCHANGED);
1107
1108         int column = 0;
1109         for (pos_type i = 0; i <= size(); ++i) {
1110
1111                 Change change = lookupChange(i);
1112                 Changes::lyxMarkChange(os, column, running_change, change);
1113                 running_change = change;
1114
1115                 if (i == size())
1116                         break;
1117
1118                 // Write font changes
1119                 Font font2 = getFontSettings(bparams, i);
1120                 if (font2 != font1) {
1121                         font2.lyxWriteChanges(font1, os);
1122                         column = 0;
1123                         font1 = font2;
1124                 }
1125
1126                 char_type const c = d->text_[i];
1127                 switch (c) {
1128                 case META_INSET:
1129                 {
1130                         Inset const * inset = getInset(i);
1131                         if (inset)
1132                                 if (inset->directWrite()) {
1133                                         // international char, let it write
1134                                         // code directly so it's shorter in
1135                                         // the file
1136                                         inset->write(buf, os);
1137                                 } else {
1138                                         if (i)
1139                                                 os << '\n';
1140                                         os << "\\begin_inset ";
1141                                         inset->write(buf, os);
1142                                         os << "\n\\end_inset\n\n";
1143                                         column = 0;
1144                                 }
1145                 }
1146                 break;
1147                 case '\\':
1148                         os << "\n\\backslash\n";
1149                         column = 0;
1150                         break;
1151                 case '.':
1152                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1153                                 os << ".\n";
1154                                 column = 0;
1155                         } else
1156                                 os << '.';
1157                         break;
1158                 default:
1159                         if ((column > 70 && c == ' ')
1160                             || column > 79) {
1161                                 os << '\n';
1162                                 column = 0;
1163                         }
1164                         // this check is to amend a bug. LyX sometimes
1165                         // inserts '\0' this could cause problems.
1166                         if (c != '\0') {
1167                                 vector<char> tmp = ucs4_to_utf8(c);
1168                                 tmp.push_back('\0');
1169                                 os << &tmp[0];
1170                         } else
1171                                 lyxerr << "ERROR (Paragraph::writeFile):"
1172                                         " NULL char in structure." << endl;
1173                         ++column;
1174                         break;
1175                 }
1176         }
1177
1178         os << "\n\\end_layout\n";
1179 }
1180
1181
1182 void Paragraph::validate(LaTeXFeatures & features) const
1183 {
1184         d->validate(features, *layout());
1185 }
1186
1187
1188 void Paragraph::insert(pos_type start, docstring const & str,
1189                        Font const & font, Change const & change)
1190 {
1191         for (size_t i = 0, n = str.size(); i != n ; ++i)
1192                 insertChar(start + i, str[i], font, change);
1193 }
1194
1195
1196 void Paragraph::appendChar(char_type c, Font const & font,
1197                 Change const & change)
1198 {
1199         // track change
1200         d->changes_.insert(change, d->text_.size());
1201         // when appending characters, no need to update tables
1202         d->text_.push_back(c);
1203         setFont(d->text_.size() - 1, font);
1204 }
1205
1206
1207 void Paragraph::appendString(docstring const & s, Font const & font,
1208                 Change const & change)
1209 {
1210         pos_type end = s.size();
1211         size_t oldsize = d->text_.size();
1212         size_t newsize = oldsize + end;
1213         size_t capacity = d->text_.capacity();
1214         if (newsize >= capacity)
1215                 d->text_.reserve(max(capacity + 100, newsize));
1216
1217         // when appending characters, no need to update tables
1218         d->text_.append(s);
1219
1220         // FIXME: Optimize this!
1221         for (pos_type i = 0; i != end; ++i) {
1222                 // track change
1223                 d->changes_.insert(change, i);
1224         }
1225         d->fontlist_.set(oldsize, font);
1226         d->fontlist_.set(newsize - 1, font);
1227 }
1228
1229
1230 void Paragraph::insertChar(pos_type pos, char_type c,
1231                            bool trackChanges)
1232 {
1233         d->insertChar(pos, c, Change(trackChanges ?
1234                            Change::INSERTED : Change::UNCHANGED));
1235 }
1236
1237
1238 void Paragraph::insertChar(pos_type pos, char_type c,
1239                            Font const & font, bool trackChanges)
1240 {
1241         d->insertChar(pos, c, Change(trackChanges ?
1242                            Change::INSERTED : Change::UNCHANGED));
1243         setFont(pos, font);
1244 }
1245
1246
1247 void Paragraph::insertChar(pos_type pos, char_type c,
1248                            Font const & font, Change const & change)
1249 {
1250         d->insertChar(pos, c, change);
1251         setFont(pos, font);
1252 }
1253
1254
1255 void Paragraph::insertInset(pos_type pos, Inset * inset,
1256                             Font const & font, Change const & change)
1257 {
1258         insertInset(pos, inset, change);
1259         // Set the font/language of the inset...
1260         setFont(pos, font);
1261 }
1262
1263
1264 bool Paragraph::insetAllowed(InsetCode code)
1265 {
1266         return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1267 }
1268
1269
1270 void Paragraph::resetFonts(Font const & font)
1271 {
1272         d->fontlist_.clear();
1273         d->fontlist_.set(0, font);
1274         d->fontlist_.set(d->text_.size() - 1, font);
1275 }
1276
1277 // Gets uninstantiated font setting at position.
1278 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1279                                          pos_type pos) const
1280 {
1281         if (pos > size()) {
1282                 lyxerr << " pos: " << pos << " size: " << size() << endl;
1283                 BOOST_ASSERT(pos <= size());
1284         }
1285
1286         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1287         if (cit != d->fontlist_.end())
1288                 return cit->font();
1289
1290         if (pos == size() && !empty())
1291                 return getFontSettings(bparams, pos - 1);
1292
1293         return Font(inherit_font, getParLanguage(bparams));
1294 }
1295
1296
1297 FontSpan Paragraph::fontSpan(pos_type pos) const
1298 {
1299         BOOST_ASSERT(pos <= size());
1300         pos_type start = 0;
1301
1302         FontList::const_iterator cit = d->fontlist_.begin();
1303         FontList::const_iterator end = d->fontlist_.end();
1304         for (; cit != end; ++cit) {
1305                 if (cit->pos() >= pos) {
1306                         if (pos >= beginOfBody())
1307                                 return FontSpan(max(start, beginOfBody()),
1308                                                 cit->pos());
1309                         else
1310                                 return FontSpan(start,
1311                                                 min(beginOfBody() - 1,
1312                                                          cit->pos()));
1313                 }
1314                 start = cit->pos() + 1;
1315         }
1316
1317         // This should not happen, but if so, we take no chances.
1318         //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1319         //      << endl;
1320         return FontSpan(pos, pos);
1321 }
1322
1323
1324 // Gets uninstantiated font setting at position 0
1325 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1326 {
1327         if (!empty() && !d->fontlist_.empty())
1328                 return d->fontlist_.begin()->font();
1329
1330         return Font(inherit_font, bparams.language);
1331 }
1332
1333
1334 // Gets the fully instantiated font at a given position in a paragraph
1335 // This is basically the same function as Text::GetFont() in text2.cpp.
1336 // The difference is that this one is used for generating the LaTeX file,
1337 // and thus cosmetic "improvements" are disallowed: This has to deliver
1338 // the true picture of the buffer. (Asger)
1339 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1340                                  Font const & outerfont) const
1341 {
1342         BOOST_ASSERT(pos >= 0);
1343
1344         Font font = getFontSettings(bparams, pos);
1345
1346         pos_type const body_pos = beginOfBody();
1347         if (pos < body_pos)
1348                 font.fontInfo().realize(d->layout_->labelfont);
1349         else
1350                 font.fontInfo().realize(d->layout_->font);
1351
1352         font.fontInfo().realize(outerfont.fontInfo());
1353         font.fontInfo().realize(bparams.getFont().fontInfo());
1354
1355         return font;
1356 }
1357
1358
1359 Font const Paragraph::getLabelFont
1360         (BufferParams const & bparams, Font const & outerfont) const
1361 {
1362         FontInfo tmpfont = layout()->labelfont;
1363         tmpfont.realize(outerfont.fontInfo());
1364         tmpfont.realize(bparams.getFont().fontInfo());
1365         return Font(tmpfont, getParLanguage(bparams));
1366 }
1367
1368
1369 Font const Paragraph::getLayoutFont
1370         (BufferParams const & bparams, Font const & outerfont) const
1371 {
1372         FontInfo tmpfont = layout()->font;
1373         tmpfont.realize(outerfont.fontInfo());
1374         tmpfont.realize(bparams.getFont().fontInfo());
1375         return Font(tmpfont, getParLanguage(bparams));
1376 }
1377
1378
1379 /// Returns the height of the highest font in range
1380 FontSize Paragraph::highestFontInRange
1381         (pos_type startpos, pos_type endpos, FontSize def_size) const
1382 {
1383         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1384 }
1385
1386
1387 char_type
1388 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1389 {
1390         char_type c = d->text_[pos];
1391         if (!lyxrc.rtl_support)
1392                 return c;
1393
1394         char_type uc = c;
1395         switch (c) {
1396         case '(':
1397                 uc = ')';
1398                 break;
1399         case ')':
1400                 uc = '(';
1401                 break;
1402         case '[':
1403                 uc = ']';
1404                 break;
1405         case ']':
1406                 uc = '[';
1407                 break;
1408         case '{':
1409                 uc = '}';
1410                 break;
1411         case '}':
1412                 uc = '{';
1413                 break;
1414         case '<':
1415                 uc = '>';
1416                 break;
1417         case '>':
1418                 uc = '<';
1419                 break;
1420         }
1421         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1422                 return uc;
1423         else
1424                 return c;
1425 }
1426
1427
1428 void Paragraph::setFont(pos_type pos, Font const & font)
1429 {
1430         BOOST_ASSERT(pos <= size());
1431
1432         // First, reduce font against layout/label font
1433         // Update: The setCharFont() routine in text2.cpp already
1434         // reduces font, so we don't need to do that here. (Asger)
1435         
1436         d->fontlist_.set(pos, font);
1437 }
1438
1439
1440 void Paragraph::makeSameLayout(Paragraph const & par)
1441 {
1442         layout(par.layout());
1443         // move to pimpl?
1444         d->params_ = par.params();
1445 }
1446
1447
1448 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1449 {
1450         if (isFreeSpacing())
1451                 return false;
1452
1453         int pos = 0;
1454         int count = 0;
1455
1456         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1457                 if (eraseChar(pos, trackChanges))
1458                         ++count;
1459                 else
1460                         ++pos;
1461         }
1462
1463         return count > 0 || pos > 0;
1464 }
1465
1466
1467 bool Paragraph::hasSameLayout(Paragraph const & par) const
1468 {
1469         return par.layout() == layout() && d->params_.sameLayout(par.params());
1470 }
1471
1472
1473 depth_type Paragraph::getDepth() const
1474 {
1475         return params().depth();
1476 }
1477
1478
1479 depth_type Paragraph::getMaxDepthAfter() const
1480 {
1481         if (layout()->isEnvironment())
1482                 return params().depth() + 1;
1483         else
1484                 return params().depth();
1485 }
1486
1487
1488 char Paragraph::getAlign() const
1489 {
1490         if (params().align() == LYX_ALIGN_LAYOUT)
1491                 return layout()->align;
1492         else
1493                 return params().align();
1494 }
1495
1496
1497 docstring const & Paragraph::getLabelstring() const
1498 {
1499         return params().labelString();
1500 }
1501
1502
1503 // the next two functions are for the manual labels
1504 docstring const Paragraph::getLabelWidthString() const
1505 {
1506         if (layout()->margintype == MARGIN_MANUAL)
1507                 return params().labelWidthString();
1508         else
1509                 return _("Senseless with this layout!");
1510 }
1511
1512
1513 void Paragraph::setLabelWidthString(docstring const & s)
1514 {
1515         params().labelWidthString(s);
1516 }
1517
1518
1519 docstring const Paragraph::translateIfPossible(docstring const & s,
1520                 BufferParams const & bparams) const
1521 {
1522         if (!isAscii(s) || s.empty()) {
1523                 // This must be a user defined layout. We cannot translate
1524                 // this, since gettext accepts only ascii keys.
1525                 return s;
1526         }
1527         // Probably standard layout, try to translate
1528         Messages & m = getMessages(getParLanguage(bparams)->code());
1529         return m.get(to_ascii(s));
1530 }
1531
1532
1533 docstring Paragraph::expandLabel(LayoutPtr const & layout,
1534                 BufferParams const & bparams, bool process_appendix) const
1535 {
1536         TextClass const & tclass = bparams.getTextClass();
1537
1538         docstring fmt;
1539         if (process_appendix && params().appendix())
1540                 fmt = translateIfPossible(layout->labelstring_appendix(),
1541                         bparams);
1542         else
1543                 fmt = translateIfPossible(layout->labelstring(), bparams);
1544
1545         if (fmt.empty() && layout->labeltype == LABEL_COUNTER 
1546             && !layout->counter.empty())
1547                 fmt = "\\the" + layout->counter;
1548
1549         // handle 'inherited level parts' in 'fmt',
1550         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1551         size_t const i = fmt.find('@', 0);
1552         if (i != docstring::npos) {
1553                 size_t const j = fmt.find('@', i + 1);
1554                 if (j != docstring::npos) {
1555                         docstring parent(fmt, i + 1, j - i - 1);
1556                         docstring label = from_ascii("??");
1557                         if (tclass.hasLayout(parent))
1558                                 docstring label = expandLabel(tclass[parent], bparams,
1559                                                       process_appendix);
1560                         fmt = docstring(fmt, 0, i) + label 
1561                                 + docstring(fmt, j + 1, docstring::npos);
1562                 }
1563         }
1564
1565         return tclass.counters().counterLabel(fmt);
1566 }
1567
1568
1569 void Paragraph::applyLayout(LayoutPtr const & new_layout)
1570 {
1571         layout(new_layout);
1572         LyXAlignment const oldAlign = params().align();
1573         
1574         if (!(oldAlign & layout()->alignpossible)) {
1575                 frontend::Alert::warning(_("Alignment not permitted"), 
1576                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1577                 params().align(LYX_ALIGN_LAYOUT);
1578         }
1579 }
1580
1581
1582 pos_type Paragraph::beginOfBody() const
1583 {
1584         return d->begin_of_body_;
1585 }
1586
1587
1588 void Paragraph::setBeginOfBody()
1589 {
1590         if (layout()->labeltype != LABEL_MANUAL) {
1591                 d->begin_of_body_ = 0;
1592                 return;
1593         }
1594
1595         // Unroll the first two cycles of the loop
1596         // and remember the previous character to
1597         // remove unnecessary getChar() calls
1598         pos_type i = 0;
1599         pos_type end = size();
1600         if (i < end && !isNewline(i)) {
1601                 ++i;
1602                 char_type previous_char = 0;
1603                 char_type temp = 0;
1604                 if (i < end) {
1605                         previous_char = d->text_[i];
1606                         if (!isNewline(i)) {
1607                                 ++i;
1608                                 while (i < end && previous_char != ' ') {
1609                                         temp = d->text_[i];
1610                                         if (isNewline(i))
1611                                                 break;
1612                                         ++i;
1613                                         previous_char = temp;
1614                                 }
1615                         }
1616                 }
1617         }
1618
1619         d->begin_of_body_ = i;
1620 }
1621
1622
1623 bool Paragraph::forceDefaultParagraphs() const
1624 {
1625         return inInset() && inInset()->forceDefaultParagraphs(0);
1626 }
1627
1628
1629 namespace {
1630
1631 // paragraphs inside floats need different alignment tags to avoid
1632 // unwanted space
1633
1634 bool noTrivlistCentering(InsetCode code)
1635 {
1636         return code == FLOAT_CODE || code == WRAP_CODE;
1637 }
1638
1639
1640 string correction(string const & orig)
1641 {
1642         if (orig == "flushleft")
1643                 return "raggedright";
1644         if (orig == "flushright")
1645                 return "raggedleft";
1646         if (orig == "center")
1647                 return "centering";
1648         return orig;
1649 }
1650
1651
1652 string const corrected_env(string const & suffix, string const & env,
1653         InsetCode code)
1654 {
1655         string output = suffix + "{";
1656         if (noTrivlistCentering(code))
1657                 output += correction(env);
1658         else
1659                 output += env;
1660         output += "}";
1661         if (suffix == "\\begin")
1662                 output += "\n";
1663         return output;
1664 }
1665
1666
1667 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1668 {
1669         if (!contains(str, "\n"))
1670                 column += str.size();
1671         else {
1672                 string tmp;
1673                 texrow.newline();
1674                 column = rsplit(str, tmp, '\n').size();
1675         }
1676 }
1677
1678 } // namespace anon
1679
1680
1681 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1682                                  odocstream & os, TexRow & texrow,
1683                                  bool moving_arg) const
1684 {
1685         int column = 0;
1686
1687         if (params_.noindent()) {
1688                 os << "\\noindent ";
1689                 column += 10;
1690         }
1691         
1692         LyXAlignment const curAlign = params_.align();
1693
1694         if (curAlign == layout_->align)
1695                 return column;
1696
1697         switch (curAlign) {
1698         case LYX_ALIGN_NONE:
1699         case LYX_ALIGN_BLOCK:
1700         case LYX_ALIGN_LAYOUT:
1701         case LYX_ALIGN_SPECIAL:
1702                 break;
1703         case LYX_ALIGN_LEFT:
1704         case LYX_ALIGN_RIGHT:
1705         case LYX_ALIGN_CENTER:
1706                 if (moving_arg) {
1707                         os << "\\protect";
1708                         column += 8;
1709                 }
1710                 break;
1711         }
1712
1713         switch (curAlign) {
1714         case LYX_ALIGN_NONE:
1715         case LYX_ALIGN_BLOCK:
1716         case LYX_ALIGN_LAYOUT:
1717         case LYX_ALIGN_SPECIAL:
1718                 break;
1719         case LYX_ALIGN_LEFT: {
1720                 string output;
1721                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1722                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1723                 else
1724                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1725                 os << from_ascii(output);
1726                 adjust_row_column(output, texrow, column);
1727                 break;
1728         } case LYX_ALIGN_RIGHT: {
1729                 string output;
1730                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1731                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1732                 else
1733                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1734                 os << from_ascii(output);
1735                 adjust_row_column(output, texrow, column);
1736                 break;
1737         } case LYX_ALIGN_CENTER: {
1738                 string output;
1739                 output = corrected_env("\\begin", "center", owner_->ownerCode());
1740                 os << from_ascii(output);
1741                 adjust_row_column(output, texrow, column);
1742                 break;
1743         }
1744         }
1745
1746         return column;
1747 }
1748
1749
1750 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1751                                odocstream & os, TexRow & texrow,
1752                                bool moving_arg) const
1753 {
1754         int column = 0;
1755
1756         switch (params_.align()) {
1757         case LYX_ALIGN_NONE:
1758         case LYX_ALIGN_BLOCK:
1759         case LYX_ALIGN_LAYOUT:
1760         case LYX_ALIGN_SPECIAL:
1761                 break;
1762         case LYX_ALIGN_LEFT:
1763         case LYX_ALIGN_RIGHT:
1764         case LYX_ALIGN_CENTER:
1765                 if (moving_arg) {
1766                         os << "\\protect";
1767                         column = 8;
1768                 }
1769                 break;
1770         }
1771
1772         switch (params_.align()) {
1773         case LYX_ALIGN_NONE:
1774         case LYX_ALIGN_BLOCK:
1775         case LYX_ALIGN_LAYOUT:
1776         case LYX_ALIGN_SPECIAL:
1777                 break;
1778         case LYX_ALIGN_LEFT: {
1779                 string output;
1780                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1781                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1782                 else
1783                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1784                 os << from_ascii(output);
1785                 adjust_row_column(output, texrow, column);
1786                 break;
1787         } case LYX_ALIGN_RIGHT: {
1788                 string output;
1789                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1790                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1791                 else
1792                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1793                 os << from_ascii(output);
1794                 adjust_row_column(output, texrow, column);
1795                 break;
1796         } case LYX_ALIGN_CENTER: {
1797                 string output;
1798                 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1799                 os << from_ascii(output);
1800                 adjust_row_column(output, texrow, column);
1801                 break;
1802         }
1803         }
1804
1805         return column;
1806 }
1807
1808
1809 // This one spits out the text of the paragraph
1810 bool Paragraph::latex(Buffer const & buf,
1811                                 BufferParams const & bparams,
1812                                 Font const & outerfont,
1813                                 odocstream & os, TexRow & texrow,
1814                                 OutputParams const & runparams) const
1815 {
1816         LYXERR(Debug::LATEX, "SimpleTeXOnePar...     " << this);
1817
1818         bool return_value = false;
1819
1820         LayoutPtr style;
1821
1822         // well we have to check if we are in an inset with unlimited
1823         // length (all in one row) if that is true then we don't allow
1824         // any special options in the paragraph and also we don't allow
1825         // any environment other than the default layout of the text class
1826         // to be valid!
1827         bool asdefault = forceDefaultParagraphs();
1828
1829         if (asdefault) {
1830                 style = bparams.getTextClass().defaultLayout();
1831         } else {
1832                 style = layout();
1833         }
1834
1835         // Current base font for all inherited font changes, without any
1836         // change caused by an individual character, except for the language:
1837         // It is set to the language of the first character.
1838         // As long as we are in the label, this font is the base font of the
1839         // label. Before the first body character it is set to the base font
1840         // of the body.
1841         Font basefont;
1842
1843         // Maybe we have to create a optional argument.
1844         pos_type body_pos = beginOfBody();
1845         unsigned int column = 0;
1846
1847         if (body_pos > 0) {
1848                 // the optional argument is kept in curly brackets in
1849                 // case it contains a ']'
1850                 os << "[{";
1851                 column += 2;
1852                 basefont = getLabelFont(bparams, outerfont);
1853         } else {
1854                 basefont = getLayoutFont(bparams, outerfont);
1855         }
1856
1857         // Which font is currently active?
1858         Font running_font(basefont);
1859         // Do we have an open font change?
1860         bool open_font = false;
1861
1862         Change runningChange = Change(Change::UNCHANGED);
1863
1864         texrow.start(id(), 0);
1865
1866         // if the paragraph is empty, the loop will not be entered at all
1867         if (empty()) {
1868                 if (style->isCommand()) {
1869                         os << '{';
1870                         ++column;
1871                 }
1872                 if (!asdefault)
1873                         column += d->startTeXParParams(bparams, os, texrow,
1874                                                     runparams.moving_arg);
1875         }
1876
1877         for (pos_type i = 0; i < size(); ++i) {
1878                 // First char in paragraph or after label?
1879                 if (i == body_pos) {
1880                         if (body_pos > 0) {
1881                                 if (open_font) {
1882                                         column += running_font.latexWriteEndChanges(
1883                                                 os, bparams, runparams,
1884                                                 basefont, basefont);
1885                                         open_font = false;
1886                                 }
1887                                 basefont = getLayoutFont(bparams, outerfont);
1888                                 running_font = basefont;
1889
1890                                 column += Changes::latexMarkChange(os, bparams,
1891                                                 runningChange, Change(Change::UNCHANGED));
1892                                 runningChange = Change(Change::UNCHANGED);
1893
1894                                 os << "}] ";
1895                                 column +=3;
1896                         }
1897                         if (style->isCommand()) {
1898                                 os << '{';
1899                                 ++column;
1900                         }
1901
1902                         if (!asdefault)
1903                                 column += d->startTeXParParams(bparams, os,
1904                                                             texrow,
1905                                                             runparams.moving_arg);
1906                 }
1907
1908                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1909                                                                  : lookupChange(i);
1910
1911                 if (bparams.outputChanges && runningChange != change) {
1912                         if (open_font) {
1913                                 column += running_font.latexWriteEndChanges(
1914                                                 os, bparams, runparams, basefont, basefont);
1915                                 open_font = false;
1916                         }
1917                         basefont = getLayoutFont(bparams, outerfont);
1918                         running_font = basefont;
1919
1920                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
1921                         runningChange = change;
1922                 }
1923
1924                 // do not output text which is marked deleted
1925                 // if change tracking output is disabled
1926                 if (!bparams.outputChanges && change.type == Change::DELETED) {
1927                         continue;
1928                 }
1929
1930                 ++column;
1931
1932                 // Fully instantiated font
1933                 Font const font = getFont(bparams, i, outerfont);
1934
1935                 Font const last_font = running_font;
1936
1937                 // Do we need to close the previous font?
1938                 if (open_font &&
1939                     (font != running_font ||
1940                      font.language() != running_font.language()))
1941                 {
1942                         column += running_font.latexWriteEndChanges(
1943                                         os, bparams, runparams, basefont,
1944                                         (i == body_pos-1) ? basefont : font);
1945                         running_font = basefont;
1946                         open_font = false;
1947                 }
1948
1949                 // close babel's font environment before opening CJK.
1950                 if (!running_font.language()->babel().empty() &&
1951                     font.language()->encoding()->package() == Encoding::CJK) {
1952                                 string end_tag = subst(lyxrc.language_command_end,
1953                                                         "$$lang",
1954                                                         running_font.language()->babel());
1955                                 os << from_ascii(end_tag);
1956                                 column += end_tag.length();
1957                 }
1958
1959                 // Switch file encoding if necessary (and allowed)
1960                 if (!runparams.verbatim && 
1961                     runparams.encoding->package() == Encoding::none &&
1962                     font.language()->encoding()->package() == Encoding::none) {
1963                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1964                                         runparams, *(runparams.encoding),
1965                                         *(font.language()->encoding()));
1966                         if (enc_switch.first) {
1967                                 column += enc_switch.second;
1968                                 runparams.encoding = font.language()->encoding();
1969                         }
1970                 }
1971
1972                 char_type const c = d->text_[i];
1973
1974                 // Do we need to change font?
1975                 if ((font != running_font ||
1976                      font.language() != running_font.language()) &&
1977                         i != body_pos - 1)
1978                 {
1979                         odocstringstream ods;
1980                         column += font.latexWriteStartChanges(ods, bparams,
1981                                                               runparams, basefont,
1982                                                               last_font);
1983                         running_font = font;
1984                         open_font = true;
1985                         docstring fontchange = ods.str();
1986                         // check if the fontchange ends with a trailing blank
1987                         // (like "\small " (see bug 3382)
1988                         if (suffixIs(fontchange, ' ') && c == ' ')
1989                                 os << fontchange.substr(0, fontchange.size() - 1) 
1990                                    << from_ascii("{}");
1991                         else
1992                                 os << fontchange;
1993                 }
1994
1995                 if (c == ' ') {
1996                         // FIXME: integrate this case in latexSpecialChar
1997                         // Do not print the separation of the optional argument
1998                         // if style->pass_thru is false. This works because
1999                         // latexSpecialChar ignores spaces if
2000                         // style->pass_thru is false.
2001                         if (i != body_pos - 1) {
2002                                 if (d->simpleTeXBlanks(
2003                                                 runparams, os, texrow,
2004                                                 i, column, font, *style)) {
2005                                         // A surrogate pair was output. We
2006                                         // must not call latexSpecialChar
2007                                         // in this iteration, since it would output
2008                                         // the combining character again.
2009                                         ++i;
2010                                         continue;
2011                                 }
2012                         }
2013                 }
2014
2015                 OutputParams rp = runparams;
2016                 rp.free_spacing = style->free_spacing;
2017                 rp.local_font = &font;
2018                 rp.intitle = style->intitle;
2019
2020                 // Two major modes:  LaTeX or plain
2021                 // Handle here those cases common to both modes
2022                 // and then split to handle the two modes separately.
2023                 if (c == META_INSET)
2024                         d->latexInset(buf, bparams, os,
2025                                         texrow, rp, running_font,
2026                                         basefont, outerfont, open_font,
2027                                         runningChange, *style, i, column);
2028                 else
2029                         d->latexSpecialChar(os, rp, running_font, runningChange,
2030                                 *style, i, column);
2031
2032                 // Set the encoding to that returned from simpleTeXSpecialChars (see
2033                 // comment for encoding member in OutputParams.h)
2034                 runparams.encoding = rp.encoding;
2035         }
2036
2037         // If we have an open font definition, we have to close it
2038         if (open_font) {
2039 #ifdef FIXED_LANGUAGE_END_DETECTION
2040                 if (next_) {
2041                         running_font
2042                                 .latexWriteEndChanges(os, bparams, runparams,
2043                                         basefont,
2044                                         next_->getFont(bparams, 0, outerfont));
2045                 } else {
2046                         running_font.latexWriteEndChanges(os, bparams,
2047                                         runparams, basefont, basefont);
2048                 }
2049 #else
2050 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2051 //FIXME: there as we start another \selectlanguage with the next paragraph if
2052 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2053                 running_font.latexWriteEndChanges(os, bparams, runparams,
2054                                 basefont, basefont);
2055 #endif
2056         }
2057
2058         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2059
2060         // Needed if there is an optional argument but no contents.
2061         if (body_pos > 0 && body_pos == size()) {
2062                 os << "}]~";
2063                 return_value = false;
2064         }
2065
2066         if (!asdefault) {
2067                 column += d->endTeXParParams(bparams, os, texrow,
2068                                           runparams.moving_arg);
2069         }
2070
2071         LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2072         return return_value;
2073 }
2074
2075
2076 bool Paragraph::emptyTag() const
2077 {
2078         for (pos_type i = 0; i < size(); ++i) {
2079                 if (isInset(i)) {
2080                         Inset const * inset = getInset(i);
2081                         InsetCode lyx_code = inset->lyxCode();
2082                         if (lyx_code != TOC_CODE &&
2083                             lyx_code != INCLUDE_CODE &&
2084                             lyx_code != GRAPHICS_CODE &&
2085                             lyx_code != ERT_CODE &&
2086                             lyx_code != LISTINGS_CODE &&
2087                             lyx_code != FLOAT_CODE &&
2088                             lyx_code != TABULAR_CODE) {
2089                                 return false;
2090                         }
2091                 } else {
2092                         char_type c = d->text_[i];
2093                         if (c != ' ' && c != '\t')
2094                                 return false;
2095                 }
2096         }
2097         return true;
2098 }
2099
2100
2101 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams) const
2102 {
2103         for (pos_type i = 0; i < size(); ++i) {
2104                 if (isInset(i)) {
2105                         Inset const * inset = getInset(i);
2106                         InsetCode lyx_code = inset->lyxCode();
2107                         if (lyx_code == LABEL_CODE) {
2108                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2109                                 docstring const & id = il->getParam("name");
2110                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2111                         }
2112                 }
2113
2114         }
2115         return string();
2116 }
2117
2118
2119 pos_type Paragraph::getFirstWord(Buffer const & buf, odocstream & os, OutputParams const & runparams) const
2120 {
2121         pos_type i;
2122         for (i = 0; i < size(); ++i) {
2123                 if (isInset(i)) {
2124                         Inset const * inset = getInset(i);
2125                         inset->docbook(buf, os, runparams);
2126                 } else {
2127                         char_type c = d->text_[i];
2128                         if (c == ' ')
2129                                 break;
2130                         os << sgml::escapeChar(c);
2131                 }
2132         }
2133         return i;
2134 }
2135
2136
2137 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2138 {
2139         Font font_old;
2140         pos_type size = text_.size();
2141         for (pos_type i = initial; i < size; ++i) {
2142                 Font font = owner_->getFont(buf.params(), i, outerfont);
2143                 if (text_[i] == META_INSET)
2144                         return false;
2145                 if (i != initial && font != font_old)
2146                         return false;
2147                 font_old = font;
2148         }
2149
2150         return true;
2151 }
2152
2153
2154 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2155                                     odocstream & os,
2156                                     OutputParams const & runparams,
2157                                     Font const & outerfont,
2158                                     pos_type initial) const
2159 {
2160         bool emph_flag = false;
2161
2162         LayoutPtr const & style = layout();
2163         FontInfo font_old =
2164                 style->labeltype == LABEL_MANUAL ? style->labelfont : style->font;
2165
2166         if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2167                 os << "]]>";
2168
2169         // parsing main loop
2170         for (pos_type i = initial; i < size(); ++i) {
2171                 Font font = getFont(buf.params(), i, outerfont);
2172
2173                 // handle <emphasis> tag
2174                 if (font_old.emph() != font.fontInfo().emph()) {
2175                         if (font.fontInfo().emph() == FONT_ON) {
2176                                 os << "<emphasis>";
2177                                 emph_flag = true;
2178                         } else if (i != initial) {
2179                                 os << "</emphasis>";
2180                                 emph_flag = false;
2181                         }
2182                 }
2183
2184                 if (isInset(i)) {
2185                         Inset const * inset = getInset(i);
2186                         inset->docbook(buf, os, runparams);
2187                 } else {
2188                         char_type c = d->text_[i];
2189
2190                         if (style->pass_thru)
2191                                 os.put(c);
2192                         else
2193                                 os << sgml::escapeChar(c);
2194                 }
2195                 font_old = font.fontInfo();
2196         }
2197
2198         if (emph_flag) {
2199                 os << "</emphasis>";
2200         }
2201
2202         if (style->free_spacing)
2203                 os << '\n';
2204         if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2205                 os << "<![CDATA[";
2206 }
2207
2208
2209 bool Paragraph::isHfill(pos_type pos) const
2210 {
2211         return isInset(pos)
2212                 && getInset(pos)->lyxCode() == HFILL_CODE;
2213 }
2214
2215
2216 bool Paragraph::isNewline(pos_type pos) const
2217 {
2218         return isInset(pos)
2219                 && getInset(pos)->lyxCode() == NEWLINE_CODE;
2220 }
2221
2222
2223 bool Paragraph::isLineSeparator(pos_type pos) const
2224 {
2225         char_type const c = d->text_[pos];
2226         return isLineSeparatorChar(c)
2227                 || (c == META_INSET && getInset(pos) &&
2228                 getInset(pos)->isLineSeparator());
2229 }
2230
2231
2232 /// Used by the spellchecker
2233 bool Paragraph::isLetter(pos_type pos) const
2234 {
2235         if (isInset(pos))
2236                 return getInset(pos)->isLetter();
2237         else {
2238                 char_type const c = d->text_[pos];
2239                 return isLetterChar(c) || isDigit(c);
2240         }
2241 }
2242
2243
2244 Language const *
2245 Paragraph::getParLanguage(BufferParams const & bparams) const
2246 {
2247         if (!empty())
2248                 return getFirstFontSettings(bparams).language();
2249         // FIXME: we should check the prev par as well (Lgb)
2250         return bparams.language;
2251 }
2252
2253
2254 bool Paragraph::isRTL(BufferParams const & bparams) const
2255 {
2256         return lyxrc.rtl_support
2257                 && getParLanguage(bparams)->rightToLeft()
2258                 && ownerCode() != ERT_CODE
2259                 && ownerCode() != LISTINGS_CODE;
2260 }
2261
2262
2263 void Paragraph::changeLanguage(BufferParams const & bparams,
2264                                Language const * from, Language const * to)
2265 {
2266         // change language including dummy font change at the end
2267         for (pos_type i = 0; i <= size(); ++i) {
2268                 Font font = getFontSettings(bparams, i);
2269                 if (font.language() == from) {
2270                         font.setLanguage(to);
2271                         setFont(i, font);
2272                 }
2273         }
2274 }
2275
2276
2277 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2278 {
2279         Language const * doc_language = bparams.language;
2280         FontList::const_iterator cit = d->fontlist_.begin();
2281         FontList::const_iterator end = d->fontlist_.end();
2282
2283         for (; cit != end; ++cit)
2284                 if (cit->font().language() != ignore_language &&
2285                     cit->font().language() != latex_language &&
2286                     cit->font().language() != doc_language)
2287                         return true;
2288         return false;
2289 }
2290
2291
2292 // Convert the paragraph to a string.
2293 // Used for building the table of contents
2294 docstring const Paragraph::asString(Buffer const & buffer, bool label) const
2295 {
2296         return asString(buffer, 0, size(), label);
2297 }
2298
2299
2300 docstring const Paragraph::asString(Buffer const & buffer,
2301                                  pos_type beg, pos_type end, bool label) const
2302 {
2303
2304         odocstringstream os;
2305
2306         if (beg == 0 && label && !params().labelString().empty())
2307                 os << params().labelString() << ' ';
2308
2309         for (pos_type i = beg; i < end; ++i) {
2310                 char_type const c = d->text_[i];
2311                 if (isPrintable(c))
2312                         os.put(c);
2313                 else if (c == META_INSET)
2314                         getInset(i)->textString(buffer, os);
2315         }
2316
2317         return os.str();
2318 }
2319
2320
2321 void Paragraph::setInsetOwner(Inset * inset)
2322 {
2323         d->inset_owner_ = inset;
2324 }
2325
2326
2327 int Paragraph::id() const
2328 {
2329         return d->id_;
2330 }
2331
2332
2333 LayoutPtr const & Paragraph::layout() const
2334 {
2335         return d->layout_;
2336 }
2337
2338
2339 void Paragraph::layout(LayoutPtr const & new_layout)
2340 {
2341         d->layout_ = new_layout;
2342 }
2343
2344
2345 Inset * Paragraph::inInset() const
2346 {
2347         return d->inset_owner_;
2348 }
2349
2350
2351 InsetCode Paragraph::ownerCode() const
2352 {
2353         return d->inset_owner_ ?
2354                 d->inset_owner_->lyxCode() : NO_CODE;
2355 }
2356
2357
2358 ParagraphParameters & Paragraph::params()
2359 {
2360         return d->params_;
2361 }
2362
2363
2364 ParagraphParameters const & Paragraph::params() const
2365 {
2366         return d->params_;
2367 }
2368
2369
2370 bool Paragraph::isFreeSpacing() const
2371 {
2372         if (layout()->free_spacing)
2373                 return true;
2374         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2375 }
2376
2377
2378 bool Paragraph::allowEmpty() const
2379 {
2380         if (layout()->keepempty)
2381                 return true;
2382         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2383 }
2384
2385
2386 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2387 {
2388         if (!Encodings::is_arabic(c))
2389                 return c;
2390
2391         char_type prev_char = ' ';
2392         char_type next_char = ' ';
2393
2394         for (pos_type i = pos - 1; i >= 0; --i) {
2395                 char_type const par_char = d->text_[i];
2396                 if (!Encodings::isComposeChar_arabic(par_char)) {
2397                         prev_char = par_char;
2398                         break;
2399                 }
2400         }
2401
2402         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2403                 char_type const par_char = d->text_[i];
2404                 if (!Encodings::isComposeChar_arabic(par_char)) {
2405                         next_char = par_char;
2406                         break;
2407                 }
2408         }
2409
2410         if (Encodings::is_arabic(next_char)) {
2411                 if (Encodings::is_arabic(prev_char) &&
2412                         !Encodings::is_arabic_special(prev_char))
2413                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2414                 else
2415                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2416         } else {
2417                 if (Encodings::is_arabic(prev_char) &&
2418                         !Encodings::is_arabic_special(prev_char))
2419                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2420                 else
2421                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2422         }
2423 }
2424
2425
2426 int Paragraph::checkBiblio(bool track_changes)
2427 {
2428         //FIXME From JS:
2429         //This is getting more and more a mess. ...We really should clean
2430         //up this bibitem issue for 1.6. See also bug 2743.
2431
2432         // Add bibitem insets if necessary
2433         if (layout()->labeltype != LABEL_BIBLIO)
2434                 return 0;
2435
2436         bool hasbibitem = !d->insetlist_.empty()
2437                 // Insist on it being in pos 0
2438                 && d->text_[0] == META_INSET
2439                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2440
2441         docstring oldkey;
2442         docstring oldlabel;
2443
2444         // remove a bibitem in pos != 0
2445         // restore it later in pos 0 if necessary
2446         // (e.g. if a user inserts contents _before_ the item)
2447         // we're assuming there's only one of these, which there
2448         // should be.
2449         int erasedInsetPosition = -1;
2450         InsetList::iterator it = d->insetlist_.begin();
2451         InsetList::iterator end = d->insetlist_.end();
2452         for (; it != end; ++it)
2453                 if (it->inset->lyxCode() == BIBITEM_CODE
2454                     && it->pos > 0) {
2455                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2456                         oldkey = olditem->getParam("key");
2457                         oldlabel = olditem->getParam("label");
2458                         erasedInsetPosition = it->pos;
2459                         eraseChar(erasedInsetPosition, track_changes);
2460                         break;
2461         }
2462
2463         //There was an InsetBibitem at the beginning, and we didn't
2464         //have to erase one.
2465         if (hasbibitem && erasedInsetPosition < 0)
2466                         return 0;
2467
2468         //There was an InsetBibitem at the beginning and we did have to
2469         //erase one. So we give its properties to the beginning inset.
2470         if (hasbibitem) {
2471                 InsetBibitem * inset =
2472                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2473                 if (!oldkey.empty())
2474                         inset->setParam("key", oldkey);
2475                 inset->setParam("label", oldlabel);
2476                 return -erasedInsetPosition;
2477         }
2478
2479         //There was no inset at the beginning, so we need to create one with
2480         //the key and label of the one we erased.
2481         InsetBibitem * inset(new InsetBibitem(InsetCommandParams(BIBITEM_CODE)));
2482         // restore values of previously deleted item in this par.
2483         if (!oldkey.empty())
2484                 inset->setParam("key", oldkey);
2485         inset->setParam("label", oldlabel);
2486         insertInset(0, static_cast<Inset *>(inset),
2487                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2488
2489         return 1;
2490 }
2491
2492
2493 unsigned int Paragraph::macrocontextPosition() const
2494 {
2495         return d->macrocontext_position_;
2496 }
2497
2498
2499 void Paragraph::setMacrocontextPosition(unsigned int pos)
2500 {
2501         d->macrocontext_position_ = pos;
2502 }
2503
2504
2505 void Paragraph::checkAuthors(AuthorList const & authorList)
2506 {
2507         d->changes_.checkAuthors(authorList);
2508 }
2509
2510
2511 bool Paragraph::isUnchanged(pos_type pos) const
2512 {
2513         return lookupChange(pos).type == Change::UNCHANGED;
2514 }
2515
2516
2517 bool Paragraph::isInserted(pos_type pos) const
2518 {
2519         return lookupChange(pos).type == Change::INSERTED;
2520 }
2521
2522
2523 bool Paragraph::isDeleted(pos_type pos) const
2524 {
2525         return lookupChange(pos).type == Change::DELETED;
2526 }
2527
2528
2529 InsetList const & Paragraph::insetList() const
2530 {
2531         return d->insetlist_;
2532 }
2533
2534
2535 Inset * Paragraph::releaseInset(pos_type pos)
2536 {
2537         Inset * inset = d->insetlist_.release(pos);
2538         /// does not honour change tracking!
2539         eraseChar(pos, false);
2540         return inset;
2541 }
2542
2543
2544 Inset * Paragraph::getInset(pos_type pos)
2545 {
2546         return d->insetlist_.get(pos);
2547 }
2548
2549
2550 Inset const * Paragraph::getInset(pos_type pos) const
2551 {
2552         return d->insetlist_.get(pos);
2553 }
2554
2555
2556 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2557                 pos_type right, TextCase action)
2558 {
2559         // process sequences of modified characters; in change
2560         // tracking mode, this approach results in much better
2561         // usability than changing case on a char-by-char basis
2562         docstring changes;
2563
2564         bool const trackChanges = bparams.trackChanges;
2565
2566         bool capitalize = true;
2567
2568         for (; pos < right; ++pos) {
2569                 char_type oldChar = d->text_[pos];
2570                 char_type newChar = oldChar;
2571
2572                 // ignore insets and don't play with deleted text!
2573                 if (oldChar != META_INSET && !isDeleted(pos)) {
2574                         switch (action) {
2575                                 case text_lowercase:
2576                                         newChar = lowercase(oldChar);
2577                                         break;
2578                                 case text_capitalization:
2579                                         if (capitalize) {
2580                                                 newChar = uppercase(oldChar);
2581                                                 capitalize = false;
2582                                         }
2583                                         break;
2584                                 case text_uppercase:
2585                                         newChar = uppercase(oldChar);
2586                                         break;
2587                         }
2588                 }
2589
2590                 if (!isLetter(pos) || isDeleted(pos)) {
2591                         // permit capitalization again
2592                         capitalize = true;
2593                 }
2594
2595                 if (oldChar != newChar)
2596                         changes += newChar;
2597
2598                 if (oldChar == newChar || pos == right - 1) {
2599                         if (oldChar != newChar) {
2600                                 // step behind the changing area
2601                                 pos++;
2602                         }
2603                         int erasePos = pos - changes.size();
2604                         for (size_t i = 0; i < changes.size(); i++) {
2605                                 insertChar(pos, changes[i],
2606                                         getFontSettings(bparams,
2607                                         erasePos),
2608                                         trackChanges);
2609                                 if (!eraseChar(erasePos, trackChanges)) {
2610                                         ++erasePos;
2611                                         ++pos; // advance
2612                                         ++right; // expand selection
2613                                 }
2614                         }
2615                         changes.clear();
2616                 }
2617         }
2618 }
2619
2620
2621 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2622                 pos_type pos, bool del) const
2623 {
2624         int const strsize = str.length();
2625         int i = 0;
2626         pos_type const parsize = d->text_.size();
2627         for (i = 0; pos + i < parsize; ++i) {
2628                 if (i >= strsize)
2629                         break;
2630                 if (cs && str[i] != d->text_[pos + i])
2631                         break;
2632                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2633                         break;
2634                 if (!del && isDeleted(pos + i))
2635                         break;
2636         }
2637
2638         if (i != strsize)
2639                 return false;
2640
2641         // if necessary, check whether string matches word
2642         if (mw) {
2643                 if (pos > 0 && isLetter(pos - 1))
2644                         return false;
2645                 if (pos + strsize < parsize
2646                         && isLetter(pos + strsize))
2647                         return false;
2648         }
2649
2650         return true;
2651 }
2652
2653
2654 char_type Paragraph::getChar(pos_type pos) const
2655 {
2656         return d->text_[pos];
2657 }
2658
2659
2660 pos_type Paragraph::size() const
2661 {
2662         return d->text_.size();
2663 }
2664
2665
2666 bool Paragraph::empty() const
2667 {
2668         return d->text_.empty();
2669 }
2670
2671
2672 bool Paragraph::isInset(pos_type pos) const
2673 {
2674         return d->text_[pos] == META_INSET;
2675 }
2676
2677
2678 bool Paragraph::isSeparator(pos_type pos) const
2679 {
2680         //FIXME: Are we sure this can be the only separator?
2681         return d->text_[pos] == ' ';
2682 }
2683
2684
2685 } // namespace lyx