]> git.lyx.org Git - lyx.git/blob - src/buffer.C
7e9bb93a714ef8531743520f1547597f35f05527
[lyx.git] / src / buffer.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  *           This file is Copyright 1996-1999
10  *           Lars Gullik Bjønnes
11  *
12  * ====================================================== 
13  */
14
15 #include <config.h>
16
17 #include <fstream>
18 #include <iomanip>
19
20 #include <cstdlib>
21 #include <cmath>
22 #include <unistd.h>
23 #include <sys/types.h>
24 #include <utime.h>
25
26 #include <algorithm>
27
28 #ifdef HAVE_LOCALE
29 #include <locale>
30 #endif
31
32 #ifdef __GNUG__
33 #pragma implementation "buffer.h"
34 #endif
35
36 #include "buffer.h"
37 #include "bufferlist.h"
38 #include "lyx_main.h"
39 #include "lyx_gui_misc.h"
40 #include "LyXAction.h"
41 #include "lyxrc.h"
42 #include "lyxlex.h"
43 #include "tex-strings.h"
44 #include "layout.h"
45 #include "bufferview_funcs.h"
46 #include "minibuffer.h"
47 #include "lyxfont.h"
48 #include "version.h"
49 #include "mathed/formulamacro.h"
50 #include "insets/lyxinset.h"
51 #include "insets/inseterror.h"
52 #include "insets/insetlabel.h"
53 #include "insets/insetref.h"
54 #include "insets/inseturl.h"
55 #include "insets/insetinfo.h"
56 #include "insets/insetquotes.h"
57 #include "insets/insetlatexaccent.h"
58 #include "insets/insetbib.h" 
59 #include "insets/insetcite.h" 
60 #include "insets/insetexternal.h"
61 #include "insets/insetindex.h" 
62 #include "insets/insetinclude.h"
63 #include "insets/insettoc.h"
64 #include "insets/insetparent.h"
65 #include "insets/insetspecialchar.h"
66 #include "insets/figinset.h"
67 #include "insets/insettext.h"
68 #include "insets/insetert.h"
69 #include "insets/insetgraphics.h"
70 #include "insets/insetfoot.h"
71 #include "insets/insetmarginal.h"
72 #include "insets/insetminipage.h"
73 #include "insets/insetfloat.h"
74 #include "insets/insetlist.h"
75 #include "insets/insettabular.h"
76 #include "insets/insettheorem.h"
77 #include "insets/insetcaption.h"
78 #include "support/filetools.h"
79 #include "support/path.h"
80 #include "LaTeX.h"
81 #include "Chktex.h"
82 #include "LyXView.h"
83 #include "debug.h"
84 #include "LaTeXFeatures.h"
85 #include "support/syscall.h"
86 #include "support/lyxlib.h"
87 #include "support/FileInfo.h"
88 #include "support/lyxmanip.h"
89 #include "lyxtext.h"
90 #include "gettext.h"
91 #include "language.h"
92 #include "lyx_gui_misc.h"       // WarnReadonly()
93 #include "frontends/Dialogs.h"
94 #include "encoding.h"
95 #include "exporter.h"
96 #include "Lsstream.h"
97
98 using std::ostream;
99 using std::ofstream;
100 using std::ifstream;
101 using std::fstream;
102 using std::ios;
103 using std::setw;
104 using std::endl;
105 using std::pair;
106 using std::vector;
107 using std::max;
108 using std::set;
109
110 // all these externs should eventually be removed.
111 extern BufferList bufferlist;
112
113 extern LyXAction lyxaction;
114
115
116 #if 0
117 static const float LYX_FORMAT = 2.17;
118 #else
119 static const int LYX_FORMAT = 218;
120 #endif
121
122 extern int tex_code_break_column;
123
124
125 Buffer::Buffer(string const & file, bool ronly)
126 {
127         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
128         filename = file;
129         filepath = OnlyPath(file);
130         paragraph = 0;
131         lyx_clean = true;
132         bak_clean = true;
133         dep_clean = 0;
134         read_only = ronly;
135         unnamed = false;
136         users = 0;
137         lyxvc.buffer(this);
138         if (read_only || (lyxrc.use_tempdir)) {
139                 tmppath = CreateBufferTmpDir();
140         } else tmppath.erase();
141 }
142
143
144 Buffer::~Buffer()
145 {
146         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
147         // here the buffer should take care that it is
148         // saved properly, before it goes into the void.
149
150         // make sure that views using this buffer
151         // forgets it.
152         if (users)
153                 users->buffer(0);
154         
155         if (!tmppath.empty()) {
156                 DestroyBufferTmpDir(tmppath);
157         }
158         
159         LyXParagraph * par = paragraph;
160         LyXParagraph * tmppar;
161         while (par) {
162                 tmppar = par->next;
163                 delete par;
164                 par = tmppar;
165         }
166         paragraph = 0;
167 }
168
169
170 string const Buffer::getLatexName(bool no_path) const
171 {
172         if (no_path)
173                 return OnlyFilename(ChangeExtension(MakeLatexName(filename), 
174                                                     ".tex"));
175         else
176                 return ChangeExtension(MakeLatexName(filename), 
177                                        ".tex"); 
178 }
179
180
181 void Buffer::setReadonly(bool flag)
182 {
183         if (read_only != flag) {
184                 read_only = flag; 
185                 updateTitles();
186                 users->owner()->getDialogs()->updateBufferDependent(false);
187         }
188         if (read_only) {
189                 WarnReadonly(filename);
190         }
191 }
192
193
194 bool Buffer::saveParamsAsDefaults() // const
195 {
196         string const fname = AddName(AddPath(user_lyxdir, "templates/"),
197                                "defaults.lyx");
198         Buffer defaults = Buffer(fname);
199         
200         // Use the current buffer's parameters as default
201         defaults.params = params;
202         
203         // add an empty paragraph. Is this enough?
204         defaults.paragraph = new LyXParagraph;
205
206         return defaults.writeFile(defaults.filename, false);
207 }
208
209
210 /// Update window titles of all users
211 // Should work on a list
212 void Buffer::updateTitles() const
213 {
214         if (users) users->owner()->updateWindowTitle();
215 }
216
217
218 /// Reset autosave timer of all users
219 // Should work on a list
220 void Buffer::resetAutosaveTimers() const
221 {
222         if (users) users->owner()->resetAutosaveTimer();
223 }
224
225
226 void Buffer::setFileName(string const & newfile)
227 {
228         filename = MakeAbsPath(newfile);
229         filepath = OnlyPath(filename);
230         setReadonly(IsFileWriteable(filename) == 0);
231         updateTitles();
232 }
233
234
235 // candidate for move to BufferView
236 // (at least some parts in the beginning of the func)
237 //
238 // Uwe C. Schroeder
239 // changed to be public and have one parameter
240 // if par = 0 normal behavior
241 // else insert behavior
242 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
243 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
244 {
245         int pos = 0;
246         char depth = 0; // signed or unsigned?
247 #ifndef NEW_INSETS
248         LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
249         LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
250 #endif
251         bool the_end_read = false;
252
253         LyXParagraph * return_par = 0;
254         LyXFont font(LyXFont::ALL_INHERIT, params.language);
255 #if 0
256         if (format < 2.16 && params.language->lang() == "hebrew")
257                 font.setLanguage(default_language);
258 #else
259         if (file_format < 216 && params.language->lang() == "hebrew")
260                 font.setLanguage(default_language);
261 #endif
262         // If we are inserting, we cheat and get a token in advance
263         bool has_token = false;
264         string pretoken;
265
266         if (!par) {
267                 par = new LyXParagraph;
268         } else {
269                 users->text->BreakParagraph(users);
270                 return_par = users->text->FirstParagraph();
271                 pos = 0;
272                 markDirty();
273                 // We don't want to adopt the parameters from the
274                 // document we insert, so we skip until the text begins:
275                 while (lex.IsOK()) {
276                         lex.nextToken();
277                         pretoken = lex.GetString();
278                         if (pretoken == "\\layout") {
279                                 has_token = true;
280                                 break;
281                         }
282                 }
283         }
284
285         while (lex.IsOK()) {
286                 if (has_token) {
287                         has_token = false;
288                 } else {
289                         lex.nextToken();
290                         pretoken = lex.GetString();
291                 }
292
293                 if (pretoken.empty()) continue;
294                 
295                 the_end_read =
296                         parseSingleLyXformat2Token(lex, par, return_par,
297                                                    pretoken, pos, depth,
298                                                    font
299 #ifndef NEW_INSETS
300                                                    , footnoteflag,
301                                                    footnotekind
302 #endif
303                                 );
304         }
305    
306         if (!return_par)
307                 return_par = par;
308
309         paragraph = return_par;
310         
311         return the_end_read;
312 }
313
314
315 // We'll remove this later. (Lgb)
316 static string last_inset_read;
317
318
319 bool
320 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
321                                    LyXParagraph *& return_par,
322                                    string const & token, int & pos,
323                                    char & depth, LyXFont & font
324 #ifndef NEW_INSETS
325                                    , LyXParagraph::footnote_flag & footnoteflag,
326                                    LyXParagraph::footnote_kind & footnotekind
327 #endif
328         )
329 {
330         bool the_end_read = false;
331         
332         if (token[0] != '\\') {
333                 for (string::const_iterator cit = token.begin();
334                      cit != token.end(); ++cit) {
335                         par->InsertChar(pos, (*cit), font);
336                         ++pos;
337                 }
338         } else if (token == "\\i") {
339                 Inset * inset = new InsetLatexAccent;
340                 inset->Read(this, lex);
341                 par->InsertInset(pos, inset, font);
342                 ++pos;
343         } else if (token == "\\layout") {
344                 if (!return_par) 
345                         return_par = par;
346                 else {
347                         par->fitToSize();
348                         par = new LyXParagraph(par);
349                 }
350                 pos = 0;
351                 lex.EatLine();
352                 string const layoutname = lex.GetString();
353                 pair<bool, LyXTextClass::LayoutList::size_type> pp
354                         = textclasslist.NumberOfLayout(params.textclass,
355                                                        layoutname);
356                 if (pp.first) {
357                         par->layout = pp.second;
358                 } else { // layout not found
359                         // use default layout "Standard" (0)
360                         par->layout = 0;
361                 }
362                 // Test whether the layout is obsolete.
363                 LyXLayout const & layout =
364                         textclasslist.Style(params.textclass,
365                                             par->layout); 
366                 if (!layout.obsoleted_by().empty())
367                         par->layout = 
368                                 textclasslist.NumberOfLayout(params.textclass, 
369                                                              layout.obsoleted_by()).second;
370 #ifndef NEW_INSETS
371                 par->footnoteflag = footnoteflag;
372                 par->footnotekind = footnotekind;
373 #endif
374                 par->depth = depth;
375                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
376 #if 0
377                 if (format < 2.16 && params.language->lang() == "hebrew")
378                         font.setLanguage(default_language);
379 #else
380                 if (file_format < 216 && params.language->lang() == "hebrew")
381                         font.setLanguage(default_language);
382 #endif
383 #ifndef NEW_INSETS
384         } else if (token == "\\end_float") {
385                 if (!return_par) 
386                         return_par = par;
387                 else {
388                         par->fitToSize();
389                         par = new LyXParagraph(par);
390                 }
391                 footnotekind = LyXParagraph::FOOTNOTE;
392                 footnoteflag = LyXParagraph::NO_FOOTNOTE;
393                 pos = 0;
394                 lex.EatLine();
395                 par->layout = LYX_DUMMY_LAYOUT;
396                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
397 #if 0
398                 if (format < 2.16 && params.language->lang() == "hebrew")
399                         font.setLanguage(default_language);
400 #else
401                 if (file_format < 216 && params.language->lang() == "hebrew")
402                         font.setLanguage(default_language);
403 #endif
404         } else if (token == "\\begin_float") {
405                 int tmpret = lex.FindToken(string_footnotekinds);
406                 if (tmpret == -1) ++tmpret;
407                 if (tmpret != LYX_LAYOUT_DEFAULT) 
408                         footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
409                 if (footnotekind == LyXParagraph::FOOTNOTE
410                     || footnotekind == LyXParagraph::MARGIN)
411                         footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
412                 else 
413                         footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
414 #else
415         } else if (token == "\\begin_float") {
416                 // This is the compability reader, unfinished but tested.
417                 // (Lgb)
418                 lex.next();
419                 string const tmptok = lex.GetString();
420                 //lyxerr << "old float: " << tmptok << endl;
421                 
422                 Inset * inset = 0;
423                 string old_float;
424                 
425                 if (tmptok == "footnote") {
426                         inset = new InsetFoot;
427                 } else if (tmptok == "margin") {
428                         inset = new InsetMarginal;
429                 } else if (tmptok == "fig") {
430                         inset = new InsetFloat("figure");
431                         old_float += "placement htbp\n";
432                 } else if (tmptok == "tab") {
433                         inset = new InsetFloat("table");
434                         old_float += "placement htbp\n";
435                 } else if (tmptok == "alg") {
436                         inset = new InsetFloat("algorithm");
437                         old_float += "placement htbp\n";
438                 } else if (tmptok == "wide-fig") {
439                         InsetFloat * tmp = new InsetFloat("figure");
440                         tmp->wide(true);
441                         inset = tmp;
442                         old_float += "placement htbp\n";
443                 } else if (tmptok == "wide-tab") {
444                         InsetFloat * tmp = new InsetFloat("table");
445                         tmp->wide(true);
446                         inset = tmp;
447                         old_float += "placement htbp\n";
448                 }
449
450                 if (!inset) return false; // no end read yet
451                 
452                 old_float += "collapsed true\n";
453
454                 // Here we need to check for \end_deeper and handle that
455                 // before we do the footnote parsing.
456                 // This _is_ a hack! (Lgb)
457                 while(true) {
458                         lex.next();
459                         string const tmp = lex.GetString();
460                         if (tmp == "\\end_deeper") {
461                                 lyxerr << "\\end_deeper caught!" << endl;
462                                 if (!depth) {
463                                         lex.printError("\\end_deeper: "
464                                                        "depth is already null");
465                                 } else
466                                         --depth;
467                                 
468                         } else {
469                                 old_float += tmp;
470                                 old_float += ' ';
471                                 break;
472                         }
473                 }
474                 
475                 old_float += lex.getLongString("\\end_float");
476                 old_float += "\n\\end_inset\n";
477                 //lyxerr << "float body: " << old_float << endl;
478
479                 istringstream istr(old_float);
480                 
481                 LyXLex nylex(0, 0);
482                 nylex.setStream(istr);
483                 
484                 inset->Read(this, nylex);
485                 par->InsertInset(pos, inset, font);
486                 ++pos;
487 #endif
488         } else if (token == "\\begin_deeper") {
489                 ++depth;
490         } else if (token == "\\end_deeper") {
491                 if (!depth) {
492                         lex.printError("\\end_deeper: "
493                                        "depth is already null");
494                 }
495                 else
496                         --depth;
497         } else if (token == "\\begin_preamble") {
498                 params.readPreamble(lex);
499         } else if (token == "\\textclass") {
500                 lex.EatLine();
501                 pair<bool, LyXTextClassList::size_type> pp = 
502                         textclasslist.NumberOfClass(lex.GetString());
503                 if (pp.first) {
504                         params.textclass = pp.second;
505                 } else {
506                         WriteAlert(string(_("Textclass error")), 
507                                 string(_("The document uses an unknown textclass \"")) + 
508                                 lex.GetString() + string("\"."),
509                                 string(_("LyX will not be able to produce output correctly.")));
510                         params.textclass = 0;
511                 }
512                 if (!textclasslist.Load(params.textclass)) {
513                                 // if the textclass wasn't loaded properly
514                                 // we need to either substitute another
515                                 // or stop loading the file.
516                                 // I can substitute but I don't see how I can
517                                 // stop loading... ideas??  ARRae980418
518                         WriteAlert(_("Textclass Loading Error!"),
519                                    string(_("Can't load textclass ")) +
520                                    textclasslist.NameOfClass(params.textclass),
521                                    _("-- substituting default"));
522                         params.textclass = 0;
523                 }
524         } else if (token == "\\options") {
525                 lex.EatLine();
526                 params.options = lex.GetString();
527         } else if (token == "\\language") {
528                 params.readLanguage(lex);    
529         } else if (token == "\\fontencoding") {
530                 lex.EatLine();
531         } else if (token == "\\inputencoding") {
532                 lex.EatLine();
533                 params.inputenc = lex.GetString();
534         } else if (token == "\\graphics") {
535                 params.readGraphicsDriver(lex);
536         } else if (token == "\\fontscheme") {
537                 lex.EatLine();
538                 params.fonts = lex.GetString();
539         } else if (token == "\\noindent") {
540                 par->noindent = true;
541         } else if (token == "\\fill_top") {
542                 par->added_space_top = VSpace(VSpace::VFILL);
543         } else if (token == "\\fill_bottom") {
544                 par->added_space_bottom = VSpace(VSpace::VFILL);
545         } else if (token == "\\line_top") {
546                 par->line_top = true;
547         } else if (token == "\\line_bottom") {
548                 par->line_bottom = true;
549         } else if (token == "\\pagebreak_top") {
550                 par->pagebreak_top = true;
551         } else if (token == "\\pagebreak_bottom") {
552                 par->pagebreak_bottom = true;
553         } else if (token == "\\start_of_appendix") {
554                 par->start_of_appendix = true;
555         } else if (token == "\\paragraph_separation") {
556                 int tmpret = lex.FindToken(string_paragraph_separation);
557                 if (tmpret == -1) ++tmpret;
558                 if (tmpret != LYX_LAYOUT_DEFAULT) 
559                         params.paragraph_separation =
560                                 static_cast<BufferParams::PARSEP>(tmpret);
561         } else if (token == "\\defskip") {
562                 lex.nextToken();
563                 params.defskip = VSpace(lex.GetString());
564         } else if (token == "\\epsfig") { // obsolete
565                 // Indeed it is obsolete, but we HAVE to be backwards
566                 // compatible until 0.14, because otherwise all figures
567                 // in existing documents are irretrivably lost. (Asger)
568                 params.readGraphicsDriver(lex);
569         } else if (token == "\\quotes_language") {
570                 int tmpret = lex.FindToken(string_quotes_language);
571                 if (tmpret == -1) ++tmpret;
572                 if (tmpret != LYX_LAYOUT_DEFAULT) {
573                         InsetQuotes::quote_language tmpl = 
574                                 InsetQuotes::EnglishQ;
575                         switch (tmpret) {
576                         case 0:
577                                 tmpl = InsetQuotes::EnglishQ;
578                                 break;
579                         case 1:
580                                 tmpl = InsetQuotes::SwedishQ;
581                                 break;
582                         case 2:
583                                 tmpl = InsetQuotes::GermanQ;
584                                 break;
585                         case 3:
586                                 tmpl = InsetQuotes::PolishQ;
587                                 break;
588                         case 4:
589                                 tmpl = InsetQuotes::FrenchQ;
590                                 break;
591                         case 5:
592                                 tmpl = InsetQuotes::DanishQ;
593                                 break;  
594                         }
595                         params.quotes_language = tmpl;
596                 }
597         } else if (token == "\\quotes_times") {
598                 lex.nextToken();
599                 switch (lex.GetInteger()) {
600                 case 1: 
601                         params.quotes_times = InsetQuotes::SingleQ; 
602                         break;
603                 case 2: 
604                         params.quotes_times = InsetQuotes::DoubleQ; 
605                         break;
606                 }
607         } else if (token == "\\papersize") {
608                 int tmpret = lex.FindToken(string_papersize);
609                 if (tmpret == -1)
610                         ++tmpret;
611                 else
612                         params.papersize2 = tmpret;
613         } else if (token == "\\paperpackage") {
614                 int tmpret = lex.FindToken(string_paperpackages);
615                 if (tmpret == -1) {
616                         ++tmpret;
617                         params.paperpackage = BufferParams::PACKAGE_NONE;
618                 } else
619                         params.paperpackage = tmpret;
620         } else if (token == "\\use_geometry") {
621                 lex.nextToken();
622                 params.use_geometry = lex.GetInteger();
623         } else if (token == "\\use_amsmath") {
624                 lex.nextToken();
625                 params.use_amsmath = lex.GetInteger();
626         } else if (token == "\\paperorientation") {
627                 int tmpret = lex.FindToken(string_orientation);
628                 if (tmpret == -1) ++tmpret;
629                 if (tmpret != LYX_LAYOUT_DEFAULT) 
630                         params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
631         } else if (token == "\\paperwidth") {
632                 lex.next();
633                 params.paperwidth = lex.GetString();
634         } else if (token == "\\paperheight") {
635                 lex.next();
636                 params.paperheight = lex.GetString();
637         } else if (token == "\\leftmargin") {
638                 lex.next();
639                 params.leftmargin = lex.GetString();
640         } else if (token == "\\topmargin") {
641                 lex.next();
642                 params.topmargin = lex.GetString();
643         } else if (token == "\\rightmargin") {
644                 lex.next();
645                 params.rightmargin = lex.GetString();
646         } else if (token == "\\bottommargin") {
647                 lex.next();
648                 params.bottommargin = lex.GetString();
649         } else if (token == "\\headheight") {
650                 lex.next();
651                 params.headheight = lex.GetString();
652         } else if (token == "\\headsep") {
653                 lex.next();
654                 params.headsep = lex.GetString();
655         } else if (token == "\\footskip") {
656                 lex.next();
657                 params.footskip = lex.GetString();
658         } else if (token == "\\paperfontsize") {
659                 lex.nextToken();
660                 params.fontsize = strip(lex.GetString());
661         } else if (token == "\\papercolumns") {
662                 lex.nextToken();
663                 params.columns = lex.GetInteger();
664         } else if (token == "\\papersides") {
665                 lex.nextToken();
666                 switch (lex.GetInteger()) {
667                 default:
668                 case 1: params.sides = LyXTextClass::OneSide; break;
669                 case 2: params.sides = LyXTextClass::TwoSides; break;
670                 }
671         } else if (token == "\\paperpagestyle") {
672                 lex.nextToken();
673                 params.pagestyle = strip(lex.GetString());
674         } else if (token == "\\bullet") {
675                 lex.nextToken();
676                 int const index = lex.GetInteger();
677                 lex.nextToken();
678                 int temp_int = lex.GetInteger();
679                 params.user_defined_bullets[index].setFont(temp_int);
680                 params.temp_bullets[index].setFont(temp_int);
681                 lex.nextToken();
682                 temp_int = lex.GetInteger();
683                 params.user_defined_bullets[index].setCharacter(temp_int);
684                 params.temp_bullets[index].setCharacter(temp_int);
685                 lex.nextToken();
686                 temp_int = lex.GetInteger();
687                 params.user_defined_bullets[index].setSize(temp_int);
688                 params.temp_bullets[index].setSize(temp_int);
689                 lex.nextToken();
690                 string const temp_str = lex.GetString();
691                 if (temp_str != "\\end_bullet") {
692                                 // this element isn't really necessary for
693                                 // parsing but is easier for humans
694                                 // to understand bullets. Put it back and
695                                 // set a debug message?
696                         lex.printError("\\end_bullet expected, got" + temp_str);
697                                 //how can I put it back?
698                 }
699         } else if (token == "\\bulletLaTeX") {
700                 lex.nextToken();
701                 int const index = lex.GetInteger();
702                 lex.next();
703                 string temp_str = lex.GetString();
704                 string sum_str;
705                 while (temp_str != "\\end_bullet") {
706                                 // this loop structure is needed when user
707                                 // enters an empty string since the first
708                                 // thing returned will be the \\end_bullet
709                                 // OR
710                                 // if the LaTeX entry has spaces. Each element
711                                 // therefore needs to be read in turn
712                         sum_str += temp_str;
713                         lex.next();
714                         temp_str = lex.GetString();
715                 }
716                 params.user_defined_bullets[index].setText(sum_str);
717                 params.temp_bullets[index].setText(sum_str);
718         } else if (token == "\\secnumdepth") {
719                 lex.nextToken();
720                 params.secnumdepth = lex.GetInteger();
721         } else if (token == "\\tocdepth") {
722                 lex.nextToken();
723                 params.tocdepth = lex.GetInteger();
724         } else if (token == "\\spacing") {
725                 lex.next();
726                 string const tmp = strip(lex.GetString());
727                 Spacing::Space tmp_space = Spacing::Default;
728                 float tmp_val = 0.0;
729                 if (tmp == "single") {
730                         tmp_space = Spacing::Single;
731                 } else if (tmp == "onehalf") {
732                         tmp_space = Spacing::Onehalf;
733                 } else if (tmp == "double") {
734                         tmp_space = Spacing::Double;
735                 } else if (tmp == "other") {
736                         lex.next();
737                         tmp_space = Spacing::Other;
738                         tmp_val = lex.GetFloat();
739                 } else {
740                         lex.printError("Unknown spacing token: '$$Token'");
741                 }
742                 // Small hack so that files written with klyx will be
743                 // parsed correctly.
744                 if (return_par) {
745                         par->spacing.set(tmp_space, tmp_val);
746                 } else {
747                         params.spacing.set(tmp_space, tmp_val);
748                 }
749         } else if (token == "\\paragraph_spacing") {
750                 lex.next();
751                 string const tmp = strip(lex.GetString());
752                 if (tmp == "single") {
753                         par->spacing.set(Spacing::Single);
754                 } else if (tmp == "onehalf") {
755                         par->spacing.set(Spacing::Onehalf);
756                 } else if (tmp == "double") {
757                         par->spacing.set(Spacing::Double);
758                 } else if (tmp == "other") {
759                         lex.next();
760                         par->spacing.set(Spacing::Other,
761                                          lex.GetFloat());
762                 } else {
763                         lex.printError("Unknown spacing token: '$$Token'");
764                 }
765         } else if (token == "\\float_placement") {
766                 lex.nextToken();
767                 params.float_placement = lex.GetString();
768         } else if (token == "\\family") { 
769                 lex.next();
770                 font.setLyXFamily(lex.GetString());
771         } else if (token == "\\series") {
772                 lex.next();
773                 font.setLyXSeries(lex.GetString());
774         } else if (token == "\\shape") {
775                 lex.next();
776                 font.setLyXShape(lex.GetString());
777         } else if (token == "\\size") {
778                 lex.next();
779                 font.setLyXSize(lex.GetString());
780         } else if (token == "\\latex") {
781                 lex.next();
782                 string const tok = lex.GetString();
783                 // This is dirty, but gone with LyX3. (Asger)
784                 if (tok == "no_latex")
785                         font.setLatex(LyXFont::OFF);
786                 else if (tok == "latex")
787                         font.setLatex(LyXFont::ON);
788                 else if (tok == "default")
789                         font.setLatex(LyXFont::INHERIT);
790                 else
791                         lex.printError("Unknown LaTeX font flag "
792                                        "`$$Token'");
793         } else if (token == "\\lang") {
794                 lex.next();
795                 string const tok = lex.GetString();
796                 Language const * lang = languages.getLanguage(tok);
797                 if (lang) {
798                         font.setLanguage(lang);
799                 } else {
800                         font.setLanguage(params.language);
801                         lex.printError("Unknown language `$$Token'");
802                 }
803         } else if (token == "\\numeric") {
804                 lex.next();
805                 font.setNumber(font.setLyXMisc(lex.GetString()));
806         } else if (token == "\\emph") {
807                 lex.next();
808                 font.setEmph(font.setLyXMisc(lex.GetString()));
809         } else if (token == "\\bar") {
810                 lex.next();
811                 string const tok = lex.GetString();
812                 // This is dirty, but gone with LyX3. (Asger)
813                 if (tok == "under")
814                         font.setUnderbar(LyXFont::ON);
815                 else if (tok == "no")
816                         font.setUnderbar(LyXFont::OFF);
817                 else if (tok == "default")
818                         font.setUnderbar(LyXFont::INHERIT);
819                 else
820                         lex.printError("Unknown bar font flag "
821                                        "`$$Token'");
822         } else if (token == "\\noun") {
823                 lex.next();
824                 font.setNoun(font.setLyXMisc(lex.GetString()));
825         } else if (token == "\\color") {
826                 lex.next();
827                 font.setLyXColor(lex.GetString());
828         } else if (token == "\\align") {
829                 int tmpret = lex.FindToken(string_align);
830                 if (tmpret == -1) ++tmpret;
831                 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
832 #if 0
833                         int tmpret2 = 1;
834                         for (; tmpret > 0; --tmpret)
835                                 tmpret2 = tmpret2 * 2;
836 #else
837                         int const tmpret2 = int(pow(2.0, tmpret));
838 #endif
839                         //lyxerr << "Tmpret2 = " << tmpret2 << endl;
840                         par->align = LyXAlignment(tmpret2);
841                 }
842         } else if (token == "\\added_space_top") {
843                 lex.nextToken();
844                 par->added_space_top = VSpace(lex.GetString());
845         } else if (token == "\\added_space_bottom") {
846                 lex.nextToken();
847                 par->added_space_bottom = VSpace(lex.GetString());
848         } else if (token == "\\pextra_type") {
849                 lex.nextToken();
850                 par->pextra_type = lex.GetInteger();
851         } else if (token == "\\pextra_width") {
852                 lex.nextToken();
853                 par->pextra_width = lex.GetString();
854         } else if (token == "\\pextra_widthp") {
855                 lex.nextToken();
856                 par->pextra_widthp = lex.GetString();
857         } else if (token == "\\pextra_alignment") {
858                 lex.nextToken();
859                 par->pextra_alignment = lex.GetInteger();
860         } else if (token == "\\pextra_hfill") {
861                 lex.nextToken();
862                 par->pextra_hfill = lex.GetInteger();
863         } else if (token == "\\pextra_start_minipage") {
864                 lex.nextToken();
865                 par->pextra_start_minipage = lex.GetInteger();
866         } else if (token == "\\labelwidthstring") {
867                 lex.EatLine();
868                 par->labelwidthstring = lex.GetString();
869                 // do not delete this token, it is still needed!
870         } else if (token == "\\end_inset") {
871                 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
872                        << "Last inset read was: " << last_inset_read
873                        << endl;
874                 // Simply ignore this. The insets do not have
875                 // to read this.
876                 // But insets should read it, it is a part of
877                 // the inset isn't it? Lgb.
878         } else if (token == "\\begin_inset") {
879                 readInset(lex, par, pos, font);
880         } else if (token == "\\SpecialChar") {
881                 LyXLayout const & layout =
882                         textclasslist.Style(params.textclass, 
883                                             par->GetLayout());
884
885                 // Insets don't make sense in a free-spacing context! ---Kayvan
886                 if (layout.free_spacing) {
887                         if (lex.IsOK()) {
888                                 lex.next();
889                                 string next_token = lex.GetString();
890                                 if (next_token == "\\-") {
891                                         par->InsertChar(pos, '-', font);
892                                 } else if (next_token == "\\protected_separator"
893                                         || next_token == "~") {
894                                         par->InsertChar(pos, ' ', font);
895                                 } else {
896                                         lex.printError("Token `$$Token' "
897                                                        "is in free space "
898                                                        "paragraph layout!");
899                                         --pos;
900                                 }
901                         }
902                 } else {
903                         Inset * inset = new InsetSpecialChar;
904                         inset->Read(this, lex);
905                         par->InsertInset(pos, inset, font);
906                 }
907                 ++pos;
908         } else if (token == "\\newline") {
909                 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
910                 ++pos;
911         } else if (token == "\\LyXTable") {
912                 Inset * inset = new InsetTabular(*this);
913                 inset->Read(this, lex);
914                 par->InsertInset(pos, inset, font);
915                 ++pos;
916         } else if (token == "\\hfill") {
917                 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
918                 ++pos;
919         } else if (token == "\\protected_separator") { // obsolete
920                 // This is a backward compability thingie. (Lgb)
921                 // Remove it later some time...introduced with fileformat
922                 // 2.16. (Lgb)
923                 LyXLayout const & layout =
924                         textclasslist.Style(params.textclass, 
925                                             par->GetLayout());
926
927                 if (layout.free_spacing) {
928                         par->InsertChar(pos, ' ', font);
929                 } else {
930                         Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
931                         par->InsertInset(pos, inset, font);
932                 }
933                 ++pos;
934         } else if (token == "\\bibitem") {  // ale970302
935                 if (!par->bibkey) {
936                         InsetCommandParams p( "bibitem" );
937                         par->bibkey = new InsetBibKey(p);
938                 }
939                 par->bibkey->Read(this, lex);                   
940         } else if (token == "\\backslash") {
941                 par->InsertChar(pos, '\\', font);
942                 ++pos;
943         } else if (token == "\\the_end") {
944                 the_end_read = true;
945         } else {
946                 // This should be insurance for the future: (Asger)
947                 lex.printError("Unknown token `$$Token'. "
948                                "Inserting as text.");
949                 string::const_iterator cit = token.begin();
950                 string::const_iterator end = token.end();
951                 for (; cit != end; ++cit) {
952                         par->InsertChar(pos, (*cit), font);
953                         ++pos;
954                 }
955         }
956         return the_end_read;
957 }
958
959
960 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
961                        int & pos, LyXFont & font)
962 {
963         // consistency check
964         if (lex.GetString() != "\\begin_inset") {
965                 lyxerr << "Buffer::readInset: Consistency check failed."
966                        << endl;
967         }
968         
969         Inset * inset = 0;
970
971         lex.next();
972         string const tmptok = lex.GetString();
973         last_inset_read = tmptok;
974
975         // test the different insets
976         if (tmptok == "LatexCommand") {
977                 InsetCommandParams inscmd;
978                 inscmd.Read(lex);
979
980                 if (inscmd.getCmdName() == "cite") {
981                         inset = new InsetCitation(inscmd);
982                 } else if (inscmd.getCmdName() == "bibitem") {
983                         lex.printError("Wrong place for bibitem");
984                         inset = new InsetBibKey(inscmd);
985                 } else if (inscmd.getCmdName() == "BibTeX") {
986                         inset = new InsetBibtex(inscmd);
987                 } else if (inscmd.getCmdName() == "index") {
988                         inset = new InsetIndex(inscmd);
989                 } else if (inscmd.getCmdName() == "include") {
990                         inset = new InsetInclude(inscmd, *this);
991                 } else if (inscmd.getCmdName() == "label") {
992                         inset = new InsetLabel(inscmd);
993                 } else if (inscmd.getCmdName() == "url"
994                            || inscmd.getCmdName() == "htmlurl") {
995                         inset = new InsetUrl(inscmd);
996                 } else if (inscmd.getCmdName() == "ref"
997                            || inscmd.getCmdName() == "pageref"
998                            || inscmd.getCmdName() == "vref"
999                            || inscmd.getCmdName() == "vpageref"
1000                            || inscmd.getCmdName() == "prettyref") {
1001                         if (!inscmd.getOptions().empty()
1002                             || !inscmd.getContents().empty()) {
1003                                 inset = new InsetRef(inscmd, *this);
1004                         }
1005                 } else if (inscmd.getCmdName() == "tableofcontents"
1006                            || inscmd.getCmdName() == "listofalgorithms"
1007                            || inscmd.getCmdName() == "listoffigures"
1008                            || inscmd.getCmdName() == "listoftables") {
1009                         inset = new InsetTOC(inscmd);
1010                 } else if (inscmd.getCmdName() == "printindex") {
1011                         inset = new InsetPrintIndex(inscmd);
1012                 } else if (inscmd.getCmdName() == "lyxparent") {
1013                         inset = new InsetParent(inscmd, *this);
1014                 }
1015         } else {
1016                 if (tmptok == "Quotes") {
1017                         inset = new InsetQuotes;
1018                 } else if (tmptok == "External") {
1019                         inset = new InsetExternal;
1020                 } else if (tmptok == "FormulaMacro") {
1021                         inset = new InsetFormulaMacro;
1022                 } else if (tmptok == "Formula") {
1023                         inset = new InsetFormula;
1024                 } else if (tmptok == "Figure") {
1025                         inset = new InsetFig(100, 100, *this);
1026                 } else if (tmptok == "Info") {
1027                         inset = new InsetInfo;
1028                 } else if (tmptok == "Include") {
1029                         InsetCommandParams p( "Include" );
1030                         inset = new InsetInclude(p, *this);
1031                 } else if (tmptok == "ERT") {
1032                         inset = new InsetERT;
1033                 } else if (tmptok == "Tabular") {
1034                         inset = new InsetTabular(*this);
1035                 } else if (tmptok == "Text") {
1036                         inset = new InsetText;
1037                 } else if (tmptok == "Foot") {
1038                         inset = new InsetFoot;
1039                 } else if (tmptok == "Marginal") {
1040                         inset = new InsetMarginal;
1041                 } else if (tmptok == "Minipage") {
1042                         inset = new InsetMinipage;
1043                 } else if (tmptok == "Float") {
1044                         lex.next();
1045                         string tmptok = lex.GetString();
1046                         inset = new InsetFloat(tmptok);
1047                 } else if (tmptok == "List") {
1048                         inset = new InsetList;
1049                 } else if (tmptok == "Theorem") {
1050                         inset = new InsetList;
1051                 } else if (tmptok == "Caption") {
1052                         inset = new InsetCaption;
1053                 } else if (tmptok == "GRAPHICS") {
1054                         inset = new InsetGraphics;
1055                 }
1056                 
1057                 if (inset) inset->Read(this, lex);
1058         }
1059         
1060         if (inset) {
1061                 par->InsertInset(pos, inset, font);
1062                 ++pos;
1063         }
1064 }
1065
1066
1067 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1068 {
1069         if (lex.IsOK()) {
1070                 lex.next();
1071                 string const token(lex.GetString());
1072                 if (token == "\\lyxformat") { // the first token _must_ be...
1073                         lex.EatLine();
1074 #if 0
1075                         format = lex.GetFloat();
1076                         if (format > 1.0) {
1077                                 if (LYX_FORMAT - format > 0.05) {
1078                                         lyxerr << fmt(_("Warning: need lyxformat %.2f but found %.2f"),
1079                                                       LYX_FORMAT, format) << endl;
1080                                 }
1081                                 if (format - LYX_FORMAT > 0.05) {
1082                                         lyxerr << fmt(_("ERROR: need lyxformat %.2f but found %.2f"),
1083                                                       LYX_FORMAT, format) << endl;
1084                                 }
1085                                 bool the_end = readLyXformat2(lex, par);
1086                                 // Formats >= 2.13 support "\the_end" marker
1087                                 if (format < 2.13)
1088                                         the_end = true;
1089
1090                                 setPaperStuff();
1091
1092                                 if (!the_end)
1093                                         WriteAlert(_("Warning!"),
1094                                                    _("Reading of document is not complete"),
1095                                                    _("Maybe the document is truncated"));
1096                                 // We simulate a safe reading anyways to allow
1097                                 // users to take the chance... (Asger)
1098                                 return true;
1099                         } // format < 1.0
1100                         else {
1101                                 WriteAlert(_("ERROR!"),
1102                                            _("Old LyX file format found. "
1103                                              "Use LyX 0.10.x to read this!"));
1104                                 return false;
1105                         }
1106
1107 #else
1108                         string tmp_format = lex.GetString();
1109                         //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1110                         // if present remove ".," from string.
1111                         string::size_type dot = tmp_format.find_first_of(".,");
1112                         //lyxerr << "           dot found at " << dot << endl;
1113                         if (dot != string::npos)
1114                                 tmp_format.erase(dot, 1);
1115                         file_format = strToInt(tmp_format);
1116                         if (file_format == LYX_FORMAT) {
1117                                 // current format
1118                         } else if (file_format > LYX_FORMAT) {
1119                                 // future format
1120                                 WriteAlert(_("Warning!"),
1121                                            _("LyX file format is newer that what"),
1122                                            _("is supported in this LyX version. Expect some problems."));
1123                                 
1124                         } else if (file_format < LYX_FORMAT) {
1125                                 // old formats
1126                                 if (file_format < 200) {
1127                                         WriteAlert(_("ERROR!"),
1128                                                    _("Old LyX file format found. "
1129                                                      "Use LyX 0.10.x to read this!"));
1130                                         return false;
1131                                 }
1132                         }
1133                         bool the_end = readLyXformat2(lex, par);
1134                         setPaperStuff();
1135                         // the_end was added in 213
1136                         if (file_format < 213)
1137                                 the_end = true;
1138
1139                         if (!the_end)
1140                                 WriteAlert(_("Warning!"),
1141                                            _("Reading of document is not complete"),
1142                                            _("Maybe the document is truncated"));
1143                         return true;
1144 #endif
1145                 } else { // "\\lyxformat" not found
1146                         WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1147                 }
1148         } else
1149                 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1150         return false;
1151 }
1152                     
1153
1154
1155 // Should probably be moved to somewhere else: BufferView? LyXView?
1156 bool Buffer::save() const
1157 {
1158         // We don't need autosaves in the immediate future. (Asger)
1159         resetAutosaveTimers();
1160
1161         // make a backup
1162         string s;
1163         if (lyxrc.make_backup) {
1164                 s = fileName() + '~';
1165                 if (!lyxrc.backupdir_path.empty())
1166                         s = AddName(lyxrc.backupdir_path,
1167                                     subst(CleanupPath(s),'/','!'));
1168
1169                 // Rename is the wrong way of making a backup,
1170                 // this is the correct way.
1171                 /* truss cp fil fil2:
1172                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1173                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1174                    open("LyXVC.lyx", O_RDONLY)                     = 3
1175                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1176                    fstat(4, 0xEFFFF508)                            = 0
1177                    fstat(3, 0xEFFFF508)                            = 0
1178                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1179                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1180                    read(3, 0xEFFFD4A0, 8192)                       = 0
1181                    close(4)                                        = 0
1182                    close(3)                                        = 0
1183                    chmod("LyXVC3.lyx", 0100644)                    = 0
1184                    lseek(0, 0, SEEK_CUR)                           = 46440
1185                    _exit(0)
1186                 */
1187
1188                 // Should proabaly have some more error checking here.
1189                 // Should be cleaned up in 0.13, at least a bit.
1190                 // Doing it this way, also makes the inodes stay the same.
1191                 // This is still not a very good solution, in particular we
1192                 // might loose the owner of the backup.
1193                 FileInfo finfo(fileName());
1194                 if (finfo.exist()) {
1195                         mode_t fmode = finfo.getMode();
1196                         struct utimbuf times = {
1197                                 finfo.getAccessTime(),
1198                                 finfo.getModificationTime() };
1199
1200                         ifstream ifs(fileName().c_str());
1201                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1202                         if (ifs && ofs) {
1203                                 ofs << ifs.rdbuf();
1204                                 ifs.close();
1205                                 ofs.close();
1206                                 ::chmod(s.c_str(), fmode);
1207                                 
1208                                 if (::utime(s.c_str(), &times)) {
1209                                         lyxerr << "utime error." << endl;
1210                                 }
1211                         } else {
1212                                 lyxerr << "LyX was not able to make "
1213                                         "backupcopy. Beware." << endl;
1214                         }
1215                 }
1216         }
1217         
1218         if (writeFile(fileName(), false)) {
1219                 markLyxClean();
1220                 removeAutosaveFile(fileName());
1221         } else {
1222                 // Saving failed, so backup is not backup
1223                 if (lyxrc.make_backup) {
1224                         lyx::rename(s, fileName());
1225                 }
1226                 return false;
1227         }
1228         return true;
1229 }
1230
1231
1232 // Returns false if unsuccesful
1233 bool Buffer::writeFile(string const & fname, bool flag) const
1234 {
1235         // if flag is false writeFile will not create any GUI
1236         // warnings, only cerr.
1237         // Needed for autosave in background or panic save (Matthias 120496)
1238
1239         if (read_only && (fname == filename)) {
1240                 // Here we should come with a question if we should
1241                 // perform the write anyway.
1242                 if (flag)
1243                         lyxerr << _("Error! Document is read-only: ")
1244                                << fname << endl;
1245                 else
1246                         WriteAlert(_("Error! Document is read-only: "),
1247                                    fname);
1248                 return false;
1249         }
1250
1251         FileInfo finfo(fname);
1252         if (finfo.exist() && !finfo.writable()) {
1253                 // Here we should come with a question if we should
1254                 // try to do the save anyway. (i.e. do a chmod first)
1255                 if (flag)
1256                         lyxerr << _("Error! Cannot write file: ")
1257                                << fname << endl;
1258                 else
1259                         WriteFSAlert(_("Error! Cannot write file: "),
1260                                      fname);
1261                 return false;
1262         }
1263
1264         ofstream ofs(fname.c_str());
1265         if (!ofs) {
1266                 if (flag)
1267                         lyxerr << _("Error! Cannot open file: ")
1268                                << fname << endl;
1269                 else
1270                         WriteFSAlert(_("Error! Cannot open file: "),
1271                                      fname);
1272                 return false;
1273         }
1274
1275 #ifdef HAVE_LOCALE
1276         // Use the standard "C" locale for file output.
1277         ofs.imbue(std::locale::classic());
1278 #endif
1279
1280         // The top of the file should not be written by params.
1281
1282         // write out a comment in the top of the file
1283         ofs << '#' << LYX_DOCVERSION 
1284             << " created this file. For more info see http://www.lyx.org/\n";
1285 #if 0
1286         ofs.setf(ios::showpoint|ios::fixed);
1287         ofs.precision(2);
1288 #ifndef HAVE_LOCALE
1289         char dummy_format[512];
1290         sprintf(dummy_format, "%.2f", LYX_FORMAT);
1291         ofs << "\\lyxformat " <<  dummy_format << "\n";
1292 #else
1293         ofs << "\\lyxformat " << setw(4) <<  LYX_FORMAT << "\n";
1294 #endif
1295 #else
1296         ofs << "\\lyxformat " << LYX_FORMAT << "\n";
1297 #endif
1298         // now write out the buffer paramters.
1299         params.writeFile(ofs);
1300
1301         char footnoteflag = 0;
1302         char depth = 0;
1303
1304         // this will write out all the paragraphs
1305         // using recursive descent.
1306         paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1307
1308         // Write marker that shows file is complete
1309         ofs << "\n\\the_end" << endl;
1310
1311         ofs.close();
1312
1313         // how to check if close went ok?
1314         // Following is an attempt... (BE 20001011)
1315         
1316         // good() returns false if any error occured, including some
1317         //        formatting error.
1318         // bad()  returns true if something bad happened in the buffer,
1319         //        which should include file system full errors.
1320
1321         bool status = true;
1322         if (!ofs.good()) {
1323                 status = false;
1324 #if 0
1325                 if (ofs.bad()) {
1326                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1327                 } else {
1328                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1329                                << endl;
1330                 }
1331 #endif
1332         }
1333         
1334         return status;
1335 }
1336
1337
1338 string const Buffer::asciiParagraph(LyXParagraph const * par,
1339                                     unsigned int linelen) const
1340 {
1341         ostringstream buffer;
1342         LyXFont font1;
1343         LyXFont font2;
1344         Inset const * inset;
1345         char c;
1346 #ifndef NEW_INSETS
1347         LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1348 #endif
1349         char depth = 0;
1350         int ltype = 0;
1351         int ltype_depth = 0;
1352         unsigned int currlinelen = 0;
1353         bool ref_printed = false;
1354
1355         int noparbreak = 0;
1356         int islatex = 0;
1357         if (
1358 #ifndef NEW_INSETS
1359                 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1360 #endif
1361                 !par->previous
1362 #ifndef NEW_INSETS
1363                 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1364 #endif
1365                 ){
1366 #ifndef NEW_INSETS
1367                 /* begins a footnote environment ? */ 
1368                 if (footnoteflag != par->footnoteflag) {
1369                         footnoteflag = par->footnoteflag;
1370                         if (footnoteflag) {
1371                                 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1372                                 if ((linelen > 0) &&
1373                                     ((currlinelen + j) > linelen)) {
1374                                         buffer << "\n";
1375                                         currlinelen = 0;
1376                                 }
1377                                 buffer << "(["
1378                                        << string_footnotekinds[par->footnotekind]
1379                                        << "] ";
1380                                 currlinelen += j;
1381                         }
1382                 }
1383 #endif
1384                 /* begins or ends a deeper area ?*/ 
1385                 if (depth != par->depth) {
1386                         if (par->depth > depth) {
1387                                 while (par->depth > depth) {
1388                                         ++depth;
1389                                 }
1390                         }
1391                         else {
1392                                 while (par->depth < depth) {
1393                                         --depth;
1394                                 }
1395                         }
1396                 }
1397                 
1398                 /* First write the layout */
1399                 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1400                 if (tmp == "Itemize") {
1401                         ltype = 1;
1402                         ltype_depth = depth+1;
1403                 } else if (tmp == "Enumerate") {
1404                         ltype = 2;
1405                         ltype_depth = depth+1;
1406                 } else if (strstr(tmp.c_str(), "ection")) {
1407                         ltype = 3;
1408                         ltype_depth = depth+1;
1409                 } else if (strstr(tmp.c_str(), "aragraph")) {
1410                         ltype = 4;
1411                         ltype_depth = depth+1;
1412                 } else if (tmp == "Description") {
1413                         ltype = 5;
1414                         ltype_depth = depth+1;
1415                 } else if (tmp == "Abstract") {
1416                         ltype = 6;
1417                         ltype_depth = 0;
1418                 } else if (tmp == "Bibliography") {
1419                         ltype = 7;
1420                         ltype_depth = 0;
1421                 } else {
1422                         ltype = 0;
1423                         ltype_depth = 0;
1424                 }
1425                 
1426                 /* maybe some vertical spaces */ 
1427                 
1428                 /* the labelwidthstring used in lists */ 
1429                 
1430                 /* some lines? */ 
1431                 
1432                 /* some pagebreaks? */ 
1433                 
1434                 /* noindent ? */ 
1435                 
1436                 /* what about the alignment */ 
1437         } else {
1438 #ifndef NEW_INSETS
1439                 /* dummy layout, that means a footnote ended */ 
1440                 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1441                 buffer << ") ";
1442                 noparbreak = 1;
1443 #else
1444                 lyxerr << "Should this ever happen?" << endl;
1445 #endif
1446         }
1447       
1448         font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1449         for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1450                 if (!i &&
1451 #ifndef NEW_INSETS
1452                     !footnoteflag &&
1453 #endif
1454                     !noparbreak) {
1455                         if (linelen > 0)
1456                                 buffer << "\n\n";
1457                         for (char j = 0; j < depth; ++j)
1458                                 buffer << "  ";
1459                         currlinelen = depth * 2;
1460                         switch (ltype) {
1461                         case 0: /* Standard */
1462                         case 4: /* (Sub)Paragraph */
1463                         case 5: /* Description */
1464                                 break;
1465                         case 6: /* Abstract */
1466                                 if (linelen > 0)
1467                                         buffer << "Abstract\n\n";
1468                                 else
1469                                         buffer << "Abstract: ";
1470                                 break;
1471                         case 7: /* Bibliography */
1472                                 if (!ref_printed) {
1473                                         if (linelen > 0)
1474                                                 buffer << "References\n\n";
1475                                         else
1476                                                 buffer << "References: ";
1477                                         ref_printed = true;
1478                                 }
1479                                 break;
1480                         default:
1481                                 buffer << par->labelstring << " ";
1482                                 break;
1483                         }
1484                         if (ltype_depth > depth) {
1485                                 for (char j = ltype_depth - 1; j > depth; --j)
1486                                         buffer << "  ";
1487                                 currlinelen += (ltype_depth-depth)*2;
1488                         }
1489                 }
1490                 font2 = par->GetFontSettings(params, i);
1491                 if (font1.latex() != font2.latex()) {
1492                         if (font2.latex() == LyXFont::OFF)
1493                                 islatex = 0;
1494                         else
1495                                 islatex = 1;
1496                 } else {
1497                         islatex = 0;
1498                 }
1499                 c = par->GetChar(i);
1500                 if (islatex)
1501                         continue;
1502                 switch (c) {
1503                 case LyXParagraph::META_INSET:
1504                         if ((inset = par->GetInset(i))) {
1505                                 if (!inset->Ascii(this, buffer)) {
1506                                         string dummy;
1507                                         string s = rsplit(buffer.str().c_str(),
1508                                                           dummy, '\n');
1509                                         currlinelen += s.length();
1510                                 } else {
1511                                         // to be sure it breaks paragraph
1512                                         currlinelen += linelen;
1513                                 }
1514                         }
1515                         break;
1516                 case LyXParagraph::META_NEWLINE:
1517                         if (linelen > 0) {
1518                                 buffer << "\n";
1519                                 for (char j = 0; j < depth; ++j)
1520                                         buffer << "  ";
1521                         }
1522                         currlinelen = depth * 2;
1523                         if (ltype_depth > depth) {
1524                                 for (char j = ltype_depth;
1525                                     j > depth; --j)
1526                                         buffer << "  ";
1527                                 currlinelen += (ltype_depth - depth) * 2;
1528                         }
1529                         break;
1530                 case LyXParagraph::META_HFILL: 
1531                         buffer << "\t";
1532                         break;
1533                 case '\\':
1534                         buffer << "\\";
1535                         break;
1536                 default:
1537                         if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1538                             (c == ' ') && ((i + 2) < par->size()))
1539                         {
1540                                 buffer << "\n";
1541                                 for (char j = 0; j < depth; ++j)
1542                                         buffer << "  ";
1543                                 currlinelen = depth * 2;
1544                                 if (ltype_depth > depth) {
1545                                         for (char j = ltype_depth;
1546                                             j > depth; --j)
1547                                                 buffer << "  ";
1548                                         currlinelen += (ltype_depth-depth)*2;
1549                                 }
1550                         } else if (c != '\0')
1551                                 buffer << c;
1552                         else if (c == '\0')
1553                                 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1554                         ++currlinelen;
1555                         break;
1556                 }
1557         }
1558         return buffer.str().c_str();
1559 }
1560
1561
1562 void Buffer::writeFileAscii(string const & fname, int linelen) 
1563 {
1564         ofstream ofs(fname.c_str());
1565         if (!ofs) {
1566                 WriteFSAlert(_("Error: Cannot write file:"), fname);
1567                 return;
1568         }
1569         writeFileAscii(ofs, linelen);
1570 }
1571
1572
1573 void Buffer::writeFileAscii(ostream & ofs, int linelen) 
1574 {
1575         LyXParagraph * par = paragraph;
1576         while (par) {
1577                 ofs << asciiParagraph(par, linelen);
1578                 par = par->next;
1579         }
1580         ofs << "\n";
1581 }
1582
1583
1584 void Buffer::makeLaTeXFile(string const & fname, 
1585                            string const & original_path,
1586                            bool nice, bool only_body)
1587 {
1588         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1589         
1590         niceFile = nice; // this will be used by Insetincludes.
1591
1592         tex_code_break_column = lyxrc.ascii_linelen;
1593
1594         LyXTextClass const & tclass =
1595                 textclasslist.TextClass(params.textclass);
1596
1597         ofstream ofs(fname.c_str());
1598         if (!ofs) {
1599                 WriteFSAlert(_("Error: Cannot open file: "), fname);
1600                 return;
1601         }
1602         
1603         // validate the buffer.
1604         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1605         LaTeXFeatures features(params, tclass.numLayouts());
1606         validate(features);
1607         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1608         
1609         texrow.reset();
1610         // The starting paragraph of the coming rows is the 
1611         // first paragraph of the document. (Asger)
1612         texrow.start(paragraph, 0);
1613
1614         if (!only_body && nice) {
1615                 ofs << "%% " LYX_DOCVERSION " created this file.  "
1616                         "For more info, see http://www.lyx.org/.\n"
1617                         "%% Do not edit unless you really know what "
1618                         "you are doing.\n";
1619                 texrow.newline();
1620                 texrow.newline();
1621         }
1622         lyxerr.debug() << "lyx header finished" << endl;
1623         // There are a few differences between nice LaTeX and usual files:
1624         // usual is \batchmode and has a 
1625         // special input@path to allow the including of figures
1626         // with either \input or \includegraphics (what figinsets do).
1627         // batchmode is not set if there is a tex_code_break_column.
1628         // In this case somebody is interested in the generated LaTeX,
1629         // so this is OK. input@path is set when the actual parameter
1630         // original_path is set. This is done for usual tex-file, but not
1631         // for nice-latex-file. (Matthias 250696)
1632         if (!only_body) {
1633                 if (!nice){
1634                         // code for usual, NOT nice-latex-file
1635                         ofs << "\\batchmode\n"; // changed
1636                         // from \nonstopmode
1637                         texrow.newline();
1638                 }
1639                 if (!original_path.empty()) {
1640                         ofs << "\\makeatletter\n"
1641                             << "\\def\\input@path{{"
1642                             << original_path << "/}}\n"
1643                             << "\\makeatother\n";
1644                         texrow.newline();
1645                         texrow.newline();
1646                         texrow.newline();
1647                 }
1648                 
1649                 ofs << "\\documentclass";
1650                 
1651                 string options; // the document class options.
1652                 
1653                 if (tokenPos(tclass.opt_fontsize(),
1654                              '|', params.fontsize) >= 0) {
1655                         // only write if existing in list (and not default)
1656                         options += params.fontsize;
1657                         options += "pt,";
1658                 }
1659                 
1660                 
1661                 if (!params.use_geometry &&
1662                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1663                         switch (params.papersize) {
1664                         case BufferParams::PAPER_A4PAPER:
1665                                 options += "a4paper,";
1666                                 break;
1667                         case BufferParams::PAPER_USLETTER:
1668                                 options += "letterpaper,";
1669                                 break;
1670                         case BufferParams::PAPER_A5PAPER:
1671                                 options += "a5paper,";
1672                                 break;
1673                         case BufferParams::PAPER_B5PAPER:
1674                                 options += "b5paper,";
1675                                 break;
1676                         case BufferParams::PAPER_EXECUTIVEPAPER:
1677                                 options += "executivepaper,";
1678                                 break;
1679                         case BufferParams::PAPER_LEGALPAPER:
1680                                 options += "legalpaper,";
1681                                 break;
1682                         }
1683                 }
1684
1685                 // if needed
1686                 if (params.sides != tclass.sides()) {
1687                         switch (params.sides) {
1688                         case LyXTextClass::OneSide:
1689                                 options += "oneside,";
1690                                 break;
1691                         case LyXTextClass::TwoSides:
1692                                 options += "twoside,";
1693                                 break;
1694                         }
1695
1696                 }
1697
1698                 // if needed
1699                 if (params.columns != tclass.columns()) {
1700                         if (params.columns == 2)
1701                                 options += "twocolumn,";
1702                         else
1703                                 options += "onecolumn,";
1704                 }
1705
1706                 if (!params.use_geometry 
1707                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1708                         options += "landscape,";
1709                 
1710                 // language should be a parameter to \documentclass
1711                 bool use_babel = false;
1712                 if (params.language->babel() == "hebrew"
1713                     && default_language->babel() != "hebrew")
1714                          // This seems necessary
1715                         features.UsedLanguages.insert(default_language);
1716 #ifdef DO_USE_DEFAULT_LANGUAGE
1717                 if (params.language->lang() != "default" ||
1718                     !features.UsedLanguages.empty()) {
1719 #endif
1720                         use_babel = true;
1721                         for (LaTeXFeatures::LanguageList::const_iterator cit =
1722                                      features.UsedLanguages.begin();
1723                              cit != features.UsedLanguages.end(); ++cit)
1724                                 options += (*cit)->babel() + ",";
1725                         options += params.language->babel() + ',';
1726 #ifdef DO_USE_DEFAULT_LANGUAGE
1727                 }
1728 #endif
1729
1730                 // the user-defined options
1731                 if (!params.options.empty()) {
1732                         options += params.options + ',';
1733                 }
1734                 
1735                 if (!options.empty()){
1736                         options = strip(options, ',');
1737                         ofs << '[' << options << ']';
1738                 }
1739                 
1740                 ofs << '{'
1741                     << textclasslist.LatexnameOfClass(params.textclass)
1742                     << "}\n";
1743                 texrow.newline();
1744                 // end of \documentclass defs
1745                 
1746                 // font selection must be done before loading fontenc.sty
1747                 // The ae package is not needed when using OT1 font encoding.
1748                 if (params.fonts != "default" &&
1749                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1750                         ofs << "\\usepackage{" << params.fonts << "}\n";
1751                         texrow.newline();
1752                         if (params.fonts == "ae") {
1753                                 ofs << "\\usepackage{aecompl}\n";
1754                                 texrow.newline();
1755                         }
1756                 }
1757                 // this one is not per buffer
1758                 if (lyxrc.fontenc != "default") {
1759                         ofs << "\\usepackage[" << lyxrc.fontenc
1760                             << "]{fontenc}\n";
1761                         texrow.newline();
1762                 }
1763
1764                 if (params.inputenc == "auto") {
1765                         string const doc_encoding =
1766                                 params.language->encoding()->LatexName();
1767
1768                         // Create a list with all the input encodings used 
1769                         // in the document
1770                         set<string> encodings;
1771                         for (LaTeXFeatures::LanguageList::const_iterator it =
1772                                      features.UsedLanguages.begin();
1773                              it != features.UsedLanguages.end(); ++it)
1774                                 if ((*it)->encoding()->LatexName() != doc_encoding)
1775                                         encodings.insert((*it)->encoding()->LatexName());
1776
1777                         ofs << "\\usepackage[";
1778                         std::copy(encodings.begin(), encodings.end(),
1779                                   std::ostream_iterator<string>(ofs, ","));
1780                         ofs << doc_encoding << "]{inputenc}\n";
1781                         texrow.newline();
1782                 } else if (params.inputenc != "default") {
1783                         ofs << "\\usepackage[" << params.inputenc
1784                             << "]{inputenc}\n";
1785                         texrow.newline();
1786                 }
1787
1788                 // At the very beginning the text parameters.
1789                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1790                         switch (params.paperpackage) {
1791                         case BufferParams::PACKAGE_A4:
1792                                 ofs << "\\usepackage{a4}\n";
1793                                 texrow.newline();
1794                                 break;
1795                         case BufferParams::PACKAGE_A4WIDE:
1796                                 ofs << "\\usepackage{a4wide}\n";
1797                                 texrow.newline();
1798                                 break;
1799                         case BufferParams::PACKAGE_WIDEMARGINSA4:
1800                                 ofs << "\\usepackage[widemargins]{a4}\n";
1801                                 texrow.newline();
1802                                 break;
1803                         }
1804                 }
1805                 if (params.use_geometry) {
1806                         ofs << "\\usepackage{geometry}\n";
1807                         texrow.newline();
1808                         ofs << "\\geometry{verbose";
1809                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1810                                 ofs << ",landscape";
1811                         switch (params.papersize2) {
1812                         case BufferParams::VM_PAPER_CUSTOM:
1813                                 if (!params.paperwidth.empty())
1814                                         ofs << ",paperwidth="
1815                                             << params.paperwidth;
1816                                 if (!params.paperheight.empty())
1817                                         ofs << ",paperheight="
1818                                             << params.paperheight;
1819                                 break;
1820                         case BufferParams::VM_PAPER_USLETTER:
1821                                 ofs << ",letterpaper";
1822                                 break;
1823                         case BufferParams::VM_PAPER_USLEGAL:
1824                                 ofs << ",legalpaper";
1825                                 break;
1826                         case BufferParams::VM_PAPER_USEXECUTIVE:
1827                                 ofs << ",executivepaper";
1828                                 break;
1829                         case BufferParams::VM_PAPER_A3:
1830                                 ofs << ",a3paper";
1831                                 break;
1832                         case BufferParams::VM_PAPER_A4:
1833                                 ofs << ",a4paper";
1834                                 break;
1835                         case BufferParams::VM_PAPER_A5:
1836                                 ofs << ",a5paper";
1837                                 break;
1838                         case BufferParams::VM_PAPER_B3:
1839                                 ofs << ",b3paper";
1840                                 break;
1841                         case BufferParams::VM_PAPER_B4:
1842                                 ofs << ",b4paper";
1843                                 break;
1844                         case BufferParams::VM_PAPER_B5:
1845                                 ofs << ",b5paper";
1846                                 break;
1847                         default:
1848                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1849                                 switch (lyxrc.default_papersize) {
1850                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1851                                 case BufferParams::PAPER_USLETTER:
1852                                         ofs << ",letterpaper";
1853                                         break;
1854                                 case BufferParams::PAPER_LEGALPAPER:
1855                                         ofs << ",legalpaper";
1856                                         break;
1857                                 case BufferParams::PAPER_EXECUTIVEPAPER:
1858                                         ofs << ",executivepaper";
1859                                         break;
1860                                 case BufferParams::PAPER_A3PAPER:
1861                                         ofs << ",a3paper";
1862                                         break;
1863                                 case BufferParams::PAPER_A4PAPER:
1864                                         ofs << ",a4paper";
1865                                         break;
1866                                 case BufferParams::PAPER_A5PAPER:
1867                                         ofs << ",a5paper";
1868                                         break;
1869                                 case BufferParams::PAPER_B5PAPER:
1870                                         ofs << ",b5paper";
1871                                         break;
1872                                 }
1873                         }
1874                         if (!params.topmargin.empty())
1875                                 ofs << ",tmargin=" << params.topmargin;
1876                         if (!params.bottommargin.empty())
1877                                 ofs << ",bmargin=" << params.bottommargin;
1878                         if (!params.leftmargin.empty())
1879                                 ofs << ",lmargin=" << params.leftmargin;
1880                         if (!params.rightmargin.empty())
1881                                 ofs << ",rmargin=" << params.rightmargin;
1882                         if (!params.headheight.empty())
1883                                 ofs << ",headheight=" << params.headheight;
1884                         if (!params.headsep.empty())
1885                                 ofs << ",headsep=" << params.headsep;
1886                         if (!params.footskip.empty())
1887                                 ofs << ",footskip=" << params.footskip;
1888                         ofs << "}\n";
1889                         texrow.newline();
1890                 }
1891                 if (params.use_amsmath
1892                     && !tclass.provides(LyXTextClass::amsmath)) {
1893                         ofs << "\\usepackage{amsmath}\n";
1894                         texrow.newline();
1895                 }
1896
1897                 if (tokenPos(tclass.opt_pagestyle(),
1898                              '|', params.pagestyle) >= 0) {
1899                         if (params.pagestyle == "fancy") {
1900                                 ofs << "\\usepackage{fancyhdr}\n";
1901                                 texrow.newline();
1902                         }
1903                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1904                         texrow.newline();
1905                 }
1906
1907                 // We try to load babel late, in case it interferes
1908                 // with other packages.
1909                 if (use_babel) {
1910                         ofs << lyxrc.language_package << endl;
1911                         texrow.newline();
1912                 }
1913
1914                 if (params.secnumdepth != tclass.secnumdepth()) {
1915                         ofs << "\\setcounter{secnumdepth}{"
1916                             << params.secnumdepth
1917                             << "}\n";
1918                         texrow.newline();
1919                 }
1920                 if (params.tocdepth != tclass.tocdepth()) {
1921                         ofs << "\\setcounter{tocdepth}{"
1922                             << params.tocdepth
1923                             << "}\n";
1924                         texrow.newline();
1925                 }
1926                 
1927                 if (params.paragraph_separation) {
1928                         switch (params.defskip.kind()) {
1929                         case VSpace::SMALLSKIP: 
1930                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1931                                 break;
1932                         case VSpace::MEDSKIP:
1933                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1934                                 break;
1935                         case VSpace::BIGSKIP:
1936                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1937                                 break;
1938                         case VSpace::LENGTH:
1939                                 ofs << "\\setlength\\parskip{"
1940                                     << params.defskip.length().asLatexString()
1941                                     << "}\n";
1942                                 break;
1943                         default: // should never happen // Then delete it.
1944                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1945                                 break;
1946                         }
1947                         texrow.newline();
1948                         
1949                         ofs << "\\setlength\\parindent{0pt}\n";
1950                         texrow.newline();
1951                 }
1952
1953                 // Now insert the LyX specific LaTeX commands...
1954
1955                 // The optional packages;
1956                 string preamble(features.getPackages());
1957
1958                 // this might be useful...
1959                 preamble += "\n\\makeatletter\n";
1960
1961                 // Some macros LyX will need
1962                 string tmppreamble(features.getMacros());
1963
1964                 if (!tmppreamble.empty()) {
1965                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1966                                 "LyX specific LaTeX commands.\n"
1967                                 + tmppreamble + '\n';
1968                 }
1969
1970                 // the text class specific preamble 
1971                 tmppreamble = features.getTClassPreamble();
1972                 if (!tmppreamble.empty()) {
1973                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1974                                 "Textclass specific LaTeX commands.\n"
1975                                 + tmppreamble + '\n';
1976                 }
1977
1978                 /* the user-defined preamble */
1979                 if (!params.preamble.empty()) {
1980                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1981                                 "User specified LaTeX commands.\n"
1982                                 + params.preamble + '\n';
1983                 }
1984
1985                 preamble += "\\makeatother\n";
1986
1987                 // Itemize bullet settings need to be last in case the user
1988                 // defines their own bullets that use a package included
1989                 // in the user-defined preamble -- ARRae
1990                 // Actually it has to be done much later than that
1991                 // since some packages like frenchb make modifications
1992                 // at \begin{document} time -- JMarc 
1993                 string bullets_def;
1994                 for (int i = 0; i < 4; ++i) {
1995                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1996                                 if (bullets_def.empty())
1997                                         bullets_def="\\AtBeginDocument{\n";
1998                                 bullets_def += "  \\renewcommand{\\labelitemi";
1999                                 switch (i) {
2000                                 // `i' is one less than the item to modify
2001                                 case 0:
2002                                         break;
2003                                 case 1:
2004                                         bullets_def += 'i';
2005                                         break;
2006                                 case 2:
2007                                         bullets_def += "ii";
2008                                         break;
2009                                 case 3:
2010                                         bullets_def += 'v';
2011                                         break;
2012                                 }
2013                                 bullets_def += "}{" + 
2014                                   params.user_defined_bullets[i].getText() 
2015                                   + "}\n";
2016                         }
2017                 }
2018
2019                 if (!bullets_def.empty())
2020                   preamble += bullets_def + "}\n\n";
2021
2022                 for (int j = countChar(preamble, '\n'); j-- ;) {
2023                         texrow.newline();
2024                 }
2025
2026                 ofs << preamble;
2027
2028                 // make the body.
2029                 ofs << "\\begin{document}\n";
2030                 texrow.newline();
2031         } // only_body
2032         lyxerr.debug() << "preamble finished, now the body." << endl;
2033 #ifdef DO_USE_DEFAULT_LANGUAGE
2034         if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
2035 #else
2036         if (!lyxrc.language_auto_begin) {
2037 #endif
2038                 ofs << subst(lyxrc.language_command_begin, "$$lang",
2039                              params.language->babel())
2040                     << endl;
2041                 texrow.newline();
2042         }
2043         
2044         latexParagraphs(ofs, paragraph, 0, texrow);
2045
2046         // add this just in case after all the paragraphs
2047         ofs << endl;
2048         texrow.newline();
2049
2050 #ifdef DO_USE_DEFAULT_LANGUAGE
2051         if (!lyxrc.language_auto_end && params.language->lang() != "default") {
2052 #else
2053                 if (!lyxrc.language_auto_end) {
2054 #endif
2055                 ofs << subst(lyxrc.language_command_end, "$$lang",
2056                              params.language->babel())
2057                     << endl;
2058                 texrow.newline();
2059         }
2060
2061         if (!only_body) {
2062                 ofs << "\\end{document}\n";
2063                 texrow.newline();
2064         
2065                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2066         } else {
2067                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2068                                      << endl;
2069         }
2070
2071         // Just to be sure. (Asger)
2072         texrow.newline();
2073
2074         // tex_code_break_column's value is used to decide
2075         // if we are in batchmode or not (within mathed_write()
2076         // in math_write.C) so we must set it to a non-zero
2077         // value when we leave otherwise we save incorrect .lyx files.
2078         tex_code_break_column = lyxrc.ascii_linelen;
2079
2080         ofs.close();
2081         if (ofs.fail()) {
2082                 lyxerr << "File was not closed properly." << endl;
2083         }
2084         
2085         lyxerr.debug() << "Finished making latex file." << endl;
2086 }
2087
2088
2089 //
2090 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2091 //
2092 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2093                              LyXParagraph * endpar, TexRow & texrow) const
2094 {
2095         bool was_title = false;
2096         bool already_title = false;
2097         std::ostringstream ftnote;
2098         TexRow ft_texrow;
2099         int ftcount = 0;
2100
2101         // if only_body
2102         while (par != endpar) {
2103 #ifndef NEW_INSETS
2104                 if (par->IsDummy())
2105                         lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2106                                              << endl;
2107 #endif
2108                 LyXLayout const & layout =
2109                         textclasslist.Style(params.textclass,
2110                                             par->layout);
2111             
2112                 if (layout.intitle) {
2113                         if (already_title) {
2114                                 lyxerr <<"Error in latexParagraphs: You"
2115                                         " should not mix title layouts"
2116                                         " with normal ones." << endl;
2117                         } else
2118                                 was_title = true;
2119                 } else if (was_title && !already_title) {
2120                         ofs << "\\maketitle\n";
2121                         texrow.newline();
2122                         already_title = true;
2123                         was_title = false;                  
2124                 }
2125                 // We are at depth 0 so we can just use
2126                 // ordinary \footnote{} generation
2127                 // flag this with ftcount
2128                 ftcount = -1;
2129                 if (layout.isEnvironment()
2130                     || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2131                         par = par->TeXEnvironment(this, params, ofs, texrow
2132 #ifndef NEW_INSETS
2133                                                   ,ftnote, ft_texrow, ftcount
2134 #endif
2135                                 );
2136                 } else {
2137                         par = par->TeXOnePar(this, params, ofs, texrow, false
2138 #ifndef NEW_INSETS
2139                                              ,
2140                                              ftnote, ft_texrow, ftcount
2141 #endif
2142                                 );
2143                 }
2144
2145                 // Write out what we've generated...
2146                 if (ftcount >= 1) {
2147                         if (ftcount > 1) {
2148                                 ofs << "\\addtocounter{footnote}{-"
2149                                     << ftcount - 1
2150                                     << '}';
2151                         }
2152                         ofs << ftnote.str();
2153                         texrow += ft_texrow;
2154
2155                         // The extra .c_str() is needed when we use
2156                         // lyxstring instead of the STL string class. 
2157                         ftnote.str(string().c_str());
2158                         ft_texrow.reset();
2159                         ftcount = 0;
2160                 }
2161         }
2162         // It might be that we only have a title in this document
2163         if (was_title && !already_title) {
2164                 ofs << "\\maketitle\n";
2165                 texrow.newline();
2166         }
2167 }
2168
2169
2170 bool Buffer::isLatex() const
2171 {
2172         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2173 }
2174
2175
2176 bool Buffer::isLinuxDoc() const
2177 {
2178         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2179 }
2180
2181
2182 bool Buffer::isLiterate() const
2183 {
2184         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2185 }
2186
2187
2188 bool Buffer::isDocBook() const
2189 {
2190         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2191 }
2192
2193
2194 bool Buffer::isSGML() const
2195 {
2196         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2197                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2198 }
2199
2200
2201 void Buffer::sgmlOpenTag(ostream & os, int depth,
2202                          string const & latexname) const
2203 {
2204         if (latexname != "!-- --")
2205                 os << string(depth, ' ') << "<" << latexname << ">\n";
2206 }
2207
2208
2209 void Buffer::sgmlCloseTag(ostream & os, int depth,
2210                           string const & latexname) const
2211 {
2212         if (latexname != "!-- --")
2213                 os << string(depth, ' ') << "</" << latexname << ">\n";
2214 }
2215
2216
2217 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2218 {
2219         LyXParagraph * par = paragraph;
2220
2221         niceFile = nice; // this will be used by Insetincludes.
2222
2223         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2224         string environment_stack[10];
2225         string item_name;
2226
2227         int depth = 0; // paragraph depth
2228
2229         ofstream ofs(fname.c_str());
2230
2231         if (!ofs) {
2232                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2233                 return;
2234         }
2235
2236         LyXTextClass const & tclass =
2237                 textclasslist.TextClass(params.textclass);
2238
2239         LaTeXFeatures features(params, tclass.numLayouts());
2240         validate(features);
2241
2242         //if (nice)
2243         tex_code_break_column = lyxrc.ascii_linelen;
2244         //else
2245         //tex_code_break_column = 0;
2246
2247         texrow.reset();
2248
2249         if (!body_only) {
2250                 string sgml_includedfiles=features.getIncludedFiles(fname);
2251
2252                 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2253                         ofs << "<!doctype linuxdoc system>\n\n";
2254                 } else {
2255                         ofs << "<!doctype linuxdoc system [ "
2256                             << params.preamble << sgml_includedfiles << " \n]>\n\n";
2257                 }
2258
2259                 if (params.options.empty())
2260                         sgmlOpenTag(ofs, 0, top_element);
2261                 else {
2262                         string top = top_element;
2263                         top += " ";
2264                         top += params.options;
2265                         sgmlOpenTag(ofs, 0, top);
2266                 }
2267         }
2268
2269         ofs << "<!-- "  << LYX_DOCVERSION 
2270             << " created this file. For more info see http://www.lyx.org/"
2271             << " -->\n";
2272
2273         while (par) {
2274                 int desc_on = 0; // description mode
2275                 LyXLayout const & style =
2276                         textclasslist.Style(params.textclass,
2277                                             par->layout);
2278
2279                 // treat <toc> as a special case for compatibility with old code
2280                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2281                         Inset * inset = par->GetInset(0);
2282                         Inset::Code lyx_code = inset->LyxCode();
2283                         if (lyx_code == Inset::TOC_CODE){
2284                                 string const temp = "toc";
2285                                 sgmlOpenTag(ofs, depth, temp);
2286
2287                                 par = par->next;
2288 #ifndef NEW_INSETS
2289                                 linuxDocHandleFootnote(ofs, par, depth);
2290 #endif
2291                                 continue;
2292                         }
2293                 }
2294
2295                 // environment tag closing
2296                 for (; depth > par->depth; --depth) {
2297                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2298                         environment_stack[depth].erase();
2299                 }
2300
2301                 // write opening SGML tags
2302                 switch (style.latextype) {
2303                 case LATEX_PARAGRAPH:
2304                         if (depth == par->depth 
2305                            && !environment_stack[depth].empty()) {
2306                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2307                                 environment_stack[depth].erase();
2308                                 if (depth) 
2309                                         --depth;
2310                                 else
2311                                         ofs << "</p>";
2312                         }
2313                         sgmlOpenTag(ofs, depth, style.latexname());
2314                         break;
2315
2316                 case LATEX_COMMAND:
2317                         if (depth!= 0)
2318                                 LinuxDocError(par, 0,
2319                                               _("Error : Wrong depth for"
2320                                                 " LatexType Command.\n"));
2321
2322                         if (!environment_stack[depth].empty()){
2323                                 sgmlCloseTag(ofs, depth,
2324                                              environment_stack[depth]);
2325                                 ofs << "</p>";
2326                         }
2327
2328                         environment_stack[depth].erase();
2329                         sgmlOpenTag(ofs, depth, style.latexname());
2330                         break;
2331
2332                 case LATEX_ENVIRONMENT:
2333                 case LATEX_ITEM_ENVIRONMENT:
2334                         if (depth == par->depth 
2335                            && environment_stack[depth] != style.latexname()
2336                            && !environment_stack[depth].empty()) {
2337
2338                                 sgmlCloseTag(ofs, depth,
2339                                              environment_stack[depth]);
2340                                 environment_stack[depth].erase();
2341                         }
2342                         if (depth < par->depth) {
2343                                depth = par->depth;
2344                                environment_stack[depth].erase();
2345                         }
2346                         if (environment_stack[depth] != style.latexname()) {
2347                                 if (depth == 0) {
2348                                         string const temp = "p";
2349                                         sgmlOpenTag(ofs, depth, temp);
2350                                 }
2351                                 environment_stack[depth] = style.latexname();
2352                                 sgmlOpenTag(ofs, depth,
2353                                             environment_stack[depth]);
2354                         }
2355                         if (style.latextype == LATEX_ENVIRONMENT) break;
2356
2357                         desc_on = (style.labeltype == LABEL_MANUAL);
2358
2359                         if (desc_on)
2360                                 item_name = "tag";
2361                         else
2362                                 item_name = "item";
2363
2364                         sgmlOpenTag(ofs, depth + 1, item_name);
2365                         break;
2366                 default:
2367                         sgmlOpenTag(ofs, depth, style.latexname());
2368                         break;
2369                 }
2370
2371 #ifndef NEW_INSETS
2372                 do {
2373 #endif
2374                         SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2375
2376                         par = par->next;
2377 #ifndef NEW_INSETS
2378                         linuxDocHandleFootnote(ofs, par, depth);
2379                 }
2380                 while(par && par->IsDummy());
2381 #endif
2382
2383                 ofs << "\n";
2384                 // write closing SGML tags
2385                 switch (style.latextype) {
2386                 case LATEX_COMMAND:
2387                 case LATEX_ENVIRONMENT:
2388                 case LATEX_ITEM_ENVIRONMENT:
2389                         break;
2390                 default:
2391                         sgmlCloseTag(ofs, depth, style.latexname());
2392                         break;
2393                 }
2394         }
2395    
2396         // Close open tags
2397         for (; depth > 0; --depth)
2398                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2399
2400         if (!environment_stack[depth].empty())
2401                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2402
2403         if (!body_only) {
2404                 ofs << "\n\n";
2405                 sgmlCloseTag(ofs, 0, top_element);
2406         }
2407
2408         ofs.close();
2409         // How to check for successful close
2410 }
2411
2412
2413 #ifndef NEW_INSETS
2414 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2415                                     int depth)
2416 {
2417         string const tag = "footnote";
2418
2419         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2420                 sgmlOpenTag(os, depth + 1, tag);
2421                 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2422                 sgmlCloseTag(os, depth + 1, tag);
2423                 par = par->next;
2424         }
2425 }
2426 #endif
2427
2428
2429 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2430                                   int depth, int desc_on,
2431                                   LyXParagraph * & par)
2432 {
2433         LyXParagraph * tpar = par;
2434         while (tpar
2435 #ifndef NEW_INSETS
2436                && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2437 #endif
2438                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2439                                                              "Caption").second))
2440                 tpar = tpar->next;
2441         if (tpar &&
2442             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2443                                                          "Caption").second) {
2444                 sgmlOpenTag(os, depth + 1, inner_tag);
2445                 string extra_par;
2446                 SimpleDocBookOnePar(os, extra_par, tpar,
2447                                     desc_on, depth + 2);
2448                 sgmlCloseTag(os, depth+1, inner_tag);
2449                 if (!extra_par.empty())
2450                         os << extra_par;
2451         }
2452 }
2453
2454
2455 #ifndef NEW_INSETS
2456 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2457                                    int depth)
2458 {
2459         string tag, inner_tag;
2460         string tmp_par, extra_par;
2461         bool inner_span = false;
2462         int desc_on = 4;
2463
2464         // Someone should give this enum a proper name (Lgb)
2465         enum SOME_ENUM {
2466                 NO_ONE,
2467                 FOOTNOTE_LIKE,
2468                 MARGIN_LIKE,
2469                 FIG_LIKE,
2470                 TAB_LIKE
2471         };
2472         SOME_ENUM last = NO_ONE;
2473         SOME_ENUM present = FOOTNOTE_LIKE;
2474
2475         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2476                 if (last == present) {
2477                         if (inner_span) {
2478                                 if (!tmp_par.empty()) {
2479                                         os << tmp_par;
2480                                         tmp_par.erase();
2481                                         sgmlCloseTag(os, depth + 1, inner_tag);
2482                                         sgmlOpenTag(os, depth + 1, inner_tag);
2483                                 }
2484                         } else {
2485                                 os << "\n";
2486                         }
2487                 } else {
2488                         os << tmp_par;
2489                         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2490                                                             inner_tag);
2491                         if (!extra_par.empty()) os << extra_par;
2492                         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2493                         extra_par.erase();
2494
2495                         switch (par->footnotekind) {
2496                         case LyXParagraph::FOOTNOTE:
2497                         case LyXParagraph::ALGORITHM:
2498                                 tag = "footnote";
2499                                 inner_tag = "para";
2500                                 present = FOOTNOTE_LIKE;
2501                                 inner_span = true;
2502                                 break;
2503                         case LyXParagraph::MARGIN:
2504                                 tag = "sidebar";
2505                                 inner_tag = "para";
2506                                 present = MARGIN_LIKE;
2507                                 inner_span = true;
2508                                 break;
2509                         case LyXParagraph::FIG:
2510                         case LyXParagraph::WIDE_FIG:
2511                                 tag = "figure";
2512                                 inner_tag = "title";
2513                                 present = FIG_LIKE;
2514                                 inner_span = false;
2515                                 break;
2516                         case LyXParagraph::TAB:
2517                         case LyXParagraph::WIDE_TAB:
2518                                 tag = "table";
2519                                 inner_tag = "title";
2520                                 present = TAB_LIKE;
2521                                 inner_span = false;
2522                                 break;
2523                         }
2524                         sgmlOpenTag(os, depth, tag);
2525                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2526                                 DocBookHandleCaption(os, inner_tag, depth,
2527                                                      desc_on, par);
2528                                 inner_tag.erase();
2529                         } else {
2530                                 sgmlOpenTag(os, depth + 1, inner_tag);
2531                         }
2532                 }
2533                 // ignore all caption here, we processed them above!!!
2534                 if (par->layout != textclasslist
2535                     .NumberOfLayout(params.textclass,
2536                                     "Caption").second) {
2537                         std::ostringstream ost;
2538                         SimpleDocBookOnePar(ost, extra_par, par,
2539                                             desc_on, depth + 2);
2540                         tmp_par += ost.str().c_str();
2541                 }
2542                 tmp_par = frontStrip(strip(tmp_par));
2543
2544                 last = present;
2545                 par = par->next;
2546         }
2547         os << tmp_par;
2548         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2549         if (!extra_par.empty()) os << extra_par;
2550         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2551 }
2552 #endif
2553
2554
2555 // push a tag in a style stack
2556 void Buffer::push_tag(ostream & os, string const & tag,
2557                       int & pos, char stack[5][3])
2558 {
2559 #ifdef WITH_WARNINGS
2560 #warning Use a real stack! (Lgb)
2561 #endif
2562         // pop all previous tags
2563         for (int j = pos; j >= 0; --j)
2564                 os << "</" << stack[j] << ">";
2565
2566         // add new tag
2567         sprintf(stack[++pos], "%s", tag.c_str());
2568
2569         // push all tags
2570         for (int i = 0; i <= pos; ++i)
2571                 os << "<" << stack[i] << ">";
2572 }
2573
2574
2575 void Buffer::pop_tag(ostream & os, string const & tag,
2576                      int & pos, char stack[5][3])
2577 {
2578 #ifdef WITH_WARNINGS
2579 #warning Use a real stack! (Lgb)
2580 #endif
2581         // Please, Lars, do not remove the global variable. I already
2582         // had to reintroduce it twice! (JMarc)
2583         // but...but... I'll remove it anyway. (well not quite) (Lgb)
2584 #if 0
2585         int j;
2586         
2587         // pop all tags till specified one
2588         for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2589                 os << "</" << stack[j] << ">";
2590
2591         // closes the tag
2592         os << "</" << tag << ">";
2593         
2594         // push all tags, but the specified one
2595         for (j = j + 1; j <= pos; ++j) {
2596                 os << "<" << stack[j] << ">";
2597                 strcpy(stack[j - 1], stack[j]);
2598         }
2599         --pos;
2600 #else
2601         // pop all tags till specified one
2602         int j = pos;
2603         for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2604                 os << "</" << stack[j] << ">";
2605
2606         // closes the tag
2607         os << "</" << tag << ">";
2608         
2609         // push all tags, but the specified one
2610         for (int i = j + 1; i <= pos; ++i) {
2611                 os << "<" << stack[i] << ">";
2612                 strcpy(stack[i - 1], stack[i]);
2613         }
2614         --pos;
2615 #endif
2616 }
2617
2618
2619 // Handle internal paragraph parsing -- layout already processed.
2620
2621 // checks, if newcol chars should be put into this line
2622 // writes newline, if necessary.
2623 static
2624 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2625                           string::size_type newcol)
2626 {
2627         colcount += newcol;
2628         if (colcount > lyxrc.ascii_linelen) {
2629                 os << "\n";
2630                 colcount = newcol; // assume write after this call
2631         }
2632 }
2633
2634
2635 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2636                                   int desc_on, int /*depth*/)
2637 {
2638         LyXFont font1;
2639         char c;
2640         Inset * inset;
2641         LyXParagraph::size_type main_body;
2642         int j;
2643         LyXLayout const & style = textclasslist.Style(params.textclass,
2644                                                       par->GetLayout());
2645
2646         char family_type = 0;               // family font flag 
2647         bool is_bold     = false;           // series font flag 
2648         char shape_type  = 0;               // shape font flag 
2649         bool is_em = false;                 // emphasis (italic) font flag 
2650
2651         int stack_num = -1;          // style stack position
2652         // Can this be rewritten to use a std::stack, please. (Lgb)
2653         char stack[5][3];            // style stack 
2654         string::size_type char_line_count = 5;     // Heuristic choice ;-) 
2655
2656         if (style.labeltype != LABEL_MANUAL)
2657                 main_body = 0;
2658         else
2659                 main_body = par->BeginningOfMainBody();
2660
2661         // gets paragraph main font
2662         if (main_body > 0)
2663                 font1 = style.labelfont;
2664         else
2665                 font1 = style.font;
2666
2667   
2668         // parsing main loop
2669         for (LyXParagraph::size_type i = 0;
2670              i < par->size(); ++i) {
2671
2672                 // handle quote tag
2673                 if (i == main_body
2674 #ifndef NEW_INSETS
2675                     && !par->IsDummy()
2676 #endif
2677                         ) {
2678                         if (main_body > 0)
2679                                 font1 = style.font;
2680                 }
2681
2682                 LyXFont const font2 = par->getFont(params, i);
2683
2684                 if (font1.family() != font2.family()) {
2685                         switch (family_type) {
2686                         case 0:
2687                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2688                                         push_tag(os, "tt", stack_num, stack);
2689                                         family_type = 1;
2690                                 }
2691                                 else if (font2.family() == LyXFont::SANS_FAMILY) {
2692                                         push_tag(os, "sf", stack_num, stack);
2693                                         family_type = 2;
2694                                 }
2695                                 break;
2696                         case 1:
2697                                 pop_tag(os, "tt", stack_num, stack);
2698                                 if (font2.family() == LyXFont::SANS_FAMILY) {
2699                                         push_tag(os, "sf", stack_num, stack);
2700                                         family_type = 2;
2701                                 } else {
2702                                         family_type = 0;
2703                                 }
2704                                 break;
2705                         case 2:
2706                                 pop_tag(os, "sf", stack_num, stack);
2707                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2708                                         push_tag(os, "tt", stack_num, stack);
2709                                         family_type = 1;
2710                                 } else {
2711                                         family_type = 0;
2712                                 }
2713                         }
2714                 }
2715
2716                 // handle bold face
2717                 if (font1.series() != font2.series()) {
2718                         if (font2.series() == LyXFont::BOLD_SERIES) {
2719                                 push_tag(os, "bf", stack_num, stack);
2720                                 is_bold = true;
2721                         } else if (is_bold) {
2722                                 pop_tag(os, "bf", stack_num, stack);
2723                                 is_bold = false;
2724                         }
2725                 }
2726
2727                 // handle italic and slanted fonts
2728                 if (font1.shape() != font2.shape()) {
2729                         switch (shape_type) {
2730                         case 0:
2731                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2732                                         push_tag(os, "it", stack_num, stack);
2733                                         shape_type = 1;
2734                                 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2735                                         push_tag(os, "sl", stack_num, stack);
2736                                         shape_type = 2;
2737                                 }
2738                                 break;
2739                         case 1:
2740                                 pop_tag(os, "it", stack_num, stack);
2741                                 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2742                                         push_tag(os, "sl", stack_num, stack);
2743                                         shape_type = 2;
2744                                 } else {
2745                                         shape_type = 0;
2746                                 }
2747                                 break;
2748                         case 2:
2749                                 pop_tag(os, "sl", stack_num, stack);
2750                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2751                                         push_tag(os, "it", stack_num, stack);
2752                                         shape_type = 1;
2753                                 } else {
2754                                         shape_type = 0;
2755                                 }
2756                         }
2757                 }
2758                 // handle <em> tag
2759                 if (font1.emph() != font2.emph()) {
2760                         if (font2.emph() == LyXFont::ON) {
2761                                 push_tag(os, "em", stack_num, stack);
2762                                 is_em = true;
2763                         } else if (is_em) {
2764                                 pop_tag(os, "em", stack_num, stack);
2765                                 is_em = false;
2766                         }
2767                 }
2768
2769                 c = par->GetChar(i);
2770
2771                 if (c == LyXParagraph::META_INSET) {
2772                         inset = par->GetInset(i);
2773                         inset->Linuxdoc(this, os);
2774                 }
2775
2776                 if (font2.latex() == LyXFont::ON) {
2777                         // "TeX"-Mode on == > SGML-Mode on.
2778                         if (c != '\0')
2779                                 os << c; // see LaTeX-Generation...
2780                         ++char_line_count;
2781                 } else {
2782                         string sgml_string;
2783                         if (par->linuxDocConvertChar(c, sgml_string)
2784                             && !style.free_spacing) { // in freespacing
2785                                                      // mode, spaces are
2786                                                      // non-breaking characters
2787                                 // char is ' '
2788                                 if (desc_on == 1) {
2789                                         ++char_line_count;
2790                                         linux_doc_line_break(os, char_line_count, 6);
2791                                         os << "</tag>";
2792                                         desc_on = 2;
2793                                 } else  {
2794                                         linux_doc_line_break(os, char_line_count, 1);
2795                                         os << c;
2796                                 }
2797                         } else {
2798                                 os << sgml_string;
2799                                 char_line_count += sgml_string.length();
2800                         }
2801                 }
2802                 font1 = font2;
2803         }
2804
2805         // needed if there is an optional argument but no contents
2806         if (main_body > 0 && main_body == par->size()) {
2807                 font1 = style.font;
2808         }
2809
2810         // pop all defined Styles
2811         for (j = stack_num; j >= 0; --j) {
2812                 linux_doc_line_break(os, 
2813                                      char_line_count, 
2814                                      3 + strlen(stack[j]));
2815                 os << "</" << stack[j] << ">";
2816         }
2817
2818         // resets description flag correctly
2819         switch (desc_on){
2820         case 1:
2821                 // <tag> not closed...
2822                 linux_doc_line_break(os, char_line_count, 6);
2823                 os << "</tag>";
2824                 break;
2825         case 2:
2826                 // fprintf(file, "</p>");
2827                 break;
2828         }
2829 }
2830
2831
2832 // Print an error message.
2833 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2834                            string const & message) 
2835 {
2836         // insert an error marker in text
2837         InsetError * new_inset = new InsetError(message);
2838         par->InsertInset(pos, new_inset);
2839 }
2840
2841 // This constant defines the maximum number of 
2842 // environment layouts that can be nesteded.
2843 // The same applies for command layouts.
2844 // These values should be more than enough.
2845 //           José Matos (1999/07/22)
2846
2847 enum { MAX_NEST_LEVEL = 25};
2848
2849 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2850 {
2851         LyXParagraph * par = paragraph;
2852
2853         niceFile = nice; // this will be used by Insetincludes.
2854
2855         string top_element= textclasslist.LatexnameOfClass(params.textclass);
2856         // Please use a real stack.
2857         string environment_stack[MAX_NEST_LEVEL];
2858         string environment_inner[MAX_NEST_LEVEL];
2859         // Please use a real stack.
2860         string command_stack[MAX_NEST_LEVEL];
2861         bool command_flag= false;
2862         int command_depth= 0, command_base= 0, cmd_depth= 0;
2863
2864         string item_name, command_name;
2865         string c_depth, c_params, tmps;
2866
2867         int depth = 0; // paragraph depth
2868         LyXTextClass const & tclass =
2869                 textclasslist.TextClass(params.textclass);
2870
2871         LaTeXFeatures features(params, tclass.numLayouts());
2872         validate(features);
2873
2874         //if (nice)
2875         tex_code_break_column = lyxrc.ascii_linelen;
2876         //else
2877         //tex_code_break_column = 0;
2878
2879         ofstream ofs(fname.c_str());
2880         if (!ofs) {
2881                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2882                 return;
2883         }
2884    
2885         texrow.reset();
2886
2887         if (!only_body) {
2888                 string sgml_includedfiles=features.getIncludedFiles(fname);
2889
2890                 ofs << "<!doctype " << top_element
2891                     << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2892
2893                 if (params.preamble.empty() && sgml_includedfiles.empty())
2894                         ofs << ">\n\n";
2895                 else
2896                         ofs << "\n [ " << params.preamble 
2897                             << sgml_includedfiles << " \n]>\n\n";
2898         }
2899
2900         if (params.options.empty())
2901                 sgmlOpenTag(ofs, 0, top_element);
2902         else {
2903                 string top = top_element;
2904                 top += " ";
2905                 top += params.options;
2906                 sgmlOpenTag(ofs, 0, top);
2907         }
2908
2909         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
2910             << "\n  See http://www.lyx.org/ for more information -->\n";
2911
2912         while (par) {
2913                 int desc_on = 0; // description mode
2914                 LyXLayout const & style =
2915                         textclasslist.Style(params.textclass,
2916                                             par->layout);
2917
2918                 // environment tag closing
2919                 for (; depth > par->depth; --depth) {
2920                         if (environment_inner[depth] != "!-- --") {
2921                                 item_name= "listitem";
2922                                 sgmlCloseTag(ofs, command_depth + depth,
2923                                              item_name);
2924                                 if (environment_inner[depth] == "varlistentry")
2925                                         sgmlCloseTag(ofs, depth+command_depth,
2926                                                      environment_inner[depth]);
2927                         }
2928                         sgmlCloseTag(ofs, depth + command_depth,
2929                                      environment_stack[depth]);
2930                         environment_stack[depth].erase();
2931                         environment_inner[depth].erase();
2932                 }
2933
2934                 if (depth == par->depth
2935                    && environment_stack[depth] != style.latexname()
2936                    && !environment_stack[depth].empty()) {
2937                         if (environment_inner[depth] != "!-- --") {
2938                                 item_name= "listitem";
2939                                 sgmlCloseTag(ofs, command_depth+depth,
2940                                              item_name);
2941                                 if (environment_inner[depth] == "varlistentry")
2942                                         sgmlCloseTag(ofs,
2943                                                      depth + command_depth,
2944                                                      environment_inner[depth]);
2945                         }
2946                         
2947                         sgmlCloseTag(ofs, depth + command_depth,
2948                                      environment_stack[depth]);
2949                         
2950                         environment_stack[depth].erase();
2951                         environment_inner[depth].erase();
2952                 }
2953
2954                 // Write opening SGML tags.
2955                 switch (style.latextype) {
2956                 case LATEX_PARAGRAPH:
2957                         sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2958                         break;
2959
2960                 case LATEX_COMMAND:
2961                         if (depth!= 0)
2962                                 LinuxDocError(par, 0,
2963                                               _("Error : Wrong depth for "
2964                                                 "LatexType Command.\n"));
2965                         
2966                         command_name = style.latexname();
2967                         
2968                         tmps = style.latexparam();
2969                         c_params = split(tmps, c_depth,'|');
2970                         
2971                         cmd_depth= lyx::atoi(c_depth);
2972                         
2973                         if (command_flag) {
2974                                 if (cmd_depth<command_base) {
2975                                         for (int j = command_depth;
2976                                             j >= command_base; --j)
2977                                                 if (!command_stack[j].empty())
2978                                                         sgmlCloseTag(ofs, j, command_stack[j]);
2979                                         command_depth= command_base= cmd_depth;
2980                                 } else if (cmd_depth <= command_depth) {
2981                                         for (int j = command_depth;
2982                                             j >= cmd_depth; --j)
2983
2984                                                 if (!command_stack[j].empty())
2985                                                         sgmlCloseTag(ofs, j, command_stack[j]);
2986                                         command_depth= cmd_depth;
2987                                 } else
2988                                         command_depth= cmd_depth;
2989                         } else {
2990                                 command_depth = command_base = cmd_depth;
2991                                 command_flag = true;
2992                         }
2993                         command_stack[command_depth]= command_name;
2994
2995                         // treat label as a special case for
2996                         // more WYSIWYM handling.
2997                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
2998                                 Inset * inset = par->GetInset(0);
2999                                 Inset::Code lyx_code = inset->LyxCode();
3000                                 if (lyx_code == Inset::LABEL_CODE){
3001                                         command_name += " id=\"";
3002                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3003                                         command_name += "\"";
3004                                         desc_on = 3;
3005                                 }
3006                         }
3007
3008                         sgmlOpenTag(ofs, depth + command_depth, command_name);
3009                         item_name = "title";
3010                         if (command_name != "!-- --")
3011                                 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3012                         break;
3013
3014                 case LATEX_ENVIRONMENT:
3015                 case LATEX_ITEM_ENVIRONMENT:
3016                         if (depth < par->depth) {
3017                                 depth = par->depth;
3018                                 environment_stack[depth].erase();
3019                         }
3020
3021                         if (environment_stack[depth] != style.latexname()) {
3022                                 environment_stack[depth] = style.latexname();
3023                                 environment_inner[depth] = "!-- --";
3024                                 sgmlOpenTag(ofs, depth + command_depth,
3025                                             environment_stack[depth]);
3026                         } else {
3027                                 if (environment_inner[depth] != "!-- --") {
3028                                         item_name= "listitem";
3029                                         sgmlCloseTag(ofs,
3030                                                      command_depth + depth,
3031                                                      item_name);
3032                                         if (environment_inner[depth] == "varlistentry")
3033                                                 sgmlCloseTag(ofs,
3034                                                              depth + command_depth,
3035                                                              environment_inner[depth]);
3036                                 }
3037                         }
3038                         
3039                         if (style.latextype == LATEX_ENVIRONMENT) {
3040                                 if (!style.latexparam().empty())
3041                                         sgmlOpenTag(ofs, depth + command_depth,
3042                                                     style.latexparam());
3043                                 break;
3044                         }
3045
3046                         desc_on = (style.labeltype == LABEL_MANUAL);
3047
3048                         if (desc_on)
3049                                 environment_inner[depth]= "varlistentry";
3050                         else
3051                                 environment_inner[depth]= "listitem";
3052
3053                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3054                                     environment_inner[depth]);
3055
3056                         if (desc_on) {
3057                                 item_name= "term";
3058                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3059                                             item_name);
3060                         } else {
3061                                 item_name= "para";
3062                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3063                                             item_name);
3064                         }
3065                         break;
3066                 default:
3067                         sgmlOpenTag(ofs, depth + command_depth,
3068                                     style.latexname());
3069                         break;
3070                 }
3071
3072 #ifndef NEW_INSETS
3073                 do {
3074 #endif
3075                         string extra_par;
3076                         SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3077                                             depth + 1 + command_depth);
3078                         par = par->next;
3079 #ifndef NEW_INSETS
3080                         DocBookHandleFootnote(ofs, par,
3081                                               depth + 1 + command_depth);
3082                 }
3083                 while(par && par->IsDummy());
3084 #endif
3085                 string end_tag;
3086                 // write closing SGML tags
3087                 switch (style.latextype) {
3088                 case LATEX_COMMAND:
3089                         end_tag = "title";
3090                         if (command_name != "!-- --")
3091                                 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3092                         break;
3093                 case LATEX_ENVIRONMENT:
3094                         if (!style.latexparam().empty())
3095                                 sgmlCloseTag(ofs, depth + command_depth,
3096                                              style.latexparam());
3097                         break;
3098                 case LATEX_ITEM_ENVIRONMENT:
3099                         if (desc_on == 1) break;
3100                         end_tag= "para";
3101                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3102                         break;
3103                 case LATEX_PARAGRAPH:
3104                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3105                         break;
3106                 default:
3107                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3108                         break;
3109                 }
3110         }
3111
3112         // Close open tags
3113         for (; depth >= 0; --depth) {
3114                 if (!environment_stack[depth].empty()) {
3115                         if (environment_inner[depth] != "!-- --") {
3116                                 item_name= "listitem";
3117                                 sgmlCloseTag(ofs, command_depth + depth,
3118                                              item_name);
3119                                if (environment_inner[depth] == "varlistentry")
3120                                        sgmlCloseTag(ofs, depth + command_depth,
3121                                                     environment_inner[depth]);
3122                         }
3123                         
3124                         sgmlCloseTag(ofs, depth + command_depth,
3125                                      environment_stack[depth]);
3126                 }
3127         }
3128         
3129         for (int j = command_depth; j >= command_base; --j)
3130                 if (!command_stack[j].empty())
3131                         sgmlCloseTag(ofs, j, command_stack[j]);
3132
3133         ofs << "\n\n";
3134         sgmlCloseTag(ofs, 0, top_element);
3135
3136         ofs.close();
3137         // How to check for successful close
3138 }
3139
3140
3141 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3142                                  LyXParagraph * par, int & desc_on,
3143                                  int depth) const
3144 {
3145         bool emph_flag = false;
3146
3147         LyXLayout const & style = textclasslist.Style(params.textclass,
3148                                                       par->GetLayout());
3149
3150         LyXParagraph::size_type main_body;
3151         if (style.labeltype != LABEL_MANUAL)
3152                 main_body = 0;
3153         else
3154                 main_body = par->BeginningOfMainBody();
3155
3156         // gets paragraph main font
3157         LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3158         
3159         int char_line_count = depth;
3160         if (!style.free_spacing)
3161                 for (int j = 0; j < depth; ++j)
3162                         os << ' ';
3163
3164         // parsing main loop
3165         for (LyXParagraph::size_type i = 0;
3166              i < par->size(); ++i) {
3167                 LyXFont font2 = par->getFont(params, i);
3168
3169                 // handle <emphasis> tag
3170                 if (font1.emph() != font2.emph() && i) {
3171                         if (font2.emph() == LyXFont::ON) {
3172                                 os << "<emphasis>";
3173                                 emph_flag = true;
3174                         }else {
3175                                 os << "</emphasis>";
3176                                 emph_flag = false;
3177                         }
3178                 }
3179       
3180                 char c = par->GetChar(i);
3181
3182                 if (c == LyXParagraph::META_INSET) {
3183                         Inset * inset = par->GetInset(i);
3184                         std::ostringstream ost;
3185                         inset->DocBook(this, ost);
3186                         string tmp_out = ost.str().c_str();
3187
3188                         //
3189                         // This code needs some explanation:
3190                         // Two insets are treated specially
3191                         //   label if it is the first element in a command paragraph
3192                         //         desc_on == 3
3193                         //   graphics inside tables or figure floats can't go on
3194                         //   title (the equivalente in latex for this case is caption
3195                         //   and title should come first
3196                         //         desc_on == 4
3197                         //
3198                         if (desc_on!= 3 || i!= 0) {
3199                                 if (!tmp_out.empty() && tmp_out[0] == '@') {
3200                                         if (desc_on == 4)
3201                                                 extra += frontStrip(tmp_out, '@');
3202                                         else
3203                                                 os << frontStrip(tmp_out, '@');
3204                                 }
3205                                 else
3206                                         os << tmp_out;
3207                         }
3208                 } else if (font2.latex() == LyXFont::ON) {
3209                         // "TeX"-Mode on ==> SGML-Mode on.
3210                         if (c != '\0')
3211                                 os << c;
3212                         ++char_line_count;
3213                 } else {
3214                         string sgml_string;
3215                         if (par->linuxDocConvertChar(c, sgml_string)
3216                             && !style.free_spacing) { // in freespacing
3217                                                      // mode, spaces are
3218                                                      // non-breaking characters
3219                                 // char is ' '
3220                                 if (desc_on == 1) {
3221                                         ++char_line_count;
3222                                         os << "\n</term><listitem><para>";
3223                                         desc_on = 2;
3224                                 } else {
3225                                         os << c;
3226                                 }
3227                         } else {
3228                                 os << sgml_string;
3229                         }
3230                 }
3231                 font1 = font2;
3232         }
3233
3234         // needed if there is an optional argument but no contents
3235         if (main_body > 0 && main_body == par->size()) {
3236                 font1 = style.font;
3237         }
3238         if (emph_flag) {
3239                 os << "</emphasis>";
3240         }
3241         
3242         // resets description flag correctly
3243         switch (desc_on){
3244         case 1:
3245                 // <term> not closed...
3246                 os << "</term>";
3247                 break;
3248         }
3249         os << '\n';
3250 }
3251
3252
3253 // This should be enabled when the Chktex class is implemented. (Asger)
3254 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3255 // Other flags: -wall -v0 -x
3256 int Buffer::runChktex()
3257 {
3258         if (!users->text) return 0;
3259
3260         ProhibitInput(users);
3261
3262         // get LaTeX-Filename
3263         string const name = getLatexName();
3264         string path = OnlyPath(filename);
3265
3266         string const org_path = path;
3267         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3268                 path = tmppath;  
3269         }
3270
3271         Path p(path); // path to LaTeX file
3272         users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3273
3274         // Remove all error insets
3275         bool const removedErrorInsets = users->removeAutoInsets();
3276
3277         // Generate the LaTeX file if neccessary
3278         makeLaTeXFile(name, org_path, false);
3279
3280         TeXErrors terr;
3281         Chktex chktex(lyxrc.chktex_command, name, filepath);
3282         int res = chktex.run(terr); // run chktex
3283
3284         if (res == -1) {
3285                 WriteAlert(_("chktex did not work!"),
3286                            _("Could not run with file:"), name);
3287         } else if (res > 0) {
3288                 // Insert all errors as errors boxes
3289                 users->insertErrors(terr);
3290         }
3291
3292         // if we removed error insets before we ran chktex or if we inserted
3293         // error insets after we ran chktex, this must be run:
3294         if (removedErrorInsets || res){
3295                 users->redraw();
3296                 users->fitCursor(users->text);
3297         }
3298         AllowInput(users);
3299
3300         return res;
3301 }
3302
3303
3304 void Buffer::validate(LaTeXFeatures & features) const
3305 {
3306         LyXParagraph * par = paragraph;
3307         LyXTextClass const & tclass = 
3308                 textclasslist.TextClass(params.textclass);
3309     
3310         // AMS Style is at document level
3311     
3312         features.amsstyle = (params.use_amsmath ||
3313                              tclass.provides(LyXTextClass::amsmath));
3314     
3315         while (par) {
3316                 // We don't use "lyxerr.debug" because of speed. (Asger)
3317                 if (lyxerr.debugging(Debug::LATEX))
3318                         lyxerr << "Paragraph: " <<  par << endl;
3319
3320                 // Now just follow the list of paragraphs and run
3321                 // validate on each of them.
3322                 par->validate(features);
3323
3324                 // and then the next paragraph
3325                 par = par->next;
3326         }
3327
3328         // the bullet shapes are buffer level not paragraph level
3329         // so they are tested here
3330         for (int i = 0; i < 4; ++i) {
3331                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3332                         int const font = params.user_defined_bullets[i].getFont();
3333                         if (font == 0) {
3334                                 int const c = params
3335                                         .user_defined_bullets[i]
3336                                         .getCharacter();
3337                                 if (c == 16
3338                                    || c == 17
3339                                    || c == 25
3340                                    || c == 26
3341                                    || c == 31) {
3342                                         features.latexsym = true;
3343                                 }
3344                         } else if (font == 1) {
3345                                 features.amssymb = true;
3346                         } else if ((font >= 2 && font <= 5)) {
3347                                 features.pifont = true;
3348                         }
3349                 }
3350         }
3351         
3352         if (lyxerr.debugging(Debug::LATEX)) {
3353                 features.showStruct();
3354         }
3355 }
3356
3357
3358 void Buffer::setPaperStuff()
3359 {
3360         params.papersize = BufferParams::PAPER_DEFAULT;
3361         char const c1 = params.paperpackage;
3362         if (c1 == BufferParams::PACKAGE_NONE) {
3363                 char const c2 = params.papersize2;
3364                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3365                         params.papersize = BufferParams::PAPER_USLETTER;
3366                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3367                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3368                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3369                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3370                 else if (c2 == BufferParams::VM_PAPER_A3)
3371                         params.papersize = BufferParams::PAPER_A3PAPER;
3372                 else if (c2 == BufferParams::VM_PAPER_A4)
3373                         params.papersize = BufferParams::PAPER_A4PAPER;
3374                 else if (c2 == BufferParams::VM_PAPER_A5)
3375                         params.papersize = BufferParams::PAPER_A5PAPER;
3376                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3377                          (c2 == BufferParams::VM_PAPER_B5))
3378                         params.papersize = BufferParams::PAPER_B5PAPER;
3379         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3380                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3381                 params.papersize = BufferParams::PAPER_A4PAPER;
3382 }
3383
3384
3385 // This function should be in Buffer because it's a buffer's property (ale)
3386 string const Buffer::getIncludeonlyList(char delim)
3387 {
3388         string lst;
3389         for (inset_iterator it = inset_iterator_begin();
3390             it != inset_iterator_end(); ++it) {
3391                 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3392                         InsetInclude * insetinc = 
3393                                 static_cast<InsetInclude *>(*it);
3394                         if (insetinc->isInclude() 
3395                             && insetinc->isNoLoad()) {
3396                                 if (!lst.empty())
3397                                         lst += delim;
3398                                 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3399                         }
3400                 }
3401         }
3402         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3403         return lst;
3404 }
3405
3406
3407 vector<string> const Buffer::getLabelList()
3408 {
3409         /// if this is a child document and the parent is already loaded
3410         /// Use the parent's list instead  [ale990407]
3411         if (!params.parentname.empty()
3412             && bufferlist.exists(params.parentname)) {
3413                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3414                 if (tmp)
3415                         return tmp->getLabelList();
3416         }
3417
3418         vector<string> label_list;
3419         for (inset_iterator it = inset_iterator_begin();
3420              it != inset_iterator_end(); ++it) {
3421                 vector<string> const l = (*it)->getLabelList();
3422                 label_list.insert(label_list.end(), l.begin(), l.end());
3423         }
3424         return label_list;
3425 }
3426
3427
3428 vector<vector<Buffer::TocItem> > const Buffer::getTocList() const
3429 {
3430         int figs = 0;
3431         int tables = 0;
3432         int algs = 0;
3433         vector<vector<TocItem> > l(4);
3434         LyXParagraph * par = paragraph;
3435         while (par) {
3436 #ifndef NEW_INSETS
3437                 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3438                         if (textclasslist.Style(params.textclass, 
3439                                                 par->GetLayout()).labeltype
3440                             == LABEL_SENSITIVE) {
3441                                 TocItem tmp;
3442                                 tmp.par = par;
3443                                 tmp.depth = 0;
3444                                 tmp.str =  par->String(this, false);
3445                                 switch (par->footnotekind) {
3446                                 case LyXParagraph::FIG:
3447                                 case LyXParagraph::WIDE_FIG:
3448                                         tmp.str = tostr(++figs) + ". "
3449                                                 + tmp.str;
3450                                         l[TOC_LOF].push_back(tmp);
3451                                         break;
3452                                 case LyXParagraph::TAB:
3453                                 case LyXParagraph::WIDE_TAB:
3454                                         tmp.str = tostr(++tables) + ". "
3455                                                 + tmp.str;
3456                                         l[TOC_LOT].push_back(tmp);
3457                                         break;
3458                                 case LyXParagraph::ALGORITHM:
3459                                         tmp.str = tostr(++algs) + ". "
3460                                                 + tmp.str;
3461                                         l[TOC_LOA].push_back(tmp);
3462                                         break;
3463                                 case LyXParagraph::FOOTNOTE:
3464                                 case LyXParagraph::MARGIN:
3465                                         break;
3466                                 }
3467                         }
3468                 } else if (!par->IsDummy()) {
3469 #endif
3470                         char const labeltype =
3471                                 textclasslist.Style(params.textclass, 
3472                                                     par->GetLayout()).labeltype;
3473       
3474                         if (labeltype >= LABEL_COUNTER_CHAPTER
3475                             && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3476                                 // insert this into the table of contents
3477                                 TocItem tmp;
3478                                 tmp.par = par;
3479                                 tmp.depth = max(0,
3480                                                 labeltype - 
3481                                                 textclasslist.TextClass(params.textclass).maxcounter());
3482                                 tmp.str =  par->String(this, true);
3483                                 l[TOC_TOC].push_back(tmp);
3484                         }
3485 #ifndef NEW_INSETS
3486                 }
3487 #endif
3488                 par = par->next;
3489         }
3490         return l;
3491 }
3492
3493
3494 // This is also a buffer property (ale)
3495 vector<pair<string,string> > const Buffer::getBibkeyList()
3496 {
3497         /// if this is a child document and the parent is already loaded
3498         /// Use the parent's list instead  [ale990412]
3499         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3500                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3501                 if (tmp)
3502                         return tmp->getBibkeyList();
3503         }
3504
3505         vector<pair<string, string> > keys;
3506         LyXParagraph * par = paragraph;
3507         while (par) {
3508                 if (par->bibkey)
3509                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3510                                                            par->String(this, false)));
3511                 par = par->next;
3512         }
3513
3514         // Might be either using bibtex or a child has bibliography
3515         if (keys.empty()) {
3516                 for (inset_iterator it = inset_iterator_begin();
3517                         it != inset_iterator_end(); ++it) {
3518                         // Search for Bibtex or Include inset
3519                         if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3520                                 vector<pair<string,string> > tmp =
3521                                         static_cast<InsetBibtex*>(*it)->getKeys(this);
3522                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3523                         } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3524                                 vector<pair<string,string> > const tmp =
3525                                         static_cast<InsetInclude*>(*it)->getKeys();
3526                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3527                         }
3528                 }
3529         }
3530  
3531         return keys;
3532 }
3533
3534
3535 bool Buffer::isDepClean(string const & name) const
3536 {
3537         DEPCLEAN * item = dep_clean;
3538         while (item && item->master != name)
3539                 item = item->next;
3540         if (!item) return true;
3541         return item->clean;
3542 }
3543
3544
3545 void Buffer::markDepClean(string const & name)
3546 {
3547         if (!dep_clean) {
3548                 dep_clean = new DEPCLEAN;
3549                 dep_clean->clean = true;
3550                 dep_clean->master = name;
3551                 dep_clean->next = 0;
3552         } else {
3553                 DEPCLEAN * item = dep_clean;
3554                 while (item && item->master != name)
3555                         item = item->next;
3556                 if (item) {
3557                         item->clean = true;
3558                 } else {
3559                         item = new DEPCLEAN;
3560                         item->clean = true;
3561                         item->master = name;
3562                         item->next = 0;
3563                 }
3564         }
3565 }
3566
3567
3568 bool Buffer::Dispatch(string const & command)
3569 {
3570         // Split command string into command and argument
3571         string cmd;
3572         string line = frontStrip(command);
3573         string const arg = strip(frontStrip(split(line, cmd, ' ')));
3574
3575         return Dispatch(lyxaction.LookupFunc(cmd), arg);
3576 }
3577
3578
3579 bool Buffer::Dispatch(int action, string const & argument)
3580 {
3581         bool dispatched = true;
3582         switch (action) {
3583                 case LFUN_EXPORT: 
3584                         Exporter::Export(this, argument, false);
3585                         break;
3586
3587                 default:
3588                         dispatched = false;
3589         }
3590         return dispatched;
3591 }
3592
3593
3594 void Buffer::resize()
3595 {
3596         /// resize the BufferViews!
3597         if (users)
3598                 users->resize();
3599 }
3600
3601
3602 void Buffer::resizeInsets(BufferView * bv)
3603 {
3604         /// then remove all LyXText in text-insets
3605         LyXParagraph * par = paragraph;
3606         for (; par; par = par->next) {
3607             par->resizeInsetsLyXText(bv);
3608         }
3609 }
3610
3611 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3612 {
3613
3614         LyXParagraph * par = paragraph;
3615         while (par) {
3616                 par->ChangeLanguage(params, from, to);
3617                 par = par->next;
3618         }
3619 }
3620
3621
3622 bool Buffer::isMultiLingual()
3623 {
3624         LyXParagraph * par = paragraph;
3625         while (par) {
3626                 if (par->isMultiLingual(params))
3627                         return true;
3628                 par = par->next;
3629         }
3630         return false;
3631 }
3632
3633
3634 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3635                                        LyXParagraph::size_type pos)
3636         : par(paragraph)
3637 {
3638         it = par->InsetIterator(pos);
3639         if (it == par->inset_iterator_end()) {
3640                 par = par->next;
3641                 SetParagraph();
3642         }
3643 }
3644
3645
3646 void Buffer::inset_iterator::SetParagraph()
3647 {
3648         while (par) {
3649                 it = par->inset_iterator_begin();
3650                 if (it != par->inset_iterator_end())
3651                         return;
3652                 par = par->next;
3653         }
3654         //it = 0;
3655         // We maintain an invariant that whenever par = 0 then it = 0
3656 }