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