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