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