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