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