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