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