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