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