]> git.lyx.org Git - features.git/blob - src/paragraph.C
more changes, read the Changelog
[features.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-2000 The LyX Team. 
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #ifdef __GNUG__
14 #pragma implementation "lyxparagraph.h"
15 #endif
16
17 #include <algorithm>
18 #include <fstream>
19 #include <csignal>
20
21 #include "lyxparagraph.h"
22 #include "support/textutils.h"
23 #include "lyxrc.h"
24 #include "layout.h"
25 #include "tex-strings.h"
26 #include "bufferparams.h"
27 #include "support/FileInfo.h"
28 #include "support/LAssert.h"
29 #include "debug.h"
30 #include "LaTeXFeatures.h"
31 #include "insets/insetinclude.h"
32 #include "insets/insetbib.h"
33 #include "insets/insettext.h"
34 #include "support/filetools.h"
35 #include "lyx_gui_misc.h"
36 #include "texrow.h"
37 #include "support/lyxmanip.h"
38 #include "BufferView.h"
39
40 using std::ostream;
41 using std::endl;
42 using std::fstream;
43 using std::ios;
44 using std::lower_bound;
45 using std::upper_bound;
46 using std::reverse;
47
48 int tex_code_break_column = 72;  // needs non-zero initialization. set later.
49 // this is a bad idea, but how can LyXParagraph find its buffer to get
50 // parameters? (JMarc)
51 extern BufferView * current_view;
52 extern string bibitemWidest(Painter &);
53
54 // this is a minibuffer
55 static char minibuffer_char;
56 static LyXFont minibuffer_font;
57 static Inset * minibuffer_inset;
58
59
60 // Initialization of the counter for the paragraph id's,
61 // declared in lyxparagraph.h
62 unsigned int LyXParagraph::paragraph_id = 0;
63
64
65 LyXParagraph::LyXParagraph()
66 {
67         text.reserve(500); // is this number too big?
68
69         for (int i = 0; i < 10; ++i) setCounter(i , 0);
70         appendix = false;
71         enumdepth = 0;
72         itemdepth = 0;
73         next = 0;
74         previous = 0;
75 #ifndef NEW_INSETS
76         footnoteflag = LyXParagraph::NO_FOOTNOTE;
77         footnotekind = LyXParagraph::FOOTNOTE; // should not be needed
78 #endif
79         align = LYX_ALIGN_BLOCK;
80
81 #ifndef NEW_TABULAR
82         /* table stuff -- begin*/ 
83         table = 0;
84         /* table stuff -- end*/
85 #endif
86         inset_owner = 0;
87         id_ = paragraph_id++;
88         bibkey = 0; // ale970302
89         Clear();
90 }
91
92
93 // This konstruktor inserts the new paragraph in a list.
94 LyXParagraph::LyXParagraph(LyXParagraph * par)
95 {
96         text.reserve(500);
97         par->text.resize(par->text.size());
98
99         for (int i = 0; i < 10; ++i) setCounter(i, 0);
100         appendix = false;
101         enumdepth = 0;
102         itemdepth = 0;
103         // double linked list begin
104         next = par->next;
105         if (next)
106                 next->previous = this;
107         previous = par;
108         previous->next = this;
109         // end
110 #ifndef NEW_INSETS
111         footnoteflag = LyXParagraph::NO_FOOTNOTE;
112         footnotekind = LyXParagraph::FOOTNOTE;
113 #endif
114 #ifndef NEW_TABULAR
115         /* table stuff -- begin*/ 
116         table = 0;
117         /* table stuff -- end*/
118 #endif
119         inset_owner = 0;
120         id_ = paragraph_id++;
121
122         bibkey = 0; // ale970302        
123     
124         Clear();
125 }
126
127
128 void LyXParagraph::writeFile(Buffer const * buf, ostream & os,
129                              BufferParams const & params,
130                              char footflag, char dth) const
131 {
132         LyXFont font1, font2;
133         int column = 0;
134         int h = 0;
135         char c = 0;
136
137         if (footnoteflag != LyXParagraph::NO_FOOTNOTE
138             || !previous
139             || previous->footnoteflag == LyXParagraph::NO_FOOTNOTE) {
140                 
141                 // The beginning or the end of a footnote environment?
142                 if (footflag != footnoteflag) {
143                         footflag = footnoteflag;
144                         if (footflag) {
145                                 os << "\n\\begin_float "
146                                    << string_footnotekinds[footnotekind]
147                                    << " ";
148                         } else {
149                                 os << "\n\\end_float ";
150                         }
151                 }
152
153                 // The beginning or end of a deeper (i.e. nested) area?
154                 if (dth != depth) {
155                         if (depth > dth) {
156                                 while (depth > dth) {
157                                         os << "\n\\begin_deeper ";
158                                         ++dth;
159                                 }
160                         } else {
161                                 while (depth < dth) {
162                                         os << "\n\\end_deeper ";
163                                         --dth;
164                                 }
165                         }
166                 }
167
168                 // First write the layout
169                 os << "\n\\layout "
170                    << textclasslist.NameOfLayout(params.textclass, layout)
171                    << "\n";
172
173                 // Maybe some vertical spaces.
174                 if (added_space_top.kind() != VSpace::NONE)
175                         os << "\\added_space_top "
176                            << added_space_top.asLyXCommand() << " ";
177                 if (added_space_bottom.kind() != VSpace::NONE)
178                         os << "\\added_space_bottom "
179                            << added_space_bottom.asLyXCommand() << " ";
180
181                 // Maybe the paragraph has special spacing
182                 spacing.writeFile(os, true);
183                 
184                 // The labelwidth string used in lists.
185                 if (!labelwidthstring.empty())
186                         os << "\\labelwidthstring "
187                            << labelwidthstring << '\n';
188
189                 // Lines above or below?
190                 if (line_top)
191                         os << "\\line_top ";
192                 if (line_bottom)
193                         os << "\\line_bottom ";
194
195                 // Pagebreaks above or below?
196                 if (pagebreak_top)
197                         os << "\\pagebreak_top ";
198                 if (pagebreak_bottom)
199                         os << "\\pagebreak_bottom ";
200                         
201                 // Start of appendix?
202                 if (start_of_appendix)
203                         os << "\\start_of_appendix ";
204
205                 // Noindent?
206                 if (noindent)
207                         os << "\\noindent ";
208                         
209                 // Alignment?
210                 if (align != LYX_ALIGN_LAYOUT) {
211                         switch (align) {
212                         case LYX_ALIGN_LEFT: h = 1; break;
213                         case LYX_ALIGN_RIGHT: h = 2; break;
214                         case LYX_ALIGN_CENTER: h = 3; break;
215                         default: h = 0; break;
216                         }
217                         os << "\\align " << string_align[h] << " ";
218                 }
219                 if (pextra_type != PEXTRA_NONE) {
220                         os << "\\pextra_type " << pextra_type;
221                         if (pextra_type == PEXTRA_MINIPAGE) {
222                                 os << " \\pextra_alignment "
223                                    << pextra_alignment;
224                                 if (pextra_hfill)
225                                         os << " \\pextra_hfill "
226                                            << pextra_hfill;
227                                 if (pextra_start_minipage)
228                                         os << " \\pextra_start_minipage "
229                                            << pextra_start_minipage;
230                         }
231                         if (!pextra_width.empty()) {
232                                 os << " \\pextra_width "
233                                    << VSpace(pextra_width).asLyXCommand();
234                         } else if (!pextra_widthp.empty()) {
235                                 os << " \\pextra_widthp "
236                                    << pextra_widthp;
237                         }
238                         os << '\n';
239                 }
240         } else {
241                 // Dummy layout. This means that a footnote ended.
242                 os << "\n\\end_float ";
243                 footflag = LyXParagraph::NO_FOOTNOTE;
244         }
245 #ifndef NEW_TABULAR     
246         // It might be a table.
247         if (table){
248                 os << "\\LyXTable\n";
249                 table->Write(os);
250         }
251 #endif
252         // bibitem  ale970302
253         if (bibkey)
254                 bibkey->Write(buf, os);
255
256         font1 = LyXFont(LyXFont::ALL_INHERIT,params.language_info);
257
258         column = 0;
259         for (size_type i = 0; i < size(); ++i) {
260                 if (!i) {
261                         os << "\n";
262                         column = 0;
263                 }
264                 
265                 // Write font changes
266                 font2 = GetFontSettings(params, i);
267                 if (font2 != font1) {
268                         font2.lyxWriteChanges(font1, os);
269                         column = 0;
270                         font1 = font2;
271                 }
272
273                 c = GetChar(i);
274                 switch (c) {
275                 case META_INSET:
276                 {
277                         Inset const * inset = GetInset(i);
278                         if (inset)
279                                 if (inset->DirectWrite()) {
280                                         // international char, let it write
281                                         // code directly so it's shorter in
282                                         // the file
283                                         inset->Write(buf, os);
284                                 } else {
285                                         os << "\n\\begin_inset ";
286                                         inset->Write(buf, os);
287                                         os << "\n\\end_inset \n\n";
288                                         column = 0;
289                                 }
290                 }
291                 break;
292                 case META_NEWLINE: 
293                         os << "\n\\newline \n";
294                         column = 0;
295                         break;
296                 case META_HFILL: 
297                         os << "\n\\hfill \n";
298                         column = 0;
299                         break;
300                 case '\\':
301                         os << "\n\\backslash \n";
302                         column = 0;
303                         break;
304                 case '.':
305                         if (i + 1 < size() && GetChar(i + 1) == ' ') {
306                                 os << ".\n";
307                                 column = 0;
308                         } else
309                                 os << ".";
310                         break;
311                 default:
312                         if ((column > 70 && c == ' ')
313                             || column > 79) {
314                                 os << "\n";
315                                 column = 0;
316                         }
317                         // this check is to amend a bug. LyX sometimes
318                         // inserts '\0' this could cause problems.
319                         if (c != '\0')
320                                 os << c;
321                         else
322                                 lyxerr << "ERROR (LyXParagraph::writeFile):"
323                                         " NULL char in structure." << endl;
324                         ++column;
325                         break;
326                 }
327         }
328
329         // now write the next paragraph
330         if (next)
331                 next->writeFile(buf, os, params, footflag, dth);
332 }
333
334
335 void LyXParagraph::validate(LaTeXFeatures & features) const
336 {
337         BufferParams const & params = features.bufferParams();
338         
339         // this will be useful later
340         LyXLayout const & layout =
341                 textclasslist.Style(params.textclass, 
342                                     GetLayout());
343         
344         // check the params.
345         if (line_top || line_bottom)
346                 features.lyxline = true;
347         if (!spacing.isDefault())
348                 features.setspace = true;
349         
350         // then the layouts
351         features.layout[GetLayout()] = true;
352
353         // then the fonts
354         Language const * doc_language = params.language_info;
355         
356         for (FontList::const_iterator cit = fontlist.begin();
357              cit != fontlist.end(); ++cit) {
358                 if ((*cit).font.noun() == LyXFont::ON) {
359                         lyxerr[Debug::LATEX] << "font.noun: "
360                                              << (*cit).font.noun()
361                                              << endl;
362                         features.noun = true;
363                         lyxerr[Debug::LATEX] << "Noun enabled. Font: "
364                                              << (*cit).font.stateText(0)
365                                              << endl;
366                 }
367                 switch ((*cit).font.color()) {
368                 case LColor::none:
369                 case LColor::inherit:
370                 case LColor::ignore:
371                         break;
372                 default:
373                         features.color = true;
374                         lyxerr[Debug::LATEX] << "Color enabled. Font: "
375                                              << (*cit).font.stateText(0)
376                                              << endl;
377                 }
378
379                 Language const * language = (*cit).font.language();
380                 if (language != doc_language) {
381                         features.UsedLanguages.insert(language);
382                         lyxerr[Debug::LATEX] << "Found language "
383                                              << language->lang() << endl;
384                 }
385         }
386
387         // then the insets
388         for (InsetList::const_iterator cit = insetlist.begin();
389              cit != insetlist.end(); ++cit) {
390                 if ((*cit).inset)
391                         (*cit).inset->Validate(features);
392         }
393
394         if (table && table->IsLongTable())
395                 features.longtable = true;
396         if (pextra_type == PEXTRA_INDENT)
397                 features.LyXParagraphIndent = true;
398         if (pextra_type == PEXTRA_FLOATFLT)
399                 features.floatflt = true;
400         if (layout.needprotect 
401             && next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE)
402                 features.NeedLyXFootnoteCode = true;
403         if (params.paragraph_separation == BufferParams::PARSEP_INDENT
404             && pextra_type == LyXParagraph::PEXTRA_MINIPAGE)
405                 features.NeedLyXMinipageIndent = true;
406         if (table && table->NeedRotating())
407                 features.rotating = true;
408         if (footnoteflag != NO_FOOTNOTE && footnotekind == ALGORITHM)
409                 features.algorithm = true;
410 }
411
412
413 // First few functions needed for cut and paste and paragraph breaking.
414 void LyXParagraph::CopyIntoMinibuffer(BufferParams const & bparams,
415                                       LyXParagraph::size_type pos) const
416 {
417         minibuffer_char = GetChar(pos);
418         minibuffer_font = GetFontSettings(bparams, pos);
419         minibuffer_inset = 0;
420         if (minibuffer_char == LyXParagraph::META_INSET) {
421                 if (GetInset(pos)) {
422                         minibuffer_inset = GetInset(pos)->Clone();
423                 } else {
424                         minibuffer_inset = 0;
425                         minibuffer_char = ' ';
426                         // This reflects what GetInset() does (ARRae)
427                 }
428         }
429 }
430
431
432 void LyXParagraph::CutIntoMinibuffer(BufferParams const & bparams,
433                                      LyXParagraph::size_type pos)
434 {
435         minibuffer_char = GetChar(pos);
436         minibuffer_font = GetFontSettings(bparams, pos);
437         minibuffer_inset = 0;
438         if (minibuffer_char == LyXParagraph::META_INSET) {
439                 if (GetInset(pos)) {
440                         minibuffer_inset = GetInset(pos);
441                         // This is a little hack since I want exactly
442                         // the inset, not just a clone. Otherwise
443                         // the inset would be deleted when calling Erase(pos)
444                         // find the entry
445                         InsetList::iterator it = lower_bound(insetlist.begin(),
446                                                              insetlist.end(),
447                                                              pos, matchIT());
448                         if (it != insetlist.end() && (*it).pos == pos)
449                                 (*it).inset = 0;
450                 } else {
451                         minibuffer_inset = 0;
452                         minibuffer_char = ' ';
453                         // This reflects what GetInset() does (ARRae)
454                 }
455
456         }
457
458         // Erase(pos); now the caller is responsible for that.
459 }
460
461
462 bool LyXParagraph::InsertFromMinibuffer(LyXParagraph::size_type pos)
463 {
464         if ((minibuffer_char == LyXParagraph::META_INSET) &&
465             !InsertInsetAllowed(minibuffer_inset))
466                 return false;
467         if (minibuffer_char == LyXParagraph::META_INSET)
468                 InsertInset(pos, minibuffer_inset, minibuffer_font);
469         else
470                 InsertChar(pos, minibuffer_char, minibuffer_font);
471         return true;
472 }
473
474 // end of minibuffer
475
476
477
478 void LyXParagraph::Clear()
479 {
480         line_top = false;
481         line_bottom = false;
482    
483         pagebreak_top = false;
484         pagebreak_bottom = false;
485
486         added_space_top = VSpace(VSpace::NONE);
487         added_space_bottom = VSpace(VSpace::NONE);
488         spacing.set(Spacing::Default);
489         
490         align = LYX_ALIGN_LAYOUT;
491         depth = 0;
492         noindent = false;
493
494         pextra_type = PEXTRA_NONE;
495         pextra_width.erase();
496         pextra_widthp.erase();
497         pextra_alignment = MINIPAGE_ALIGN_TOP;
498         pextra_hfill = false;
499         pextra_start_minipage = false;
500
501         labelstring.erase();
502         labelwidthstring.erase();
503         layout = 0;
504         bibkey = 0;
505         
506         start_of_appendix = false;
507 }
508
509
510 // the destructor removes the new paragraph from the list
511 LyXParagraph::~LyXParagraph()
512 {
513         if (previous)
514                 previous->next = next;
515         if (next)
516                 next->previous = previous;
517
518         for (InsetList::iterator it = insetlist.begin();
519              it != insetlist.end(); ++it) {
520                 delete (*it).inset;
521         }
522 #ifndef NEW_TABULAR
523         /* table stuff -- begin*/ 
524         delete table;
525         /* table stuff -- end*/
526 #endif
527
528         // ale970302
529         delete bibkey;
530         //
531         //lyxerr << "LyXParagraph::paragraph_id = "
532         //       << LyXParagraph::paragraph_id << endl;
533 }
534
535
536 void LyXParagraph::Erase(LyXParagraph::size_type pos)
537 {
538         // > because last is the next unused position, and you can 
539         // use it if you want
540         if (pos > size()) {
541 #ifndef NEW_INSETS
542                 if (next && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
543                         NextAfterFootnote()->Erase(pos - text.size() - 1);
544                 else 
545 #endif
546                         lyxerr.debug() << "ERROR (LyXParagraph::Erase): "
547                                 "position does not exist." << endl;
548                 return;
549         }
550         if (pos < size()) { // last is free for insertation, but should be empty
551                 // if it is an inset, delete the inset entry 
552                 if (text[pos] == LyXParagraph::META_INSET) {
553                         // find the entry
554                         InsetList::iterator it = lower_bound(insetlist.begin(),
555                                                              insetlist.end(),
556                                                              pos, matchIT());
557                         if (it != insetlist.end() && (*it).pos == pos) {
558                                 delete (*it).inset;
559                                 insetlist.erase(it);
560                         }
561                 }
562                 text.erase(text.begin() + pos);
563
564                 // Erase entries in the tables.
565                 FontList::iterator it = lower_bound(fontlist.begin(),
566                                                     fontlist.end(),
567                                                     pos, matchFT());
568                 if (it != fontlist.end() && (*it).pos == pos &&
569                     (pos == 0 || 
570                      (it != fontlist.begin() && (*(it-1)).pos == pos - 1))) {
571                         // If it is a multi-character font
572                         // entry, we just make it smaller
573                         // (see update below), otherwise we
574                         // should delete it.
575                         unsigned int i = it - fontlist.begin();
576                         fontlist.erase(fontlist.begin() + i);
577                         it = fontlist.begin() + i;
578                         if (i > 0 && i < fontlist.size() &&
579                             fontlist[i-1].font == fontlist[i].font) {
580                                 fontlist.erase(fontlist.begin() + i-1);
581                                 it = fontlist.begin() + i-1;
582                         }
583                 }
584
585                 // Update all other entries.
586                 for (; it != fontlist.end(); ++it)
587                         --(*it).pos;
588
589                 // Update the inset table.
590                 for (InsetList::iterator it = upper_bound(insetlist.begin(),
591                                                           insetlist.end(),
592                                                           pos, matchIT());
593                      it != insetlist.end(); ++it)
594                         --(*it).pos;
595         } else {
596                 lyxerr << "ERROR (LyXParagraph::Erase): "
597                         "can't erase non-existant char." << endl;
598         }
599 }
600
601
602 void LyXParagraph::InsertChar(LyXParagraph::size_type pos, char c)
603 {
604         LyXFont f(LyXFont::ALL_INHERIT);
605         InsertChar(pos, c, f);
606 }
607
608
609 void LyXParagraph::InsertChar(LyXParagraph::size_type pos,
610                               char c, LyXFont const & font)
611 {
612         // > because last is the next unused position, and you can 
613         // use it if you want
614         if (pos > size()) {
615 #ifndef NEW_INSETS
616                 if (next
617                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
618                         NextAfterFootnote()->InsertChar(pos - text.size() - 1,
619                                                         c);
620                 else 
621 #endif
622                         lyxerr.debug() << "ERROR (LyXParagraph::InsertChar): "
623                                 "position does not exist." << endl;
624                 return;
625         }
626         text.insert(text.begin() + pos, c);
627         // Update the font table.
628         for (FontList::iterator it = lower_bound(fontlist.begin(),
629                                                  fontlist.end(),
630                                                  pos, matchFT());
631              it != fontlist.end(); ++it)
632                 ++(*it).pos;
633    
634         // Update the inset table.
635         for (InsetList::iterator it = lower_bound(insetlist.begin(),
636                                                   insetlist.end(),
637                                                   pos, matchIT());
638              it != insetlist.end(); ++it)
639                 ++(*it).pos;
640
641         SetFont(pos, font);
642 }
643
644
645 void LyXParagraph::InsertInset(LyXParagraph::size_type pos,
646                                Inset * inset)
647 {
648         LyXFont f(LyXFont::ALL_INHERIT);
649         InsertInset(pos, inset, f);
650 }
651
652
653 void LyXParagraph::InsertInset(LyXParagraph::size_type pos,
654                                Inset * inset, LyXFont const & font)
655 {
656         Assert(inset);
657         
658         // > because last is the next unused position, and you can 
659         // use it if you want
660         if (pos > size()) {
661 #ifndef NEW_INSETS
662                 if (next
663                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
664                         NextAfterFootnote()
665                                 ->InsertInset(pos - text.size() - 1,
666                                               inset, font);
667                 else
668 #endif
669                         lyxerr << "ERROR (LyXParagraph::InsertInset): " 
670                                 "position does not exist: " << pos << endl;
671                 return;
672         }
673         
674         InsertChar(pos, META_INSET, font);
675         Assert(text[pos] == META_INSET);
676         
677         // Add a new entry in the inset table.
678         InsetList::iterator it = lower_bound(insetlist.begin(),
679                                              insetlist.end(),
680                                              pos, matchIT());
681         if (it != insetlist.end() && (*it).pos == pos)
682                 lyxerr << "ERROR (LyXParagraph::InsertInset): "
683                         "there is an inset in position: " << pos << endl;
684         else
685                 insetlist.insert(it, InsetTable(pos, inset));
686         if (inset_owner)
687                 inset->setOwner(inset_owner);
688 }
689
690
691 bool LyXParagraph::InsertInsetAllowed(Inset * inset)
692 {
693         lyxerr << "LyXParagraph::InsertInsetAllowed" << endl;
694         
695         if (inset_owner)
696                 return inset_owner->InsertInsetAllowed(inset);
697         return true;
698 }
699
700
701 Inset * LyXParagraph::GetInset(LyXParagraph::size_type pos)
702 {
703         if (pos >= size()) {
704 #ifndef NEW_INSETS
705                 if (next
706                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
707                         return NextAfterFootnote()
708                                 ->GetInset(pos - text.size() - 1);
709                 else
710 #endif
711                         lyxerr << "ERROR (LyXParagraph::GetInset): "
712                                 "position does not exist: "
713                                << pos << endl;
714                 
715                 return 0;
716         }
717         // Find the inset.
718         InsetList::iterator it = lower_bound(insetlist.begin(),
719                                              insetlist.end(),
720                                              pos, matchIT());
721         if (it != insetlist.end() && (*it).pos == pos)
722                 return (*it).inset;
723
724         lyxerr << "ERROR (LyXParagraph::GetInset): "
725                 "Inset does not exist: " << pos << endl;
726         //::raise(SIGSTOP);
727         
728         // text[pos] = ' '; // WHY!!! does this set the pos to ' '????
729         // Did this commenting out introduce a bug? So far I have not
730         // see any, please enlighten me. (Lgb)
731         // My guess is that since the inset does not exist, we might
732         // as well replace it with a space to prevent craches. (Asger)
733         return 0;
734 }
735
736
737 Inset const * LyXParagraph::GetInset(LyXParagraph::size_type pos) const
738 {
739         if (pos >= size()) {
740 #ifndef NEW_INSETS
741                 if (next
742                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
743                         return NextAfterFootnote()
744                                 ->GetInset(pos - text.size() - 1);
745                 else
746 #endif
747                         lyxerr << "ERROR (LyXParagraph::GetInset): "
748                                 "position does not exist: "
749                                << pos << endl;
750
751                 return 0;
752         }
753         // Find the inset.
754         InsetList::const_iterator cit = lower_bound(insetlist.begin(),
755                                                     insetlist.end(),
756                                                     pos, matchIT());
757         if (cit != insetlist.end() && (*cit).pos == pos)
758                 return (*cit).inset;
759
760         lyxerr << "ERROR (LyXParagraph::GetInset): "
761                 "Inset does not exist: " << pos << endl;
762         //::raise(SIGSTOP);
763         //text[pos] = ' '; // WHY!!! does this set the pos to ' '????
764         // Did this commenting out introduce a bug? So far I have not
765         // see any, please enlighten me. (Lgb)
766         // My guess is that since the inset does not exist, we might
767         // as well replace it with a space to prevent craches. (Asger)
768         return 0;
769 }
770
771
772 // Gets uninstantiated font setting at position.
773 // Optimized after profiling. (Asger)
774 LyXFont LyXParagraph::GetFontSettings(BufferParams const & bparams,
775                                       LyXParagraph::size_type pos) const
776 {
777         if (pos < size()) {
778                 FontList::const_iterator cit = lower_bound(fontlist.begin(),
779                                                     fontlist.end(),
780                                                     pos, matchFT());
781                 if (cit != fontlist.end())
782                         return (*cit).font;
783         }
784         // > because last is the next unused position, and you can 
785         // use it if you want
786         else if (pos > size()) {
787 #ifndef NEW_INSETS
788                 if (next
789                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
790                         return NextAfterFootnote()
791                                 ->GetFontSettings(bparams,
792                                                   pos - text.size() - 1);
793                 else
794 #endif
795                         // Why is it an error to ask for the font of a
796                         // position that does not exist? Would it be
797                         // enough for this to be enabled on debug?
798                         // We want strict error checking, but it's ok to only
799                         // have it when debugging. (Asger)
800                         lyxerr << "ERROR (LyXParagraph::GetFontSettings): "
801                                 "position does not exist. "
802                                << pos << " (" << static_cast<int>(pos)
803                                << ")" << endl;
804         } else if (pos > 0) {
805                 return GetFontSettings(bparams, pos - 1);
806         } else // pos = size() = 0
807                 return LyXFont(LyXFont::ALL_INHERIT, getParLanguage(bparams));
808
809         return LyXFont(LyXFont::ALL_INHERIT);
810 }
811
812 // Gets uninstantiated font setting at position 0
813 LyXFont LyXParagraph::GetFirstFontSettings() const
814 {
815         if (size() > 0) {
816                 if (!fontlist.empty())
817                         return fontlist[0].font;
818         }
819         
820 #ifndef NEW_INSETS
821         else if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE) 
822                 return NextAfterFootnote()->GetFirstFontSettings();
823 #endif
824         return LyXFont(LyXFont::ALL_INHERIT);
825 }
826
827
828 // Gets the fully instantiated font at a given position in a paragraph
829 // This is basically the same function as LyXText::GetFont() in text2.C.
830 // The difference is that this one is used for generating the LaTeX file,
831 // and thus cosmetic "improvements" are disallowed: This has to deliver
832 // the true picture of the buffer. (Asger)
833 // If position is -1, we get the layout font of the paragraph.
834 // If position is -2, we get the font of the manual label of the paragraph.
835 LyXFont LyXParagraph::getFont(BufferParams const & bparams,
836                               LyXParagraph::size_type pos) const
837 {
838         LyXFont tmpfont;
839         LyXLayout const & layout =
840                 textclasslist.Style(bparams.textclass, 
841                                     GetLayout());
842         LyXParagraph::size_type main_body = 0;
843         if (layout.labeltype == LABEL_MANUAL)
844                 main_body = BeginningOfMainBody();
845
846         if (pos >= 0) {
847                 LyXFont layoutfont;
848                 if (pos < main_body)
849                         layoutfont = layout.labelfont;
850                 else
851                         layoutfont = layout.font;
852                 tmpfont = GetFontSettings(bparams, pos);
853                 tmpfont.realize(layoutfont);
854         } else {
855                 // process layoutfont for pos == -1 and labelfont for pos < -1
856                 if (pos == -1)
857                         tmpfont = layout.font;
858                 else
859                         tmpfont = layout.labelfont;
860                 tmpfont.setLanguage(getParLanguage(bparams));
861         }
862
863         // check for environment font information
864         char par_depth = GetDepth();
865         LyXParagraph const * par = this;
866         while (par && par_depth && !tmpfont.resolved()) {
867                 par = par->DepthHook(par_depth - 1);
868                 if (par) {
869                         tmpfont.realize(textclasslist.
870                                         Style(bparams.textclass,
871                                               par->GetLayout()).font);
872                         par_depth = par->GetDepth();
873                 }
874         }
875
876         tmpfont.realize(textclasslist
877                         .TextClass(bparams.textclass)
878                         .defaultfont());
879         return tmpfont;
880 }
881
882
883 /// Returns the height of the highest font in range
884 LyXFont::FONT_SIZE
885 LyXParagraph::HighestFontInRange(LyXParagraph::size_type startpos,
886                                  LyXParagraph::size_type endpos) const
887 {
888         LyXFont::FONT_SIZE maxsize = LyXFont::SIZE_TINY;
889         if (fontlist.empty())
890                 return maxsize;
891         
892         FontList::const_iterator end_it = lower_bound(fontlist.begin(),
893                                                       fontlist.end(),
894                                                       endpos, matchFT());
895         if (end_it != fontlist.end())
896                 ++end_it;
897
898         for (FontList::const_iterator cit = lower_bound(fontlist.begin(),
899                                                         fontlist.end(),
900                                                         startpos, matchFT());
901              cit != end_it; ++cit) {
902                 LyXFont::FONT_SIZE size = (*cit).font.size();
903                 if (size > maxsize && size <= LyXFont::SIZE_HUGER)
904                         maxsize = size;
905         }
906         return maxsize;
907 }
908
909
910 char LyXParagraph::GetChar(LyXParagraph::size_type pos)
911 {
912         Assert(pos >= 0);
913
914         if (pos < size()) {
915                 return text[pos];
916         }
917         // > because last is the next unused position, and you can 
918         // use it if you want
919         else if (pos > size()) {
920 #ifndef NEW_INSETS
921                 if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE) 
922                         return NextAfterFootnote()
923                                 ->GetChar(pos - text.size() - 1);
924                 else
925 #endif
926                         {
927                         lyxerr << "ERROR (LyXParagraph::GetChar): "
928                                 "position does not exist."
929                                << pos << " (" << static_cast<int>(pos)
930                                << ")\n";
931                         // Assert(false); // This triggers sometimes...
932                         // Why?
933                 }
934                 
935                 return '\0';
936         }
937         
938 #ifndef NEW_INSETS
939         else {
940                 // We should have a footnote environment.
941                 if (!next || next->footnoteflag == LyXParagraph::NO_FOOTNOTE) {
942                         // Notice that LyX does request the
943                         // last char from time to time. (Asger)
944                         //lyxerr << "ERROR (LyXParagraph::GetChar): "
945                         //      "expected footnote." << endl;
946                         return '\0';
947                 }
948                 switch (next->footnotekind) {
949                 case LyXParagraph::FOOTNOTE:
950                         return LyXParagraph::META_FOOTNOTE;
951                 case LyXParagraph::MARGIN:
952                         return LyXParagraph::META_MARGIN;
953                 case LyXParagraph::FIG:
954                 case LyXParagraph::WIDE_FIG:
955                         return LyXParagraph::META_FIG;
956                 case LyXParagraph::TAB:
957                 case LyXParagraph::WIDE_TAB:
958                         return LyXParagraph::META_TAB;
959                 case LyXParagraph::ALGORITHM:
960                         return LyXParagraph::META_ALGORITHM;
961                 }
962                 return '\0'; // to shut up gcc
963         }
964 #endif
965 }
966
967
968 char LyXParagraph::GetChar(LyXParagraph::size_type pos) const
969 {
970         Assert(pos >= 0);
971
972         if (pos < size()) {
973                 return text[pos];
974         }
975         // > because last is the next unused position, and you can 
976         // use it if you want
977         else if (pos > size()) {
978 #ifndef NEW_INSETS
979                 if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE) 
980                         return NextAfterFootnote()
981                                 ->GetChar(pos - text.size() - 1);
982                 else
983 #endif
984                         {
985                         lyxerr << "ERROR (LyXParagraph::GetChar const): "
986                                 "position does not exist."
987                                << pos << " (" << static_cast<int>(pos)
988                                << ")\n";
989                         Assert(false);
990                 }
991                 return '\0';
992         }
993 #ifndef NEW_INSETS
994         else {
995                 // We should have a footnote environment.
996                 if (!next || next->footnoteflag == LyXParagraph::NO_FOOTNOTE) {
997                         // Notice that LyX does request the
998                         // last char from time to time. (Asger)
999                         //lyxerr << "ERROR (LyXParagraph::GetChar): "
1000                         //      "expected footnote." << endl;
1001                         return '\0';
1002                 }
1003                 switch (next->footnotekind) {
1004                 case LyXParagraph::FOOTNOTE:
1005                         return LyXParagraph::META_FOOTNOTE;
1006                 case LyXParagraph::MARGIN:
1007                         return LyXParagraph::META_MARGIN;
1008                 case LyXParagraph::FIG:
1009                 case LyXParagraph::WIDE_FIG:
1010                         return LyXParagraph::META_FIG;
1011                 case LyXParagraph::TAB:
1012                 case LyXParagraph::WIDE_TAB:
1013                         return LyXParagraph::META_TAB;
1014                 case LyXParagraph::ALGORITHM:
1015                         return LyXParagraph::META_ALGORITHM;
1016                 }
1017                 return '\0'; // to shut up gcc
1018         }
1019 #endif
1020 }
1021
1022
1023 // return an string of the current word, and the end of the word in lastpos.
1024 string LyXParagraph::GetWord(LyXParagraph::size_type & lastpos) const
1025 {
1026         Assert(lastpos>=0);
1027
1028         // the current word is defined as starting at the first character
1029         // from the immediate left of lastpospos which meets the definition
1030         // of IsLetter(), continuing to the last character to the right
1031         // of this meeting IsLetter.
1032
1033         string theword;
1034
1035         // grab a word
1036                 
1037         // move back until we have a letter
1038
1039         //there's no real reason to have firstpos & lastpos as
1040         //separate variables as this is written, but maybe someon
1041         // will want to return firstpos in the future.
1042
1043         //since someone might have typed a punctuation first
1044         int firstpos = lastpos;
1045         
1046         while ((firstpos >= 0) && !IsLetter(firstpos))
1047                 --firstpos;
1048
1049         // now find the beginning by looking for a nonletter
1050         
1051         while ((firstpos>= 0) && IsLetter(firstpos))
1052                 --firstpos;
1053
1054         // the above is now pointing to the preceeding non-letter
1055         ++firstpos;
1056         lastpos = firstpos;
1057
1058         // so copy characters into theword  until we get a nonletter
1059         // note that this can easily exceed lastpos, wich means
1060         // that if used in the middle of a word, the whole word
1061         // is included
1062
1063         while (IsLetter(lastpos)) theword += GetChar(lastpos++);
1064         
1065         return theword;
1066
1067 }
1068
1069  
1070 LyXParagraph::size_type LyXParagraph::Last() const
1071 {
1072 #ifndef NEW_INSETS
1073         if (next && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE)
1074                 return text.size() + NextAfterFootnote()->Last() + 1;
1075         // the 1 is the symbol
1076         // for the footnote
1077         else
1078 #endif
1079                 return text.size();
1080 }
1081
1082
1083 LyXParagraph * LyXParagraph::ParFromPos(LyXParagraph::size_type pos)
1084 {
1085         // > because last is the next unused position, and you can 
1086         // use it if you want
1087         if (pos > size()) {
1088 #ifndef NEW_INSETS
1089                 if (next
1090                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
1091                         return NextAfterFootnote()
1092                                 ->ParFromPos(pos - text.size() - 1);
1093                 else
1094 #endif
1095                         lyxerr << "ERROR (LyXParagraph::ParFromPos): "
1096                                 "position does not exist." << endl;
1097                 return this;
1098         } else
1099                 return this;
1100 }
1101
1102
1103 int LyXParagraph::PositionInParFromPos(LyXParagraph::size_type pos) const
1104 {
1105         // > because last is the next unused position, and you can 
1106         // use it if you want
1107         if (pos > size()) {
1108 #ifndef NEW_INSETS
1109                 if (next
1110                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
1111                         return NextAfterFootnote()
1112                                 ->PositionInParFromPos(pos - text.size() - 1);
1113                 else
1114 #endif
1115                         lyxerr <<
1116                                 "ERROR (LyXParagraph::PositionInParFromPos): "
1117                                 "position does not exist." << endl;
1118                 return pos;
1119         }
1120         else
1121                 return pos;
1122 }
1123
1124
1125 void LyXParagraph::SetFont(LyXParagraph::size_type pos,
1126                            LyXFont const & font)
1127 {
1128         // > because last is the next unused position, and you can 
1129         // use it if you want
1130         if (pos > size()) {
1131 #ifndef NEW_INSETS
1132                 if (next &&
1133                     next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1134                         NextAfterFootnote()->SetFont(pos - text.size() - 1,
1135                                                      font);
1136                 } else
1137 #endif
1138                         lyxerr << "ERROR (LyXParagraph::SetFont): "
1139                                 "position does not exist." << endl;
1140                 
1141                 return;
1142         }
1143
1144         // First, reduce font against layout/label font
1145         // Update: The SetCharFont() routine in text2.C already
1146         // reduces font, so we don't need to do that here. (Asger)
1147         // No need to simplify this because it will disappear
1148         // in a new kernel. (Asger)
1149         // Next search font table
1150
1151         FontList::iterator it = lower_bound(fontlist.begin(),
1152                                             fontlist.end(),
1153                                             pos, matchFT());
1154         unsigned int i = it - fontlist.begin();
1155         bool notfound = it == fontlist.end();
1156
1157         if (!notfound && fontlist[i].font == font)
1158                 return;
1159
1160         bool begin = pos == 0 || notfound ||
1161                 (i > 0 && fontlist[i-1].pos == pos - 1);
1162         // Is position pos is a beginning of a font block?
1163         bool end = !notfound && fontlist[i].pos == pos;
1164         // Is position pos is the end of a font block?
1165         if (begin && end) { // A single char block
1166                 if (i+1 < fontlist.size() &&
1167                     fontlist[i+1].font == font) {
1168                         // Merge the singleton block with the next block
1169                         fontlist.erase(fontlist.begin() + i);
1170                         if (i > 0 && fontlist[i-1].font == font)
1171                                 fontlist.erase(fontlist.begin() + i-1);
1172                 } else if (i > 0 && fontlist[i-1].font == font) {
1173                         // Merge the singleton block with the previous block
1174                         fontlist[i-1].pos = pos;
1175                         fontlist.erase(fontlist.begin() + i);
1176                 } else
1177                         fontlist[i].font = font;
1178         } else if (begin) {
1179                 if (i > 0 && fontlist[i-1].font == font)
1180                         fontlist[i-1].pos = pos;
1181                 else
1182                         fontlist.insert(fontlist.begin() + i,
1183                                         FontTable(pos, font));
1184         } else if (end) {
1185                 fontlist[i].pos = pos - 1;
1186                 if (!(i+1 < fontlist.size() &&
1187                       fontlist[i+1].font == font))
1188                         fontlist.insert(fontlist.begin() + i+1,
1189                                         FontTable(pos, font));
1190         } else { // The general case. The block is splitted into 3 blocks
1191                 fontlist.insert(fontlist.begin() + i, 
1192                                 FontTable(pos - 1, fontlist[i].font));
1193                 fontlist.insert(fontlist.begin() + i+1, FontTable(pos, font));
1194         }
1195 }
1196
1197    
1198 // This function is able to hide closed footnotes.
1199 LyXParagraph * LyXParagraph::Next()
1200 {
1201 #ifndef NEW_INSETS
1202         if (next && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1203                 LyXParagraph * tmp = next;
1204                 while (tmp
1205                        && tmp->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE)
1206                         tmp = tmp->next;
1207                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1208                         return tmp->Next(); /* there can be more than one
1209                                                footnote in a logical
1210                                                paragraph */
1211                 else
1212                         return next;  // This should never happen!
1213         } else
1214 #endif
1215                 return next;
1216 }
1217
1218
1219 LyXParagraph * LyXParagraph::NextAfterFootnote()
1220 {
1221 #ifndef NEW_INSETS
1222         if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
1223                 LyXParagraph * tmp = next;
1224                 while (tmp && tmp->footnoteflag != LyXParagraph::NO_FOOTNOTE)
1225                         tmp = tmp->next;
1226                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1227                         return tmp;   /* there can be more than one footnote
1228                                          in a logical paragraph */
1229                 else
1230                         return next;  // This should never happen!
1231         } else
1232 #endif
1233                 return next;
1234 }
1235
1236
1237 LyXParagraph const * LyXParagraph::NextAfterFootnote() const
1238 {
1239 #ifndef NEW_INSETS
1240         if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
1241                 LyXParagraph * tmp = next;
1242                 while (tmp && tmp->footnoteflag != LyXParagraph::NO_FOOTNOTE)
1243                         tmp = tmp->next;
1244                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1245                         return tmp;   /* there can be more than one footnote
1246                                          in a logical paragraph */
1247                 else
1248                         return next;  // This should never happen!
1249         } else
1250 #endif
1251                 return next;
1252 }
1253
1254
1255 LyXParagraph * LyXParagraph::PreviousBeforeFootnote()
1256 {
1257 #ifndef NEW_INSETS
1258         LyXParagraph * tmp;
1259         if (previous && previous->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
1260                 tmp = previous;
1261                 while (tmp && tmp->footnoteflag != LyXParagraph::NO_FOOTNOTE)
1262                         tmp = tmp->previous;
1263                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1264                         return tmp;    /* there can be more than one footnote
1265                                           in a logical paragraph */
1266                 else
1267                         return previous;  // This should never happen!
1268         } else
1269 #endif
1270                 return previous;
1271 }
1272
1273
1274 LyXParagraph * LyXParagraph::LastPhysicalPar()
1275 {
1276 #ifndef NEW_INSETS
1277         if (footnoteflag != LyXParagraph::NO_FOOTNOTE)
1278                 return this;
1279    
1280         LyXParagraph * tmp = this;
1281         while (tmp->next
1282                && tmp->next->footnoteflag != LyXParagraph::NO_FOOTNOTE)
1283                 tmp = tmp->NextAfterFootnote();
1284    
1285         return tmp;
1286 #else
1287         return this;
1288 #endif
1289 }
1290
1291 LyXParagraph const * LyXParagraph::LastPhysicalPar() const
1292 {
1293 #ifndef NEW_INSETS
1294         if (footnoteflag != LyXParagraph::NO_FOOTNOTE)
1295                 return this;
1296    
1297         LyXParagraph const * tmp = this;
1298         while (tmp->next
1299                && tmp->next->footnoteflag != LyXParagraph::NO_FOOTNOTE)
1300                 tmp = tmp->NextAfterFootnote();
1301    
1302         return tmp;
1303 #else
1304         return this;
1305 #endif
1306 }
1307
1308 LyXParagraph * LyXParagraph::FirstPhysicalPar()
1309 {
1310 #ifndef NEW_INSETS
1311         if (!IsDummy())
1312                 return this;
1313         LyXParagraph * tmppar = this;
1314
1315         while (tmppar &&
1316                (tmppar->IsDummy()
1317                 || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE))
1318                 tmppar = tmppar->previous;
1319    
1320         if (!tmppar) {
1321                 return this;
1322         } else
1323                 return tmppar;
1324 #else
1325         return this;
1326 #endif
1327 }
1328
1329
1330 LyXParagraph const * LyXParagraph::FirstPhysicalPar() const
1331 {
1332 #ifndef NEW_INSETS
1333         if (!IsDummy())
1334                 return this;
1335         LyXParagraph const * tmppar = this;
1336
1337         while (tmppar &&
1338                (tmppar->IsDummy()
1339                 || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE))
1340                 tmppar = tmppar->previous;
1341    
1342         if (!tmppar) {
1343                 return this;
1344         } else
1345                 return tmppar;
1346 #else
1347         return this;
1348 #endif
1349 }
1350
1351
1352 // This function is able to hide closed footnotes.
1353 LyXParagraph * LyXParagraph::Previous()
1354 {
1355         LyXParagraph * tmp = previous;
1356         if (!tmp)
1357                 return tmp;
1358
1359 #ifndef NEW_INSETS
1360         if (tmp->previous
1361             && tmp->previous->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1362                 tmp = tmp->previous;
1363                 while (tmp
1364                        && tmp->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE)
1365                         tmp = tmp->previous;
1366                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1367                         return tmp->next->Previous();   
1368
1369                 else
1370                         return previous; 
1371         } else
1372 #endif
1373                 return previous;
1374 }
1375
1376
1377 // This function is able to hide closed footnotes.
1378 LyXParagraph const * LyXParagraph::Previous() const
1379 {
1380         LyXParagraph * tmp = previous;
1381         if (!tmp)
1382                 return tmp;
1383 #ifndef NEW_INSETS
1384         if (tmp->previous
1385             && tmp->previous->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1386                 tmp = tmp->previous;
1387                 while (tmp
1388                        && tmp->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE)
1389                         tmp = tmp->previous;
1390                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1391                         return tmp->next->Previous();   
1392
1393                 else
1394                         return previous; 
1395         } else
1396 #endif
1397                 return previous;
1398 }
1399
1400
1401 void LyXParagraph::BreakParagraph(BufferParams const & bparams,
1402                                   LyXParagraph::size_type pos,
1403                                   int flag)
1404 {
1405         size_type i, j, pos_end, pos_first;
1406         // create a new paragraph
1407         LyXParagraph * par = ParFromPos(pos);
1408         LyXParagraph * firstpar = FirstPhysicalPar();
1409    
1410         LyXParagraph * tmp = new LyXParagraph(par);
1411
1412 #ifndef NEW_INSETS
1413         tmp->footnoteflag = footnoteflag;
1414         tmp->footnotekind = footnotekind;
1415 #endif
1416         // this is an idea for a more userfriendly layout handling, I will
1417         // see what the users say
1418    
1419         // layout stays the same with latex-environments
1420         if (flag) {
1421                 tmp->SetOnlyLayout(bparams, firstpar->layout);
1422                 tmp->SetLabelWidthString(firstpar->labelwidthstring);
1423         }
1424
1425         if (Last() > pos || !Last() || flag == 2) {
1426                 tmp->SetOnlyLayout(bparams, firstpar->layout);
1427                 tmp->align = firstpar->align;
1428                 tmp->SetLabelWidthString(firstpar->labelwidthstring);
1429       
1430                 tmp->line_bottom = firstpar->line_bottom;
1431                 firstpar->line_bottom = false;
1432                 tmp->pagebreak_bottom = firstpar->pagebreak_bottom;
1433                 firstpar->pagebreak_bottom = false;
1434                 tmp->added_space_bottom = firstpar->added_space_bottom;
1435                 firstpar->added_space_bottom = VSpace(VSpace::NONE);
1436       
1437                 tmp->depth = firstpar->depth;
1438                 tmp->noindent = firstpar->noindent;
1439    
1440                 // copy everything behind the break-position
1441                 // to the new paragraph
1442                 pos_first = 0;
1443                 while (ParFromPos(pos_first) != par)
1444                         ++pos_first;
1445
1446                 pos_end = pos_first + par->text.size() - 1;
1447
1448                 for (i = j = pos; i <= pos_end; ++i) {
1449                         par->CutIntoMinibuffer(bparams, i - pos_first);
1450                         if (tmp->InsertFromMinibuffer(j - pos))
1451                                 ++j;
1452                 }
1453                 tmp->text.resize(tmp->text.size());
1454                 for (i = pos_end; i >= pos; --i)
1455                         par->Erase(i - pos_first);
1456
1457                 par->text.resize(par->text.size());
1458         }
1459
1460         // just an idea of me
1461         if (!pos) {
1462                 tmp->line_top = firstpar->line_top;
1463                 tmp->pagebreak_top = firstpar->pagebreak_top;
1464                 tmp->added_space_top = firstpar->added_space_top;
1465                 tmp->bibkey = firstpar->bibkey;
1466                 firstpar->Clear();
1467                 // layout stays the same with latex-environments
1468                 if (flag) {
1469                         firstpar->SetOnlyLayout(bparams, tmp->layout);
1470                         firstpar->SetLabelWidthString(tmp->labelwidthstring);
1471                         firstpar->depth = tmp->depth;
1472                 }
1473         }
1474 }
1475
1476
1477 void LyXParagraph::MakeSameLayout(LyXParagraph const * par)
1478 {
1479         par = par->FirstPhysicalPar();
1480 #ifndef NEW_INSETS
1481         footnoteflag = par->footnoteflag;
1482         footnotekind = par->footnotekind;
1483 #endif
1484         layout = par->layout;
1485         align = par-> align;
1486         SetLabelWidthString(par->labelwidthstring);
1487
1488         line_bottom = par->line_bottom;
1489         pagebreak_bottom = par->pagebreak_bottom;
1490         added_space_bottom = par->added_space_bottom;
1491
1492         line_top = par->line_top;
1493         pagebreak_top = par->pagebreak_top;
1494         added_space_top = par->added_space_top;
1495
1496         spacing = par->spacing;
1497         
1498         pextra_type = par->pextra_type;
1499         pextra_width = par->pextra_width;
1500         pextra_widthp = par->pextra_widthp;
1501         pextra_alignment = par->pextra_alignment;
1502         pextra_hfill = par->pextra_hfill;
1503         pextra_start_minipage = par->pextra_start_minipage;
1504
1505         noindent = par->noindent;
1506         depth = par->depth;
1507 }
1508
1509
1510 #ifndef NEW_INSETS
1511 LyXParagraph * LyXParagraph::FirstSelfrowPar()
1512 {
1513         LyXParagraph * tmppar = this;
1514         while (tmppar && (
1515                 (tmppar->IsDummy()
1516                  && tmppar->previous->footnoteflag == 
1517                  LyXParagraph::CLOSED_FOOTNOTE)
1518                 || tmppar->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE))
1519                 tmppar = tmppar->previous;
1520    
1521         if (!tmppar)
1522                 return this;  // This should never happen!
1523         else
1524                 return tmppar;
1525 }
1526 #endif
1527
1528
1529 int LyXParagraph::StripLeadingSpaces(LyXTextClassList::size_type tclass) 
1530 {
1531         if (textclasslist.Style(tclass, GetLayout()).free_spacing)
1532                 return 0;
1533         
1534         int i = 0;
1535         if (!IsDummy() && !table){
1536                 while (Last()
1537                        && (IsNewline(0) || IsLineSeparator(0))){
1538                         Erase(0);
1539                         ++i;
1540                 }
1541         }
1542         return i;
1543 }
1544
1545
1546 LyXParagraph * LyXParagraph::Clone() const
1547 {
1548         // create a new paragraph
1549         LyXParagraph * result = new LyXParagraph;
1550    
1551         result->MakeSameLayout(this);
1552
1553         // this is because of the dummy layout of the paragraphs that
1554         // follow footnotes
1555         result->layout = layout;
1556
1557 #ifndef NEW_TABULAR
1558         /* table stuff -- begin*/ 
1559         if (table)
1560                 result->table = table->Clone();
1561         else
1562                 result->table = 0;
1563         /* table stuff -- end*/ 
1564 #endif
1565         result->inset_owner = inset_owner;
1566    
1567         // ale970302
1568         result->bibkey = (bibkey) ? new InsetBibKey(bibkey): 0;
1569                
1570     
1571         // copy everything behind the break-position to the new paragraph
1572
1573         result->text = text;
1574         result->fontlist = fontlist;
1575         result->insetlist = insetlist;
1576         for (InsetList::iterator it = result->insetlist.begin();
1577              it != result->insetlist.end(); ++it)
1578                 (*it).inset = (*it).inset->Clone();
1579         return result;
1580 }
1581
1582
1583 bool LyXParagraph::HasSameLayout(LyXParagraph const * par) const
1584 {
1585         par = par->FirstPhysicalPar();
1586
1587         return (
1588 #ifndef NEW_INSETS
1589                 par->footnoteflag == footnoteflag &&
1590                 par->footnotekind == footnotekind &&
1591 #endif
1592                 par->layout == layout &&
1593
1594                 par->align == align &&
1595
1596                 par->line_bottom == line_bottom &&
1597                 par->pagebreak_bottom == pagebreak_bottom &&
1598                 par->added_space_bottom == added_space_bottom &&
1599
1600                 par->line_top == line_top &&
1601                 par->pagebreak_top == pagebreak_top &&
1602                 par->added_space_top == added_space_top &&
1603
1604                 par->spacing == spacing &&
1605                 
1606                 par->pextra_type == pextra_type &&
1607                 par->pextra_width == pextra_width && 
1608                 par->pextra_widthp == pextra_widthp && 
1609                 par->pextra_alignment == pextra_alignment && 
1610                 par->pextra_hfill == pextra_hfill && 
1611                 par->pextra_start_minipage == pextra_start_minipage && 
1612 #ifndef NEW_TABULAR
1613                 par->table == table && // what means: NO TABLE AT ALL
1614 #endif
1615
1616                 par->noindent == noindent &&
1617                 par->depth == depth);
1618 }
1619
1620
1621 void LyXParagraph::BreakParagraphConservative(BufferParams const & bparams,
1622                                               LyXParagraph::size_type pos)
1623 {
1624         // create a new paragraph
1625         LyXParagraph * par = ParFromPos(pos);
1626
1627         LyXParagraph * tmp = new LyXParagraph(par);
1628    
1629         tmp->MakeSameLayout(par);
1630
1631         // When can pos < Last()?
1632         // I guess pos == Last() is possible.
1633         if (Last() > pos) {
1634                 // copy everything behind the break-position to the new
1635                 // paragraph
1636                 size_type pos_first = 0;
1637                 while (ParFromPos(pos_first) != par)
1638                         ++pos_first;
1639                 size_type pos_end = pos_first + par->text.size() - 1;
1640
1641                 size_type i, j;
1642                 for (i = j = pos; i <= pos_end; ++i) {
1643                         par->CutIntoMinibuffer(bparams, i - pos_first);
1644                         if (tmp->InsertFromMinibuffer(j - pos))
1645                                 ++j;
1646                 }
1647                 tmp->text.resize(tmp->text.size());
1648                 for (size_type i = pos_end; i >= pos; --i)
1649                         par->Erase(i - pos_first);
1650
1651                 par->text.resize(par->text.size());
1652         }
1653 }
1654    
1655
1656 // Be carefull, this does not make any check at all.
1657 void LyXParagraph::PasteParagraph(BufferParams const & bparams)
1658 {
1659         // copy the next paragraph to this one
1660         LyXParagraph * the_next = Next();
1661    
1662         LyXParagraph * firstpar = FirstPhysicalPar();
1663    
1664         // first the DTP-stuff
1665         firstpar->line_bottom = the_next->line_bottom;
1666         firstpar->added_space_bottom = the_next->added_space_bottom;
1667         firstpar->pagebreak_bottom = the_next->pagebreak_bottom;
1668
1669         size_type pos_end = the_next->text.size() - 1;
1670         size_type pos_insert = Last();
1671
1672         // ok, now copy the paragraph
1673         size_type i, j;
1674         for (i = j = 0; i <= pos_end; ++i) {
1675                 the_next->CutIntoMinibuffer(bparams, i);
1676                 if (InsertFromMinibuffer(pos_insert + j))
1677                         ++j;
1678         }
1679    
1680         // delete the next paragraph
1681         LyXParagraph * ppar = the_next->previous;
1682         LyXParagraph * npar = the_next->next;
1683         delete the_next;
1684         ppar->next = npar;
1685 }
1686
1687
1688 #ifndef NEW_INSETS
1689 void LyXParagraph::OpenFootnote(LyXParagraph::size_type pos)
1690 {
1691         LyXParagraph * par = ParFromPos(pos);
1692         par = par->next;
1693         while (par && par->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1694                 par->footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
1695                 par = par->next;
1696         }
1697 }
1698
1699
1700 void LyXParagraph::CloseFootnote(LyXParagraph::size_type pos)
1701 {
1702         LyXParagraph * par = ParFromPos(pos);
1703         par = par->next;
1704         while (par && par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
1705                 par->footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
1706                 par = par->next;
1707         }
1708 }
1709 #endif
1710
1711 int LyXParagraph::GetEndLabel(BufferParams const & bparams) const
1712 {
1713         LyXParagraph const * par = this;
1714         int par_depth = GetDepth();
1715         while (par) {
1716                 LyXTextClass::LayoutList::size_type layout = par->GetLayout();
1717                 int endlabeltype =
1718                         textclasslist.Style(bparams.textclass,
1719                                             layout).endlabeltype;
1720                 if (endlabeltype != END_LABEL_NO_LABEL) {
1721                         LyXParagraph const * last = this;
1722                         if( footnoteflag == NO_FOOTNOTE)
1723                                 last = LastPhysicalPar();
1724                         else if (next->footnoteflag == NO_FOOTNOTE)
1725                                 return endlabeltype;
1726
1727                         if (!last || !last->next)
1728                                 return endlabeltype;
1729
1730                         int next_depth = last->next->GetDepth();
1731                         if (par_depth > next_depth ||
1732                             (par_depth == next_depth && layout != last->next->GetLayout() ))
1733                                 return endlabeltype;
1734                         break;
1735                 }
1736                 if (par_depth == 0)
1737                         break;
1738                 par = par->DepthHook(par_depth - 1);
1739                 if (par)
1740                         par_depth = par->GetDepth();
1741         }
1742         return END_LABEL_NO_LABEL;
1743 }
1744
1745
1746 LyXTextClass::size_type LyXParagraph::GetLayout() const
1747 {
1748         return FirstPhysicalPar()->layout;
1749 }
1750
1751
1752 char LyXParagraph::GetDepth() const
1753 {
1754         return FirstPhysicalPar()->depth;
1755 }
1756
1757
1758 char LyXParagraph::GetAlign() const
1759 {
1760         return FirstPhysicalPar()->align;
1761 }
1762
1763
1764 string LyXParagraph::GetLabelstring() const
1765 {
1766         return FirstPhysicalPar()->labelstring;
1767 }
1768
1769
1770 int LyXParagraph::GetFirstCounter(int i) const
1771 {
1772         return FirstPhysicalPar()->counter_[i];
1773 }
1774
1775
1776 // the next two functions are for the manual labels
1777 string LyXParagraph::GetLabelWidthString() const
1778 {
1779         if (!FirstPhysicalPar()->labelwidthstring.empty())
1780                 return FirstPhysicalPar()->labelwidthstring;
1781         else
1782                 return _("Senseless with this layout!");
1783 }
1784
1785
1786 void LyXParagraph::SetLabelWidthString(string const & s)
1787 {
1788         LyXParagraph * par = FirstPhysicalPar();
1789
1790         par->labelwidthstring = s;
1791 }
1792
1793
1794 void LyXParagraph::SetOnlyLayout(BufferParams const & bparams,
1795                                  LyXTextClass::size_type new_layout)
1796 {
1797         LyXParagraph * par = FirstPhysicalPar();
1798         LyXParagraph * ppar = 0;
1799         LyXParagraph * npar = 0;
1800
1801         par->layout = new_layout;
1802 #ifndef NEW_TABULAR
1803         /* table stuff -- begin*/ 
1804         if (table) 
1805                 par->layout = 0;
1806         /* table stuff -- end*/
1807 #endif
1808         if (par->pextra_type == PEXTRA_NONE) {
1809                 if (par->Previous()) {
1810                         ppar = par->Previous()->FirstPhysicalPar();
1811                         while(ppar
1812                               && ppar->Previous()
1813                               && (ppar->depth > par->depth))
1814                                 ppar = ppar->Previous()->FirstPhysicalPar();
1815                 }
1816                 if (par->Next()) {
1817                         npar = par->Next()->NextAfterFootnote();
1818                         while(npar
1819                               && npar->Next()
1820                               && (npar->depth > par->depth))
1821                                 npar = npar->Next()->NextAfterFootnote();
1822                 }
1823                 if (ppar && (ppar->pextra_type != PEXTRA_NONE)) {
1824                         string
1825                                 p1 = ppar->pextra_width,
1826                                 p2 = ppar->pextra_widthp;
1827                         ppar->SetPExtraType(bparams, ppar->pextra_type,
1828                                             p1.c_str(), p2.c_str());
1829                 }
1830                 if ((par->pextra_type == PEXTRA_NONE) &&
1831                     npar && (npar->pextra_type != PEXTRA_NONE)) {
1832                         string
1833                                 p1 = npar->pextra_width,
1834                                 p2 = npar->pextra_widthp;
1835                         npar->SetPExtraType(bparams, npar->pextra_type,
1836                                             p1.c_str(), p2.c_str());
1837                 }
1838         }
1839 }
1840
1841
1842 void LyXParagraph::SetLayout(BufferParams const & bparams,
1843                              LyXTextClass::size_type new_layout)
1844 {
1845         LyXParagraph
1846                 * par = FirstPhysicalPar(),
1847                 * ppar = 0,
1848                 * npar = 0;
1849
1850         par->layout = new_layout;
1851         par->labelwidthstring.erase();
1852         par->align = LYX_ALIGN_LAYOUT;
1853         par->added_space_top = VSpace(VSpace::NONE);
1854         par->added_space_bottom = VSpace(VSpace::NONE);
1855         par->spacing.set(Spacing::Default);
1856
1857 #ifndef NEW_TABULAR
1858         /* table stuff -- begin*/ 
1859         if (table) 
1860                 par->layout = 0;
1861         /* table stuff -- end*/
1862 #endif
1863         if (par->pextra_type == PEXTRA_NONE) {
1864                 if (par->Previous()) {
1865                         ppar = par->Previous()->FirstPhysicalPar();
1866                         while(ppar
1867                               && ppar->Previous()
1868                               && (ppar->depth > par->depth))
1869                                 ppar = ppar->Previous()->FirstPhysicalPar();
1870                 }
1871                 if (par->Next()) {
1872                         npar = par->Next()->NextAfterFootnote();
1873                         while(npar
1874                               && npar->Next()
1875                               && (npar->depth > par->depth))
1876                                 npar = npar->Next()->NextAfterFootnote();
1877                 }
1878                 if (ppar && (ppar->pextra_type != PEXTRA_NONE)) {
1879                         string
1880                                 p1 = ppar->pextra_width,
1881                                 p2 = ppar->pextra_widthp;
1882                         ppar->SetPExtraType(bparams, ppar->pextra_type,
1883                                             p1.c_str(), p2.c_str());
1884                 }
1885                 if ((par->pextra_type == PEXTRA_NONE) &&
1886                     npar && (npar->pextra_type != PEXTRA_NONE)) {
1887                         string
1888                                 p1 = npar->pextra_width,
1889                                 p2 = npar->pextra_widthp;
1890                         npar->SetPExtraType(bparams, npar->pextra_type,
1891                                             p1.c_str(), p2.c_str());
1892                 }
1893         }
1894 }
1895
1896
1897 // if the layout of a paragraph contains a manual label, the beginning of the 
1898 // main body is the beginning of the second word. This is what the par-
1899 // function returns. If the layout does not contain a label, the main
1900 // body always starts with position 0. This differentiation is necessary,
1901 // because there cannot be a newline or a blank <= the beginning of the 
1902 // main body in TeX.
1903
1904 int LyXParagraph::BeginningOfMainBody() const
1905 {
1906         if (FirstPhysicalPar() != this)
1907                 return -1;
1908    
1909         // Unroll the first two cycles of the loop
1910         // and remember the previous character to
1911         // remove unnecessary GetChar() calls
1912         size_type i = 0;
1913         if (i < size()
1914             && GetChar(i) != LyXParagraph::META_NEWLINE
1915                 ) {
1916                 ++i;
1917                 char previous_char = 0, temp = 0; 
1918                 if (i < size()
1919                     && (previous_char = GetChar(i)) != LyXParagraph::META_NEWLINE) {
1920                         // Yes, this  ^ is supposed to be "= " not "=="
1921                         ++i;
1922                         while (i < size()
1923                                && previous_char != ' '
1924                                && (temp = GetChar(i)) != LyXParagraph::META_NEWLINE) {
1925                                 ++i;
1926                                 previous_char = temp;
1927                         }
1928                 }
1929         }
1930
1931         if (i == 0 && i == size() &&
1932             !(footnoteflag == LyXParagraph::NO_FOOTNOTE
1933               && next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE))
1934                 ++i;                           /* the cursor should not jump  
1935                                                 * to the main body if there
1936                                                 * is nothing in! */
1937         return i;
1938 }
1939
1940
1941 LyXParagraph * LyXParagraph::DepthHook(int deth)
1942 {
1943         LyXParagraph * newpar = this;
1944         if (deth < 0)
1945                 return 0;
1946    
1947         do {
1948                 newpar = newpar->FirstPhysicalPar()->Previous();
1949         } while (newpar && newpar->GetDepth() > deth
1950                  && newpar->footnoteflag == footnoteflag);
1951    
1952         if (!newpar) {
1953                 if (Previous() || GetDepth())
1954                         lyxerr << "ERROR (LyXParagraph::DepthHook): "
1955                                 "no hook." << endl;
1956                 newpar = this;
1957         }
1958         return newpar->FirstPhysicalPar();
1959 }
1960
1961
1962 LyXParagraph const * LyXParagraph::DepthHook(int deth) const
1963 {
1964         LyXParagraph const * newpar = this;
1965         if (deth < 0)
1966                 return 0;
1967    
1968         do {
1969                 newpar = newpar->FirstPhysicalPar()->Previous();
1970         } while (newpar && newpar->GetDepth() > deth
1971                  && newpar->footnoteflag == footnoteflag);
1972    
1973         if (!newpar) {
1974                 if (Previous() || GetDepth())
1975                         lyxerr << "ERROR (LyXParagraph::DepthHook): "
1976                                 "no hook." << endl;
1977                 newpar = this;
1978         }
1979         return newpar->FirstPhysicalPar();
1980 }
1981
1982
1983 int LyXParagraph::AutoDeleteInsets()
1984 {
1985         int count = 0;
1986         InsetList::size_type index = 0;
1987         while (index < insetlist.size()) {
1988                 if (insetlist[index].inset && insetlist[index].inset->AutoDelete()) {
1989                         Erase(insetlist[index].pos); 
1990                         // Erase() calls to insetlist.erase(&insetlist[index])
1991                         // so index shouldn't be increased.
1992                         ++count;
1993                 } else
1994                         ++index;
1995         }
1996         return count;
1997 }
1998
1999
2000 LyXParagraph::inset_iterator LyXParagraph::InsetIterator(LyXParagraph::size_type pos)
2001 {
2002         InsetList::iterator it = lower_bound(insetlist.begin(),
2003                                              insetlist.end(),
2004                                              pos, matchIT());
2005         return inset_iterator(it);
2006 }
2007
2008
2009 // returns -1 if inset not found
2010 int LyXParagraph::GetPositionOfInset(Inset * inset) const
2011 {
2012         // Find the entry.
2013         // We could use lower_bound here too, we just need to add
2014         // the approp. operator() to matchIT (and change the name
2015         // of that struct). Code would then be:
2016         // InsetList::const_iterator cit = lower_bound(insetlist.begin(),
2017         //                                             insetlist.end(),
2018         //                                             inset, matchIT());
2019         // if ((*cit).inset == inset) {
2020         //         return (*cit).pos;
2021         // }
2022         for (InsetList::const_iterator cit = insetlist.begin();
2023              cit != insetlist.end(); ++cit) {
2024                 if ((*cit).inset == inset) {
2025                         return (*cit).pos;
2026                 }
2027         }
2028         // Think about footnotes.
2029         if (footnoteflag == LyXParagraph::NO_FOOTNOTE 
2030             && next && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
2031                 int further = 
2032                         NextAfterFootnote()->GetPositionOfInset(inset);
2033                 if (further != -1)
2034                         return text.size() + 1 + further;
2035         }
2036         return -1;
2037 }
2038
2039
2040 LyXParagraph * LyXParagraph::TeXOnePar(Buffer const * buf,
2041                                        BufferParams const & bparams,
2042                                        ostream & os, TexRow & texrow,
2043                                        bool moving_arg, 
2044                                        ostream & foot,
2045                                        TexRow & foot_texrow,
2046                                        int & foot_count)
2047 {
2048         lyxerr[Debug::LATEX] << "TeXOnePar...     " << this << endl;
2049         LyXLayout const & style =
2050                 textclasslist.Style(bparams.textclass,
2051                                     layout);
2052
2053         bool further_blank_line = false;
2054         if (IsDummy())
2055                 lyxerr << "ERROR (LyXParagraph::TeXOnePar) is dummy." << endl;
2056
2057         if (start_of_appendix) {
2058                 os << "\\appendix\n";
2059                 texrow.newline();
2060         }
2061
2062         if (!spacing.isDefault()
2063             && (!Previous() || !Previous()->HasSameLayout(this))) {
2064                 os << spacing.writeEnvirBegin() << "\n";
2065                 texrow.newline();
2066         }
2067         
2068         if (tex_code_break_column && style.isCommand()){
2069                 os << '\n';
2070                 texrow.newline();
2071         }
2072
2073         if (pagebreak_top) {
2074                 os << "\\newpage";
2075                 further_blank_line = true;
2076         }
2077         if (added_space_top.kind() != VSpace::NONE) {
2078                 os << added_space_top.asLatexCommand(bparams);
2079                 further_blank_line = true;
2080         }
2081       
2082         if (line_top) {
2083                 os << "\\lyxline{\\" << getFont(bparams, 0).latexSize() << '}'
2084                    << "\\vspace{-1\\parskip}";
2085                 further_blank_line = true;
2086         }
2087
2088         if (further_blank_line){
2089                 os << '\n';
2090                 texrow.newline();
2091         }
2092
2093         Language const * language = getParLanguage(bparams);
2094         Language const * doc_language = bparams.language_info;
2095         if (language != doc_language &&
2096             (!previous || previous->getParLanguage(bparams) != language)) {
2097                 os << subst(lyxrc.language_command_begin, "$$lang",
2098                             language->lang())
2099                    << endl;
2100                 texrow.newline();
2101         }
2102         
2103         switch (style.latextype) {
2104         case LATEX_COMMAND:
2105                 os << '\\'
2106                    << style.latexname()
2107                    << style.latexparam();
2108                 break;
2109         case LATEX_ITEM_ENVIRONMENT:
2110                 if (bibkey) {
2111                         bibkey->Latex(buf, os, false, false);
2112                 } else
2113                         os << "\\item ";
2114                 break;
2115         case LATEX_LIST_ENVIRONMENT:
2116                 os << "\\item ";
2117                 break;
2118         default:
2119                 break;
2120         }
2121
2122         bool need_par = SimpleTeXOnePar(buf, bparams, os, texrow, moving_arg);
2123  
2124 #ifndef NEW_INSETS
2125         // Spit out footnotes
2126         LyXParagraph * par = next;
2127         if (lyxrc.rtl_support) {
2128                 if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE
2129                     && next->footnoteflag != footnoteflag) {
2130                         LyXParagraph * p = 0;
2131                         bool is_rtl = (size() > 0) 
2132                                 ? GetFontSettings(bparams,
2133                                                   size()-1).isRightToLeft()
2134                                 : language->RightToLeft();
2135                         if ( (p = NextAfterFootnote()) != 0 &&
2136                              p->size() > 0 &&
2137                              p->GetFontSettings(bparams, 0).isRightToLeft() != is_rtl)
2138                                 is_rtl = getParLanguage(bparams)->RightToLeft();
2139                         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE
2140                                && par->footnoteflag != footnoteflag) {
2141                                 par = par->TeXFootnote(buf, bparams,
2142                                                        os, texrow, foot,
2143                                                        foot_texrow, foot_count,
2144                                                        is_rtl);
2145                                 par->SimpleTeXOnePar(buf, bparams,
2146                                                      os, texrow, moving_arg);
2147                                 is_rtl = (par->size() > 0)
2148                                         ? par->GetFontSettings(bparams,
2149                                                                par->size()-1).isRightToLeft()
2150                                         : language->RightToLeft();
2151                                 if (par->next &&
2152                                     par->next->footnoteflag != LyXParagraph::NO_FOOTNOTE &&
2153                                     (p = par->NextAfterFootnote()) != 0 &&
2154                                     p->size() > 0 &&
2155                                     p->GetFontSettings(bparams, 0).isRightToLeft() != is_rtl)
2156                                         is_rtl = language->RightToLeft();
2157                                 par = par->next;
2158                         }
2159                 }
2160         } else {
2161                 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE
2162                        && par->footnoteflag != footnoteflag) {
2163                         par = par->TeXFootnote(buf, bparams,
2164                                                os, texrow,
2165                                                foot, foot_texrow, foot_count,
2166                                                false);
2167                         par->SimpleTeXOnePar(buf, bparams, os, texrow, moving_arg);
2168                         par = par->next;
2169                 }
2170         }
2171 #endif
2172
2173         // Make sure that \\par is done with the font of the last
2174         // character if this has another size as the default.
2175         // This is necessary because LaTeX (and LyX on the screen)
2176         // calculates the space between the baselines according
2177         // to this font. (Matthias)
2178         LyXFont font = getFont(bparams, Last() - 1);
2179         if (need_par) {
2180                 if (style.resfont.size() != font.size()) {
2181                         os << '\\'
2182                            << font.latexSize()
2183                            << ' ';
2184                 }
2185                 os << "\\par}";
2186         } else if (textclasslist.Style(bparams.textclass,
2187                                        GetLayout()).isCommand()) {
2188                 if (style.resfont.size() != font.size()) {
2189                         os << '\\'
2190                            << font.latexSize()
2191                            << ' ';
2192                 }
2193                 os << '}';
2194         } else if (style.resfont.size() != font.size()){
2195                 os << "{\\" << font.latexSize() << " \\par}";
2196         }
2197
2198         if (language != doc_language &&
2199             (!par
2200              || (footnoteflag != NO_FOOTNOTE && par->footnoteflag != footnoteflag)
2201              || par->getParLanguage(bparams) != language)) {
2202                 os << endl 
2203                    << subst(lyxrc.language_command_end, "$$lang",
2204                             doc_language->lang());
2205         }
2206         
2207         switch (style.latextype) {
2208         case LATEX_ITEM_ENVIRONMENT:
2209         case LATEX_LIST_ENVIRONMENT:
2210                 if (par && (depth < par->depth)) {
2211                         os << '\n';
2212                         texrow.newline();
2213                 }
2214                 break;
2215         case LATEX_ENVIRONMENT:
2216                 // if its the last paragraph of the current environment
2217                 // skip it otherwise fall through
2218                 if (par
2219                     && (par->layout != layout
2220                         || par->depth != depth
2221                         || par->pextra_type != pextra_type))
2222                         break;
2223         default:
2224                 // we don't need it for the last paragraph!!!
2225                 if (next && !(footnoteflag != LyXParagraph::NO_FOOTNOTE
2226                       && footnotekind != LyXParagraph::FOOTNOTE
2227                       && footnotekind != LyXParagraph::MARGIN
2228                       && (table
2229                           || (par
2230                               && par->table)))) {
2231                         // don't insert this if we would be adding it
2232                         // before or after a table in a float.  This 
2233                         // little trick is needed in order to allow
2234                         // use of tables in \subfigures or \subtables.
2235                         os << '\n';
2236                         texrow.newline();
2237                 }
2238         }
2239         
2240         further_blank_line = false;
2241         if (line_bottom) {
2242                 os << "\\lyxline{\\" << getFont(bparams, Last() - 1).latexSize() << '}';
2243                 further_blank_line = true;
2244         }
2245
2246         if (added_space_bottom.kind() != VSpace::NONE) {
2247                 os << added_space_bottom.asLatexCommand(bparams);
2248                 further_blank_line = true;
2249         }
2250       
2251         if (pagebreak_bottom) {
2252                 os << "\\newpage";
2253                 further_blank_line = true;
2254         }
2255
2256         if (further_blank_line){
2257                 os << '\n';
2258                 texrow.newline();
2259         }
2260
2261         if (!spacing.isDefault()
2262             && (!par || !par->HasSameLayout(this))) {
2263                 os << spacing.writeEnvirEnd() << "\n";
2264                 texrow.newline();
2265         }
2266         
2267         // we don't need it for the last paragraph!!!
2268         if (next && !(footnoteflag != LyXParagraph::NO_FOOTNOTE && par &&
2269               par->footnoteflag == LyXParagraph::NO_FOOTNOTE)) {
2270                 os << '\n';
2271                 texrow.newline();
2272         }
2273
2274         lyxerr[Debug::LATEX] << "TeXOnePar...done " << par << endl;
2275         return par;
2276 }
2277
2278
2279 // This one spits out the text of the paragraph
2280 bool LyXParagraph::SimpleTeXOnePar(Buffer const * buf,
2281                                    BufferParams const & bparams,
2282                                    ostream & os, TexRow & texrow,
2283                                    bool moving_arg)
2284 {
2285         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...     " << this << endl;
2286
2287 #ifndef NEW_TABULAR
2288         if (table)
2289                 return SimpleTeXOneTablePar(buf, bparams, os, texrow);
2290 #endif
2291
2292         bool return_value = false;
2293
2294         LyXLayout const & style =
2295                 textclasslist.Style(bparams.textclass,
2296                                     GetLayout());
2297         LyXFont basefont, last_font;
2298
2299         // Maybe we have to create a optional argument.
2300         size_type main_body;
2301         if (style.labeltype != LABEL_MANUAL)
2302                 main_body = 0;
2303         else
2304                 main_body = BeginningOfMainBody();
2305
2306         if (main_body > 0) {
2307                 os << '[';
2308                 basefont = getFont(bparams, -2); // Get label font
2309         } else {
2310                 basefont = getFont(bparams, -1); // Get layout font
2311         }
2312
2313         int column = 0;
2314
2315         if (main_body >= 0
2316             && !text.size()
2317             && !IsDummy()) {
2318                 if (style.isCommand()) {
2319                         os << '{';
2320                         ++column;
2321                 } else if (align != LYX_ALIGN_LAYOUT) {
2322                         os << '{';
2323                         ++column;
2324                         return_value = true;
2325                 }
2326         }
2327
2328         moving_arg |= style.needprotect;
2329  
2330         // Which font is currently active?
2331         LyXFont running_font(basefont);
2332         // Do we have an open font change?
2333         bool open_font = false;
2334
2335         texrow.start(this, 0);
2336
2337         for (size_type i = 0; i < size(); ++i) {
2338                 ++column;
2339                 // First char in paragraph or after label?
2340                 if (i == main_body && !IsDummy()) {
2341                         if (main_body > 0) {
2342                                 if (open_font) {
2343                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
2344                                         open_font = false;
2345                                 }
2346                                 basefont = getFont(bparams, -1); // Now use the layout font
2347                                 running_font = basefont;
2348                                 os << ']';
2349                                 ++column;
2350                         }
2351                         if (style.isCommand()) {
2352                                 os << '{';
2353                                 ++column;
2354                         } else if (align != LYX_ALIGN_LAYOUT) {
2355                                 os << "{\\par";
2356                                 column += 4;
2357                                 return_value = true;
2358                         }
2359
2360                         if (noindent) {
2361                                 os << "\\noindent ";
2362                                 column += 10;
2363                         }
2364                         switch (align) {
2365                         case LYX_ALIGN_NONE:
2366                         case LYX_ALIGN_BLOCK:
2367                         case LYX_ALIGN_LAYOUT:
2368                         case LYX_ALIGN_SPECIAL:
2369                                 break;
2370                         case LYX_ALIGN_LEFT:
2371                                 if (getParLanguage(bparams)->lang() != "hebrew") {
2372                                         os << "\\raggedright ";
2373                                         column+= 13;
2374                                 } else {
2375                                         os << "\\raggedleft ";
2376                                         column+= 12;
2377                                 }
2378                                 break;
2379                         case LYX_ALIGN_RIGHT:
2380                                 if (getParLanguage(bparams)->lang() != "hebrew") {
2381                                         os << "\\raggedleft ";
2382                                         column+= 12;
2383                                 } else {
2384                                         os << "\\raggedright ";
2385                                         column+= 13;
2386                                 }
2387                                 break;
2388                         case LYX_ALIGN_CENTER:
2389                                 os << "\\centering ";
2390                                 column+= 11;
2391                                 break;
2392                         }        
2393                 }
2394
2395                 int c = GetChar(i);
2396
2397                 // Fully instantiated font
2398                 LyXFont font = getFont(bparams, i);
2399                 LyXParagraph * p = 0;
2400                 if (i == 0 && previous && 
2401                     previous->footnoteflag != LyXParagraph::NO_FOOTNOTE &&
2402                     (p = PreviousBeforeFootnote()) != 0)
2403                         last_font = p->getFont(bparams, p->size()-1);
2404                 else
2405                         last_font = running_font;
2406
2407                 // Spaces at end of font change are simulated to be
2408                 // outside font change, i.e. we write "\textXX{text} "
2409                 // rather than "\textXX{text }". (Asger)
2410                 if (open_font && c == ' ' && i <= size() - 2 
2411                     && !getFont(bparams, i + 1).equalExceptLatex(running_font) 
2412                     && !getFont(bparams, i + 1).equalExceptLatex(font)) {
2413                         font = getFont(bparams, i + 1);
2414                 }
2415                 // We end font definition before blanks
2416                 if (!font.equalExceptLatex(running_font) && open_font) {
2417                         column += running_font.latexWriteEndChanges(os,
2418                                                                     basefont,
2419                                                                     (i == main_body-1) ? basefont : font);
2420                         running_font = basefont;
2421                         open_font = false;
2422                 }
2423
2424                 // Blanks are printed before start of fontswitch
2425                 if (c == ' ') {
2426                         // Do not print the separation of the optional argument
2427                         if (i != main_body - 1) {
2428                                 SimpleTeXBlanks(os, texrow, i,
2429                                                 column, font, style);
2430                         }
2431                 }
2432
2433                 // Do we need to change font?
2434                 if (!font.equalExceptLatex(running_font)
2435                     && i != main_body-1) {
2436                         column += font.latexWriteStartChanges(os, basefont,
2437                                                               last_font);
2438                         running_font = font;
2439                         open_font = true;
2440                 }
2441
2442                 if (c == LyXParagraph::META_NEWLINE) {
2443                         // newlines are handled differently here than
2444                         // the default in SimpleTeXSpecialChars().
2445                         if (!style.newline_allowed
2446                             || font.latex() == LyXFont::ON) {
2447                                 os << '\n';
2448                         } else {
2449                                 if (open_font) {
2450                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
2451                                         open_font = false;
2452                                 }
2453                                 basefont = getFont(bparams, -1);
2454                                 running_font = basefont;
2455                                 if (font.family() == 
2456                                     LyXFont::TYPEWRITER_FAMILY) {
2457                                         os << "~";
2458                                 }
2459                                 if (moving_arg)
2460                                         os << "\\protect ";
2461                                 os << "\\\\\n";
2462                         }
2463                         texrow.newline();
2464                         texrow.start(this, i + 1);
2465                         column = 0;
2466                 } else {
2467                         SimpleTeXSpecialChars(buf, bparams,
2468                                               os, texrow, moving_arg,
2469                                               font, running_font, basefont,
2470                                               open_font, style, i, column, c);
2471                 }
2472         }
2473
2474         // If we have an open font definition, we have to close it
2475         if (open_font) {
2476                 LyXParagraph * p = 0;
2477                 if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE
2478                     && (p =  NextAfterFootnote()) != 0)
2479                         running_font.latexWriteEndChanges(os, basefont,
2480                                                           p->getFont(bparams, 0));
2481                 else
2482                         running_font.latexWriteEndChanges(os, basefont, basefont);
2483         }
2484
2485         // Needed if there is an optional argument but no contents.
2486         if (main_body > 0 && main_body == size()) {
2487                 os << "]~";
2488                 return_value = false;
2489         }
2490
2491         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...done " << this << endl;
2492         return return_value;
2493 }
2494
2495
2496 // This one spits out the text of a table paragraph
2497 bool LyXParagraph::SimpleTeXOneTablePar(Buffer const * buf,
2498                                         BufferParams const & bparams,
2499                                         ostream & os, TexRow & texrow)
2500 {
2501         lyxerr[Debug::LATEX] << "SimpleTeXOneTablePar...     " << this << endl;
2502    
2503         bool return_value = false;
2504
2505         LyXLayout const & style = 
2506                 textclasslist.Style(bparams.textclass, GetLayout());
2507  
2508         int column = 0;
2509         if (!IsDummy()) { // it is dummy if it is in a float!!!
2510                 if (style.isCommand()) {
2511                         os << '{';
2512                         ++column;
2513                 } else if (align != LYX_ALIGN_LAYOUT) {
2514                         os << '{';
2515                         ++column;
2516                         return_value = true;
2517                 }
2518                 if (noindent) {
2519                         os << "\\noindent ";
2520                         column += 10;
2521                 }
2522                 switch (align) {
2523                 case LYX_ALIGN_NONE:
2524                 case LYX_ALIGN_BLOCK:
2525                 case LYX_ALIGN_LAYOUT:
2526                 case LYX_ALIGN_SPECIAL: break;
2527                 case LYX_ALIGN_LEFT:
2528                         os << "\\raggedright ";
2529                         column+= 13;
2530                         break;
2531                 case LYX_ALIGN_RIGHT:
2532                         os << "\\raggedleft ";
2533                         column+= 12;
2534                         break;
2535                 case LYX_ALIGN_CENTER:
2536                         os << "\\centering ";
2537                         column+= 11;
2538                         break;
2539                 }
2540         }
2541
2542         LyXFont basefont = getFont(bparams, -1); // Get layout font
2543         // Which font is currently active?
2544         LyXFont running_font = basefont;
2545         LyXFont last_font;
2546         // Do we have an open font change?
2547         bool open_font = false;
2548         int current_cell_number = -1;
2549         int tmp = table->TexEndOfCell(os, current_cell_number);
2550         for (; tmp > 0 ; --tmp)
2551                 texrow.newline();
2552         
2553         texrow.start(this, 0);
2554
2555         bool is_rtl = getParLanguage(bparams)->RightToLeft();
2556         bool first_in_cell = true;
2557                 
2558         for (size_type i = 0; i < size(); ++i) {
2559                 char c = GetChar(i);
2560                 if (table->IsContRow(current_cell_number + 1)) {
2561                         if (c == LyXParagraph::META_NEWLINE)
2562                                 ++current_cell_number;
2563                         continue;
2564                 }
2565                 ++column;
2566
2567                 if (first_in_cell && is_rtl) {
2568                         os << "\\R{";
2569                         column += 3;
2570                         first_in_cell = false;
2571                 }
2572
2573                 // Fully instantiated font
2574                 LyXFont font = getFont(bparams, i);
2575                 last_font = running_font;
2576
2577                 // Spaces at end of font change are simulated to be
2578                 // outside font change.
2579                 // i.e. we write "\textXX{text} " rather than
2580                 // "\textXX{text }". (Asger)
2581                 if (open_font && c == ' ' && i <= size() - 2
2582                     && getFont(bparams, i + 1) != running_font
2583                     && getFont(bparams, i + 1) != font) {
2584                         font = getFont(bparams, i + 1);
2585                 }
2586
2587                 // We end font definition before blanks
2588                 if (font != running_font && open_font) {
2589                         column += running_font.latexWriteEndChanges(os,
2590                                                                     basefont,
2591                                                                     font);
2592                         running_font = basefont;
2593                         open_font = false;
2594                 }
2595                 // Blanks are printed before start of fontswitch
2596                 if (c == ' '){
2597                         SimpleTeXBlanks(os, texrow, i, column, font, style);
2598                 }
2599                 // Do we need to change font?
2600                 if (font != running_font) {
2601                         column += font.latexWriteStartChanges(os, basefont,
2602                                                               last_font);
2603                         running_font = font;
2604                         open_font = true;
2605                 }
2606                 // Do we need to turn on LaTeX mode?
2607                 if (font.latex() != running_font.latex()) {
2608                         if (font.latex() == LyXFont::ON
2609                             && style.needprotect) {
2610                                 os << "\\protect ";
2611                                 column += 9;
2612                         }
2613                 }
2614                 if (c == LyXParagraph::META_NEWLINE) {
2615                         // special case for inside a table
2616                         // different from default case in
2617                         // SimpleTeXSpecialChars()
2618                         if (open_font) {
2619                                 column += running_font
2620                                         .latexWriteEndChanges(os, basefont,
2621                                                               basefont);
2622                                 open_font = false;
2623                         }
2624                         basefont = getFont(bparams, -1);
2625                         running_font = basefont;
2626                         ++current_cell_number;
2627                         if (table->CellHasContRow(current_cell_number) >= 0) {
2628                                 TeXContTableRows(buf, bparams, os, i + 1,
2629                                                  current_cell_number,
2630                                                  column, texrow);
2631                         }
2632                         if (is_rtl && !first_in_cell) {
2633                                 os << "}";
2634                                 first_in_cell = true;
2635                         }
2636
2637                         // if this cell follow only ContRows till end don't
2638                         // put the EndOfCell because it is put after the
2639                         // for(...)
2640                         if (table->ShouldBeVeryLastCell(current_cell_number)) {
2641                                 --current_cell_number;
2642                                 break;
2643                         }
2644                         int tmp = table->TexEndOfCell(os,
2645                                                       current_cell_number);
2646                         if (tmp > 0) {
2647                                 column = 0;
2648                         } else if (tmp < 0) {
2649                                 tmp = -tmp;
2650                         }
2651                         for (; tmp--;) {
2652                                 texrow.newline();
2653                         }
2654                         texrow.start(this, i + 1);
2655                 } else {
2656                         SimpleTeXSpecialChars(buf, bparams,
2657                                               os, texrow, false,
2658                                               font, running_font, basefont,
2659                                               open_font, style, i, column, c);
2660                 }
2661         }
2662
2663         // If we have an open font definition, we have to close it
2664         if (open_font) {
2665                 running_font.latexWriteEndChanges(os, basefont, basefont);
2666         }
2667         ++current_cell_number;
2668         if (is_rtl && !first_in_cell)
2669                 os << "}";
2670         tmp = table->TexEndOfCell(os, current_cell_number);
2671         for (; tmp > 0; --tmp)
2672                 texrow.newline();
2673         lyxerr[Debug::LATEX] << "SimpleTeXOneTablePar...done " << this << endl;
2674         return return_value;
2675 }
2676
2677
2678 // This one spits out the text off ContRows in tables
2679 bool LyXParagraph::TeXContTableRows(Buffer const * buf,
2680                                     BufferParams const & bparams,
2681                                     ostream & os,
2682                                     LyXParagraph::size_type i,
2683                                     int current_cell_number,
2684                                     int & column, TexRow & texrow)
2685 {
2686         lyxerr[Debug::LATEX] << "TeXContTableRows...     " << this << endl;
2687         if (!table)
2688                 return false;
2689     
2690         bool return_value = false;
2691         LyXLayout const & style =
2692                 textclasslist.Style(bparams.textclass,
2693                                     GetLayout());
2694         LyXFont basefont = getFont(bparams, -1); // Get layout font
2695         LyXFont last_font;
2696         // Which font is currently active?
2697         LyXFont running_font = basefont;
2698         // Do we have an open font change?
2699         bool open_font = false;
2700
2701         size_type lastpos = i;
2702         int cell = table->CellHasContRow(current_cell_number);
2703         ++current_cell_number;
2704         char c;
2705         while(cell >= 0) {
2706                 // first find the right position
2707                 i = lastpos;
2708                 for (; (i < size()) && (current_cell_number<cell); ++i) {
2709                         c = GetChar(i);
2710                         if (c == LyXParagraph::META_NEWLINE)
2711                                 ++current_cell_number;
2712                 }
2713                 lastpos = i;
2714                 c = GetChar(i);
2715                 if (table->Linebreaks(table->FirstVirtualCell(cell))) {
2716                         os << " \\\\\n";
2717                         texrow.newline();
2718                         column = 0;
2719                 } else if ((c != ' ') && (c != LyXParagraph::META_NEWLINE)) {
2720                         os << ' ';
2721                 }
2722
2723                 for (; i < size()
2724                              && (c = GetChar(i)) != LyXParagraph::META_NEWLINE;
2725                      ++i) {
2726                         ++column;
2727
2728                         // Fully instantiated font
2729                         LyXFont font = getFont(bparams, i);
2730                         last_font = running_font;
2731
2732                         // Spaces at end of font change are simulated to
2733                         // be outside font change. i.e. we write
2734                         // "\textXX{text} " rather than "\textXX{text }".
2735                         // (Asger)
2736                         if (open_font && c == ' ' && i <= size() - 2 
2737                             && getFont(bparams, i + 1) != running_font
2738                             && getFont(bparams, i + 1) != font) {
2739                                 font = getFont(bparams, i + 1);
2740                         }
2741
2742                         // We end font definition before blanks
2743                         if (font != running_font && open_font) {
2744                                 column += running_font.latexWriteEndChanges(os, basefont, font);
2745                                 running_font = basefont;
2746                                 open_font = false;
2747                         }
2748                         // Blanks are printed before start of fontswitch
2749                         if (c == ' '){
2750                                 SimpleTeXBlanks(os, texrow, i,
2751                                                 column, font, style);
2752                         }
2753                         // Do we need to change font?
2754                         if (font != running_font) {
2755                                 column +=
2756                                         font.latexWriteStartChanges(os,
2757                                                                     basefont,
2758                                                                     last_font);
2759                                 running_font = font;
2760                                 open_font = true;
2761                         }
2762                         // Do we need to turn on LaTeX mode?
2763                         if (font.latex() != running_font.latex()) {
2764                                 if (font.latex() == LyXFont::ON
2765                                     && style.needprotect) {
2766                                         os << "\\protect ";
2767                                         column += 9;
2768                                 }
2769                         }
2770                         SimpleTeXSpecialChars(buf, bparams,
2771                                               os, texrow, false, font,
2772                                               running_font, basefont,
2773                                               open_font, style, i, column, c);
2774                 }
2775                 // If we have an open font definition, we have to close it
2776                 if (open_font) {
2777                         running_font.latexWriteEndChanges(os, basefont,
2778                                                           basefont);
2779                         open_font = false;
2780                 }
2781                 basefont = getFont(bparams, -1);
2782                 running_font = basefont;
2783                 cell = table->CellHasContRow(current_cell_number);
2784         }
2785         lyxerr[Debug::LATEX] << "TeXContTableRows...done " << this << endl;
2786         return return_value;
2787 }
2788
2789
2790 bool LyXParagraph::linuxDocConvertChar(char c, string & sgml_string)
2791 {
2792         bool retval = false;
2793         switch (c) {
2794         case LyXParagraph::META_HFILL:
2795                 sgml_string.erase();
2796                 break;
2797         case LyXParagraph::META_NEWLINE:
2798                 sgml_string = '\n';
2799                 break;
2800         case '&': 
2801                 sgml_string = "&amp;";
2802                 break;
2803         case '<': 
2804                 sgml_string = "&lt;"; 
2805                 break;
2806         case '>':
2807                 sgml_string = "&gt;"; 
2808                 break;
2809         case '$': 
2810                 sgml_string = "&dollar;"; 
2811                 break;
2812         case '#': 
2813                 sgml_string = "&num;";
2814                 break;
2815         case '%': 
2816                 sgml_string = "&percnt;";
2817                 break;
2818         case '[': 
2819                 sgml_string = "&lsqb;";
2820                 break;
2821         case ']': 
2822                 sgml_string = "&rsqb;";
2823                 break;
2824         case '{': 
2825                 sgml_string = "&lcub;";
2826                 break;
2827         case '}': 
2828                 sgml_string = "&rcub;";
2829                 break;
2830         case '~': 
2831                 sgml_string = "&tilde;";
2832                 break;
2833         case '"': 
2834                 sgml_string = "&quot;";
2835                 break;
2836         case '\\': 
2837                 sgml_string = "&bsol;";
2838                 break;
2839         case ' ':
2840                 retval = true;
2841                 sgml_string = ' ';
2842                 break;
2843         case '\0': // Ignore :-)
2844                 sgml_string.erase();
2845                 break;
2846         default:
2847                 sgml_string = c;
2848                 break;
2849         }
2850         return retval;
2851 }
2852
2853
2854 void LyXParagraph::SimpleDocBookOneTablePar(Buffer const * buffer, 
2855                                             ostream & os, string & extra,
2856                                             int & desc_on, int depth) 
2857 {
2858         BufferParams const & bparams = buffer->params;
2859         if (!table) return;
2860         lyxerr[Debug::LATEX] << "SimpleDocbookOneTablePar... " << this << endl;
2861         int column = 0;
2862         LyXFont font1, font2;
2863         char c;
2864         Inset * inset;
2865         size_type main_body;
2866         bool emph_flag = false;
2867         
2868         LyXLayout const & style =
2869                 textclasslist.Style(bparams.textclass,
2870                                     GetLayout());
2871         
2872         if (style.labeltype != LABEL_MANUAL)
2873                 main_body = 0;
2874         else
2875                 main_body = BeginningOfMainBody();
2876         
2877         // Gets paragraph main font.
2878         if (main_body > 0)
2879                 font1 = style.labelfont;
2880         else
2881                 font1 = style.font;
2882         
2883         int char_line_count = depth;
2884         os << newlineAndDepth(depth);
2885         if (footnoteflag == LyXParagraph::NO_FOOTNOTE) {
2886                 os << "<INFORMALTABLE>"
2887                    << newlineAndDepth(++depth);
2888         }
2889         int current_cell_number = -1;
2890         int tmp = table->DocBookEndOfCell(os, current_cell_number, depth);
2891         
2892         // Parsing main loop.
2893         for (size_type i = 0; i < size(); ++i) {
2894                 c = GetChar(i);
2895                 if (table->IsContRow(current_cell_number+1)) {
2896                         if (c == LyXParagraph::META_NEWLINE)
2897                                 ++current_cell_number;
2898                         continue;
2899                 }
2900                 ++column;
2901                 
2902                 // Fully instantiated font
2903                 font2 = getFont(bparams, i);
2904                 
2905                 // Handle <emphasis> tag.
2906                 if (font1.emph() != font2.emph() && i) {
2907                         if (font2.emph() == LyXFont::ON) {
2908                                 os << "<emphasis>";
2909                                 emph_flag= true;
2910                         } else if (emph_flag) {
2911                                 os << "</emphasis>";
2912                                 emph_flag= false;
2913                         }
2914                 }
2915                 if (c == LyXParagraph::META_NEWLINE) {
2916                         // We have only to control for emphasis open here!
2917                         if (emph_flag) {
2918                                 os << "</emphasis>";
2919                                 emph_flag= false;
2920                         }
2921                         font1 = font2 = getFont(bparams, -1);
2922                         ++current_cell_number;
2923                         if (table->CellHasContRow(current_cell_number) >= 0) {
2924                                 DocBookContTableRows(buffer,
2925                                                      os, extra, desc_on, i + 1,
2926                                                      current_cell_number,
2927                                                      column);
2928                         }
2929                         // if this cell follow only ContRows till end don't
2930                         // put the EndOfCell because it is put after the
2931                         // for(...)
2932                         if (table->ShouldBeVeryLastCell(current_cell_number)) {
2933                                 --current_cell_number;
2934                                 break;
2935                         }
2936                         tmp = table->DocBookEndOfCell(os,
2937                                                       current_cell_number,
2938                                                       depth);
2939                         
2940                         if (tmp > 0)
2941                                 column = 0;
2942                 } else if (c == LyXParagraph::META_INSET) {
2943                         inset = GetInset(i);
2944 #ifdef HAVE_SSTREAM
2945                         std::ostringstream ost;
2946                         inset->DocBook(buffer, ost);
2947                         string tmp_out = ost.str().c_str();
2948 #else
2949                         ostrstream ost;
2950                         inset->DocBook(buffer, ost);
2951                         ost << '\0';
2952                         char * ctmp = ost.str();
2953                         string tmp_out(ctmp);
2954                         delete [] ctmp;
2955 #endif
2956                         //
2957                         // This code needs some explanation:
2958                         // Two insets are treated specially
2959                         //   label if it is the first element in a
2960                         //   command paragraph
2961                         //         desc_on == 3
2962                         //   graphics inside tables or figure floats
2963                         //   can't go on
2964                         //   title (the equivalente in latex for this
2965                         //   case is caption
2966                         //   and title should come first
2967                         //         desc_on == 4
2968                         //
2969                         if(desc_on != 3 || i != 0) {
2970                                 if(tmp_out[0] == '@') {
2971                                         if(desc_on == 4)
2972                                                 extra += frontStrip(tmp_out,
2973                                                                     '@');
2974                                         else
2975                                                 os << frontStrip(tmp_out,
2976                                                                  '@');
2977                                 } else
2978                                         os << tmp_out;
2979                         }
2980                 } else if (font2.latex() == LyXFont::ON) {
2981                         // "TeX"-Mode on == > SGML-Mode on.
2982                         if (c != '\0')
2983                                 os << c;
2984                         ++char_line_count;
2985                 } else {
2986                         string sgml_string;
2987                         if (linuxDocConvertChar(c, sgml_string) 
2988                             && !style.free_spacing) {
2989                                 // in freespacing mode, spaces are
2990                                 // non-breaking characters
2991                                 // char is ' '
2992                                 if (desc_on == 1) {
2993                                         ++char_line_count;
2994                                         os << '\n'
2995                                            << "</term><listitem><para>";
2996                                         desc_on = 2;
2997                                 } else  {
2998                                         os << c;
2999                                 }
3000                         } else {
3001                                 os << sgml_string;
3002                         }
3003                 }
3004                 font1 = font2;
3005         }
3006         
3007         // Needed if there is an optional argument but no contents.
3008         if (main_body > 0 && main_body == size()) {
3009                 font1 = style.font;
3010         }
3011
3012         if (emph_flag) {
3013                 os << "</emphasis>";
3014         }
3015         
3016         ++current_cell_number;
3017         tmp = table->DocBookEndOfCell(os, current_cell_number, depth);
3018         // Resets description flag correctly.
3019         switch(desc_on){
3020         case 1:
3021                 // <term> not closed...
3022                 os << "</term>";
3023                 break;
3024         }
3025         if (footnoteflag == LyXParagraph::NO_FOOTNOTE)
3026                 os << "</INFORMALTABLE>";
3027         os << '\n';
3028         lyxerr[Debug::LATEX] << "SimpleDocbookOneTablePar...done "
3029                              << this << endl;
3030 }
3031
3032
3033 void LyXParagraph::DocBookContTableRows(Buffer const * buffer,
3034                                         ostream & os, string & extra,
3035                                         int & desc_on,
3036                                         LyXParagraph::size_type i,
3037                                         int current_cell_number, int &column) 
3038
3039 {
3040         if (!table) return;
3041
3042         BufferParams const & bparams = buffer->params;
3043         
3044         lyxerr[Debug::LATEX] << "DocBookContTableRows... " << this << endl;
3045
3046         LyXFont font2;
3047         char c;
3048         Inset * inset;
3049         //string emph = "emphasis";
3050         bool emph_flag = false;
3051         int char_line_count = 0;
3052         
3053         LyXLayout const & style =
3054                 textclasslist.Style(bparams.textclass,
3055                                     GetLayout());
3056         
3057         size_type main_body;
3058         if (style.labeltype != LABEL_MANUAL)
3059                 main_body = 0;
3060         else
3061                 main_body = BeginningOfMainBody();
3062         
3063         // Gets paragraph main font.
3064         LyXFont font1;
3065         if (main_body > 0)
3066                 font1 = style.labelfont;
3067         else
3068                 font1 = style.font;
3069         
3070         size_type lastpos = i;
3071         int cell = table->CellHasContRow(current_cell_number);
3072         ++current_cell_number;
3073         while(cell >= 0) {
3074                 // first find the right position
3075                 i = lastpos;
3076                 for (; i < size() && current_cell_number < cell; ++i) {
3077                         c = GetChar(i);
3078                         if (c == LyXParagraph::META_NEWLINE)
3079                                 ++current_cell_number;
3080                 }
3081                 lastpos = i;
3082                 c = GetChar(i);
3083                 // I don't know how to handle this so I comment it
3084                 // for the moment (Jug)
3085 //             if (table->Linebreaks(table->FirstVirtualCell(cell))) {
3086 //                     file += " \\\\\n";
3087 //                     column = 0;
3088 //             } else
3089                 if ((c != ' ') && (c != LyXParagraph::META_NEWLINE)) {
3090                         os << ' ';
3091                 }
3092
3093                 for (; i < size()
3094                              && (c = GetChar(i)) != LyXParagraph::META_NEWLINE;
3095                      ++i) {
3096                         ++column;
3097                         
3098                         // Fully instantiated font
3099                         font2 = getFont(bparams, i);
3100                         
3101                         // Handle <emphasis> tag.
3102                         if (font1.emph() != font2.emph() && i) {
3103                                 if (font2.emph() == LyXFont::ON) {
3104                                         os << "<emphasis>";
3105                                         emph_flag= true;
3106                                 } else if (emph_flag) {
3107                                         os << "</emphasis>";
3108                                         emph_flag= false;
3109                                 }
3110                         }
3111                         if (c == LyXParagraph::META_INSET) {
3112                                 inset = GetInset(i);
3113 #ifdef HAVE_SSTREAM
3114                                 std::ostringstream ost;
3115                                 inset->DocBook(buffer, ost);
3116                                 string tmp_out = ost.str().c_str();
3117 #else
3118                                 ostrstream ost;
3119                                 inset->DocBook(buffer, ost);
3120                                 ost << '\0';
3121                                 char * ctmp = ost.str();
3122                                 string tmp_out(ctmp);
3123                                 delete [] ctmp;
3124 #endif
3125                                 //
3126                                 // This code needs some explanation:
3127                                 // Two insets are treated specially
3128                                 //   label if it is the first element in a
3129                                 //   command paragraph
3130                                 //       desc_on == 3
3131                                 //   graphics inside tables or figure floats
3132                                 //   can't go on title (the equivalente in
3133                                 //   latex for this case is caption and title
3134                                 //   should come first
3135                                 //       desc_on == 4
3136                                 //
3137                                 if(desc_on != 3 || i != 0) {
3138                                         if(tmp_out[0] == '@') {
3139                                                 if(desc_on == 4)
3140                                                         extra += frontStrip(tmp_out, '@');
3141                                                 else
3142                                                         os << frontStrip(tmp_out, '@');
3143                                         } else
3144                                                 os << tmp_out;
3145                                 }
3146                         } else if (font2.latex() == LyXFont::ON) {
3147                                 // "TeX"-Mode on == > SGML-Mode on.
3148                                 if (c!= '\0')
3149                                         os << c;
3150                                 ++char_line_count;
3151                         } else {
3152                                 string sgml_string;
3153                                 if (linuxDocConvertChar(c, sgml_string) 
3154                                     && !style.free_spacing) {
3155                                         // in freespacing mode, spaces are
3156                                         // non-breaking characters
3157                                         // char is ' '
3158                                         if (desc_on == 1) {
3159                                                 ++char_line_count;
3160                                                 os << '\n'
3161                                                    << "</term><listitem><para>";
3162                                                 desc_on = 2;
3163                                         } else  {
3164                                                 os << c;
3165                                         }
3166                                 } else {
3167                                         os << sgml_string;
3168                                 }
3169                         }
3170                 }
3171                 // we have only to control for emphasis open here!
3172                 if (emph_flag) {
3173                         os << "</emphasis>";
3174                         emph_flag= false;
3175                 }
3176                 font1 = font2 = getFont(bparams, -1);
3177                 cell = table->CellHasContRow(current_cell_number);
3178         }
3179         lyxerr[Debug::LATEX] << "DocBookContTableRows...done " << this << endl;
3180 }
3181
3182
3183 void LyXParagraph::SimpleTeXBlanks(ostream & os, TexRow & texrow,
3184                                    LyXParagraph::size_type const i,
3185                                    int & column, LyXFont const & font,
3186                                    LyXLayout const & style)
3187 {
3188         if (column > tex_code_break_column
3189             && i 
3190             && GetChar(i - 1) != ' '
3191             && (i < size() - 1)
3192             // In LaTeX mode, we don't want to
3193             // break lines since some commands
3194             // do not like this
3195             && ! (font.latex() == LyXFont::ON)
3196             // same in FreeSpacing mode
3197             && !style.free_spacing
3198             // In typewriter mode, we want to avoid 
3199             // ! . ? : at the end of a line
3200             && !(font.family() == LyXFont::TYPEWRITER_FAMILY
3201                  && (GetChar(i-1) == '.'
3202                      || GetChar(i-1) == '?' 
3203                      || GetChar(i-1) == ':'
3204                      || GetChar(i-1) == '!'))) {
3205                 if (tex_code_break_column == 0) {
3206                         // in batchmode we need LaTeX to still
3207                         // see it as a space not as an extra '\n'
3208                         os << " %\n";
3209                 } else {
3210                         os << '\n';
3211                 }
3212                 texrow.newline();
3213                 texrow.start(this, i + 1);
3214                 column = 0;
3215         } else if (font.latex() == LyXFont::OFF) {
3216                 if (style.free_spacing) {
3217                         os << '~';
3218                 } else {
3219                         os << ' ';
3220                 }
3221         }
3222 }
3223
3224
3225 void LyXParagraph::SimpleTeXSpecialChars(Buffer const * buf,
3226                                          BufferParams const & bparams,
3227                                          ostream & os, TexRow & texrow,
3228                                          bool moving_arg,
3229                                          LyXFont & font,
3230                                          LyXFont & running_font,
3231                                          LyXFont & basefont,
3232                                          bool & open_font,
3233                                          LyXLayout const & style,
3234                                          LyXParagraph::size_type & i,
3235                                          int & column, char const c)
3236 {
3237         // Two major modes:  LaTeX or plain
3238         // Handle here those cases common to both modes
3239         // and then split to handle the two modes separately.
3240         switch (c) {
3241         case LyXParagraph::META_INSET: {
3242                 Inset * inset = GetInset(i);
3243                 if (inset) {
3244                         bool close = false;
3245                         int len = os.tellp();
3246                         if ((inset->LyxCode() == Inset::GRAPHICS_CODE
3247                              || inset->LyxCode() == Inset::MATH_CODE
3248                              || inset->LyxCode() == Inset::URL_CODE)
3249                             && running_font.isRightToLeft()) {
3250                                 os << "\\L{";
3251                                 close = true;
3252                         }
3253
3254                         int tmp = inset->Latex(buf, os, moving_arg,
3255                                                style.free_spacing);
3256
3257                         if (close)
3258                                 os << "}";
3259
3260                         if (tmp) {
3261                                 column = 0;
3262                         } else {
3263                                 column += os.tellp() - len;
3264                         }
3265                         for (; tmp--;) {
3266                                 texrow.newline();
3267                         }
3268                 }
3269         }
3270         break;
3271
3272         case LyXParagraph::META_NEWLINE:
3273                 if (open_font) {
3274                         column += running_font.latexWriteEndChanges(os,
3275                                                                     basefont,
3276                                                                     basefont);
3277                         open_font = false;
3278                 }
3279                 basefont = getFont(bparams, -1);
3280                 running_font = basefont;
3281                 break;
3282
3283         case LyXParagraph::META_HFILL: 
3284                 os << "\\hfill{}";
3285                 column += 7;
3286                 break;
3287
3288         default:
3289                 // And now for the special cases within each mode
3290                 // Are we in LaTeX mode?
3291                 if (font.latex() == LyXFont::ON) {
3292                         // at present we only have one option
3293                         // but I'll leave it as a switch statement
3294                         // so its simpler to extend. (ARRae)
3295                         switch (c) {
3296                         default:
3297                                 // make sure that we will not print
3298                                 // error generating chars to the tex
3299                                 // file. This test would not be needed
3300                                 // if it were done in the buffer
3301                                 // itself.
3302                                 if (c != '\0') {
3303                                         os << c;
3304                                 }
3305                                 break;
3306                         }
3307                 } else {
3308                         // Plain mode (i.e. not LaTeX)
3309                         switch (c) {
3310                         case '\\': 
3311                                 os << "\\textbackslash{}";
3312                                 column += 15;
3313                                 break;
3314                 
3315                         case '°': case '±': case '²': case '³':  
3316                         case '×': case '÷': case '¹': case 'ª':
3317                         case 'º': case '¬': case 'µ':
3318                                 if (bparams.inputenc == "latin1") {
3319                                         os << "\\ensuremath{"
3320                                            << c
3321                                            << '}';
3322                                         column += 13;
3323                                 } else {
3324                                         os << c;
3325                                 }
3326                                 break;
3327
3328                         case '|': case '<': case '>':
3329                                 // In T1 encoding, these characters exist
3330                                 if (lyxrc.fontenc == "T1") {
3331                                         os << c;
3332                                         //... but we should avoid ligatures
3333                                         if ((c == '>' || c == '<')
3334                                             && i <= size() - 2
3335                                             && GetChar(i + 1) == c) {
3336                                                 //os << "\\textcompwordmark{}";
3337                                                 // Jean-Marc, have a look at
3338                                                 // this. I think this works
3339                                                 // equally well:
3340                                                 os << "\\,{}";
3341                                                 // Lgb
3342                                                 column += 19;
3343                                         }
3344                                         break;
3345                                 }
3346                                 // Typewriter font also has them
3347                                 if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
3348                                         os << c;
3349                                         break;
3350                                 } 
3351                                 // Otherwise, we use what LaTeX
3352                                 // provides us.
3353                                 switch(c) {
3354                                 case '<':
3355                                         os << "\\textless{}";
3356                                         column += 10;
3357                                         break;
3358                                 case '>':
3359                                         os << "\\textgreater{}";
3360                                         column += 13;
3361                                         break;
3362                                 case '|':
3363                                         os << "\\textbar{}";
3364                                         column += 9;
3365                                         break;
3366                                 }
3367                                 break;
3368
3369                         case '-': // "--" in Typewriter mode -> "-{}-"
3370                                 if (i <= size() - 2
3371                                     && GetChar(i + 1) == '-'
3372                                     && font.family() == LyXFont::TYPEWRITER_FAMILY) {
3373                                         os << "-{}";
3374                                         column += 2;
3375                                 } else {
3376                                         os << '-';
3377                                 }
3378                                 break;
3379
3380                         case '\"': 
3381                                 os << "\\char`\\\"{}";
3382                                 column += 9;
3383                                 break;
3384
3385                         case '£':
3386                                 if (bparams.inputenc == "default") {
3387                                         os << "\\pounds{}";
3388                                         column += 8;
3389                                 } else {
3390                                         os << c;
3391                                 }
3392                                 break;
3393
3394                         case '$': case '&':
3395                         case '%': case '#': case '{':
3396                         case '}': case '_':
3397                                 os << '\\' << c;
3398                                 column += 1;
3399                                 break;
3400
3401                         case '~':
3402                                 os << "\\textasciitilde{}";
3403                                 column += 16;
3404                                 break;
3405
3406                         case '^':
3407                                 os << "\\textasciicircum{}";
3408                                 column += 17;
3409                                 break;
3410
3411                         case '*': case '[': case ']':
3412                                 // avoid being mistaken for optional arguments
3413                                 os << '{' << c << '}';
3414                                 column += 2;
3415                                 break;
3416
3417                         case ' ':
3418                                 // Blanks are printed before font switching.
3419                                 // Sure? I am not! (try nice-latex)
3420                                 // I am sure it's correct. LyX might be smarter
3421                                 // in the future, but for now, nothing wrong is
3422                                 // written. (Asger)
3423                                 break;
3424
3425                         default:
3426                                 /* idea for labels --- begin*/
3427                                 // Check for "LyX"
3428                                 if (c ==  'L'
3429                                     && i <= size() - 3
3430                                     && font.family() != LyXFont::TYPEWRITER_FAMILY
3431                                     && GetChar(i + 1) == 'y'
3432                                     && GetChar(i + 2) == 'X') {
3433                                         os << "\\LyX{}";
3434                                         i += 2;
3435                                         column += 5;
3436                                 }
3437                                 // Check for "TeX"
3438                                 else if (c == 'T'
3439                                          && i <= size() - 3
3440                                          && font.family() != LyXFont::TYPEWRITER_FAMILY
3441                                          && GetChar(i + 1) == 'e'
3442                                          && GetChar(i + 2) == 'X') {
3443                                         os << "\\TeX{}";
3444                                         i += 2;
3445                                         column += 5;
3446                                 }
3447                                 // Check for "LaTeX2e"
3448                                 else if (c == 'L'
3449                                          && i <= size() - 7
3450                                          && font.family() != LyXFont::TYPEWRITER_FAMILY
3451                                          && GetChar(i + 1) == 'a'
3452                                          && GetChar(i + 2) == 'T'
3453                                          && GetChar(i + 3) == 'e'
3454                                          && GetChar(i + 4) == 'X'
3455                                          && GetChar(i + 5) == '2'
3456                                          && GetChar(i + 6) == 'e') {
3457                                         os << "\\LaTeXe{}";
3458                                         i += 6;
3459                                         column += 8;
3460                                 }
3461                                 // Check for "LaTeX"
3462                                 else if (c == 'L'
3463                                          && i <= size() - 5
3464                                          && font.family() != LyXFont::TYPEWRITER_FAMILY
3465                                          && GetChar(i + 1) == 'a'
3466                                          && GetChar(i + 2) == 'T'
3467                                          && GetChar(i + 3) == 'e'
3468                                          && GetChar(i + 4) == 'X') {
3469                                         os << "\\LaTeX{}";
3470                                         i += 4;
3471                                         column += 7;
3472                                         /* idea for labels --- end*/ 
3473                                 } else if (c != '\0') {
3474                                         os << c;
3475                                 }
3476                                 break;
3477                         }
3478                 }
3479         }
3480 }
3481
3482
3483 LyXParagraph * LyXParagraph::TeXDeeper(Buffer const * buf,
3484                                        BufferParams const & bparams,
3485                                        ostream & os, TexRow & texrow,
3486                                        ostream & foot,
3487                                        TexRow & foot_texrow,
3488                                        int & foot_count)
3489 {
3490         lyxerr[Debug::LATEX] << "TeXDeeper...     " << this << endl;
3491         LyXParagraph * par = this;
3492
3493         while (par &&
3494                (par->depth == depth) &&
3495                (par->footnoteflag == footnoteflag)) {
3496                 if (par->IsDummy())
3497                         lyxerr << "ERROR (LyXParagraph::TeXDeeper)" << endl;
3498                 if (textclasslist.Style(bparams.textclass, 
3499                                         par->layout).isEnvironment()
3500                     || par->pextra_type != PEXTRA_NONE) {
3501                         par = par->TeXEnvironment(buf, bparams,
3502                                                   os, texrow,
3503                                                   foot, foot_texrow,
3504                                                   foot_count);
3505                 } else {
3506                         par = par->TeXOnePar(buf, bparams,
3507                                              os, texrow, false,
3508                                              foot, foot_texrow,
3509                                              foot_count);
3510                 }
3511         }
3512         lyxerr[Debug::LATEX] << "TeXDeeper...done " << par << endl;
3513
3514         return par;
3515 }
3516
3517
3518 LyXParagraph * LyXParagraph::TeXEnvironment(Buffer const * buf,
3519                                             BufferParams const & bparams,
3520                                             ostream & os, TexRow & texrow,
3521                                             ostream & foot,
3522                                             TexRow & foot_texrow,
3523                                             int & foot_count)
3524 {
3525         bool eindent_open = false;
3526         bool foot_this_level = false;
3527         // flags when footnotetext should be appended to file.
3528         static bool minipage_open = false;
3529         static int minipage_open_depth = 0;
3530         char par_sep = bparams.paragraph_separation;
3531     
3532         lyxerr[Debug::LATEX] << "TeXEnvironment...     " << this << endl;
3533         if (IsDummy())
3534                 lyxerr << "ERROR (LyXParagraph::TeXEnvironment)" << endl;
3535
3536         LyXLayout const & style =
3537                 textclasslist.Style(bparams.textclass,
3538                                     layout);
3539        
3540         if (pextra_type == PEXTRA_INDENT) {
3541                 if (!pextra_width.empty()) {
3542                         os << "\\begin{LyXParagraphIndent}{"
3543                            << pextra_width << "}\n";
3544                 } else {
3545                         //float ib = atof(pextra_widthp.c_str())/100;
3546                         // string can't handle floats at present (971109)
3547                         // so I'll do a conversion by hand knowing that
3548                         // the limits are 0.0 to 1.0. ARRae.
3549                         os << "\\begin{LyXParagraphIndent}{";
3550                         switch (pextra_widthp.length()) {
3551                         case 3:
3552                                 os << "1.00";
3553                                 break;
3554                         case 2:
3555                                 os << "0."
3556                                    << pextra_widthp;
3557                                 break;
3558                         case 1:
3559                                 os << "0.0"
3560                                    << pextra_widthp;
3561                         }
3562                         os << "\\columnwidth}\n";
3563                 }
3564                 texrow.newline();
3565                 eindent_open = true;
3566         }
3567         if ((pextra_type == PEXTRA_MINIPAGE) && !minipage_open) {
3568                 if (pextra_hfill && Previous() &&
3569                     (Previous()->pextra_type == PEXTRA_MINIPAGE)) {
3570                         os << "\\hfill{}\n";
3571                         texrow.newline();
3572                 }
3573                 if (par_sep == BufferParams::PARSEP_INDENT) {
3574                         os << "{\\setlength\\parindent{0pt}\n";
3575                         texrow.newline();
3576                 }
3577                 os << "\\begin{minipage}";
3578                 switch(pextra_alignment) {
3579                 case MINIPAGE_ALIGN_TOP:
3580                         os << "[t]";
3581                         break;
3582                 case MINIPAGE_ALIGN_MIDDLE:
3583                         os << "[m]";
3584                         break;
3585                 case MINIPAGE_ALIGN_BOTTOM:
3586                         os << "[b]";
3587                         break;
3588                 }
3589                 if (!pextra_width.empty()) {
3590                         os << '{' << pextra_width << "}\n";
3591                 } else {
3592                         //float ib = atof(par->pextra_width.c_str())/100;
3593                         // string can't handle floats at present
3594                         // so I'll do a conversion by hand knowing that
3595                         // the limits are 0.0 to 1.0. ARRae.
3596                         os << '{';
3597                         switch (pextra_widthp.length()) {
3598                         case 3:
3599                                 os << "1.00";
3600                                 break;
3601                         case 2:
3602                                 os << "0."
3603                                    << pextra_widthp;
3604                                 break;
3605                         case 1:
3606                                 os << "0.0"
3607                                    << pextra_widthp;
3608                         }
3609                         os << "\\columnwidth}\n";
3610                 }
3611                 texrow.newline();
3612                 if (par_sep == BufferParams::PARSEP_INDENT) {
3613                         os << "\\setlength\\parindent{\\LyXMinipageIndent}\n";
3614                         texrow.newline();
3615                 }
3616                 minipage_open = true;
3617                 minipage_open_depth = depth;
3618         }
3619
3620 #ifdef WITH_WARNINGS
3621 #warning Define FANCY_FOOTNOTE_CODE to re-enable Allan footnote code
3622         //I disabled it because it breaks when lists span on several
3623         //pages (JMarc)
3624 #endif
3625         if (style.isEnvironment()){
3626                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
3627 #ifdef FANCY_FOOTNOTE_CODE
3628                         if (foot_count < 0) {
3629                                 // flag that footnote[mark][text] should be
3630                                 // used for any footnotes from now on
3631                                 foot_count = 0;
3632                                 foot_this_level = true;
3633                         }
3634 #endif
3635                         os << "\\begin{" << style.latexname() << "}{"
3636                            << labelwidthstring << "}\n";
3637                 } else if (style.labeltype == LABEL_BIBLIO) {
3638                         // ale970405
3639                         os << "\\begin{" << style.latexname() << "}{"
3640                            <<  bibitemWidest(current_view->painter())
3641                            << "}\n";
3642                 } else if (style.latextype == LATEX_ITEM_ENVIRONMENT) {
3643 #ifdef FANCY_FOOTNOTE_CODE
3644                         if (foot_count < 0) {
3645                                 // flag that footnote[mark][text] should be
3646                                 // used for any footnotes from now on
3647                                 foot_count = 0;
3648                                 foot_this_level = true;
3649                         }
3650 #endif
3651                         os << "\\begin{" << style.latexname() << '}'
3652                            << style.latexparam() << '\n';
3653                 } else 
3654                         os << "\\begin{" << style.latexname() << '}'
3655                            << style.latexparam() << '\n';
3656                 texrow.newline();
3657         }
3658         LyXParagraph * par = this;
3659         do {
3660                 par = par->TeXOnePar(buf, bparams,
3661                                      os, texrow, false,
3662                                      foot, foot_texrow, foot_count);
3663
3664                 if (minipage_open && par && !style.isEnvironment() &&
3665                     (par->pextra_type == PEXTRA_MINIPAGE) &&
3666                     par->pextra_start_minipage) {
3667                         os << "\\end{minipage}\n";
3668                         texrow.newline();
3669                         if (par_sep == BufferParams::PARSEP_INDENT) {
3670                                 os << "}\n";
3671                                 texrow.newline();
3672                         }
3673                         minipage_open = false;
3674                 }
3675                 if (par && par->depth > depth) {
3676                         if (textclasslist.Style(bparams.textclass,
3677                                                 par->layout).isParagraph()
3678                             && !par->table
3679                             // Thinko!
3680                             // How to handle this? (Lgb)
3681                             //&& !suffixIs(os, "\n\n")
3682                                 ) {
3683                                 // There should be at least one '\n' already
3684                                 // but we need there to be two for Standard 
3685                                 // paragraphs that are depth-increment'ed to be
3686                                 // output correctly.  However, tables can
3687                                 // also be paragraphs so don't adjust them.
3688                                 // ARRae
3689                                 // Thinkee:
3690                                 // Will it ever harm to have one '\n' too
3691                                 // many? i.e. that we sometimes will have
3692                                 // three in a row. (Lgb)
3693                                 os << '\n';
3694                                 texrow.newline();
3695                         }
3696                         par = par->TeXDeeper(buf, bparams, os, texrow,
3697                                              foot, foot_texrow, foot_count);
3698                 }
3699                 if (par && par->layout == layout && par->depth == depth &&
3700                     (par->pextra_type == PEXTRA_MINIPAGE) && !minipage_open) {
3701                         if (par->pextra_hfill && par->Previous() &&
3702                             (par->Previous()->pextra_type == PEXTRA_MINIPAGE)){
3703                                 os << "\\hfill{}\n";
3704                                 texrow.newline();
3705                         }
3706                         if (par_sep == BufferParams::PARSEP_INDENT) {
3707                                 os << "{\\setlength\\parindent{0pt}\n";
3708                                 texrow.newline();
3709                         }
3710                         os << "\\begin{minipage}";
3711                         switch(par->pextra_alignment) {
3712                         case MINIPAGE_ALIGN_TOP:
3713                                 os << "[t]";
3714                                 break;
3715                         case MINIPAGE_ALIGN_MIDDLE:
3716                                 os << "[m]";
3717                                 break;
3718                         case MINIPAGE_ALIGN_BOTTOM:
3719                                 os << "[b]";
3720                                 break;
3721                         }
3722                         if (!par->pextra_width.empty()) {
3723                                 os << '{' << par->pextra_width << "}\n";
3724                         } else {
3725                                 //float ib = atof(par->pextra_widthp.c_str())/100;
3726                                 // string can't handle floats at present
3727                                 // so I'll do a conversion by hand knowing that
3728                                 // the limits are 0.0 to 1.0. ARRae.
3729                                 os << '{';
3730                                 switch (par->pextra_widthp.length()) {
3731                                 case 3:
3732                                         os << "1.00";
3733                                         break;
3734                                 case 2:
3735                                         os << "0." << par->pextra_widthp;
3736                                         break;
3737                                 case 1:
3738                                         os << "0.0" << par->pextra_widthp;
3739                                 }
3740                                 os << "\\columnwidth}\n";
3741                         }
3742                         texrow.newline();
3743                         if (par_sep == BufferParams::PARSEP_INDENT) {
3744                                 os << "\\setlength\\parindent{\\LyXMinipageIndent}\n";
3745                                 texrow.newline();
3746                         }
3747                         minipage_open = true;
3748                         minipage_open_depth = par->depth;
3749                 }
3750         } while (par
3751                  && par->layout == layout
3752                  && par->depth == depth
3753                  && par->pextra_type == pextra_type
3754                  && par->footnoteflag == footnoteflag);
3755  
3756         if (style.isEnvironment()) {
3757                 os << "\\end{" << style.latexname() << '}';
3758                 // maybe this should go after the minipage closes?
3759                 if (foot_this_level) {
3760                         if (foot_count >= 1) {
3761                                 if (foot_count > 1) {
3762                                         os << "\\addtocounter{footnote}{-"
3763                                            << foot_count - 1
3764                                            << '}';
3765                                 }
3766                                 os << foot;
3767                                 texrow += foot_texrow;
3768                                 foot.clear();
3769                                 foot_texrow.reset();
3770                                 foot_count = 0;
3771                         }
3772                 }
3773         }
3774         if (minipage_open && (minipage_open_depth == depth) &&
3775             (!par || par->pextra_start_minipage ||
3776              par->pextra_type != PEXTRA_MINIPAGE)) {
3777                 os << "\\end{minipage}\n";
3778                 texrow.newline();
3779                 if (par_sep == BufferParams::PARSEP_INDENT) {
3780                         os << "}\n";
3781                         texrow.newline();
3782                 }
3783                 if (par && par->pextra_type != PEXTRA_MINIPAGE) {
3784                         os << "\\medskip\n\n";
3785                         texrow.newline();
3786                         texrow.newline();
3787                 }
3788                 minipage_open = false;
3789         }
3790         if (eindent_open) {
3791                 os << "\\end{LyXParagraphIndent}\n";
3792                 texrow.newline();
3793         }
3794         if (!(par && (par->pextra_type == PEXTRA_MINIPAGE) 
3795               && par->pextra_hfill)) {
3796                 os << '\n';
3797                 texrow.newline();
3798         }
3799         lyxerr[Debug::LATEX] << "TeXEnvironment...done " << par << endl;
3800         return par;  // ale970302
3801 }
3802
3803
3804 #ifndef NEW_INSETS
3805 LyXParagraph * LyXParagraph::TeXFootnote(Buffer const * buf,
3806                                          BufferParams const & bparams,
3807                                          ostream & os, TexRow & texrow,
3808                                          ostream & foot, TexRow & foot_texrow,
3809                                          int & foot_count,
3810                                          bool parent_is_rtl)
3811 {
3812         lyxerr[Debug::LATEX] << "TeXFootnote...  " << this << endl;
3813         if (footnoteflag == LyXParagraph::NO_FOOTNOTE)
3814                 lyxerr << "ERROR (LyXParagraph::TeXFootnote): "
3815                         "No footnote!" << endl;
3816
3817         LyXParagraph * par = this;
3818         LyXLayout const & style =
3819                 textclasslist.Style(bparams.textclass, 
3820                                     previous->GetLayout());
3821         
3822         if (style.needprotect && footnotekind != LyXParagraph::FOOTNOTE){
3823                 lyxerr << "ERROR (LyXParagraph::TeXFootnote): "
3824                         "Float other than footnote in command"
3825                         " with moving argument is illegal" << endl;
3826         }
3827
3828         if (footnotekind != LyXParagraph::FOOTNOTE
3829             && footnotekind != LyXParagraph::MARGIN
3830             && os.tellp()
3831             // Thinko
3832             // How to solve this?
3833             //&& !suffixIs(file, '\n')
3834                 ) {
3835                 // we need to ensure that real floats like tables and figures
3836                 // have their \begin{} on a new line otherwise we can get
3837                 // incorrect results when using the endfloat.sty package
3838                 // especially if two floats follow one another.  ARRae 981022
3839                 // NOTE: if the file is length 0 it must have just been
3840                 //       written out so we assume it ended with a '\n'
3841                 // Thinkee:
3842                 // As far as I can see there is never any harm in writing
3843                 // a '\n' too much. Please tell me if I am wrong. (Lgb)
3844                 os << '\n';
3845                 texrow.newline();
3846         }
3847
3848         bool moving_arg = false;
3849         bool need_closing = false;
3850         bool is_rtl = isRightToLeftPar(bparams);
3851
3852         if (is_rtl != parent_is_rtl) {
3853                 if (is_rtl)
3854                         os << "\\R{";
3855                 else
3856                         os << "\\L{";
3857                 need_closing = true;
3858         }
3859         
3860         //BufferParams * params = &current_view->buffer()->params;
3861         bool footer_in_body = true;
3862         switch (footnotekind) {
3863         case LyXParagraph::FOOTNOTE:
3864                 if (style.intitle) {
3865                         os << "\\thanks{\n";
3866                         footer_in_body = false;
3867                         moving_arg = true;
3868                 } else {
3869                         if (foot_count == -1) {
3870                                 // we're at depth 0 so we can use:
3871                                 os << "\\footnote{%\n";
3872                                 footer_in_body = false;
3873                         } else {
3874                                 os << "\\footnotemark{}%\n";
3875                                 if (foot_count) {
3876                                         // we only need this when there are
3877                                         // multiple footnotes
3878                                         os << "\\stepcounter{footnote}";
3879                                 }
3880                                 os << "\\footnotetext{%\n";
3881                                 foot_texrow.start(this, 0);
3882                                 foot_texrow.newline();
3883                                 ++foot_count;
3884                         }
3885                 }
3886                 break;
3887         case LyXParagraph::MARGIN:
3888                 os << "\\marginpar{\n";
3889                 break;
3890         case LyXParagraph::FIG:
3891                 if (pextra_type == PEXTRA_FLOATFLT
3892                     && (!pextra_width.empty()
3893                         || !pextra_widthp.empty())) {
3894                         if (!pextra_width.empty())
3895                                 os << "\\begin{floatingfigure}{"
3896                                    << pextra_width << "}\n";
3897                         else
3898                                 os << "\\begin{floatingfigure}{"
3899                                    << atoi(pextra_widthp.c_str())/100.0
3900                                    << "\\textwidth}\n";
3901                 } else {
3902                         os << "\\begin{figure}";
3903                         if (!bparams.float_placement.empty()) { 
3904                                 os << '[' << bparams.float_placement << "]\n";
3905                         } else {
3906                                 os << '\n';
3907                         }
3908                 }
3909                 break;
3910         case LyXParagraph::TAB:
3911                 os << "\\begin{table}";
3912                 if (!bparams.float_placement.empty()) { 
3913                         os << '[' << bparams.float_placement << "]\n";
3914                 } else {
3915                         os << '\n';
3916                 }
3917                 break;
3918         case LyXParagraph::WIDE_FIG:
3919                 os << "\\begin{figure*}";
3920                 if (!bparams.float_placement.empty()) { 
3921                         os << '[' << bparams.float_placement << "]\n";
3922                 } else {
3923                         os << '\n';
3924                 }
3925                 break;
3926         case LyXParagraph::WIDE_TAB:
3927                 os << "\\begin{table*}";
3928                 if (!bparams.float_placement.empty()) { 
3929                         os << '[' << bparams.float_placement << "]\n";
3930                 } else {
3931                         os << '\n';
3932                 }
3933                 break;
3934         case LyXParagraph::ALGORITHM:
3935                 os << "\\begin{algorithm}\n";
3936                 break;
3937         }
3938         texrow.newline();
3939    
3940         if (footnotekind != LyXParagraph::FOOTNOTE
3941             || !footer_in_body) {
3942                 // Process text for all floats except footnotes in body
3943                 do {
3944                         LyXLayout const & style =
3945                                 textclasslist
3946                                 .Style(bparams.textclass, par->layout);
3947                         if (par->IsDummy())
3948                                 lyxerr << "ERROR (LyXParagraph::TeXFootnote)"
3949                                        << endl;
3950                         if (style.isEnvironment()
3951                             || par->pextra_type == PEXTRA_MINIPAGE) { /* && !minipage_open ?? */
3952                                 // Allows the use of minipages within float
3953                                 // environments. Shouldn't be circular because
3954                                 // we don't support footnotes inside
3955                                 // floats (yet). ARRae
3956                                 par = par->TeXEnvironment(buf, bparams, os,
3957                                                           texrow,
3958                                                           foot, foot_texrow,
3959                                                           foot_count);
3960                         } else {
3961                                 par = par->TeXOnePar(buf, bparams,
3962                                                      os, texrow, moving_arg,
3963                                                      foot, foot_texrow,
3964                                                      foot_count);
3965                         }
3966                         
3967                         if (par && !par->IsDummy() && par->depth > depth) {
3968                                 par = par->TeXDeeper(buf, bparams, os, texrow,
3969                                                      foot, foot_texrow,
3970                                                      foot_count);
3971                         }
3972                 } while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE);
3973         } else {
3974                 // process footnotes > depth 0 or in environments separately
3975                 // NOTE: Currently don't support footnotes within footnotes
3976                 //       even though that is possible using the \footnotemark
3977 #ifdef HAVE_SSTREAM
3978                 std::ostringstream dummy;
3979 #else
3980                 ostrstream dummy;
3981 #endif
3982                 TexRow dummy_texrow;
3983                 int dummy_count = 0;
3984                 do {
3985                         LyXLayout const & style =
3986                                 textclasslist
3987                                 .Style(bparams.textclass, par->layout);
3988                         if (par->IsDummy())
3989                                 lyxerr << "ERROR (LyXParagraph::TeXFootnote)"
3990                                        << endl;
3991                         if (style.isEnvironment()
3992                             || par->pextra_type == PEXTRA_MINIPAGE) { /* && !minipage_open ?? */
3993                                 // Allows the use of minipages within float
3994                                 // environments. Shouldn't be circular because
3995                                 // we don't support footnotes inside
3996                                 // floats (yet). ARRae
3997                                 par = par->TeXEnvironment(buf, bparams,
3998                                                           foot, foot_texrow,
3999                                                           dummy, dummy_texrow,
4000                                                           dummy_count);
4001                         } else {
4002                                 par = par->TeXOnePar(buf, bparams,
4003                                                      foot, foot_texrow,
4004                                                      moving_arg,
4005                                                      dummy, dummy_texrow,
4006                                                      dummy_count);
4007                         }
4008
4009                         if (par && !par->IsDummy() && par->depth > depth) {
4010                                 par = par->TeXDeeper(buf, bparams,
4011                                                      foot, foot_texrow,
4012                                                      dummy, dummy_texrow,
4013                                                      dummy_count);
4014                         }
4015                 } while (par
4016                          && par->footnoteflag != LyXParagraph::NO_FOOTNOTE);
4017                 if (dummy_count) {
4018                         lyxerr << "ERROR (LyXParagraph::TeXFootnote): "
4019                                 "Footnote in a Footnote -- not supported"
4020                                << endl;
4021                 }
4022 #ifndef HAVE_OSTREAM
4023                 delete [] dummy.str();
4024 #endif
4025         }
4026
4027         switch (footnotekind) {
4028         case LyXParagraph::FOOTNOTE:
4029                 if (footer_in_body) {
4030                         // This helps tell which of the multiple
4031                         // footnotetexts an error was in.
4032                         foot << "}%\n";
4033                         foot_texrow.newline();
4034                 } else {
4035                         os << '}';
4036                 }
4037                 break;
4038         case LyXParagraph::MARGIN:
4039                 os << '}';
4040                 break;
4041         case LyXParagraph::FIG:
4042                 if (pextra_type == PEXTRA_FLOATFLT
4043                     && (!pextra_width.empty()
4044                         || !pextra_widthp.empty()))
4045                         os << "\\end{floatingfigure}";
4046                 else
4047                         os << "\\end{figure}";
4048                 break;
4049         case LyXParagraph::TAB:
4050                 os << "\\end{table}";
4051                 break;
4052         case LyXParagraph::WIDE_FIG:
4053                 os << "\\end{figure*}";
4054                 break;
4055         case LyXParagraph::WIDE_TAB:
4056                 os << "\\end{table*}";
4057                 break;
4058         case LyXParagraph::ALGORITHM:
4059                 os << "\\end{algorithm}";
4060                 break;
4061         }
4062
4063         if (need_closing)
4064                 os << "}";
4065
4066         if (footnotekind != LyXParagraph::FOOTNOTE
4067             && footnotekind != LyXParagraph::MARGIN) {
4068                 // we need to ensure that real floats like tables and figures
4069                 // have their \end{} on a line of their own otherwise we can
4070                 // get incorrect results when using the endfloat.sty package.
4071                 os << "\n";
4072                 texrow.newline();
4073         }
4074
4075         lyxerr[Debug::LATEX] << "TeXFootnote...done " << par->next << endl;
4076         return par;
4077 }
4078
4079
4080 bool LyXParagraph::IsDummy() const
4081 {
4082         return (footnoteflag == LyXParagraph::NO_FOOTNOTE && previous
4083                 && previous->footnoteflag != LyXParagraph::NO_FOOTNOTE);
4084 }
4085 #endif
4086
4087 void LyXParagraph::SetPExtraType(BufferParams const & bparams,
4088                                  int type, char const * width,
4089                                  char const * widthp)
4090 {
4091         pextra_type = type;
4092         pextra_width = width;
4093         pextra_widthp = widthp;
4094
4095         if (textclasslist.Style(bparams.textclass, 
4096                                 layout).isEnvironment()) {
4097                 LyXParagraph
4098                         * par = this,
4099                         * ppar = par;
4100
4101                 while (par && (par->layout == layout)
4102                        && (par->depth == depth)) {
4103                         ppar = par;
4104                         par = par->Previous();
4105                         if (par)
4106                                 par = par->FirstPhysicalPar();
4107                         while (par && par->depth > depth) {
4108                                 par = par->Previous();
4109                                 if (par)
4110                                         par = par->FirstPhysicalPar();
4111                         }
4112                 }
4113                 par = ppar;
4114                 while (par && (par->layout == layout)
4115                        && (par->depth == depth)) {
4116                         par->pextra_type = type;
4117                         par->pextra_width = width;
4118                         par->pextra_widthp = widthp;
4119                         par = par->NextAfterFootnote();
4120                         if (par && (par->depth > depth))
4121                                 par->SetPExtraType(bparams,
4122                                                    type, width, widthp);
4123                         while (par && ((par->depth > depth) || par->IsDummy()))
4124                                 par = par->NextAfterFootnote();
4125                 }
4126         }
4127 }
4128
4129
4130 void LyXParagraph::UnsetPExtraType(BufferParams const & bparams)
4131 {
4132         if (pextra_type == PEXTRA_NONE)
4133                 return;
4134     
4135         pextra_type = PEXTRA_NONE;
4136         pextra_width.erase();
4137         pextra_widthp.erase();
4138
4139         if (textclasslist.Style(bparams.textclass, 
4140                                 layout).isEnvironment()) {
4141                 LyXParagraph
4142                         * par = this,
4143                         * ppar = par;
4144
4145                 while (par && (par->layout == layout)
4146                        && (par->depth == depth)) {
4147                         ppar = par;
4148                         par = par->Previous();
4149                         if (par)
4150                                 par = par->FirstPhysicalPar();
4151                         while (par && par->depth > depth) {
4152                                 par = par->Previous();
4153                                 if (par)
4154                                         par = par->FirstPhysicalPar();
4155                         }
4156                 }
4157                 par = ppar;
4158                 while (par && (par->layout == layout)
4159                        && (par->depth == depth)) {
4160                         par->pextra_type = PEXTRA_NONE;
4161                         par->pextra_width.erase();
4162                         par->pextra_widthp.erase();
4163                         par = par->NextAfterFootnote();
4164                         if (par && (par->depth > depth))
4165                                 par->UnsetPExtraType(bparams);
4166                         while (par && ((par->depth > depth) || par->IsDummy()))
4167                                 par = par->NextAfterFootnote();
4168                 }
4169         }
4170 }
4171
4172
4173 bool LyXParagraph::IsHfill(size_type pos) const
4174 {
4175         return IsHfillChar(GetChar(pos));
4176 }
4177
4178
4179 bool LyXParagraph::IsInset(size_type pos) const
4180 {
4181         return IsInsetChar(GetChar(pos));
4182 }
4183
4184
4185 bool LyXParagraph::IsFloat(size_type pos) const
4186 {
4187         return IsFloatChar(GetChar(pos));
4188 }
4189
4190
4191 bool LyXParagraph::IsNewline(size_type pos) const
4192 {
4193         return pos >= 0 && IsNewlineChar(GetChar(pos));
4194 }
4195
4196
4197 bool LyXParagraph::IsSeparator(size_type pos) const
4198 {
4199         return IsSeparatorChar(GetChar(pos));
4200 }
4201
4202
4203 bool LyXParagraph::IsLineSeparator(size_type pos) const
4204 {
4205         return IsLineSeparatorChar(GetChar(pos));
4206 }
4207
4208
4209 bool LyXParagraph::IsKomma(size_type pos) const
4210 {
4211         return IsKommaChar(GetChar(pos));
4212 }
4213
4214
4215 /// Used by the spellchecker
4216 bool LyXParagraph::IsLetter(LyXParagraph::size_type pos) const
4217 {
4218         unsigned char c = GetChar(pos);
4219         if (IsLetterChar(c))
4220                 return true;
4221         // '\0' is not a letter, allthough every string contains "" (below)
4222         if( c == '\0')
4223                 return false;
4224         // We want to pass the ' and escape chars to ispell
4225         string extra = lyxrc.isp_esc_chars + '\'';
4226         char ch[2];
4227         ch[0] = c;
4228         ch[1] = 0;
4229         return contains(extra, ch);
4230 }
4231  
4232  
4233 bool LyXParagraph::IsWord(size_type pos ) const
4234 {
4235         return IsWordChar(GetChar(pos)) ;
4236 }
4237
4238
4239 Language const *
4240 LyXParagraph::getParLanguage(BufferParams const & bparams) const 
4241 {
4242         if (IsDummy())
4243                 return FirstPhysicalPar()->getParLanguage(bparams);
4244         else if (size() > 0)
4245 #ifndef NEW_TABULAR
4246                 if (!table)
4247 #endif
4248                         return GetFirstFontSettings().language();
4249 #ifndef NEW_TABULAR
4250                 else {
4251                         for (size_type pos = 0; pos < size(); ++pos)
4252                                 if (IsNewline(pos))
4253                                         return GetFontSettings(bparams, pos).language();
4254                         return GetFirstFontSettings().language();
4255                 }
4256 #endif
4257         else if (previous)
4258                 return previous->getParLanguage(bparams);
4259         else
4260                 return bparams.language_info;
4261 }
4262
4263
4264 bool LyXParagraph::isRightToLeftPar(BufferParams const & bparams) const
4265 {
4266         return lyxrc.rtl_support && !table
4267                 && getParLanguage(bparams)->RightToLeft();
4268 }
4269
4270
4271 void LyXParagraph::ChangeLanguage(BufferParams const & bparams,
4272                                   Language const * from, Language const * to)
4273 {
4274         for(size_type i = 0; i < size(); ++i) {
4275                 LyXFont font = GetFontSettings(bparams, i);
4276                 if (font.language() == from) {
4277                         font.setLanguage(to);
4278                         SetFont(i, font);
4279                 }
4280         }
4281 }
4282
4283
4284 bool LyXParagraph::isMultiLingual(BufferParams const & bparams)
4285 {
4286         Language const * doc_language =
4287                 bparams.language_info;
4288         for(size_type i = 0; i < size(); ++i) {
4289                 LyXFont font = GetFontSettings(bparams, i);
4290                 if (font.language() != doc_language)
4291                         return true;
4292         }
4293         return false;
4294 }
4295
4296
4297 // Convert the paragraph to a string.
4298 // Used for building the table of contents
4299 string LyXParagraph::String(Buffer const * buffer, bool label)
4300 {
4301         BufferParams const & bparams = buffer->params;
4302         string s;
4303         if (label && !IsDummy() && !labelstring.empty())
4304                 s += labelstring + ' ';
4305         string::size_type len = s.size();
4306
4307         for (LyXParagraph::size_type i = 0; i < size(); ++i) {
4308                 unsigned char c = GetChar(i);
4309                 if (IsPrintable(c))
4310                         s += c;
4311                 else if (c == META_INSET &&
4312                          GetInset(i)->LyxCode() == Inset::MATH_CODE) {
4313 #ifdef HAVE_SSTREAM
4314                         std::ostringstream ost;
4315                         GetInset(i)->Ascii(buffer, ost);
4316 #else
4317                         ostrstream ost;
4318                         GetInset(i)->Ascii(buffer, ost);
4319                         ost << '\0';
4320 #endif
4321                         s += subst(ost.str(),'\n',' ');
4322                 }
4323         }
4324
4325 #ifndef NEW_INSETS
4326         if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE 
4327             && footnoteflag == LyXParagraph::NO_FOOTNOTE)
4328                 s += NextAfterFootnote()->String(buffer, false);
4329
4330         if (!IsDummy())
4331 #endif
4332                 {
4333                 if (isRightToLeftPar(bparams))
4334                         reverse(s.begin() + len,s.end());
4335         }
4336         return s;
4337 }
4338
4339
4340 string LyXParagraph::String(Buffer const * buffer, 
4341                             LyXParagraph::size_type beg,
4342                             LyXParagraph::size_type end)
4343 {
4344         string s;
4345         int actcell = 0;
4346         int cell = 1;
4347 #ifndef NEW_TABULAR
4348         if (table)
4349                 for (LyXParagraph::size_type i = 0; i < beg; ++i)
4350                         if (IsNewline(i)) {
4351                                 if (cell >= table->NumberOfCellsInRow(actcell))
4352                                         cell = 1;
4353                                 else
4354                                         ++cell;
4355                                 ++actcell;
4356                         }
4357 #endif
4358         
4359         if (beg == 0 && !IsDummy() && !labelstring.empty())
4360                 s += labelstring + ' ';
4361
4362         for (LyXParagraph::size_type i = beg; i < end; ++i) {
4363                 unsigned char c = GetChar(i);
4364                 if (IsPrintable(c))
4365                         s += c;
4366                 else if (c == META_INSET) {
4367 #ifdef HAVE_SSTREAM
4368                         std::ostringstream ost;
4369                         GetInset(i)->Ascii(buffer, ost);
4370 #else
4371                         ostrstream ost;
4372                         GetInset(i)->Ascii(buffer, ost);
4373                         ost << '\0';
4374 #endif
4375                         s += ost.str();
4376                 } else if (table && IsNewlineChar(c)) {
4377                         if (cell >= table->NumberOfCellsInRow(actcell)) {
4378                                 s += '\n';
4379                                 cell = 1;
4380                         } else {
4381                                 s += ' ';
4382                                 ++cell;
4383                         }
4384                         ++actcell;
4385                 }
4386         }
4387
4388         //if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE)
4389         //      s += NextAfterFootnote()->String(false);
4390
4391         return s;
4392 }
4393
4394
4395 void LyXParagraph::SetInsetOwner(Inset *i)
4396 {
4397         inset_owner = i;
4398         for (InsetList::const_iterator cit = insetlist.begin();
4399              cit != insetlist.end(); ++cit) {
4400                 if ((*cit).inset)
4401                         (*cit).inset->setOwner(i);
4402         }
4403 }
4404
4405
4406 void LyXParagraph::deleteInsetsLyXText(BufferView * bv)
4407 {
4408         // then the insets
4409         for (InsetList::const_iterator cit = insetlist.begin();
4410              cit != insetlist.end(); ++cit) {
4411                 if ((*cit).inset) {
4412                         if ((*cit).inset->IsTextInset()) {
4413                                 static_cast<UpdatableInset *>
4414                                         ((*cit).inset)->deleteLyXText(bv);
4415                         }
4416                 }
4417         }
4418 }