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