]> git.lyx.org Git - lyx.git/blob - src/paragraph.C
da35bb359141c2936f07ca5ad9b68c4910f3e63a
[lyx.git] / src / paragraph.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team. 
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #ifdef __GNUG__
14 #pragma implementation
15 #endif
16
17 #include <algorithm>
18 #include <fstream>
19 #include <csignal>
20
21 #include "paragraph.h"
22 #include "paragraph_pimpl.h"
23 #include "support/textutils.h"
24 #include "lyxrc.h"
25 #include "layout.h"
26 #include "language.h"
27 #include "tex-strings.h"
28 #include "buffer.h"
29 #include "bufferparams.h"
30 #include "support/FileInfo.h"
31 #include "support/LAssert.h"
32 #include "debug.h"
33 #include "LaTeXFeatures.h"
34 #include "insets/insetinclude.h"
35 #include "insets/insetbib.h"
36 #include "insets/insettext.h"
37 #include "support/filetools.h"
38 #include "lyx_gui_misc.h"
39 #include "texrow.h"
40 #include "support/lyxmanip.h"
41 #include "BufferView.h"
42 #include "encoding.h"
43 #include "ParameterStruct.h"
44 #include "gettext.h"
45
46 using std::ostream;
47 using std::endl;
48 using std::fstream;
49 using std::ios;
50 using std::lower_bound;
51 using std::upper_bound;
52 using std::reverse;
53
54 int tex_code_break_column = 72;  // needs non-zero initialization. set later.
55 // this is a bad idea, but how can Paragraph find its buffer to get
56 // parameters? (JMarc)
57
58 extern string bibitemWidest(Buffer const *);
59
60 // this is a minibuffer
61
62 namespace {
63
64 char minibuffer_char;
65 LyXFont minibuffer_font;
66 Inset * minibuffer_inset;
67
68 } // namespace anon
69
70
71 extern BufferView * current_view;
72
73
74 Paragraph::Paragraph()
75                 : pimpl_(new Paragraph::Pimpl(this))
76 {
77         for (int i = 0; i < 10; ++i) setCounter(i , 0);
78         next_ = 0;
79         previous_ = 0;
80         enumdepth = 0;
81         itemdepth = 0;
82         bibkey = 0; // ale970302
83         clear();
84 }
85
86
87 // This konstruktor inserts the new paragraph in a list.
88 Paragraph::Paragraph(Paragraph * par)
89                 : pimpl_(new Paragraph::Pimpl(this))
90 {
91         for (int i = 0; i < 10; ++i)
92                 setCounter(i, 0);
93         enumdepth = 0;
94         itemdepth = 0;
95
96         // double linked list begin
97         next_ = par->next_;
98         if (next_)
99                 next_->previous_ = this;
100         previous_ = par;
101         previous_->next_ = this;
102         // end
103
104         bibkey = 0; // ale970302        
105     
106         clear();
107 }
108
109
110 Paragraph::Paragraph(Paragraph const & lp)
111         : pimpl_(new Paragraph::Pimpl(*lp.pimpl_, this))
112 {
113         for (int i = 0; i < 10; ++i) setCounter(i , 0);
114         enumdepth = 0;
115         itemdepth = 0;
116         next_ = 0;
117         previous_ = 0;
118         clear();
119
120         makeSameLayout(&lp);
121
122         // this is because of the dummy layout of the paragraphs that
123         // follow footnotes
124         layout = lp.layout;
125
126         // ale970302
127         if (lp.bibkey)
128                 bibkey = static_cast<InsetBibKey *>
129                         (lp.bibkey->clone(*current_view->buffer()));
130         else
131                 bibkey = 0;
132         
133         // copy everything behind the break-position to the new paragraph
134
135         insetlist = lp.insetlist;
136         for (InsetList::iterator it = insetlist.begin();
137              it != insetlist.end(); ++it)
138                 it->inset = it->inset->clone(*current_view->buffer());
139 }
140
141
142 // the destructor removes the new paragraph from the list
143 Paragraph::~Paragraph()
144 {
145         if (previous_)
146                 previous_->next_ = next_;
147         if (next_)
148                 next_->previous_ = previous_;
149
150         for (InsetList::iterator it = insetlist.begin();
151              it != insetlist.end(); ++it) {
152                 delete (*it).inset;
153         }
154
155         // ale970302
156         delete bibkey;
157
158         delete pimpl_;
159         //
160         //lyxerr << "Paragraph::paragraph_id = "
161         //       << Paragraph::paragraph_id << endl;
162 }
163
164
165 void Paragraph::writeFile(Buffer const * buf, ostream & os,
166                              BufferParams const & bparams,
167                              depth_type dth) const
168 {
169         // The beginning or end of a deeper (i.e. nested) area?
170         if (dth != params().depth()) {
171                 if (params().depth() > dth) {
172                         while (params().depth() > dth) {
173                                 os << "\n\\begin_deeper ";
174                                 ++dth;
175                         }
176                 } else {
177                         while (params().depth() < dth) {
178                                 os << "\n\\end_deeper ";
179                                 --dth;
180                         }
181                 }
182         }
183         
184         // First write the layout
185         os << "\n\\layout "
186            << textclasslist.NameOfLayout(bparams.textclass, layout)
187            << "\n";
188         
189         // Maybe some vertical spaces.
190         if (params().spaceTop().kind() != VSpace::NONE)
191                 os << "\\added_space_top "
192                    << params().spaceTop().asLyXCommand() << " ";
193         if (params().spaceBottom().kind() != VSpace::NONE)
194                 os << "\\added_space_bottom "
195                    << params().spaceBottom().asLyXCommand() << " ";
196         
197         // Maybe the paragraph has special spacing
198         params().spacing().writeFile(os, true);
199         
200         // The labelwidth string used in lists.
201         if (!params().labelWidthString().empty())
202                 os << "\\labelwidthstring "
203                    << params().labelWidthString() << '\n';
204         
205         // Lines above or below?
206         if (params().lineTop())
207                 os << "\\line_top ";
208         if (params().lineBottom())
209                 os << "\\line_bottom ";
210         
211         // Pagebreaks above or below?
212         if (params().pagebreakTop())
213                 os << "\\pagebreak_top ";
214         if (params().pagebreakBottom())
215                 os << "\\pagebreak_bottom ";
216         
217         // Start of appendix?
218         if (params().startOfAppendix())
219                 os << "\\start_of_appendix ";
220         
221         // Noindent?
222         if (params().noindent())
223                 os << "\\noindent ";
224         
225         // Alignment?
226         if (params().align() != LYX_ALIGN_LAYOUT) {
227                 int h = 0;
228                 switch (params().align()) {
229                 case LYX_ALIGN_LEFT: h = 1; break;
230                 case LYX_ALIGN_RIGHT: h = 2; break;
231                 case LYX_ALIGN_CENTER: h = 3; break;
232                 default: h = 0; break;
233                 }
234                 os << "\\align " << string_align[h] << " ";
235         }
236         
237         // bibitem  ale970302
238         if (bibkey)
239                 bibkey->write(buf, os);
240         
241         LyXFont font1(LyXFont::ALL_INHERIT, bparams.language);
242         
243         int column = 0;
244         for (size_type i = 0; i < size(); ++i) {
245                 if (!i) {
246                         os << "\n";
247                         column = 0;
248                 }
249                 
250                 // Write font changes
251                 LyXFont font2 = getFontSettings(bparams, i);
252                 if (font2 != font1) {
253                         font2.lyxWriteChanges(font1, os);
254                         column = 0;
255                         font1 = font2;
256                 }
257                 
258                 value_type const c = getChar(i);
259                 switch (c) {
260                 case META_INSET:
261                 {
262                         Inset const * inset = getInset(i);
263                         if (inset)
264                                 if (inset->directWrite()) {
265                                         // international char, let it write
266                                         // code directly so it's shorter in
267                                         // the file
268                                         inset->write(buf, os);
269                                 } else {
270                                         os << "\n\\begin_inset ";
271                                         inset->write(buf, os);
272                                         os << "\n\\end_inset \n\n";
273                                         column = 0;
274                                 }
275                 }
276                 break;
277                 case META_NEWLINE: 
278                         os << "\n\\newline \n";
279                         column = 0;
280                         break;
281                 case META_HFILL: 
282                         os << "\n\\hfill \n";
283                         column = 0;
284                         break;
285                 case '\\':
286                         os << "\n\\backslash \n";
287                         column = 0;
288                         break;
289                 case '.':
290                         if (i + 1 < size() && getChar(i + 1) == ' ') {
291                                 os << ".\n";
292                                 column = 0;
293                         } else
294                                 os << ".";
295                         break;
296                 default:
297                         if ((column > 70 && c == ' ')
298                             || column > 79) {
299                                 os << "\n";
300                                 column = 0;
301                         }
302                         // this check is to amend a bug. LyX sometimes
303                         // inserts '\0' this could cause problems.
304                         if (c != '\0')
305                                 os << c;
306                         else
307                                 lyxerr << "ERROR (Paragraph::writeFile):"
308                                         " NULL char in structure." << endl;
309                         ++column;
310                         break;
311                 }
312         }
313         
314         // now write the next paragraph
315         if (next_)
316                 next_->writeFile(buf, os, bparams, dth);
317 }
318
319
320 void Paragraph::validate(LaTeXFeatures & features) const
321 {
322         BufferParams const & bparams = features.bufferParams();
323
324         // check the params.
325         if (params().lineTop() || params().lineBottom())
326                 features.lyxline = true;
327         if (!params().spacing().isDefault())
328                 features.setspace = true;
329         
330         // then the layouts
331         features.layout[getLayout()] = true;
332
333         // then the fonts
334         Language const * doc_language = bparams.language;
335         
336         for (Pimpl::FontList::const_iterator cit = pimpl_->fontlist.begin();
337              cit != pimpl_->fontlist.end(); ++cit) {
338                 if ((*cit).font().noun() == LyXFont::ON) {
339                         lyxerr[Debug::LATEX] << "font.noun: "
340                                              << (*cit).font().noun()
341                                              << endl;
342                         features.noun = true;
343                         lyxerr[Debug::LATEX] << "Noun enabled. Font: "
344                                              << (*cit).font().stateText(0)
345                                              << endl;
346                 }
347                 switch ((*cit).font().color()) {
348                 case LColor::none:
349                 case LColor::inherit:
350                 case LColor::ignore:
351                         break;
352                 default:
353                         features.color = true;
354                         lyxerr[Debug::LATEX] << "Color enabled. Font: "
355                                              << (*cit).font().stateText(0)
356                                              << endl;
357                 }
358
359                 Language const * language = (*cit).font().language();
360                 if (language->babel() != doc_language->babel()) {
361                         features.UsedLanguages.insert(language);
362                         lyxerr[Debug::LATEX] << "Found language "
363                                              << language->babel() << endl;
364                 }
365         }
366
367         // then the insets
368         for (InsetList::const_iterator cit = insetlist.begin();
369              cit != insetlist.end(); ++cit) {
370                 if ((*cit).inset)
371                         (*cit).inset->validate(features);
372         }
373 }
374
375
376 // First few functions needed for cut and paste and paragraph breaking.
377 void Paragraph::copyIntoMinibuffer(Buffer const & buffer,
378                                       Paragraph::size_type pos) const
379 {
380         BufferParams bparams = buffer.params;
381
382         minibuffer_char = getChar(pos);
383         minibuffer_font = getFontSettings(bparams, pos);
384         minibuffer_inset = 0;
385         if (minibuffer_char == Paragraph::META_INSET) {
386                 if (getInset(pos)) {
387                         minibuffer_inset = getInset(pos)->clone(buffer);
388                 } else {
389                         minibuffer_inset = 0;
390                         minibuffer_char = ' ';
391                         // This reflects what GetInset() does (ARRae)
392                 }
393         }
394 }
395
396
397 void Paragraph::cutIntoMinibuffer(BufferParams const & bparams,
398                                      Paragraph::size_type pos)
399 {
400         minibuffer_char = getChar(pos);
401         minibuffer_font = getFontSettings(bparams, pos);
402         minibuffer_inset = 0;
403         if (minibuffer_char == Paragraph::META_INSET) {
404                 if (getInset(pos)) {
405                         minibuffer_inset = getInset(pos);
406                         // This is a little hack since I want exactly
407                         // the inset, not just a clone. Otherwise
408                         // the inset would be deleted when calling Erase(pos)
409                         // find the entry
410                         InsetTable search_elem(pos, 0);
411                         InsetList::iterator it =
412                                 lower_bound(insetlist.begin(),
413                                             insetlist.end(),
414                                             search_elem, Pimpl::matchIT());
415                         if (it != insetlist.end() && (*it).pos == pos)
416                                 (*it).inset = 0;
417                 } else {
418                         minibuffer_inset = 0;
419                         minibuffer_char = ' ';
420                         // This reflects what GetInset() does (ARRae)
421                 }
422
423         }
424
425         // Erase(pos); now the caller is responsible for that.
426 }
427
428
429 bool Paragraph::insertFromMinibuffer(Paragraph::size_type pos)
430 {
431         if ((minibuffer_char == Paragraph::META_INSET) &&
432             !insertInsetAllowed(minibuffer_inset))
433                 return false;
434         if (minibuffer_char == Paragraph::META_INSET)
435                 insertInset(pos, minibuffer_inset, minibuffer_font);
436         else
437                 insertChar(pos, minibuffer_char, minibuffer_font);
438         return true;
439 }
440
441 // end of minibuffer
442
443
444
445 void Paragraph::clear()
446 {
447         params().clear();
448         
449         layout = 0;
450         bibkey = 0;
451 }
452
453
454 void Paragraph::erase(Paragraph::size_type pos)
455 {
456         pimpl_->erase(pos);
457 }
458
459
460 void Paragraph::insertChar(Paragraph::size_type pos,
461                               Paragraph::value_type c)
462 {
463         LyXFont const f(LyXFont::ALL_INHERIT);
464         insertChar(pos, c, f);
465 }
466
467
468 void Paragraph::insertChar(Paragraph::size_type pos,
469                               Paragraph::value_type c,
470                               LyXFont const & font)
471 {
472         pimpl_->insertChar(pos, c, font);
473 }
474
475
476 void Paragraph::insertInset(Paragraph::size_type pos,
477                                Inset * inset)
478 {
479         LyXFont const f(LyXFont::ALL_INHERIT);
480         insertInset(pos, inset, f);
481 }
482
483
484 void Paragraph::insertInset(Paragraph::size_type pos,
485                                Inset * inset, LyXFont const & font)
486 {
487         pimpl_->insertInset(pos, inset, font);
488 }
489
490
491 bool Paragraph::insertInsetAllowed(Inset * inset)
492 {
493         //lyxerr << "Paragraph::InsertInsetAllowed" << endl;
494         
495         if (pimpl_->inset_owner)
496                 return pimpl_->inset_owner->insertInsetAllowed(inset);
497         return true;
498 }
499
500
501 Inset * Paragraph::getInset(Paragraph::size_type pos)
502 {
503         lyx::Assert(pos < size());
504
505         // Find the inset.
506         InsetTable search_inset(pos, 0);
507         InsetList::iterator it = lower_bound(insetlist.begin(),
508                                              insetlist.end(),
509                                              search_inset, Pimpl::matchIT());
510         if (it != insetlist.end() && (*it).pos == pos)
511                 return (*it).inset;
512
513         lyxerr << "ERROR (Paragraph::GetInset): "
514                 "Inset does not exist: " << pos << endl;
515         //::raise(SIGSTOP);
516         
517         // text[pos] = ' '; // WHY!!! does this set the pos to ' '????
518         // Did this commenting out introduce a bug? So far I have not
519         // see any, please enlighten me. (Lgb)
520         // My guess is that since the inset does not exist, we might
521         // as well replace it with a space to prevent craches. (Asger)
522         return 0;
523 }
524
525
526 Inset const * Paragraph::getInset(Paragraph::size_type pos) const
527 {
528         lyx::Assert(pos < size());
529
530         // Find the inset.
531         InsetTable search_inset(pos, 0);
532         InsetList::const_iterator cit = lower_bound(insetlist.begin(),
533                                                     insetlist.end(),
534                                                     search_inset, Pimpl::matchIT());
535         if (cit != insetlist.end() && (*cit).pos == pos)
536                 return (*cit).inset;
537
538         lyxerr << "ERROR (Paragraph::GetInset): "
539                 "Inset does not exist: " << pos << endl;
540         //::raise(SIGSTOP);
541         //text[pos] = ' '; // WHY!!! does this set the pos to ' '????
542         // Did this commenting out introduce a bug? So far I have not
543         // see any, please enlighten me. (Lgb)
544         // My guess is that since the inset does not exist, we might
545         // as well replace it with a space to prevent craches. (Asger)
546         return 0;
547 }
548
549
550 // Gets uninstantiated font setting at position.
551 LyXFont const Paragraph::getFontSettings(BufferParams const & bparams,
552                                             Paragraph::size_type pos) const
553 {
554         lyx::Assert(pos <= size());
555         
556         Pimpl::FontTable search_font(pos, LyXFont());
557         Pimpl::FontList::const_iterator cit = lower_bound(pimpl_->fontlist.begin(),
558                                                    pimpl_->fontlist.end(),
559                                                    search_font, Pimpl::matchFT());
560         if (cit != pimpl_->fontlist.end())
561                 return (*cit).font();
562         
563         if (pos == size() && size())
564                 return getFontSettings(bparams, pos - 1);
565         
566         return LyXFont(LyXFont::ALL_INHERIT, getParLanguage(bparams));
567 }
568
569
570 // Gets uninstantiated font setting at position 0
571 LyXFont const Paragraph::getFirstFontSettings() const
572 {
573         if (size() > 0) {
574                 if (!pimpl_->fontlist.empty())
575                         return pimpl_->fontlist[0].font();
576         }
577         
578         return LyXFont(LyXFont::ALL_INHERIT);
579 }
580
581
582 // Gets the fully instantiated font at a given position in a paragraph
583 // This is basically the same function as LyXText::GetFont() in text2.C.
584 // The difference is that this one is used for generating the LaTeX file,
585 // and thus cosmetic "improvements" are disallowed: This has to deliver
586 // the true picture of the buffer. (Asger)
587 // If position is -1, we get the layout font of the paragraph.
588 // If position is -2, we get the font of the manual label of the paragraph.
589 LyXFont const Paragraph::getFont(BufferParams const & bparams,
590                               Paragraph::size_type pos) const
591 {
592         LyXFont tmpfont;
593         LyXLayout const & layout =
594                 textclasslist.Style(bparams.textclass, 
595                                     getLayout());
596         Paragraph::size_type main_body = 0;
597         if (layout.labeltype == LABEL_MANUAL)
598                 main_body = beginningOfMainBody();
599
600         if (pos >= 0) {
601                 LyXFont layoutfont;
602                 if (pos < main_body)
603                         layoutfont = layout.labelfont;
604                 else
605                         layoutfont = layout.font;
606                 tmpfont = getFontSettings(bparams, pos);
607                 tmpfont.realize(layoutfont);
608         } else {
609                 // process layoutfont for pos == -1 and labelfont for pos < -1
610                 if (pos == -1)
611                         tmpfont = layout.font;
612                 else
613                         tmpfont = layout.labelfont;
614                 tmpfont.setLanguage(getParLanguage(bparams));
615         }
616
617         // check for environment font information
618         char par_depth = getDepth();
619         Paragraph const * par = this;
620         while (par && par->getDepth() && !tmpfont.resolved()) {
621                 par = par->outerHook();
622                 if (par) {
623                         tmpfont.realize(textclasslist.
624                                         Style(bparams.textclass,
625                                               par->getLayout()).font);
626                         par_depth = par->getDepth();
627                 }
628         }
629
630         tmpfont.realize(textclasslist
631                         .TextClass(bparams.textclass)
632                         .defaultfont());
633         return tmpfont;
634 }
635
636
637 /// Returns the height of the highest font in range
638 LyXFont::FONT_SIZE
639 Paragraph::highestFontInRange(Paragraph::size_type startpos,
640                                  Paragraph::size_type endpos) const
641 {
642         LyXFont::FONT_SIZE maxsize = LyXFont::SIZE_TINY;
643         if (pimpl_->fontlist.empty())
644                 return maxsize;
645
646         Pimpl::FontTable end_search(endpos, LyXFont());
647         Pimpl::FontList::const_iterator end_it = lower_bound(pimpl_->fontlist.begin(),
648                                                       pimpl_->fontlist.end(),
649                                                       end_search, Pimpl::matchFT());
650         if (end_it != pimpl_->fontlist.end())
651                 ++end_it;
652
653         Pimpl::FontTable start_search(startpos, LyXFont());
654         for (Pimpl::FontList::const_iterator cit =
655                      lower_bound(pimpl_->fontlist.begin(),
656                                  pimpl_->fontlist.end(),
657                                  start_search, Pimpl::matchFT());
658              cit != end_it; ++cit) {
659                 LyXFont::FONT_SIZE size = (*cit).font().size();
660                 if (size > maxsize && size <= LyXFont::SIZE_HUGER)
661                         maxsize = size;
662         }
663         return maxsize;
664 }
665
666
667 Paragraph::value_type
668 Paragraph::getUChar(BufferParams const & bparams,
669                        Paragraph::size_type pos) const
670 {
671         value_type c = getChar(pos);
672         if (!lyxrc.rtl_support)
673                 return c;
674
675         value_type uc = c;
676         switch (c) {
677         case '(':
678                 uc = ')';
679                 break;
680         case ')':
681                 uc = '(';
682                 break;
683         case '[':
684                 uc = ']';
685                 break;
686         case ']':
687                 uc = '[';
688                 break;
689         case '{':
690                 uc = '}';
691                 break;
692         case '}':
693                 uc = '{';
694                 break;
695         case '<':
696                 uc = '>';
697                 break;
698         case '>':
699                 uc = '<';
700                 break;
701         }
702         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
703                 return uc;
704         else
705                 return c;
706 }
707
708
709 // return an string of the current word, and the end of the word in lastpos.
710 string const Paragraph::getWord(Paragraph::size_type & lastpos) const
711 {
712         lyx::Assert(lastpos >= 0);
713
714         // the current word is defined as starting at the first character
715         // from the immediate left of lastpospos which meets the definition
716         // of IsLetter(), continuing to the last character to the right
717         // of this meeting IsLetter.
718
719         string theword;
720
721         // grab a word
722                 
723         // move back until we have a letter
724
725         //there's no real reason to have firstpos & lastpos as
726         //separate variables as this is written, but maybe someon
727         // will want to return firstpos in the future.
728
729         //since someone might have typed a punctuation first
730         int firstpos = lastpos;
731         
732         while ((firstpos >= 0) && !isLetter(firstpos))
733                 --firstpos;
734
735         // now find the beginning by looking for a nonletter
736         
737         while ((firstpos>= 0) && isLetter(firstpos))
738                 --firstpos;
739
740         // the above is now pointing to the preceeding non-letter
741         ++firstpos;
742         lastpos = firstpos;
743
744         // so copy characters into theword  until we get a nonletter
745         // note that this can easily exceed lastpos, wich means
746         // that if used in the middle of a word, the whole word
747         // is included
748
749         while (isLetter(lastpos)) theword += getChar(lastpos++);
750         
751         return theword;
752 }
753
754
755 void Paragraph::setFont(Paragraph::size_type pos,
756                            LyXFont const & font)
757 {
758         lyx::Assert(pos <= size());
759
760         // First, reduce font against layout/label font
761         // Update: The SetCharFont() routine in text2.C already
762         // reduces font, so we don't need to do that here. (Asger)
763         // No need to simplify this because it will disappear
764         // in a new kernel. (Asger)
765         // Next search font table
766
767         Pimpl::FontTable search_font(pos, LyXFont());
768         Pimpl::FontList::iterator it = lower_bound(pimpl_->fontlist.begin(),
769                                             pimpl_->fontlist.end(),
770                                             search_font, Pimpl::matchFT());
771         unsigned int i = it - pimpl_->fontlist.begin();
772         bool notfound = it == pimpl_->fontlist.end();
773
774         if (!notfound && pimpl_->fontlist[i].font() == font)
775                 return;
776
777         bool begin = pos == 0 || notfound ||
778                 (i > 0 && pimpl_->fontlist[i-1].pos() == pos - 1);
779         // Is position pos is a beginning of a font block?
780         bool end = !notfound && pimpl_->fontlist[i].pos() == pos;
781         // Is position pos is the end of a font block?
782         if (begin && end) { // A single char block
783                 if (i + 1 < pimpl_->fontlist.size() &&
784                     pimpl_->fontlist[i + 1].font() == font) {
785                         // Merge the singleton block with the next block
786                         pimpl_->fontlist.erase(pimpl_->fontlist.begin() + i);
787                         if (i > 0 && pimpl_->fontlist[i - 1].font() == font)
788                                 pimpl_->fontlist.erase(pimpl_->fontlist.begin() + i-1);
789                 } else if (i > 0 && pimpl_->fontlist[i - 1].font() == font) {
790                         // Merge the singleton block with the previous block
791                         pimpl_->fontlist[i - 1].pos(pos);
792                         pimpl_->fontlist.erase(pimpl_->fontlist.begin() + i);
793                 } else
794                         pimpl_->fontlist[i].font(font);
795         } else if (begin) {
796                 if (i > 0 && pimpl_->fontlist[i - 1].font() == font)
797                         pimpl_->fontlist[i - 1].pos(pos);
798                 else
799                         pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i,
800                                         Pimpl::FontTable(pos, font));
801         } else if (end) {
802                 pimpl_->fontlist[i].pos(pos - 1);
803                 if (!(i + 1 < pimpl_->fontlist.size() &&
804                       pimpl_->fontlist[i + 1].font() == font))
805                         pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i + 1,
806                                         Pimpl::FontTable(pos, font));
807         } else { // The general case. The block is splitted into 3 blocks
808                 pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i, 
809                                 Pimpl::FontTable(pos - 1, pimpl_->fontlist[i].font()));
810                 pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i + 1,
811                                 Pimpl::FontTable(pos, font));
812         }
813 }
814
815
816
817 void Paragraph::next(Paragraph * p)
818 {
819         next_ = p;
820 }
821
822
823 // This function is able to hide closed footnotes.
824 Paragraph * Paragraph::next()
825 {
826         return next_;
827 }
828
829
830 Paragraph const * Paragraph::next() const
831 {
832         return next_;
833 }
834
835
836 void Paragraph::previous(Paragraph * p)
837 {
838         previous_ = p;
839 }
840
841
842 // This function is able to hide closed footnotes.
843 Paragraph * Paragraph::previous()
844 {
845         return previous_;
846 }
847
848
849 // This function is able to hide closed footnotes.
850 Paragraph const * Paragraph::previous() const
851 {
852         return previous_;
853 }
854
855
856 void Paragraph::breakParagraph(BufferParams const & bparams,
857                                   Paragraph::size_type pos,
858                                   int flag)
859 {
860         // create a new paragraph
861         Paragraph * tmp = new Paragraph(this);
862         // remember to set the inset_owner
863         tmp->setInsetOwner(InInset());
864         
865         // this is an idea for a more userfriendly layout handling, I will
866         // see what the users say
867         
868         // layout stays the same with latex-environments
869         if (flag) {
870                 tmp->setOnlyLayout(layout);
871                 tmp->setLabelWidthString(params().labelWidthString());
872         }
873         
874         if (size() > pos || !size() || flag == 2) {
875                 tmp->setOnlyLayout(layout);
876                 tmp->params().align(params().align());
877                 tmp->setLabelWidthString(params().labelWidthString());
878                 
879                 tmp->params().lineBottom(params().lineBottom());
880                 params().lineBottom(false);
881                 tmp->params().pagebreakBottom(params().pagebreakBottom());
882                 params().pagebreakBottom(false);
883                 tmp->params().spaceBottom(params().spaceBottom());
884                 params().spaceBottom(VSpace(VSpace::NONE));
885                 
886                 tmp->params().depth(params().depth());
887                 tmp->params().noindent(params().noindent());
888                 
889                 // copy everything behind the break-position
890                 // to the new paragraph
891                 size_type pos_end = pimpl_->size() - 1;
892                 size_type i = pos;
893                 size_type j = pos;
894                 for (; i <= pos_end; ++i) {
895                         cutIntoMinibuffer(bparams, i);
896                         if (tmp->insertFromMinibuffer(j - pos))
897                                 ++j;
898                 }
899                 for (i = pos_end; i >= pos; --i) {
900                         erase(i);
901                 }
902         }
903         
904         // just an idea of me
905         if (!pos) {
906                 tmp->params().lineTop(params().lineTop());
907                 tmp->params().pagebreakTop(params().pagebreakTop());
908                 tmp->params().spaceTop(params().spaceTop());
909                 tmp->bibkey = bibkey;
910                 clear();
911                 // layout stays the same with latex-environments
912                 if (flag) {
913                         setOnlyLayout(tmp->layout);
914                         setLabelWidthString(tmp->params().labelWidthString());
915                         params().depth(tmp->params().depth());
916                 }
917         }
918 }
919         
920
921 void Paragraph::makeSameLayout(Paragraph const * par)
922 {
923         layout = par->layout;
924         params().makeSame(par->params());
925         
926         // This can be changed after NEW_INSETS is in effect. (Lgb)
927         setLabelWidthString(par->params().labelWidthString());
928 }
929
930
931 int Paragraph::stripLeadingSpaces(LyXTextClassList::size_type tclass) 
932 {
933         if (textclasslist.Style(tclass, getLayout()).free_spacing)
934                 return 0;
935         
936         int i = 0;
937         while (size()
938                && (isNewline(0) || isLineSeparator(0))){
939                 erase(0);
940                 ++i;
941         }
942
943         return i;
944 }
945
946
947 bool Paragraph::hasSameLayout(Paragraph const * par) const
948 {
949         return 
950                 par->layout == layout &&
951                 params().sameLayout(par->params());
952 }
953
954
955 void Paragraph::breakParagraphConservative(BufferParams const & bparams,
956                                            Paragraph::size_type pos)
957 {
958         // create a new paragraph
959         Paragraph * tmp = new Paragraph(this);
960         tmp->makeSameLayout(this);
961
962         // When can pos > Last()?
963         // I guess pos == Last() is possible.
964         if (size() > pos) {
965                 // copy everything behind the break-position to the new
966                 // paragraph
967                 size_type pos_end = pimpl_->size() - 1;
968
969                 //size_type i = pos;
970                 //size_type j = pos;
971                 for (size_type i = pos, j = pos; i <= pos_end; ++i) {
972                         cutIntoMinibuffer(bparams, i);
973                         if (tmp->insertFromMinibuffer(j - pos))
974                                 ++j;
975                 }
976                 
977                 for (size_type k = pos_end; k >= pos; --k) {
978                         erase(k);
979                 }
980         }
981 }
982    
983
984 // Be carefull, this does not make any check at all.
985 // This method has wrong name, it combined this par with the next par.
986 // In that sense it is the reverse of break paragraph. (Lgb)
987 void Paragraph::pasteParagraph(BufferParams const & bparams)
988 {
989         // copy the next paragraph to this one
990         Paragraph * the_next = next();
991    
992         // first the DTP-stuff
993         params().lineBottom(the_next->params().lineBottom());
994         params().spaceBottom(the_next->params().spaceBottom());
995         params().pagebreakBottom(the_next->params().pagebreakBottom());
996
997         size_type pos_end = the_next->pimpl_->size() - 1;
998         size_type pos_insert = size();
999
1000         // ok, now copy the paragraph
1001         for (size_type i = 0, j = 0; i <= pos_end; ++i) {
1002                 the_next->cutIntoMinibuffer(bparams, i);
1003                 if (insertFromMinibuffer(pos_insert + j))
1004                         ++j;
1005         }
1006    
1007         // delete the next paragraph
1008         Paragraph * ppar = the_next->previous_;
1009         Paragraph * npar = the_next->next_;
1010         delete the_next;
1011         ppar->next(npar);
1012 }
1013
1014
1015 int Paragraph::getEndLabel(BufferParams const & bparams) const
1016 {
1017         Paragraph const * par = this;
1018         depth_type par_depth = getDepth();
1019         while (par) {
1020                 LyXTextClass::LayoutList::size_type layout = par->getLayout();
1021                 int const endlabeltype =
1022                         textclasslist.Style(bparams.textclass,
1023                                             layout).endlabeltype;
1024                 if (endlabeltype != END_LABEL_NO_LABEL) {
1025                         if (!next_)
1026                                 return endlabeltype;
1027
1028                         depth_type const next_depth = next_->getDepth();
1029                         if (par_depth > next_depth ||
1030                             (par_depth == next_depth
1031                              && layout != next_->getLayout()))
1032                                 return endlabeltype;
1033                         break;
1034                 }
1035                 if (par_depth == 0)
1036                         break;
1037                 par = par->outerHook();
1038                 if (par)
1039                         par_depth = par->getDepth();
1040         }
1041         return END_LABEL_NO_LABEL;
1042 }
1043
1044
1045 Paragraph::depth_type Paragraph::getDepth() const
1046 {
1047         return params().depth();
1048 }
1049
1050
1051 char Paragraph::getAlign() const
1052 {
1053         return params().align();
1054 }
1055
1056
1057 string const & Paragraph::getLabelstring() const
1058 {
1059         return params().labelString();
1060 }
1061
1062
1063 int Paragraph::getFirstCounter(int i) const
1064 {
1065         return pimpl_->counter_[i];
1066 }
1067
1068
1069 // the next two functions are for the manual labels
1070 string const Paragraph::getLabelWidthString() const
1071 {
1072         if (!params().labelWidthString().empty())
1073                 return params().labelWidthString();
1074         else
1075                 return _("Senseless with this layout!");
1076 }
1077
1078
1079 void Paragraph::setLabelWidthString(string const & s)
1080 {
1081         params().labelWidthString(s);
1082 }
1083
1084
1085 void Paragraph::setOnlyLayout(LyXTextClass::size_type new_layout)
1086 {
1087         layout = new_layout;
1088 }
1089
1090
1091 void Paragraph::setLayout(LyXTextClass::size_type new_layout)
1092 {
1093         layout = new_layout;
1094         params().labelWidthString(string());
1095         params().align(LYX_ALIGN_LAYOUT);
1096         params().spaceTop(VSpace(VSpace::NONE));
1097         params().spaceBottom(VSpace(VSpace::NONE));
1098         params().spacing(Spacing(Spacing::Default));
1099 }
1100
1101
1102 // if the layout of a paragraph contains a manual label, the beginning of the 
1103 // main body is the beginning of the second word. This is what the par-
1104 // function returns. If the layout does not contain a label, the main
1105 // body always starts with position 0. This differentiation is necessary,
1106 // because there cannot be a newline or a blank <= the beginning of the 
1107 // main body in TeX.
1108
1109 int Paragraph::beginningOfMainBody() const
1110 {
1111         // Unroll the first two cycles of the loop
1112         // and remember the previous character to
1113         // remove unnecessary GetChar() calls
1114         size_type i = 0;
1115         if (i < size()
1116             && getChar(i) != Paragraph::META_NEWLINE) {
1117                 ++i;
1118                 char previous_char = 0;
1119                 char temp = 0; 
1120                 if (i < size()
1121                     && (previous_char = getChar(i)) != Paragraph::META_NEWLINE) {
1122                         // Yes, this  ^ is supposed to be "= " not "=="
1123                         ++i;
1124                         while (i < size()
1125                                && previous_char != ' '
1126                                && (temp = getChar(i)) != Paragraph::META_NEWLINE) {
1127                                 ++i;
1128                                 previous_char = temp;
1129                         }
1130                 }
1131         }
1132
1133         return i;
1134 }
1135
1136
1137 Paragraph * Paragraph::depthHook(depth_type depth)
1138 {
1139         Paragraph * newpar = this;
1140   
1141         do {
1142                 newpar = newpar->previous();
1143         } while (newpar && newpar->getDepth() > depth);
1144    
1145         if (!newpar) {
1146                 if (previous() || getDepth())
1147                         lyxerr << "ERROR (Paragraph::DepthHook): "
1148                                 "no hook." << endl;
1149                 newpar = this;
1150         }
1151
1152         return newpar;
1153 }
1154
1155
1156 Paragraph const * Paragraph::depthHook(depth_type depth) const
1157 {
1158         Paragraph const * newpar = this;
1159    
1160         do {
1161                 newpar = newpar->previous();
1162         } while (newpar && newpar->getDepth() > depth);
1163    
1164         if (!newpar) {
1165                 if (previous() || getDepth())
1166                         lyxerr << "ERROR (Paragraph::DepthHook): "
1167                                 "no hook." << endl;
1168                 newpar = this;
1169         }
1170
1171         return newpar;
1172 }
1173
1174 Paragraph * Paragraph::outerHook()
1175 {
1176         if(!getDepth())
1177                 return 0;
1178         return depthHook(depth_type(getDepth() - 1));
1179 }
1180
1181 Paragraph const * Paragraph::outerHook() const
1182 {
1183         if(!getDepth())
1184                 return 0;
1185         return depthHook(depth_type(getDepth() - 1));
1186 }
1187
1188 int Paragraph::autoDeleteInsets()
1189 {
1190         int count = 0;
1191         InsetList::size_type index = 0;
1192         while (index < insetlist.size()) {
1193                 if (insetlist[index].inset && insetlist[index].inset->autoDelete()) {
1194                         erase(insetlist[index].pos); 
1195                         // Erase() calls to insetlist.erase(&insetlist[index])
1196                         // so index shouldn't be increased.
1197                         ++count;
1198                 } else
1199                         ++index;
1200         }
1201         return count;
1202 }
1203
1204
1205 Paragraph::inset_iterator
1206 Paragraph::InsetIterator(Paragraph::size_type pos)
1207 {
1208         InsetTable search_inset(pos, 0);
1209         InsetList::iterator it = lower_bound(insetlist.begin(),
1210                                              insetlist.end(),
1211                                              search_inset, Pimpl::matchIT());
1212         return inset_iterator(it);
1213 }
1214
1215
1216 // returns -1 if inset not found
1217 int Paragraph::getPositionOfInset(Inset * inset) const
1218 {
1219         // Find the entry.
1220         for (InsetList::const_iterator cit = insetlist.begin();
1221              cit != insetlist.end(); ++cit) {
1222                 if ((*cit).inset == inset) {
1223                         return (*cit).pos;
1224                 }
1225         }
1226         if (inset == bibkey)
1227                 return 0;
1228
1229         return -1;
1230 }
1231
1232
1233 Paragraph * Paragraph::TeXOnePar(Buffer const * buf,
1234                                        BufferParams const & bparams,
1235                                        ostream & os, TexRow & texrow,
1236                                        bool moving_arg)
1237 {
1238         lyxerr[Debug::LATEX] << "TeXOnePar...     " << this << endl;
1239         LyXLayout const & style =
1240                 textclasslist.Style(bparams.textclass,
1241                                     layout);
1242
1243         bool further_blank_line = false;
1244
1245         if (params().startOfAppendix()) {
1246                 os << "\\appendix\n";
1247                 texrow.newline();
1248         }
1249
1250         if (!params().spacing().isDefault()
1251             && (!previous() || !previous()->hasSameLayout(this))) {
1252                 os << params().spacing().writeEnvirBegin() << "\n";
1253                 texrow.newline();
1254         }
1255         
1256         if (tex_code_break_column && style.isCommand()){
1257                 os << '\n';
1258                 texrow.newline();
1259         }
1260
1261         if (params().pagebreakTop()) {
1262                 os << "\\newpage";
1263                 further_blank_line = true;
1264         }
1265         if (params().spaceTop().kind() != VSpace::NONE) {
1266                 os << params().spaceTop().asLatexCommand(bparams);
1267                 further_blank_line = true;
1268         }
1269       
1270         if (params().lineTop()) {
1271                 os << "\\lyxline{\\" << getFont(bparams, 0).latexSize() << '}'
1272                    << "\\vspace{-1\\parskip}";
1273                 further_blank_line = true;
1274         }
1275
1276         if (further_blank_line){
1277                 os << '\n';
1278                 texrow.newline();
1279         }
1280
1281         Language const * language = getParLanguage(bparams);
1282         Language const * doc_language = bparams.language;
1283         Language const * previous_language = previous_
1284                 ? previous_->getParLanguage(bparams) : doc_language;
1285         if (language->babel() != doc_language->babel() &&
1286             language->babel() != previous_language->babel()) {
1287                 os << subst(lyxrc.language_command_begin, "$$lang",
1288                             language->babel())
1289                    << endl;
1290                 texrow.newline();
1291         }
1292
1293         if (bparams.inputenc == "auto" &&
1294             language->encoding() != previous_language->encoding()) {
1295                 os << "\\inputencoding{"
1296                    << language->encoding()->LatexName()
1297                    << "}" << endl;
1298                 texrow.newline();
1299         }
1300         
1301         switch (style.latextype) {
1302         case LATEX_COMMAND:
1303                 os << '\\'
1304                    << style.latexname()
1305                    << style.latexparam();
1306                 break;
1307         case LATEX_ITEM_ENVIRONMENT:
1308                 if (bibkey) {
1309                         bibkey->latex(buf, os, false, false);
1310                 } else
1311                         os << "\\item ";
1312                 break;
1313         case LATEX_LIST_ENVIRONMENT:
1314                 os << "\\item ";
1315                 break;
1316         default:
1317                 break;
1318         }
1319
1320         bool need_par = simpleTeXOnePar(buf, bparams, os, texrow, moving_arg);
1321  
1322         // Make sure that \\par is done with the font of the last
1323         // character if this has another size as the default.
1324         // This is necessary because LaTeX (and LyX on the screen)
1325         // calculates the space between the baselines according
1326         // to this font. (Matthias)
1327         //
1328         // Is this really needed ? (Dekel)
1329         // We do not need to use to change the font for the last paragraph
1330         // or for a command.
1331         LyXFont font = getFont(bparams, size() - 1);
1332
1333         bool is_command = textclasslist.Style(bparams.textclass,
1334                                               getLayout()).isCommand();
1335         if (style.resfont.size() != font.size() && next_ && !is_command) {
1336                 if (!need_par)
1337                         os << "{";
1338                 os << "\\" << font.latexSize() << " \\par}";
1339         } else if (need_par) {
1340                 os << "\\par}";
1341         } else if (is_command)
1342                 os << "}";
1343
1344         if (language->babel() != doc_language->babel() &&
1345             (!next_
1346              || next_->getParLanguage(bparams)->babel() != language->babel())) {
1347                 os << endl 
1348                    << subst(lyxrc.language_command_end, "$$lang",
1349                             doc_language->babel());
1350         }
1351         
1352         switch (style.latextype) {
1353         case LATEX_ITEM_ENVIRONMENT:
1354         case LATEX_LIST_ENVIRONMENT:
1355                 if (next_ && (params().depth() < next_->params().depth())) {
1356                         os << '\n';
1357                         texrow.newline();
1358                 }
1359                 break;
1360         case LATEX_ENVIRONMENT:
1361                 // if its the last paragraph of the current environment
1362                 // skip it otherwise fall through
1363                 if (next_
1364                     && (next_->layout != layout
1365                         || next_->params().depth() != params().depth()))
1366                         break;
1367         default:
1368                 // we don't need it for the last paragraph!!!
1369                 // or for tables in floats
1370                 //   -- effectively creates a \par where there isn't one which
1371                 //      breaks a \subfigure or \subtable.
1372                 if (next_) {
1373                         os << '\n';
1374                         texrow.newline();
1375                 }
1376         }
1377         
1378         further_blank_line = false;
1379         if (params().lineBottom()) {
1380                 os << "\\lyxline{\\" << getFont(bparams,
1381                                                 size() - 1).latexSize() << '}';
1382                 further_blank_line = true;
1383         }
1384
1385         if (params().spaceBottom().kind() != VSpace::NONE) {
1386                 os << params().spaceBottom().asLatexCommand(bparams);
1387                 further_blank_line = true;
1388         }
1389       
1390         if (params().pagebreakBottom()) {
1391                 os << "\\newpage";
1392                 further_blank_line = true;
1393         }
1394
1395         if (further_blank_line){
1396                 os << '\n';
1397                 texrow.newline();
1398         }
1399
1400         if (!params().spacing().isDefault()
1401             && (!next_ || !next_->hasSameLayout(this))) {
1402                 os << params().spacing().writeEnvirEnd() << "\n";
1403                 texrow.newline();
1404         }
1405         
1406         // we don't need it for the last paragraph!!!
1407         if (next_) {
1408                 os << '\n';
1409                 texrow.newline();
1410         }
1411
1412         lyxerr[Debug::LATEX] << "TeXOnePar...done " << next_ << endl;
1413         return next_;
1414 }
1415
1416
1417 // This one spits out the text of the paragraph
1418 bool Paragraph::simpleTeXOnePar(Buffer const * buf,
1419                                    BufferParams const & bparams,
1420                                    ostream & os, TexRow & texrow,
1421                                    bool moving_arg)
1422 {
1423         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...     " << this << endl;
1424
1425         bool return_value = false;
1426
1427         LyXLayout const & style =
1428                 textclasslist.Style(bparams.textclass,
1429                                     getLayout());
1430         LyXFont basefont;
1431
1432         // Maybe we have to create a optional argument.
1433         size_type main_body;
1434         if (style.labeltype != LABEL_MANUAL)
1435                 main_body = 0;
1436         else
1437                 main_body = beginningOfMainBody();
1438
1439         int column = 0;
1440
1441         if (main_body > 0) {
1442                 os << '[';
1443                 ++column;
1444                 basefont = getFont(bparams, -2); // Get label font
1445         } else {
1446                 basefont = getFont(bparams, -1); // Get layout font
1447         }
1448
1449         if (main_body >= 0
1450             && !pimpl_->size()) {
1451                 if (style.isCommand()) {
1452                         os << '{';
1453                         ++column;
1454                 }
1455         }
1456
1457         moving_arg |= style.needprotect;
1458  
1459         // Which font is currently active?
1460         LyXFont running_font(basefont);
1461         // Do we have an open font change?
1462         bool open_font = false;
1463
1464         texrow.start(this, 0);
1465
1466         for (size_type i = 0; i < size(); ++i) {
1467                 ++column;
1468                 // First char in paragraph or after label?
1469                 if (i == main_body) {
1470                         if (main_body > 0) {
1471                                 if (open_font) {
1472                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
1473                                         open_font = false;
1474                                 }
1475                                 basefont = getFont(bparams, -1); // Now use the layout font
1476                                 running_font = basefont;
1477                                 os << ']';
1478                                 ++column;
1479                         }
1480                         if (style.isCommand()) {
1481                                 os << '{';
1482                                 ++column;
1483                         }
1484
1485                         if (params().noindent()) {
1486                                 os << "\\noindent ";
1487                                 column += 10;
1488                         }
1489                         switch (params().align()) {
1490                         case LYX_ALIGN_NONE:
1491                         case LYX_ALIGN_BLOCK:
1492                         case LYX_ALIGN_LAYOUT:
1493                         case LYX_ALIGN_SPECIAL:
1494                                 break;
1495                         case LYX_ALIGN_LEFT:
1496                                 if (getParLanguage(bparams)->babel() != "hebrew") {
1497                                         os << "\\begin{flushleft}";
1498                                         column+= 17;
1499                                 } else {
1500                                         os << "\\begin{flushright}";
1501                                         column+= 18;
1502                                 }
1503                                 break;
1504                         case LYX_ALIGN_RIGHT:
1505                                 if (getParLanguage(bparams)->babel() != "hebrew") {
1506                                         os << "\\begin{flushright}";
1507                                         column+= 18;
1508                                 } else {
1509                                         os << "\\begin{flushleft}";
1510                                         column+= 17;
1511                                 }
1512                                 break;
1513                         case LYX_ALIGN_CENTER:
1514                                 os << "\\begin{center}";
1515                                 column+= 14;
1516                                 break;
1517                         }        
1518                 }
1519
1520                 value_type c = getChar(i);
1521
1522                 // Fully instantiated font
1523                 LyXFont font = getFont(bparams, i);
1524
1525                 LyXFont last_font = running_font;
1526
1527                 // Spaces at end of font change are simulated to be
1528                 // outside font change, i.e. we write "\textXX{text} "
1529                 // rather than "\textXX{text }". (Asger)
1530                 if (open_font && c == ' ' && i <= size() - 2 
1531                     && !getFont(bparams, i + 1).equalExceptLatex(running_font) 
1532                     && !getFont(bparams, i + 1).equalExceptLatex(font)) {
1533                         font = getFont(bparams, i + 1);
1534                 }
1535                 // We end font definition before blanks
1536                 if (!font.equalExceptLatex(running_font) && open_font) {
1537                         column += running_font.latexWriteEndChanges(os,
1538                                                                     basefont,
1539                                                                     (i == main_body-1) ? basefont : font);
1540                         running_font = basefont;
1541                         open_font = false;
1542                 }
1543
1544                 // Blanks are printed before start of fontswitch
1545                 if (c == ' ') {
1546                         // Do not print the separation of the optional argument
1547                         if (i != main_body - 1) {
1548                                 pimpl_->simpleTeXBlanks(os, texrow, i,
1549                                                        column, font, style);
1550                         }
1551                 }
1552
1553                 // Do we need to change font?
1554                 if (!font.equalExceptLatex(running_font)
1555                     && i != main_body-1) {
1556                         column += font.latexWriteStartChanges(os, basefont,
1557                                                               last_font);
1558                         running_font = font;
1559                         open_font = true;
1560                 }
1561
1562                 if (c == Paragraph::META_NEWLINE) {
1563                         // newlines are handled differently here than
1564                         // the default in SimpleTeXSpecialChars().
1565                         if (!style.newline_allowed
1566 #ifndef NO_LATEX
1567                             || font.latex() == LyXFont::ON
1568 #endif
1569                                 ) {
1570                                 os << '\n';
1571                         } else {
1572                                 if (open_font) {
1573                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
1574                                         open_font = false;
1575                                 }
1576                                 basefont = getFont(bparams, -1);
1577                                 running_font = basefont;
1578                                 if (font.family() == 
1579                                     LyXFont::TYPEWRITER_FAMILY) {
1580                                         os << "~";
1581                                 }
1582                                 if (moving_arg)
1583                                         os << "\\protect ";
1584                                 os << "\\\\\n";
1585                         }
1586                         texrow.newline();
1587                         texrow.start(this, i + 1);
1588                         column = 0;
1589                 } else {
1590                         pimpl_->simpleTeXSpecialChars(buf, bparams,
1591                                                       os, texrow, moving_arg,
1592                                                       font, running_font, 
1593                                                       basefont, open_font, 
1594                                                       style, i, column, c);
1595                 }
1596         }
1597
1598         // If we have an open font definition, we have to close it
1599         if (open_font) {
1600                 if (next_) {
1601                         running_font
1602                                 .latexWriteEndChanges(os, basefont,
1603                                                       next_->getFont(bparams,
1604                                                                      0));
1605                 } else {
1606                         running_font.latexWriteEndChanges(os, basefont,
1607                                                           basefont);
1608                 }
1609         }
1610
1611         // Needed if there is an optional argument but no contents.
1612         if (main_body > 0 && main_body == size()) {
1613                 os << "]~";
1614                 return_value = false;
1615         }
1616
1617         switch (params().align()) {
1618         case LYX_ALIGN_NONE:
1619         case LYX_ALIGN_BLOCK:
1620         case LYX_ALIGN_LAYOUT:
1621         case LYX_ALIGN_SPECIAL:
1622                 break;
1623         case LYX_ALIGN_LEFT:
1624                 if (getParLanguage(bparams)->babel() != "hebrew") {
1625                         os << "\\end{flushleft}";
1626                         column+= 15;
1627                 } else {
1628                         os << "\\end{flushright}";
1629                         column+= 16;
1630                 }
1631                 break;
1632         case LYX_ALIGN_RIGHT:
1633                 if (getParLanguage(bparams)->babel() != "hebrew") {
1634                         os << "\\end{flushright}";
1635                         column+= 16;
1636                 } else {
1637                         os << "\\end{flushleft}";
1638                         column+= 15;
1639                 }
1640                 break;
1641         case LYX_ALIGN_CENTER:
1642                 os << "\\end{center}";
1643                 column+= 12;
1644                 break;
1645         }        
1646
1647         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...done " << this << endl;
1648         return return_value;
1649 }
1650
1651
1652 bool Paragraph::linuxDocConvertChar(char c, string & sgml_string)
1653 {
1654         bool retval = false;
1655         switch (c) {
1656         case Paragraph::META_HFILL:
1657                 sgml_string.erase();
1658                 break;
1659         case Paragraph::META_NEWLINE:
1660                 sgml_string = '\n';
1661                 break;
1662         case '&': 
1663                 sgml_string = "&amp;";
1664                 break;
1665         case '<': 
1666                 sgml_string = "&lt;"; 
1667                 break;
1668         case '>':
1669                 sgml_string = "&gt;"; 
1670                 break;
1671         case '$': 
1672                 sgml_string = "&dollar;"; 
1673                 break;
1674         case '#': 
1675                 sgml_string = "&num;";
1676                 break;
1677         case '%': 
1678                 sgml_string = "&percnt;";
1679                 break;
1680         case '[': 
1681                 sgml_string = "&lsqb;";
1682                 break;
1683         case ']': 
1684                 sgml_string = "&rsqb;";
1685                 break;
1686         case '{': 
1687                 sgml_string = "&lcub;";
1688                 break;
1689         case '}': 
1690                 sgml_string = "&rcub;";
1691                 break;
1692         case '~': 
1693                 sgml_string = "&tilde;";
1694                 break;
1695         case '"': 
1696                 sgml_string = "&quot;";
1697                 break;
1698         case '\\': 
1699                 sgml_string = "&bsol;";
1700                 break;
1701         case ' ':
1702                 retval = true;
1703                 sgml_string = ' ';
1704                 break;
1705         case '\0': // Ignore :-)
1706                 sgml_string.erase();
1707                 break;
1708         default:
1709                 sgml_string = c;
1710                 break;
1711         }
1712         return retval;
1713 }
1714
1715
1716 Paragraph * Paragraph::TeXEnvironment(Buffer const * buf,
1717                                             BufferParams const & bparams,
1718                                             ostream & os, TexRow & texrow)
1719 {
1720         lyxerr[Debug::LATEX] << "TeXEnvironment...     " << this << endl;
1721
1722         LyXLayout const & style =
1723                 textclasslist.Style(bparams.textclass,
1724                                     layout);
1725
1726         if (style.isEnvironment()){
1727                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
1728                         os << "\\begin{" << style.latexname() << "}{"
1729                            << params().labelWidthString() << "}\n";
1730                 } else if (style.labeltype == LABEL_BIBLIO) {
1731                         // ale970405
1732                         os << "\\begin{" << style.latexname() << "}{"
1733                            <<  bibitemWidest(buf)
1734                            << "}\n";
1735                 } else if (style.latextype == LATEX_ITEM_ENVIRONMENT) {
1736                         os << "\\begin{" << style.latexname() << '}'
1737                            << style.latexparam() << '\n';
1738                 } else 
1739                         os << "\\begin{" << style.latexname() << '}'
1740                            << style.latexparam() << '\n';
1741                 texrow.newline();
1742         }
1743         Paragraph * par = this;
1744         do {
1745                 par = par->TeXOnePar(buf, bparams,
1746                                      os, texrow, false);
1747
1748                 if (par && par->params().depth() > params().depth()) {
1749                         if (textclasslist.Style(bparams.textclass,
1750                                                 par->layout).isParagraph()
1751                             // Thinko!
1752                             // How to handle this? (Lgb)
1753                             //&& !suffixIs(os, "\n\n")
1754                                 ) {
1755                                 // There should be at least one '\n' already
1756                                 // but we need there to be two for Standard 
1757                                 // paragraphs that are depth-increment'ed to be
1758                                 // output correctly.  However, tables can
1759                                 // also be paragraphs so don't adjust them.
1760                                 // ARRae
1761                                 // Thinkee:
1762                                 // Will it ever harm to have one '\n' too
1763                                 // many? i.e. that we sometimes will have
1764                                 // three in a row. (Lgb)
1765                                 os << '\n';
1766                                 texrow.newline();
1767                         }
1768                         par = par->pimpl_->TeXDeeper(buf, bparams, os, texrow);
1769                 }
1770         } while (par
1771                  && par->layout == layout
1772                  && par->params().depth() == params().depth());
1773  
1774         if (style.isEnvironment()) {
1775                 os << "\\end{" << style.latexname() << "}\n";
1776         }
1777
1778         lyxerr[Debug::LATEX] << "TeXEnvironment...done " << par << endl;
1779         return par;  // ale970302
1780 }
1781
1782
1783 bool Paragraph::isHfill(size_type pos) const
1784 {
1785         return IsHfillChar(getChar(pos));
1786 }
1787
1788
1789 bool Paragraph::isInset(size_type pos) const
1790 {
1791         return IsInsetChar(getChar(pos));
1792 }
1793
1794
1795 bool Paragraph::isNewline(size_type pos) const
1796 {
1797         return pos >= 0 && IsNewlineChar(getChar(pos));
1798 }
1799
1800
1801 bool Paragraph::isSeparator(size_type pos) const
1802 {
1803         return IsSeparatorChar(getChar(pos));
1804 }
1805
1806
1807 bool Paragraph::isLineSeparator(size_type pos) const
1808 {
1809         return IsLineSeparatorChar(getChar(pos));
1810 }
1811
1812
1813 bool Paragraph::isKomma(size_type pos) const
1814 {
1815         return IsKommaChar(getChar(pos));
1816 }
1817
1818
1819 /// Used by the spellchecker
1820 bool Paragraph::isLetter(Paragraph::size_type pos) const
1821 {
1822         value_type const c = getChar(pos);
1823         if (IsLetterChar(c))
1824                 return true;
1825         // '\0' is not a letter, allthough every string contains "" (below)
1826         if (c == '\0')
1827                 return false;
1828         // We want to pass the ' and escape chars to ispell
1829         string const extra = lyxrc.isp_esc_chars + '\'';
1830         char ch[2] = { c, 0 };
1831         return contains(extra, ch);
1832 }
1833  
1834  
1835 bool Paragraph::isWord(size_type pos ) const
1836 {
1837         return IsWordChar(getChar(pos)) ;
1838 }
1839
1840
1841 Language const *
1842 Paragraph::getParLanguage(BufferParams const & bparams) const 
1843 {
1844         if (size() > 0)
1845                 return getFirstFontSettings().language();
1846         else if (previous_)
1847                 return previous_->getParLanguage(bparams);
1848         else
1849                 return bparams.language;
1850 }
1851
1852
1853 bool Paragraph::isRightToLeftPar(BufferParams const & bparams) const
1854 {
1855         return lyxrc.rtl_support
1856                 && getParLanguage(bparams)->RightToLeft();
1857 }
1858
1859
1860 void Paragraph::changeLanguage(BufferParams const & bparams,
1861                                   Language const * from, Language const * to)
1862 {
1863         for (size_type i = 0; i < size(); ++i) {
1864                 LyXFont font = getFontSettings(bparams, i);
1865                 if (font.language() == from) {
1866                         font.setLanguage(to);
1867                         setFont(i, font);
1868                 }
1869         }
1870 }
1871
1872
1873 bool Paragraph::isMultiLingual(BufferParams const & bparams)
1874 {
1875         Language const * doc_language = bparams.language;
1876         for (Pimpl::FontList::const_iterator cit = pimpl_->fontlist.begin();
1877              cit != pimpl_->fontlist.end(); ++cit)
1878                 if ((*cit).font().language() != doc_language)
1879                         return true;
1880         return false;
1881 }
1882
1883
1884 // Convert the paragraph to a string.
1885 // Used for building the table of contents
1886 string const Paragraph::asString(Buffer const * buffer, bool label)
1887 {
1888         BufferParams const & bparams = buffer->params;
1889         string s;
1890         if (label && !params().labelString().empty())
1891                 s += params().labelString() + ' ';
1892         string::size_type const len = s.size();
1893
1894         for (Paragraph::size_type i = 0; i < size(); ++i) {
1895                 value_type c = getChar(i);
1896                 if (IsPrintable(c))
1897                         s += c;
1898                 else if (c == META_INSET &&
1899                          getInset(i)->lyxCode() == Inset::MATH_CODE) {
1900                         std::ostringstream ost;
1901                         getInset(i)->ascii(buffer, ost);
1902                         s += subst(ost.str().c_str(),'\n',' ');
1903                 }
1904         }
1905
1906         if (isRightToLeftPar(bparams))
1907                 reverse(s.begin() + len,s.end());
1908
1909         return s;
1910 }
1911
1912
1913 string const Paragraph::asString(Buffer const * buffer, 
1914                             Paragraph::size_type beg,
1915                             Paragraph::size_type end)
1916 {
1917         std::ostringstream ost;
1918
1919         if (beg == 0 && !params().labelString().empty())
1920                 ost << params().labelString() << ' ';
1921
1922         for (Paragraph::size_type i = beg; i < end; ++i) {
1923                 value_type const c = getUChar(buffer->params, i);
1924                 if (IsPrintable(c))
1925                         ost << c;
1926                 else if (c == META_INSET) {
1927                         getInset(i)->ascii(buffer, ost);
1928                 }
1929         }
1930
1931         return ost.str().c_str();
1932 }
1933
1934
1935 void Paragraph::setInsetOwner(Inset * i)
1936 {
1937         pimpl_->inset_owner = i;
1938         for (InsetList::const_iterator cit = insetlist.begin();
1939              cit != insetlist.end(); ++cit) {
1940                 if ((*cit).inset)
1941                         (*cit).inset->setOwner(i);
1942         }
1943 }
1944
1945
1946 void Paragraph::deleteInsetsLyXText(BufferView * bv)
1947 {
1948         // then the insets
1949         for (InsetList::const_iterator cit = insetlist.begin();
1950              cit != insetlist.end(); ++cit) {
1951                 if ((*cit).inset) {
1952                         if ((*cit).inset->isTextInset()) {
1953                                 static_cast<UpdatableInset *>
1954                                         ((*cit).inset)->deleteLyXText(bv, true);
1955                         }
1956                 }
1957         }
1958 }
1959
1960
1961 void Paragraph::resizeInsetsLyXText(BufferView * bv)
1962 {
1963         // then the insets
1964         for (InsetList::const_iterator cit = insetlist.begin();
1965              cit != insetlist.end(); ++cit) {
1966                 if ((*cit).inset) {
1967                         if ((*cit).inset->isTextInset()) {
1968                                 static_cast<UpdatableInset *>
1969                                         ((*cit).inset)->resizeLyXText(bv, true);
1970                         }
1971                 }
1972         }
1973 }
1974
1975
1976 void Paragraph::setContentsFromPar(Paragraph * par)
1977 {
1978         pimpl_->setContentsFromPar(par);
1979 }
1980
1981
1982 Paragraph::size_type Paragraph::size() const
1983 {
1984         return pimpl_->size();
1985 }
1986
1987
1988 Paragraph::value_type
1989 Paragraph::getChar(Paragraph::size_type pos) const
1990 {
1991         return pimpl_->getChar(pos);
1992 }
1993
1994
1995 int Paragraph::id() const
1996 {
1997         return pimpl_->id_;
1998 }
1999
2000
2001 void  Paragraph::id(int id_arg)
2002 {
2003         pimpl_->id_ = id_arg;
2004 }
2005
2006
2007 LyXTextClass::LayoutList::size_type Paragraph::getLayout() const
2008 {
2009         return layout;
2010 }
2011
2012
2013 bool Paragraph::isFirstInSequence() const
2014 {
2015         Paragraph const * dhook = depthHook(getDepth());
2016         return (dhook == this
2017                 || dhook->getLayout() != getLayout()
2018                 || dhook->getDepth() != getDepth());
2019 }
2020
2021
2022 Inset * Paragraph::InInset()
2023 {
2024         return pimpl_->inset_owner;
2025 }
2026
2027
2028 void Paragraph::clearContents()
2029 {
2030         pimpl_->clear();
2031 }
2032
2033
2034 void Paragraph::setCounter(int i, int v)
2035 {
2036         pimpl_->counter_[i] = v;
2037 }
2038
2039
2040 int Paragraph::getCounter(int i) const
2041 {
2042         return pimpl_->counter_[i];
2043 }
2044
2045
2046 void Paragraph::incCounter(int i)
2047 {
2048         pimpl_->counter_[i]++;
2049 }
2050
2051
2052 void Paragraph::setChar(size_type pos, value_type c)
2053 {
2054         pimpl_->setChar(pos, c);
2055 }
2056
2057
2058 Paragraph::inset_iterator::inset_iterator(Paragraph::InsetList::iterator const & iter)
2059  : it(iter) 
2060 {
2061
2062 }
2063
2064
2065 Paragraph::inset_iterator Paragraph::inset_iterator_begin()
2066 {
2067         return inset_iterator(insetlist.begin());
2068 }
2069
2070
2071 Paragraph::inset_iterator Paragraph::inset_iterator_end()
2072 {
2073         return inset_iterator(insetlist.end());
2074 }
2075
2076
2077 ParagraphParameters & Paragraph::params()
2078 {
2079         return pimpl_->params;
2080 }
2081
2082 ParagraphParameters const & Paragraph::params() const
2083 {
2084         return pimpl_->params;
2085 }
2086