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