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