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