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