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