]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Fix reading of old format templates
[lyx.git] / src / buffer.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  *           This file is Copyright 1996-2001
10  *           Lars Gullik Bjønnes
11  *
12  * ======================================================
13  */
14
15 #include <config.h>
16
17 #ifdef __GNUG__
18 #pragma implementation
19 #endif
20
21 #include "buffer.h"
22 #include "bufferlist.h"
23 #include "LyXAction.h"
24 #include "lyxrc.h"
25 #include "lyxlex.h"
26 #include "tex-strings.h"
27 #include "layout.h"
28 #include "bufferview_funcs.h"
29 #include "lyxfont.h"
30 #include "version.h"
31 #include "LaTeX.h"
32 #include "Chktex.h"
33 #include "debug.h"
34 #include "LaTeXFeatures.h"
35 #include "lyxtext.h"
36 #include "gettext.h"
37 #include "language.h"
38 #include "encoding.h"
39 #include "exporter.h"
40 #include "Lsstream.h"
41 #include "converter.h"
42 #include "BufferView.h"
43 #include "ParagraphParameters.h"
44 #include "iterators.h"
45 #include "lyxtextclasslist.h"
46 #include "sgml.h"
47 #include "paragraph_funcs.h"
48
49 #include "frontends/LyXView.h"
50
51 #include "mathed/formulamacro.h"
52 #include "mathed/formula.h"
53
54 #include "insets/inset.h"
55 #include "insets/inseterror.h"
56 #include "insets/insetlabel.h"
57 #include "insets/insetref.h"
58 #include "insets/inseturl.h"
59 #include "insets/insetnote.h"
60 #include "insets/insetquotes.h"
61 #include "insets/insetlatexaccent.h"
62 #include "insets/insetbib.h"
63 #include "insets/insetcite.h"
64 #include "insets/insetexternal.h"
65 #include "insets/insetindex.h"
66 #include "insets/insetinclude.h"
67 #include "insets/insettoc.h"
68 #include "insets/insetparent.h"
69 #include "insets/insetspecialchar.h"
70 #include "insets/insettext.h"
71 #include "insets/insetert.h"
72 #include "insets/insetgraphics.h"
73 #include "insets/insetfoot.h"
74 #include "insets/insetmarginal.h"
75 #include "insets/insetoptarg.h"
76 #include "insets/insetminipage.h"
77 #include "insets/insetfloat.h"
78 #include "insets/insetwrap.h"
79 #include "insets/insettabular.h"
80 #if 0
81 #include "insets/insettheorem.h"
82 #include "insets/insetlist.h"
83 #endif
84 #include "insets/insetcaption.h"
85 #include "insets/insetfloatlist.h"
86
87 #include "frontends/Dialogs.h"
88 #include "frontends/Alert.h"
89
90 #include "graphics/Previews.h"
91
92 #include "support/textutils.h"
93 #include "support/filetools.h"
94 #include "support/path.h"
95 #include "support/os.h"
96 #include "support/lyxlib.h"
97 #include "support/FileInfo.h"
98 #include "support/lyxmanip.h"
99 #include "support/lyxalgo.h" // for lyx::count
100
101 #include <boost/bind.hpp>
102 #include <boost/tuple/tuple.hpp>
103
104 #include <fstream>
105 #include <iomanip>
106 #include <map>
107 #include <stack>
108 #include <list>
109 #include <algorithm>
110
111 #include <cstdlib>
112 #include <cmath>
113 #include <unistd.h>
114 #include <sys/types.h>
115 #include <utime.h>
116
117 #ifdef HAVE_LOCALE
118 #include <locale>
119 #endif
120
121 #ifndef CXX_GLOBAL_CSTD
122 using std::pow;
123 #endif
124
125 using std::ostream;
126 using std::ofstream;
127 using std::ifstream;
128 using std::fstream;
129 using std::ios;
130 using std::setw;
131 using std::endl;
132 using std::pair;
133 using std::make_pair;
134 using std::vector;
135 using std::map;
136 using std::max;
137 using std::set;
138 using std::stack;
139 using std::list;
140 using std::for_each;
141
142 using lyx::pos_type;
143 using lyx::textclass_type;
144
145 // all these externs should eventually be removed.
146 extern BufferList bufferlist;
147
148 namespace {
149
150 const int LYX_FORMAT = 221;
151
152 } // namespace anon
153
154 Buffer::Buffer(string const & file, bool ronly)
155         : niceFile(true), lyx_clean(true), bak_clean(true),
156           unnamed(false), dep_clean(0), read_only(ronly),
157           filename_(file), users(0)
158 {
159         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
160         filepath_ = OnlyPath(file);
161         lyxvc.buffer(this);
162         if (read_only || lyxrc.use_tempdir) {
163                 tmppath = CreateBufferTmpDir();
164         } else {
165                 tmppath.erase();
166         }
167 }
168
169
170 Buffer::~Buffer()
171 {
172         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
173         // here the buffer should take care that it is
174         // saved properly, before it goes into the void.
175
176         // make sure that views using this buffer
177         // forgets it.
178         if (users)
179                 users->buffer(0);
180
181         if (!tmppath.empty()) {
182                 DestroyBufferTmpDir(tmppath);
183         }
184
185         paragraphs.clear();
186
187         // Remove any previewed LaTeX snippets assocoated with this buffer.
188         grfx::Previews::get().removeLoader(this);
189 }
190
191
192 string const Buffer::getLatexName(bool no_path) const
193 {
194         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
195         if (no_path)
196                 return OnlyFilename(name);
197         else
198                 return name;
199 }
200
201
202 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
203 {
204         string const filename = getLatexName(false);
205
206         if (filename.empty())
207                 return make_pair(Buffer::latexlog, string());
208
209         string path = OnlyPath(filename);
210
211         if (lyxrc.use_tempdir || !IsDirWriteable(path))
212                 path = tmppath;
213
214         string const fname = AddName(path,
215                                      OnlyFilename(ChangeExtension(filename,
216                                                                   ".log")));
217         string const bname =
218                 AddName(path, OnlyFilename(
219                         ChangeExtension(filename,
220                                         formats.extension("literate") + ".out")));
221
222         // If no Latex log or Build log is newer, show Build log
223
224         FileInfo const f_fi(fname);
225         FileInfo const b_fi(bname);
226
227         if (b_fi.exist() &&
228             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
229                 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
230                 return make_pair(Buffer::buildlog, bname);
231         }
232         lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
233         return make_pair(Buffer::latexlog, fname);
234 }
235
236
237 void Buffer::setReadonly(bool flag)
238 {
239         if (read_only != flag) {
240                 read_only = flag;
241                 updateTitles();
242                 users->owner()->getDialogs().updateBufferDependent(false);
243         }
244 }
245
246
247 /// Update window titles of all users
248 // Should work on a list
249 void Buffer::updateTitles() const
250 {
251         if (users)
252                 users->owner()->updateWindowTitle();
253 }
254
255
256 /// Reset autosave timer of all users
257 // Should work on a list
258 void Buffer::resetAutosaveTimers() const
259 {
260         if (users)
261                 users->owner()->resetAutosaveTimer();
262 }
263
264
265 void Buffer::setFileName(string const & newfile)
266 {
267         filename_ = MakeAbsPath(newfile);
268         filepath_ = OnlyPath(filename_);
269         setReadonly(IsFileWriteable(filename_) == 0);
270         updateTitles();
271 }
272
273
274 // We'll remove this later. (Lgb)
275 namespace {
276
277 string last_inset_read;
278
279 #ifdef WITH_WARNINGS
280 #warning And _why_ is this here? (Lgb)
281 #endif
282 int unknown_layouts;
283 int unknown_tokens;
284
285 } // anon
286
287
288 // candidate for move to BufferView
289 // (at least some parts in the beginning of the func)
290 //
291 // Uwe C. Schroeder
292 // changed to be public and have one parameter
293 // if par = 0 normal behavior
294 // else insert behavior
295 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
296 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
297 {
298         unknown_layouts = 0;
299         unknown_tokens = 0;
300
301         int pos = 0;
302         Paragraph::depth_type depth = 0;
303         bool the_end_read = false;
304
305         Paragraph * first_par = 0;
306         LyXFont font(LyXFont::ALL_INHERIT, params.language);
307
308 #if 0
309         if (file_format < 216 && params.language->lang() == "hebrew")
310                 font.setLanguage(default_language);
311 #endif
312
313         if (!par) {
314                 par = new Paragraph;
315                 par->layout(params.getLyXTextClass().defaultLayout());
316         } else {
317                 // We are inserting into an existing document
318                 users->text->breakParagraph(users);
319                 first_par = users->text->ownerParagraph();
320                 pos = 0;
321                 markDirty();
322                 // We don't want to adopt the parameters from the
323                 // document we insert, so we skip until the text begins:
324                 while (lex.isOK()) {
325                         lex.nextToken();
326                         string const pretoken = lex.getString();
327                         if (pretoken == "\\layout") {
328                                 lex.pushToken(pretoken);
329                                 break;
330                         }
331                 }
332         }
333
334         while (lex.isOK()) {
335                 lex.nextToken();
336                 string const token = lex.getString();
337
338                 if (token.empty()) continue;
339
340                 lyxerr[Debug::PARSER] << "Handling token: `"
341                                       << token << "'" << endl;
342
343                 the_end_read =
344                         parseSingleLyXformat2Token(lex, par, first_par,
345                                                    token, pos, depth,
346                                                    font);
347         }
348
349         if (!first_par)
350                 first_par = par;
351
352         paragraphs.set(first_par);
353
354         if (unknown_layouts > 0) {
355                 string s = _("Couldn't set the layout for ");
356                 if (unknown_layouts == 1) {
357                         s += _("one paragraph");
358                 } else {
359                         s += tostr(unknown_layouts);
360                         s += _(" paragraphs");
361                 }
362                 Alert::alert(_("Textclass Loading Error!"), s,
363                            _("When reading " + fileName()));
364         }
365
366         if (unknown_tokens > 0) {
367                 string s = _("Encountered ");
368                 if (unknown_tokens == 1) {
369                         s += _("one unknown token");
370                 } else {
371                         s += tostr(unknown_tokens);
372                         s += _(" unknown tokens");
373                 }
374                 Alert::alert(_("Textclass Loading Error!"), s,
375                            _("When reading " + fileName()));
376         }
377
378         return the_end_read;
379 }
380
381
382 bool
383 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
384                                    Paragraph *& first_par,
385                                    string const & token, int & pos,
386                                    Paragraph::depth_type & depth,
387                                    LyXFont & font
388         )
389 {
390         bool the_end_read = false;
391
392         // The order of the tags tested may seem unnatural, but this
393         // has been done in order to reduce the number of string
394         // comparisons needed to recognize a given token. This leads
395         // on large documents like UserGuide to a reduction of a
396         // factor 5! (JMarc)
397         if (token[0] != '\\') {
398                 for (string::const_iterator cit = token.begin();
399                      cit != token.end(); ++cit) {
400                         par->insertChar(pos, (*cit), font);
401                         ++pos;
402                 }
403         } else if (token == "\\layout") {
404                 // reset the font as we start a new layout and if the font is
405                 // not ALL_INHERIT,document_language then it will be set to the
406                 // right values after this tag (Jug 20020420)
407                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
408
409 #if 0
410                 if (file_format < 216 && params.language->lang() == "hebrew")
411                         font.setLanguage(default_language);
412 #endif
413
414                 lex.eatLine();
415                 string layoutname = lex.getString();
416
417                 LyXTextClass const & tclass = params.getLyXTextClass();
418
419                 if (layoutname.empty()) {
420                         layoutname = tclass.defaultLayoutName();
421                 }
422                 bool hasLayout = tclass.hasLayout(layoutname);
423                 if (!hasLayout) {
424                         lyxerr << "Layout '" << layoutname << "' does not"
425                                << " exist in textclass '" << tclass.name()
426                                << "'." << endl;
427                         lyxerr << "Trying to use default layout instead."
428                                << endl;
429                         layoutname = tclass.defaultLayoutName();
430                 }
431
432 #ifdef USE_CAPTION
433                 // The is the compability reading of layout caption.
434                 // It can be removed in LyX version 1.3.0. (Lgb)
435                 if (compare_ascii_no_case(layoutname, "caption") == 0) {
436                         // We expect that the par we are now working on is
437                         // really inside a InsetText inside a InsetFloat.
438                         // We also know that captions can only be
439                         // one paragraph. (Lgb)
440
441                         // We should now read until the next "\layout"
442                         // is reached.
443                         // This is probably not good enough, what if the
444                         // caption is the last par in the document (Lgb)
445                         istream & ist = lex.getStream();
446                         stringstream ss;
447                         string line;
448                         int begin = 0;
449                         while (true) {
450                                 getline(ist, line);
451                                 if (prefixIs(line, "\\layout")) {
452                                         lex.pushToken(line);
453                                         break;
454                                 }
455                                 if (prefixIs(line, "\\begin_inset"))
456                                         ++begin;
457                                 if (prefixIs(line, "\\end_inset")) {
458                                         if (begin)
459                                                 --begin;
460                                         else {
461                                                 lex.pushToken(line);
462                                                 break;
463                                         }
464                                 }
465
466                                 ss << line << '\n';
467                         }
468                         // Now we should have the whole layout in ss
469                         // we should now be able to give this to the
470                         // caption inset.
471                         ss << "\\end_inset\n";
472
473                         // This seems like a bug in stringstream.
474                         // We really should be able to use ss
475                         // directly. (Lgb)
476                         istringstream is(ss.str());
477                         LyXLex tmplex(0, 0);
478                         tmplex.setStream(is);
479                         Inset * inset = new InsetCaption;
480                         inset->Read(this, tmplex);
481                         par->InsertInset(pos, inset, font);
482                         ++pos;
483                 } else {
484 #endif
485                         if (!first_par)
486                                 first_par = par;
487                         else {
488                                 par = new Paragraph(par);
489                                 par->layout(params.getLyXTextClass().defaultLayout());
490                         }
491                         pos = 0;
492                         par->layout(params.getLyXTextClass()[layoutname]);
493                         // Test whether the layout is obsolete.
494                         LyXLayout_ptr const & layout = par->layout();
495                         if (!layout->obsoleted_by().empty())
496                                 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
497                         par->params().depth(depth);
498 #if USE_CAPTION
499                 }
500 #endif
501
502         } else if (token == "\\end_inset") {
503                 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
504                        << "Last inset read was: " << last_inset_read
505                        << endl;
506                 // Simply ignore this. The insets do not have
507                 // to read this.
508                 // But insets should read it, it is a part of
509                 // the inset isn't it? Lgb.
510         } else if (token == "\\begin_inset") {
511                 readInset(lex, par, pos, font);
512         } else if (token == "\\family") {
513                 lex.next();
514                 font.setLyXFamily(lex.getString());
515         } else if (token == "\\series") {
516                 lex.next();
517                 font.setLyXSeries(lex.getString());
518         } else if (token == "\\shape") {
519                 lex.next();
520                 font.setLyXShape(lex.getString());
521         } else if (token == "\\size") {
522                 lex.next();
523                 font.setLyXSize(lex.getString());
524         } else if (token == "\\lang") {
525                 lex.next();
526                 string const tok = lex.getString();
527                 Language const * lang = languages.getLanguage(tok);
528                 if (lang) {
529                         font.setLanguage(lang);
530                 } else {
531                         font.setLanguage(params.language);
532                         lex.printError("Unknown language `$$Token'");
533                 }
534         } else if (token == "\\numeric") {
535                 lex.next();
536                 font.setNumber(font.setLyXMisc(lex.getString()));
537         } else if (token == "\\emph") {
538                 lex.next();
539                 font.setEmph(font.setLyXMisc(lex.getString()));
540         } else if (token == "\\bar") {
541                 lex.next();
542                 string const tok = lex.getString();
543                 // This is dirty, but gone with LyX3. (Asger)
544                 if (tok == "under")
545                         font.setUnderbar(LyXFont::ON);
546                 else if (tok == "no")
547                         font.setUnderbar(LyXFont::OFF);
548                 else if (tok == "default")
549                         font.setUnderbar(LyXFont::INHERIT);
550                 else
551                         lex.printError("Unknown bar font flag "
552                                        "`$$Token'");
553         } else if (token == "\\noun") {
554                 lex.next();
555                 font.setNoun(font.setLyXMisc(lex.getString()));
556         } else if (token == "\\color") {
557                 lex.next();
558                 font.setLyXColor(lex.getString());
559         } else if (token == "\\SpecialChar") {
560                 LyXLayout_ptr const & layout = par->layout();
561
562                 // Insets don't make sense in a free-spacing context! ---Kayvan
563                 if (layout->free_spacing || par->isFreeSpacing()) {
564                         if (lex.isOK()) {
565                                 lex.next();
566                                 string next_token = lex.getString();
567                                 if (next_token == "\\-") {
568                                         par->insertChar(pos, '-', font);
569                                 } else if (next_token == "\\protected_separator"
570                                         || next_token == "~") {
571                                         par->insertChar(pos, ' ', font);
572                                 } else {
573                                         lex.printError("Token `$$Token' "
574                                                        "is in free space "
575                                                        "paragraph layout!");
576                                         --pos;
577                                 }
578                         }
579                 } else {
580                         Inset * inset = new InsetSpecialChar;
581                         inset->read(this, lex);
582                         par->insertInset(pos, inset, font);
583                 }
584                 ++pos;
585         } else if (token == "\\i") {
586                 Inset * inset = new InsetLatexAccent;
587                 inset->read(this, lex);
588                 par->insertInset(pos, inset, font);
589                 ++pos;
590         } else if (token == "\\backslash") {
591                 par->insertChar(pos, '\\', font);
592                 ++pos;
593         } else if (token == "\\begin_deeper") {
594                 ++depth;
595         } else if (token == "\\end_deeper") {
596                 if (!depth) {
597                         lex.printError("\\end_deeper: "
598                                        "depth is already null");
599                 }
600                 else
601                         --depth;
602         } else if (token == "\\begin_preamble") {
603                 params.readPreamble(lex);
604         } else if (token == "\\textclass") {
605                 lex.eatLine();
606                 pair<bool, textclass_type> pp =
607                         textclasslist.NumberOfClass(lex.getString());
608                 if (pp.first) {
609                         params.textclass = pp.second;
610                 } else {
611                         Alert::alert(string(_("Textclass error")),
612                                 string(_("The document uses an unknown textclass \"")) +
613                                 lex.getString() + string("\"."),
614                                 string(_("LyX will not be able to produce output correctly.")));
615                         params.textclass = 0;
616                 }
617                 if (!params.getLyXTextClass().load()) {
618                         // if the textclass wasn't loaded properly
619                         // we need to either substitute another
620                         // or stop loading the file.
621                         // I can substitute but I don't see how I can
622                         // stop loading... ideas??  ARRae980418
623                         Alert::alert(_("Textclass Loading Error!"),
624                                    string(_("Can't load textclass ")) +
625                                    params.getLyXTextClass().name(),
626                                    _("-- substituting default"));
627                         params.textclass = 0;
628                 }
629         } else if (token == "\\options") {
630                 lex.eatLine();
631                 params.options = lex.getString();
632         } else if (token == "\\language") {
633                 params.readLanguage(lex);
634         } else if (token == "\\fontencoding") {
635                 lex.eatLine();
636         } else if (token == "\\inputencoding") {
637                 lex.eatLine();
638                 params.inputenc = lex.getString();
639         } else if (token == "\\graphics") {
640                 params.readGraphicsDriver(lex);
641         } else if (token == "\\fontscheme") {
642                 lex.eatLine();
643                 params.fonts = lex.getString();
644         } else if (token == "\\noindent") {
645                 par->params().noindent(true);
646         } else if (token == "\\leftindent") {
647                 lex.nextToken();
648                 LyXLength value(lex.getString());
649                 par->params().leftIndent(value);
650         } else if (token == "\\fill_top") {
651                 par->params().spaceTop(VSpace(VSpace::VFILL));
652         } else if (token == "\\fill_bottom") {
653                 par->params().spaceBottom(VSpace(VSpace::VFILL));
654         } else if (token == "\\line_top") {
655                 par->params().lineTop(true);
656         } else if (token == "\\line_bottom") {
657                 par->params().lineBottom(true);
658         } else if (token == "\\pagebreak_top") {
659                 par->params().pagebreakTop(true);
660         } else if (token == "\\pagebreak_bottom") {
661                 par->params().pagebreakBottom(true);
662         } else if (token == "\\start_of_appendix") {
663                 par->params().startOfAppendix(true);
664         } else if (token == "\\paragraph_separation") {
665                 int tmpret = lex.findToken(string_paragraph_separation);
666                 if (tmpret == -1)
667                         ++tmpret;
668                 params.paragraph_separation =
669                         static_cast<BufferParams::PARSEP>(tmpret);
670         } else if (token == "\\defskip") {
671                 lex.nextToken();
672                 params.defskip = VSpace(lex.getString());
673         } else if (token == "\\quotes_language") {
674                 int tmpret = lex.findToken(string_quotes_language);
675                 if (tmpret == -1)
676                         ++tmpret;
677                 InsetQuotes::quote_language tmpl =
678                         InsetQuotes::EnglishQ;
679                 switch (tmpret) {
680                 case 0:
681                         tmpl = InsetQuotes::EnglishQ;
682                         break;
683                 case 1:
684                         tmpl = InsetQuotes::SwedishQ;
685                         break;
686                 case 2:
687                         tmpl = InsetQuotes::GermanQ;
688                         break;
689                 case 3:
690                         tmpl = InsetQuotes::PolishQ;
691                         break;
692                 case 4:
693                         tmpl = InsetQuotes::FrenchQ;
694                         break;
695                 case 5:
696                         tmpl = InsetQuotes::DanishQ;
697                         break;
698                 }
699                 params.quotes_language = tmpl;
700         } else if (token == "\\quotes_times") {
701                 lex.nextToken();
702                 switch (lex.getInteger()) {
703                 case 1:
704                         params.quotes_times = InsetQuotes::SingleQ;
705                         break;
706                 case 2:
707                         params.quotes_times = InsetQuotes::DoubleQ;
708                         break;
709                 }
710         } else if (token == "\\papersize") {
711                 int tmpret = lex.findToken(string_papersize);
712                 if (tmpret == -1)
713                         ++tmpret;
714                 else
715                         params.papersize2 = tmpret;
716         } else if (token == "\\paperpackage") {
717                 int tmpret = lex.findToken(string_paperpackages);
718                 if (tmpret == -1) {
719                         ++tmpret;
720                         params.paperpackage = BufferParams::PACKAGE_NONE;
721                 } else
722                         params.paperpackage = tmpret;
723         } else if (token == "\\use_geometry") {
724                 lex.nextToken();
725                 params.use_geometry = lex.getInteger();
726         } else if (token == "\\use_amsmath") {
727                 lex.nextToken();
728                 params.use_amsmath = lex.getInteger();
729         } else if (token == "\\use_natbib") {
730                 lex.nextToken();
731                 params.use_natbib = lex.getInteger();
732         } else if (token == "\\use_numerical_citations") {
733                 lex.nextToken();
734                 params.use_numerical_citations = lex.getInteger();
735         } else if (token == "\\paperorientation") {
736                 int tmpret = lex.findToken(string_orientation);
737                 if (tmpret == -1)
738                         ++tmpret;
739                 params.orientation =
740                         static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
741         } else if (token == "\\paperwidth") {
742                 lex.next();
743                 params.paperwidth = lex.getString();
744         } else if (token == "\\paperheight") {
745                 lex.next();
746                 params.paperheight = lex.getString();
747         } else if (token == "\\leftmargin") {
748                 lex.next();
749                 params.leftmargin = lex.getString();
750         } else if (token == "\\topmargin") {
751                 lex.next();
752                 params.topmargin = lex.getString();
753         } else if (token == "\\rightmargin") {
754                 lex.next();
755                 params.rightmargin = lex.getString();
756         } else if (token == "\\bottommargin") {
757                 lex.next();
758                 params.bottommargin = lex.getString();
759         } else if (token == "\\headheight") {
760                 lex.next();
761                 params.headheight = lex.getString();
762         } else if (token == "\\headsep") {
763                 lex.next();
764                 params.headsep = lex.getString();
765         } else if (token == "\\footskip") {
766                 lex.next();
767                 params.footskip = lex.getString();
768         } else if (token == "\\paperfontsize") {
769                 lex.nextToken();
770                 params.fontsize = rtrim(lex.getString());
771         } else if (token == "\\papercolumns") {
772                 lex.nextToken();
773                 params.columns = lex.getInteger();
774         } else if (token == "\\papersides") {
775                 lex.nextToken();
776                 switch (lex.getInteger()) {
777                 default:
778                 case 1: params.sides = LyXTextClass::OneSide; break;
779                 case 2: params.sides = LyXTextClass::TwoSides; break;
780                 }
781         } else if (token == "\\paperpagestyle") {
782                 lex.nextToken();
783                 params.pagestyle = rtrim(lex.getString());
784         } else if (token == "\\bullet") {
785                 lex.nextToken();
786                 int const index = lex.getInteger();
787                 lex.nextToken();
788                 int temp_int = lex.getInteger();
789                 params.user_defined_bullets[index].setFont(temp_int);
790                 params.temp_bullets[index].setFont(temp_int);
791                 lex.nextToken();
792                 temp_int = lex.getInteger();
793                 params.user_defined_bullets[index].setCharacter(temp_int);
794                 params.temp_bullets[index].setCharacter(temp_int);
795                 lex.nextToken();
796                 temp_int = lex.getInteger();
797                 params.user_defined_bullets[index].setSize(temp_int);
798                 params.temp_bullets[index].setSize(temp_int);
799                 lex.nextToken();
800                 string const temp_str = lex.getString();
801                 if (temp_str != "\\end_bullet") {
802                                 // this element isn't really necessary for
803                                 // parsing but is easier for humans
804                                 // to understand bullets. Put it back and
805                                 // set a debug message?
806                         lex.printError("\\end_bullet expected, got" + temp_str);
807                                 //how can I put it back?
808                 }
809         } else if (token == "\\bulletLaTeX") {
810                 // The bullet class should be able to read this.
811                 lex.nextToken();
812                 int const index = lex.getInteger();
813                 lex.next();
814                 string temp_str = lex.getString();
815                 string sum_str;
816                 while (temp_str != "\\end_bullet") {
817                                 // this loop structure is needed when user
818                                 // enters an empty string since the first
819                                 // thing returned will be the \\end_bullet
820                                 // OR
821                                 // if the LaTeX entry has spaces. Each element
822                                 // therefore needs to be read in turn
823                         sum_str += temp_str;
824                         lex.next();
825                         temp_str = lex.getString();
826                 }
827
828                 params.user_defined_bullets[index].setText(sum_str);
829                 params.temp_bullets[index].setText(sum_str);
830         } else if (token == "\\secnumdepth") {
831                 lex.nextToken();
832                 params.secnumdepth = lex.getInteger();
833         } else if (token == "\\tocdepth") {
834                 lex.nextToken();
835                 params.tocdepth = lex.getInteger();
836         } else if (token == "\\spacing") {
837                 lex.next();
838                 string const tmp = rtrim(lex.getString());
839                 Spacing::Space tmp_space = Spacing::Default;
840                 float tmp_val = 0.0;
841                 if (tmp == "single") {
842                         tmp_space = Spacing::Single;
843                 } else if (tmp == "onehalf") {
844                         tmp_space = Spacing::Onehalf;
845                 } else if (tmp == "double") {
846                         tmp_space = Spacing::Double;
847                 } else if (tmp == "other") {
848                         lex.next();
849                         tmp_space = Spacing::Other;
850                         tmp_val = lex.getFloat();
851                 } else {
852                         lex.printError("Unknown spacing token: '$$Token'");
853                 }
854                 // Small hack so that files written with klyx will be
855                 // parsed correctly.
856                 if (first_par) {
857                         par->params().spacing(Spacing(tmp_space, tmp_val));
858                 } else {
859                         params.spacing.set(tmp_space, tmp_val);
860                 }
861         } else if (token == "\\paragraph_spacing") {
862                 lex.next();
863                 string const tmp = rtrim(lex.getString());
864                 if (tmp == "single") {
865                         par->params().spacing(Spacing(Spacing::Single));
866                 } else if (tmp == "onehalf") {
867                         par->params().spacing(Spacing(Spacing::Onehalf));
868                 } else if (tmp == "double") {
869                         par->params().spacing(Spacing(Spacing::Double));
870                 } else if (tmp == "other") {
871                         lex.next();
872                         par->params().spacing(Spacing(Spacing::Other,
873                                          lex.getFloat()));
874                 } else {
875                         lex.printError("Unknown spacing token: '$$Token'");
876                 }
877         } else if (token == "\\float_placement") {
878                 lex.nextToken();
879                 params.float_placement = lex.getString();
880         } else if (token == "\\align") {
881                 int tmpret = lex.findToken(string_align);
882                 if (tmpret == -1) ++tmpret;
883                 int const tmpret2 = int(pow(2.0, tmpret));
884                 par->params().align(LyXAlignment(tmpret2));
885         } else if (token == "\\added_space_top") {
886                 lex.nextToken();
887                 VSpace value = VSpace(lex.getString());
888                 // only add the length when value > 0 or
889                 // with option keep
890                 if ((value.length().len().value() != 0) ||
891                     value.keep() ||
892                     (value.kind() != VSpace::LENGTH))
893                         par->params().spaceTop(value);
894         } else if (token == "\\added_space_bottom") {
895                 lex.nextToken();
896                 VSpace value = VSpace(lex.getString());
897                 // only add the length when value > 0 or
898                 // with option keep
899                 if ((value.length().len().value() != 0) ||
900                    value.keep() ||
901                     (value.kind() != VSpace::LENGTH))
902                         par->params().spaceBottom(value);
903         } else if (token == "\\labelwidthstring") {
904                 lex.eatLine();
905                 par->params().labelWidthString(lex.getString());
906                 // do not delete this token, it is still needed!
907         } else if (token == "\\newline") {
908                 par->insertChar(pos, Paragraph::META_NEWLINE, font);
909                 ++pos;
910         } else if (token == "\\LyXTable") {
911                 Inset * inset = new InsetTabular(*this);
912                 inset->read(this, lex);
913                 par->insertInset(pos, inset, font);
914                 ++pos;
915         } else if (token == "\\hfill") {
916                 par->insertChar(pos, Paragraph::META_HFILL, font);
917                 ++pos;
918         } else if (token == "\\protected_separator") { // obsolete
919                 // This is a backward compability thingie. (Lgb)
920                 // Remove it later some time...introduced with fileformat
921                 // 2.16. (Lgb)
922                 LyXLayout_ptr const & layout = par->layout();
923
924                 if (layout->free_spacing || par->isFreeSpacing()) {
925                         par->insertChar(pos, ' ', font);
926                 } else {
927                         Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
928                         par->insertInset(pos, inset, font);
929                 }
930                 ++pos;
931         } else if (token == "\\bibitem") {  // ale970302
932                 if (!par->bibkey) {
933                         InsetCommandParams p("bibitem", "dummy");
934                         par->bibkey = new InsetBibKey(p);
935                 }
936                 par->bibkey->read(this, lex);
937         } else if (token == "\\the_end") {
938                 the_end_read = true;
939         } else {
940                 // This should be insurance for the future: (Asger)
941                 ++unknown_tokens;
942                 lex.eatLine();
943                 string const s = _("Unknown token: ") + token
944                         + " " + lex.text()  + "\n";
945                 // we can do this here this way because we're actually reading
946                 // the buffer and don't care about LyXText right now.
947                 InsetError * new_inset = new InsetError(s);
948                 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
949                                  params.language));
950
951         }
952
953         return the_end_read;
954 }
955
956 // needed to insert the selection
957 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
958                                  LyXFont const & fn,string const & str) const
959 {
960         LyXLayout_ptr const & layout = par->layout();
961
962         LyXFont font = fn;
963
964         par->checkInsertChar(font);
965         // insert the string, don't insert doublespace
966         bool space_inserted = true;
967         bool autobreakrows = !par->inInset() ||
968                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
969         for(string::const_iterator cit = str.begin();
970             cit != str.end(); ++cit) {
971                 if (*cit == '\n') {
972                         if (autobreakrows && (!par->empty() || layout->keepempty)) {
973                                 breakParagraph(params, par, pos,
974                                                layout->isEnvironment());
975                                 par = par->next();
976                                 pos = 0;
977                                 space_inserted = true;
978                         } else {
979                                 continue;
980                         }
981                         // do not insert consecutive spaces if !free_spacing
982                 } else if ((*cit == ' ' || *cit == '\t') &&
983                            space_inserted && !layout->free_spacing &&
984                                    !par->isFreeSpacing())
985                 {
986                         continue;
987                 } else if (*cit == '\t') {
988                         if (!layout->free_spacing && !par->isFreeSpacing()) {
989                                 // tabs are like spaces here
990                                 par->insertChar(pos, ' ', font);
991                                 ++pos;
992                                 space_inserted = true;
993                         } else {
994                                 const pos_type nb = 8 - pos % 8;
995                                 for (pos_type a = 0; a < nb ; ++a) {
996                                         par->insertChar(pos, ' ', font);
997                                         ++pos;
998                                 }
999                                 space_inserted = true;
1000                         }
1001                 } else if (!IsPrintable(*cit)) {
1002                         // Ignore unprintables
1003                         continue;
1004                 } else {
1005                         // just insert the character
1006                         par->insertChar(pos, *cit, font);
1007                         ++pos;
1008                         space_inserted = (*cit == ' ');
1009                 }
1010
1011         }
1012 }
1013
1014
1015 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1016                        int & pos, LyXFont & font)
1017 {
1018         // consistency check
1019         if (lex.getString() != "\\begin_inset") {
1020                 lyxerr << "Buffer::readInset: Consistency check failed."
1021                        << endl;
1022         }
1023
1024         Inset * inset = 0;
1025
1026         lex.next();
1027         string const tmptok = lex.getString();
1028         last_inset_read = tmptok;
1029
1030         // test the different insets
1031         if (tmptok == "LatexCommand") {
1032                 InsetCommandParams inscmd;
1033                 inscmd.read(lex);
1034
1035                 string const cmdName = inscmd.getCmdName();
1036
1037                 // This strange command allows LyX to recognize "natbib" style
1038                 // citations: citet, citep, Citet etc.
1039                 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
1040                         inset = new InsetCitation(inscmd);
1041                 } else if (cmdName == "bibitem") {
1042                         lex.printError("Wrong place for bibitem");
1043                         inset = new InsetBibKey(inscmd);
1044                 } else if (cmdName == "BibTeX") {
1045                         inset = new InsetBibtex(inscmd);
1046                 } else if (cmdName == "index") {
1047                         inset = new InsetIndex(inscmd);
1048                 } else if (cmdName == "include") {
1049                         inset = new InsetInclude(inscmd, *this);
1050                 } else if (cmdName == "label") {
1051                         inset = new InsetLabel(inscmd);
1052                 } else if (cmdName == "url"
1053                            || cmdName == "htmlurl") {
1054                         inset = new InsetUrl(inscmd);
1055                 } else if (cmdName == "ref"
1056                            || cmdName == "pageref"
1057                            || cmdName == "vref"
1058                            || cmdName == "vpageref"
1059                            || cmdName == "prettyref") {
1060                         if (!inscmd.getOptions().empty()
1061                             || !inscmd.getContents().empty()) {
1062                                 inset = new InsetRef(inscmd, *this);
1063                         }
1064                 } else if (cmdName == "tableofcontents") {
1065                         inset = new InsetTOC(inscmd);
1066                 } else if (cmdName == "listofalgorithms") {
1067                         inset = new InsetFloatList("algorithm");
1068                 } else if (cmdName == "listoffigures") {
1069                         inset = new InsetFloatList("figure");
1070                 } else if (cmdName == "listoftables") {
1071                         inset = new InsetFloatList("table");
1072                 } else if (cmdName == "printindex") {
1073                         inset = new InsetPrintIndex(inscmd);
1074                 } else if (cmdName == "lyxparent") {
1075                         inset = new InsetParent(inscmd, *this);
1076                 }
1077         } else {
1078                 bool alreadyread = false;
1079                 if (tmptok == "Quotes") {
1080                         inset = new InsetQuotes;
1081                 } else if (tmptok == "External") {
1082                         inset = new InsetExternal;
1083                 } else if (tmptok == "FormulaMacro") {
1084                         inset = new InsetFormulaMacro;
1085                 } else if (tmptok == "Formula") {
1086                         inset = new InsetFormula;
1087                 } else if (tmptok == "Figure") { // Backward compatibility
1088 //                      inset = new InsetFig(100, 100, *this);
1089                         inset = new InsetGraphics;
1090                 } else if (tmptok == "Graphics") {
1091                         inset = new InsetGraphics;
1092                 } else if (tmptok == "Info") {// backwards compatibility
1093                         inset = new InsetNote(this,
1094                                               lex.getLongString("\\end_inset"),
1095                                               true);
1096                         alreadyread = true;
1097                 } else if (tmptok == "Note") {
1098                         inset = new InsetNote(params);
1099                 } else if (tmptok == "Include") {
1100                         InsetCommandParams p("Include");
1101                         inset = new InsetInclude(p, *this);
1102                 } else if (tmptok == "ERT") {
1103                         inset = new InsetERT(params);
1104                 } else if (tmptok == "Tabular") {
1105                         inset = new InsetTabular(*this);
1106                 } else if (tmptok == "Text") {
1107                         inset = new InsetText(params);
1108                 } else if (tmptok == "Foot") {
1109                         inset = new InsetFoot(params);
1110                 } else if (tmptok == "Marginal") {
1111                         inset = new InsetMarginal(params);
1112                 } else if (tmptok == "OptArg") {
1113                         inset = new InsetOptArg(params);
1114                 } else if (tmptok == "Minipage") {
1115                         inset = new InsetMinipage(params);
1116                 } else if (tmptok == "Float") {
1117                         lex.next();
1118                         string tmptok = lex.getString();
1119                         inset = new InsetFloat(params, tmptok);
1120                 } else if (tmptok == "Wrap") {
1121                         lex.next();
1122                         string tmptok = lex.getString();
1123                         inset = new InsetWrap(params, tmptok);
1124 #if 0
1125                 } else if (tmptok == "List") {
1126                         inset = new InsetList;
1127                 } else if (tmptok == "Theorem") {
1128                         inset = new InsetList;
1129 #endif
1130                 } else if (tmptok == "Caption") {
1131                         inset = new InsetCaption(params);
1132                 } else if (tmptok == "FloatList") {
1133                         inset = new InsetFloatList;
1134                 }
1135
1136                 if (inset && !alreadyread) inset->read(this, lex);
1137         }
1138
1139         if (inset) {
1140                 par->insertInset(pos, inset, font);
1141                 ++pos;
1142         }
1143 }
1144
1145
1146 bool Buffer::readFile(LyXLex & lex, string const & filename, Paragraph * par)
1147 {
1148         if (lex.isOK()) {
1149                 lex.next();
1150                 string const token(lex.getString());
1151                 if (token == "\\lyxformat") { // the first token _must_ be...
1152                         lex.eatLine();
1153                         string tmp_format = lex.getString();
1154                         //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1155                         // if present remove ".," from string.
1156                         string::size_type dot = tmp_format.find_first_of(".,");
1157                         //lyxerr << "           dot found at " << dot << endl;
1158                         if (dot != string::npos)
1159                                 tmp_format.erase(dot, 1);
1160                         file_format = strToInt(tmp_format);
1161                         //lyxerr << "format: " << file_format << endl;
1162                         if (file_format == LYX_FORMAT) {
1163                                 // current format
1164                         } else if (file_format > LYX_FORMAT) {
1165                                 // future format
1166                                 Alert::alert(_("Warning!"),
1167                                         _("The file was created with a newer version of"
1168                                         "LyX. This is likely to cause problems."));
1169
1170                         } else if (file_format < LYX_FORMAT) {
1171                                 // old formats
1172                                 if (file_format < 200) {
1173                                         Alert::alert(_("ERROR!"),
1174                                                    _("Old LyX file format found. "
1175                                                      "Use LyX 0.10.x to read this!"));
1176                                         return false;
1177                                 } else if (!filename.empty()) {
1178                                         string command =
1179                                                 LibFileSearch("lyx2lyx", "lyx2lyx");
1180                                         if (command.empty()) {
1181                                                 Alert::alert(_("ERROR!"),
1182                                                              _("Can't find conversion script."));
1183                                                 return false;
1184                                         }
1185                                         command += " -t"
1186                                                 +tostr(LYX_FORMAT)+" "
1187                                                 + QuoteName(filename);
1188                                         lyxerr[Debug::INFO] << "Running '"
1189                                                             << command << "'" << endl;
1190                                         cmd_ret const ret = RunCommand(command);
1191                                         if (ret.first) {
1192                                                 Alert::alert(_("ERROR!"),
1193                                                              _("An error occured while "
1194                                                                "running the conversion script."));
1195                                                 return false;
1196                                         }
1197                                         istringstream is(ret.second);
1198                                         LyXLex tmplex(0, 0);
1199                                         tmplex.setStream(is);
1200                                         return readFile(tmplex, string());
1201                                 } else {
1202                                         // This code is reached if lyx2lyx failed (for
1203                                         // some reason) to change the file format of
1204                                         // the file.
1205                                         lyx::Assert(false);
1206                                         return false;
1207                                 }
1208                         }
1209                         bool the_end = readLyXformat2(lex, par);
1210                         params.setPaperStuff();
1211
1212 #if 0
1213                         // the_end was added in 213
1214                         if (file_format < 213)
1215                                 the_end = true;
1216 #endif
1217
1218                         if (!the_end) {
1219                                 Alert::alert(_("Warning!"),
1220                                            _("Reading of document is not complete"),
1221                                            _("Maybe the document is truncated"));
1222                         }
1223                         return true;
1224                 } else { // "\\lyxformat" not found
1225                         Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1226                 }
1227         } else
1228                 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1229         return false;
1230 }
1231
1232
1233 // Should probably be moved to somewhere else: BufferView? LyXView?
1234 bool Buffer::save() const
1235 {
1236         // We don't need autosaves in the immediate future. (Asger)
1237         resetAutosaveTimers();
1238
1239         // make a backup
1240         string s;
1241         if (lyxrc.make_backup) {
1242                 s = fileName() + '~';
1243                 if (!lyxrc.backupdir_path.empty())
1244                         s = AddName(lyxrc.backupdir_path,
1245                                     subst(os::slashify_path(s),'/','!'));
1246
1247                 // Rename is the wrong way of making a backup,
1248                 // this is the correct way.
1249                 /* truss cp fil fil2:
1250                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1251                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1252                    open("LyXVC.lyx", O_RDONLY)                     = 3
1253                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1254                    fstat(4, 0xEFFFF508)                            = 0
1255                    fstat(3, 0xEFFFF508)                            = 0
1256                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1257                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1258                    read(3, 0xEFFFD4A0, 8192)                       = 0
1259                    close(4)                                        = 0
1260                    close(3)                                        = 0
1261                    chmod("LyXVC3.lyx", 0100644)                    = 0
1262                    lseek(0, 0, SEEK_CUR)                           = 46440
1263                    _exit(0)
1264                 */
1265
1266                 // Should probably have some more error checking here.
1267                 // Doing it this way, also makes the inodes stay the same.
1268                 // This is still not a very good solution, in particular we
1269                 // might loose the owner of the backup.
1270                 FileInfo finfo(fileName());
1271                 if (finfo.exist()) {
1272                         mode_t fmode = finfo.getMode();
1273                         struct utimbuf times = {
1274                                 finfo.getAccessTime(),
1275                                 finfo.getModificationTime() };
1276
1277                         ifstream ifs(fileName().c_str());
1278                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1279                         if (ifs && ofs) {
1280                                 ofs << ifs.rdbuf();
1281                                 ifs.close();
1282                                 ofs.close();
1283                                 ::chmod(s.c_str(), fmode);
1284
1285                                 if (::utime(s.c_str(), &times)) {
1286                                         lyxerr << "utime error." << endl;
1287                                 }
1288                         } else {
1289                                 lyxerr << "LyX was not able to make "
1290                                         "backup copy. Beware." << endl;
1291                         }
1292                 }
1293         }
1294
1295         if (writeFile(fileName())) {
1296                 markClean();
1297                 removeAutosaveFile(fileName());
1298         } else {
1299                 // Saving failed, so backup is not backup
1300                 if (lyxrc.make_backup) {
1301                         lyx::rename(s, fileName());
1302                 }
1303                 return false;
1304         }
1305         return true;
1306 }
1307
1308
1309 bool Buffer::writeFile(string const & fname) const
1310 {
1311         if (read_only && (fname == fileName())) {
1312                 return false;
1313         }
1314
1315         FileInfo finfo(fname);
1316         if (finfo.exist() && !finfo.writable()) {
1317                 return false;
1318         }
1319
1320         ofstream ofs(fname.c_str());
1321         if (!ofs) {
1322                 return false;
1323         }
1324
1325 #ifdef HAVE_LOCALE
1326         // Use the standard "C" locale for file output.
1327         ofs.imbue(std::locale::classic());
1328 #endif
1329
1330         // The top of the file should not be written by params.
1331
1332         // write out a comment in the top of the file
1333         ofs << '#' << lyx_docversion
1334             << " created this file. For more info see http://www.lyx.org/\n"
1335             << "\\lyxformat " << LYX_FORMAT << "\n";
1336
1337         // now write out the buffer paramters.
1338         params.writeFile(ofs);
1339
1340         Paragraph::depth_type depth = 0;
1341
1342         // this will write out all the paragraphs
1343         // using recursive descent.
1344         ParagraphList::iterator pit = paragraphs.begin();
1345         ParagraphList::iterator pend = paragraphs.end();
1346         for (; pit != pend; ++pit)
1347                 pit->write(this, ofs, params, depth);
1348
1349         // Write marker that shows file is complete
1350         ofs << "\n\\the_end" << endl;
1351
1352         ofs.close();
1353
1354         // how to check if close went ok?
1355         // Following is an attempt... (BE 20001011)
1356
1357         // good() returns false if any error occured, including some
1358         //        formatting error.
1359         // bad()  returns true if something bad happened in the buffer,
1360         //        which should include file system full errors.
1361
1362         bool status = true;
1363         if (!ofs.good()) {
1364                 status = false;
1365 #if 0
1366                 if (ofs.bad()) {
1367                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1368                 } else {
1369                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1370                                << endl;
1371                 }
1372 #endif
1373         }
1374
1375         return status;
1376 }
1377
1378
1379 namespace {
1380
1381 pair<int, string> const addDepth(int depth, int ldepth)
1382 {
1383         int d = depth * 2;
1384         if (ldepth > depth)
1385                 d += (ldepth - depth) * 2;
1386         return make_pair(d, string(d, ' '));
1387 }
1388
1389 }
1390
1391
1392 string const Buffer::asciiParagraph(Paragraph const & par,
1393                                     unsigned int linelen,
1394                                     bool noparbreak) const
1395 {
1396         ostringstream buffer;
1397         Paragraph::depth_type depth = 0;
1398         int ltype = 0;
1399         Paragraph::depth_type ltype_depth = 0;
1400         bool ref_printed = false;
1401 //      if (!par->previous()) {
1402 #if 0
1403         // begins or ends a deeper area ?
1404         if (depth != par->params().depth()) {
1405                 if (par->params().depth() > depth) {
1406                         while (par->params().depth() > depth) {
1407                                 ++depth;
1408                         }
1409                 } else {
1410                         while (par->params().depth() < depth) {
1411                                 --depth;
1412                         }
1413                 }
1414         }
1415 #else
1416         depth = par.params().depth();
1417 #endif
1418
1419         // First write the layout
1420         string const & tmp = par.layout()->name();
1421         if (compare_no_case(tmp, "itemize") == 0) {
1422                 ltype = 1;
1423                 ltype_depth = depth + 1;
1424         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1425                 ltype = 2;
1426                 ltype_depth = depth + 1;
1427         } else if (contains(ascii_lowercase(tmp), "ection")) {
1428                 ltype = 3;
1429                 ltype_depth = depth + 1;
1430         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1431                 ltype = 4;
1432                 ltype_depth = depth + 1;
1433         } else if (compare_ascii_no_case(tmp, "description") == 0) {
1434                 ltype = 5;
1435                 ltype_depth = depth + 1;
1436         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1437                 ltype = 6;
1438                 ltype_depth = 0;
1439         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1440                 ltype = 7;
1441                 ltype_depth = 0;
1442         } else {
1443                 ltype = 0;
1444                 ltype_depth = 0;
1445         }
1446
1447         /* maybe some vertical spaces */
1448
1449         /* the labelwidthstring used in lists */
1450
1451         /* some lines? */
1452
1453         /* some pagebreaks? */
1454
1455         /* noindent ? */
1456
1457         /* what about the alignment */
1458 //      } else {
1459 //              lyxerr << "Should this ever happen?" << endl;
1460 //      }
1461
1462         // linelen <= 0 is special and means we don't have paragraph breaks
1463
1464         string::size_type currlinelen = 0;
1465
1466         if (!noparbreak) {
1467                 if (linelen > 0)
1468                         buffer << "\n\n";
1469
1470                 buffer << string(depth * 2, ' ');
1471                 currlinelen += depth * 2;
1472
1473                 //--
1474                 // we should probably change to the paragraph language in the
1475                 // gettext here (if possible) so that strings are outputted in
1476                 // the correct language! (20012712 Jug)
1477                 //--
1478                 switch (ltype) {
1479                 case 0: // Standard
1480                 case 4: // (Sub)Paragraph
1481                 case 5: // Description
1482                         break;
1483                 case 6: // Abstract
1484                         if (linelen > 0) {
1485                                 buffer << _("Abstract") << "\n\n";
1486                                 currlinelen = 0;
1487                         } else {
1488                                 string const abst = _("Abstract: ");
1489                                 buffer << abst;
1490                                 currlinelen += abst.length();
1491                         }
1492                         break;
1493                 case 7: // Bibliography
1494                         if (!ref_printed) {
1495                                 if (linelen > 0) {
1496                                         buffer << _("References") << "\n\n";
1497                                         currlinelen = 0;
1498                                 } else {
1499                                         string const refs = _("References: ");
1500                                         buffer << refs;
1501                                         currlinelen += refs.length();
1502                                 }
1503
1504                                 ref_printed = true;
1505                         }
1506                         break;
1507                 default:
1508                 {
1509                         string const parlab = par.params().labelString();
1510                         buffer << parlab << " ";
1511                         currlinelen += parlab.length() + 1;
1512                 }
1513                 break;
1514
1515                 }
1516         }
1517
1518         if (!currlinelen) {
1519                 pair<int, string> p = addDepth(depth, ltype_depth);
1520                 buffer << p.second;
1521                 currlinelen += p.first;
1522         }
1523
1524         // this is to change the linebreak to do it by word a bit more
1525         // intelligent hopefully! (only in the case where we have a
1526         // max linelenght!) (Jug)
1527
1528         string word;
1529
1530         for (pos_type i = 0; i < par.size(); ++i) {
1531                 char c = par.getUChar(params, i);
1532                 switch (c) {
1533                 case Paragraph::META_INSET:
1534                 {
1535                         Inset const * inset = par.getInset(i);
1536                         if (inset) {
1537                                 if (linelen > 0) {
1538                                         buffer << word;
1539                                         currlinelen += word.length();
1540                                         word.erase();
1541                                 }
1542                                 if (inset->ascii(this, buffer, linelen)) {
1543                                         // to be sure it breaks paragraph
1544                                         currlinelen += linelen;
1545                                 }
1546                         }
1547                 }
1548                 break;
1549
1550                 case Paragraph::META_NEWLINE:
1551                         if (linelen > 0) {
1552                                 buffer << word << "\n";
1553                                 word.erase();
1554
1555                                 pair<int, string> p = addDepth(depth,
1556                                                                ltype_depth);
1557                                 buffer << p.second;
1558                                 currlinelen = p.first;
1559                         }
1560                         break;
1561
1562                 case Paragraph::META_HFILL:
1563                         buffer << word << "\t";
1564                         currlinelen += word.length() + 1;
1565                         word.erase();
1566                         break;
1567
1568                 default:
1569                         if (c == ' ') {
1570                                 if (linelen > 0 &&
1571                                     currlinelen + word.length() > linelen - 10) {
1572                                         buffer << "\n";
1573                                         pair<int, string> p =
1574                                                 addDepth(depth, ltype_depth);
1575                                         buffer << p.second;
1576                                         currlinelen = p.first;
1577                                 }
1578
1579                                 buffer << word << ' ';
1580                                 currlinelen += word.length() + 1;
1581                                 word.erase();
1582
1583                         } else {
1584                                 if (c != '\0') {
1585                                         word += c;
1586                                 } else {
1587                                         lyxerr[Debug::INFO] <<
1588                                                 "writeAsciiFile: NULL char in structure." << endl;
1589                                 }
1590                                 if ((linelen > 0) &&
1591                                         (currlinelen + word.length()) > linelen)
1592                                 {
1593                                         buffer << "\n";
1594
1595                                         pair<int, string> p =
1596                                                 addDepth(depth, ltype_depth);
1597                                         buffer << p.second;
1598                                         currlinelen = p.first;
1599                                 }
1600                         }
1601                         break;
1602                 }
1603         }
1604         buffer << word;
1605         return buffer.str().c_str();
1606 }
1607
1608
1609 void Buffer::writeFileAscii(string const & fname, int linelen)
1610 {
1611         ofstream ofs(fname.c_str());
1612         if (!ofs) {
1613                 Alert::err_alert(_("Error: Cannot write file:"), fname);
1614                 return;
1615         }
1616         writeFileAscii(ofs, linelen);
1617 }
1618
1619
1620 void Buffer::writeFileAscii(ostream & os, int linelen)
1621 {
1622         ParagraphList::iterator beg = paragraphs.begin();
1623         ParagraphList::iterator end = paragraphs.end();
1624         ParagraphList::iterator it = beg;
1625         for (; it != end; ++it) {
1626                 os << asciiParagraph(*it, linelen, it == beg);
1627         }
1628         os << "\n";
1629 }
1630
1631
1632 bool use_babel;
1633
1634
1635 void Buffer::makeLaTeXFile(string const & fname,
1636                            string const & original_path,
1637                            bool nice, bool only_body, bool only_preamble)
1638 {
1639         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1640
1641         ofstream ofs(fname.c_str());
1642         if (!ofs) {
1643                 Alert::err_alert(_("Error: Cannot open file: "), fname);
1644                 return;
1645         }
1646
1647         makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1648
1649         ofs.close();
1650         if (ofs.fail()) {
1651                 lyxerr << "File was not closed properly." << endl;
1652         }
1653 }
1654
1655
1656 void Buffer::makeLaTeXFile(ostream & os,
1657                            string const & original_path,
1658                            bool nice, bool only_body, bool only_preamble)
1659 {
1660         niceFile = nice; // this will be used by Insetincludes.
1661
1662         // validate the buffer.
1663         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1664         LaTeXFeatures features(params);
1665         validate(features);
1666         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1667
1668         texrow.reset();
1669         // The starting paragraph of the coming rows is the
1670         // first paragraph of the document. (Asger)
1671         texrow.start(&*(paragraphs.begin()), 0);
1672
1673         if (!only_body && nice) {
1674                 os << "%% " << lyx_docversion << " created this file.  "
1675                         "For more info, see http://www.lyx.org/.\n"
1676                         "%% Do not edit unless you really know what "
1677                         "you are doing.\n";
1678                 texrow.newline();
1679                 texrow.newline();
1680         }
1681         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1682         // There are a few differences between nice LaTeX and usual files:
1683         // usual is \batchmode and has a
1684         // special input@path to allow the including of figures
1685         // with either \input or \includegraphics (what figinsets do).
1686         // input@path is set when the actual parameter
1687         // original_path is set. This is done for usual tex-file, but not
1688         // for nice-latex-file. (Matthias 250696)
1689         if (!only_body) {
1690                 if (!nice) {
1691                         // code for usual, NOT nice-latex-file
1692                         os << "\\batchmode\n"; // changed
1693                         // from \nonstopmode
1694                         texrow.newline();
1695                 }
1696                 if (!original_path.empty()) {
1697                         string inputpath = os::external_path(original_path);
1698                         subst(inputpath, "~", "\\string~");
1699                         os << "\\makeatletter\n"
1700                             << "\\def\\input@path{{"
1701                             << inputpath << "/}}\n"
1702                             << "\\makeatother\n";
1703                         texrow.newline();
1704                         texrow.newline();
1705                         texrow.newline();
1706                 }
1707
1708                 os << "\\documentclass";
1709
1710                 LyXTextClass const & tclass = params.getLyXTextClass();
1711
1712                 ostringstream options; // the document class options.
1713
1714                 if (tokenPos(tclass.opt_fontsize(),
1715                              '|', params.fontsize) >= 0) {
1716                         // only write if existing in list (and not default)
1717                         options << params.fontsize << "pt,";
1718                 }
1719
1720
1721                 if (!params.use_geometry &&
1722                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1723                         switch (params.papersize) {
1724                         case BufferParams::PAPER_A4PAPER:
1725                                 options << "a4paper,";
1726                                 break;
1727                         case BufferParams::PAPER_USLETTER:
1728                                 options << "letterpaper,";
1729                                 break;
1730                         case BufferParams::PAPER_A5PAPER:
1731                                 options << "a5paper,";
1732                                 break;
1733                         case BufferParams::PAPER_B5PAPER:
1734                                 options << "b5paper,";
1735                                 break;
1736                         case BufferParams::PAPER_EXECUTIVEPAPER:
1737                                 options << "executivepaper,";
1738                                 break;
1739                         case BufferParams::PAPER_LEGALPAPER:
1740                                 options << "legalpaper,";
1741                                 break;
1742                         }
1743                 }
1744
1745                 // if needed
1746                 if (params.sides != tclass.sides()) {
1747                         switch (params.sides) {
1748                         case LyXTextClass::OneSide:
1749                                 options << "oneside,";
1750                                 break;
1751                         case LyXTextClass::TwoSides:
1752                                 options << "twoside,";
1753                                 break;
1754                         }
1755                 }
1756
1757                 // if needed
1758                 if (params.columns != tclass.columns()) {
1759                         if (params.columns == 2)
1760                                 options << "twocolumn,";
1761                         else
1762                                 options << "onecolumn,";
1763                 }
1764
1765                 if (!params.use_geometry
1766                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1767                         options << "landscape,";
1768
1769                 // language should be a parameter to \documentclass
1770                 use_babel = false;
1771                 ostringstream language_options;
1772                 if (params.language->babel() == "hebrew"
1773                     && default_language->babel() != "hebrew")
1774                          // This seems necessary
1775                         features.useLanguage(default_language);
1776
1777                 if (lyxrc.language_use_babel ||
1778                     params.language->lang() != lyxrc.default_language ||
1779                     features.hasLanguages()) {
1780                         use_babel = true;
1781                         language_options << features.getLanguages();
1782                         language_options << params.language->babel();
1783                         if (lyxrc.language_global_options)
1784                                 options << language_options.str() << ',';
1785                 }
1786
1787                 // the user-defined options
1788                 if (!params.options.empty()) {
1789                         options << params.options << ',';
1790                 }
1791
1792                 string strOptions(options.str().c_str());
1793                 if (!strOptions.empty()) {
1794                         strOptions = rtrim(strOptions, ",");
1795                         os << '[' << strOptions << ']';
1796                 }
1797
1798                 os << '{' << tclass.latexname() << "}\n";
1799                 texrow.newline();
1800                 // end of \documentclass defs
1801
1802                 // font selection must be done before loading fontenc.sty
1803                 // The ae package is not needed when using OT1 font encoding.
1804                 if (params.fonts != "default" &&
1805                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1806                         os << "\\usepackage{" << params.fonts << "}\n";
1807                         texrow.newline();
1808                         if (params.fonts == "ae") {
1809                                 os << "\\usepackage{aecompl}\n";
1810                                 texrow.newline();
1811                         }
1812                 }
1813                 // this one is not per buffer
1814                 if (lyxrc.fontenc != "default") {
1815                         os << "\\usepackage[" << lyxrc.fontenc
1816                             << "]{fontenc}\n";
1817                         texrow.newline();
1818                 }
1819
1820                 if (params.inputenc == "auto") {
1821                         string const doc_encoding =
1822                                 params.language->encoding()->LatexName();
1823
1824                         // Create a list with all the input encodings used
1825                         // in the document
1826                         set<string> encodings = features.getEncodingSet(doc_encoding);
1827
1828                         os << "\\usepackage[";
1829                         std::copy(encodings.begin(), encodings.end(),
1830                                   std::ostream_iterator<string>(os, ","));
1831                         os << doc_encoding << "]{inputenc}\n";
1832                         texrow.newline();
1833                 } else if (params.inputenc != "default") {
1834                         os << "\\usepackage[" << params.inputenc
1835                             << "]{inputenc}\n";
1836                         texrow.newline();
1837                 }
1838
1839                 // At the very beginning the text parameters.
1840                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1841                         switch (params.paperpackage) {
1842                         case BufferParams::PACKAGE_A4:
1843                                 os << "\\usepackage{a4}\n";
1844                                 texrow.newline();
1845                                 break;
1846                         case BufferParams::PACKAGE_A4WIDE:
1847                                 os << "\\usepackage{a4wide}\n";
1848                                 texrow.newline();
1849                                 break;
1850                         case BufferParams::PACKAGE_WIDEMARGINSA4:
1851                                 os << "\\usepackage[widemargins]{a4}\n";
1852                                 texrow.newline();
1853                                 break;
1854                         }
1855                 }
1856                 if (params.use_geometry) {
1857                         os << "\\usepackage{geometry}\n";
1858                         texrow.newline();
1859                         os << "\\geometry{verbose";
1860                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1861                                 os << ",landscape";
1862                         switch (params.papersize2) {
1863                         case BufferParams::VM_PAPER_CUSTOM:
1864                                 if (!params.paperwidth.empty())
1865                                         os << ",paperwidth="
1866                                             << params.paperwidth;
1867                                 if (!params.paperheight.empty())
1868                                         os << ",paperheight="
1869                                             << params.paperheight;
1870                                 break;
1871                         case BufferParams::VM_PAPER_USLETTER:
1872                                 os << ",letterpaper";
1873                                 break;
1874                         case BufferParams::VM_PAPER_USLEGAL:
1875                                 os << ",legalpaper";
1876                                 break;
1877                         case BufferParams::VM_PAPER_USEXECUTIVE:
1878                                 os << ",executivepaper";
1879                                 break;
1880                         case BufferParams::VM_PAPER_A3:
1881                                 os << ",a3paper";
1882                                 break;
1883                         case BufferParams::VM_PAPER_A4:
1884                                 os << ",a4paper";
1885                                 break;
1886                         case BufferParams::VM_PAPER_A5:
1887                                 os << ",a5paper";
1888                                 break;
1889                         case BufferParams::VM_PAPER_B3:
1890                                 os << ",b3paper";
1891                                 break;
1892                         case BufferParams::VM_PAPER_B4:
1893                                 os << ",b4paper";
1894                                 break;
1895                         case BufferParams::VM_PAPER_B5:
1896                                 os << ",b5paper";
1897                                 break;
1898                         default:
1899                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1900                                 switch (lyxrc.default_papersize) {
1901                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1902                                 case BufferParams::PAPER_USLETTER:
1903                                         os << ",letterpaper";
1904                                         break;
1905                                 case BufferParams::PAPER_LEGALPAPER:
1906                                         os << ",legalpaper";
1907                                         break;
1908                                 case BufferParams::PAPER_EXECUTIVEPAPER:
1909                                         os << ",executivepaper";
1910                                         break;
1911                                 case BufferParams::PAPER_A3PAPER:
1912                                         os << ",a3paper";
1913                                         break;
1914                                 case BufferParams::PAPER_A4PAPER:
1915                                         os << ",a4paper";
1916                                         break;
1917                                 case BufferParams::PAPER_A5PAPER:
1918                                         os << ",a5paper";
1919                                         break;
1920                                 case BufferParams::PAPER_B5PAPER:
1921                                         os << ",b5paper";
1922                                         break;
1923                                 }
1924                         }
1925                         if (!params.topmargin.empty())
1926                                 os << ",tmargin=" << params.topmargin;
1927                         if (!params.bottommargin.empty())
1928                                 os << ",bmargin=" << params.bottommargin;
1929                         if (!params.leftmargin.empty())
1930                                 os << ",lmargin=" << params.leftmargin;
1931                         if (!params.rightmargin.empty())
1932                                 os << ",rmargin=" << params.rightmargin;
1933                         if (!params.headheight.empty())
1934                                 os << ",headheight=" << params.headheight;
1935                         if (!params.headsep.empty())
1936                                 os << ",headsep=" << params.headsep;
1937                         if (!params.footskip.empty())
1938                                 os << ",footskip=" << params.footskip;
1939                         os << "}\n";
1940                         texrow.newline();
1941                 }
1942
1943                 if (tokenPos(tclass.opt_pagestyle(),
1944                              '|', params.pagestyle) >= 0) {
1945                         if (params.pagestyle == "fancy") {
1946                                 os << "\\usepackage{fancyhdr}\n";
1947                                 texrow.newline();
1948                         }
1949                         os << "\\pagestyle{" << params.pagestyle << "}\n";
1950                         texrow.newline();
1951                 }
1952
1953                 if (params.secnumdepth != tclass.secnumdepth()) {
1954                         os << "\\setcounter{secnumdepth}{"
1955                             << params.secnumdepth
1956                             << "}\n";
1957                         texrow.newline();
1958                 }
1959                 if (params.tocdepth != tclass.tocdepth()) {
1960                         os << "\\setcounter{tocdepth}{"
1961                             << params.tocdepth
1962                             << "}\n";
1963                         texrow.newline();
1964                 }
1965
1966                 if (params.paragraph_separation) {
1967                         switch (params.defskip.kind()) {
1968                         case VSpace::SMALLSKIP:
1969                                 os << "\\setlength\\parskip{\\smallskipamount}\n";
1970                                 break;
1971                         case VSpace::MEDSKIP:
1972                                 os << "\\setlength\\parskip{\\medskipamount}\n";
1973                                 break;
1974                         case VSpace::BIGSKIP:
1975                                 os << "\\setlength\\parskip{\\bigskipamount}\n";
1976                                 break;
1977                         case VSpace::LENGTH:
1978                                 os << "\\setlength\\parskip{"
1979                                     << params.defskip.length().asLatexString()
1980                                     << "}\n";
1981                                 break;
1982                         default: // should never happen // Then delete it.
1983                                 os << "\\setlength\\parskip{\\medskipamount}\n";
1984                                 break;
1985                         }
1986                         texrow.newline();
1987
1988                         os << "\\setlength\\parindent{0pt}\n";
1989                         texrow.newline();
1990                 }
1991
1992                 // Now insert the LyX specific LaTeX commands...
1993
1994                 // The optional packages;
1995                 string preamble(features.getPackages());
1996
1997                 // this might be useful...
1998                 preamble += "\n\\makeatletter\n";
1999
2000                 // Some macros LyX will need
2001                 string tmppreamble(features.getMacros());
2002
2003                 if (!tmppreamble.empty()) {
2004                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2005                                 "LyX specific LaTeX commands.\n"
2006                                 + tmppreamble + '\n';
2007                 }
2008
2009                 // the text class specific preamble
2010                 tmppreamble = features.getTClassPreamble();
2011                 if (!tmppreamble.empty()) {
2012                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2013                                 "Textclass specific LaTeX commands.\n"
2014                                 + tmppreamble + '\n';
2015                 }
2016
2017                 /* the user-defined preamble */
2018                 if (!params.preamble.empty()) {
2019                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2020                                 "User specified LaTeX commands.\n"
2021                                 + params.preamble + '\n';
2022                 }
2023
2024                 // Itemize bullet settings need to be last in case the user
2025                 // defines their own bullets that use a package included
2026                 // in the user-defined preamble -- ARRae
2027                 // Actually it has to be done much later than that
2028                 // since some packages like frenchb make modifications
2029                 // at \begin{document} time -- JMarc
2030                 string bullets_def;
2031                 for (int i = 0; i < 4; ++i) {
2032                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2033                                 if (bullets_def.empty())
2034                                         bullets_def="\\AtBeginDocument{\n";
2035                                 bullets_def += "  \\renewcommand{\\labelitemi";
2036                                 switch (i) {
2037                                 // `i' is one less than the item to modify
2038                                 case 0:
2039                                         break;
2040                                 case 1:
2041                                         bullets_def += 'i';
2042                                         break;
2043                                 case 2:
2044                                         bullets_def += "ii";
2045                                         break;
2046                                 case 3:
2047                                         bullets_def += 'v';
2048                                         break;
2049                                 }
2050                                 bullets_def += "}{" +
2051                                   params.user_defined_bullets[i].getText()
2052                                   + "}\n";
2053                         }
2054                 }
2055
2056                 if (!bullets_def.empty())
2057                   preamble += bullets_def + "}\n\n";
2058
2059                 int const nlines =
2060                         int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2061                 for (int j = 0; j != nlines; ++j) {
2062                         texrow.newline();
2063                 }
2064
2065                 // We try to load babel late, in case it interferes
2066                 // with other packages.
2067                 if (use_babel) {
2068                         string tmp = lyxrc.language_package;
2069                         if (!lyxrc.language_global_options
2070                             && tmp == "\\usepackage{babel}")
2071                                 tmp = string("\\usepackage[") +
2072                                         language_options.str().c_str() +
2073                                         "]{babel}";
2074                         preamble += tmp + "\n";
2075                         preamble += features.getBabelOptions();
2076                 }
2077
2078                 preamble += "\\makeatother\n";
2079
2080                 os << preamble;
2081
2082                 if (only_preamble)
2083                         return;
2084
2085                 // make the body.
2086                 os << "\\begin{document}\n";
2087                 texrow.newline();
2088         } // only_body
2089         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2090
2091         if (!lyxrc.language_auto_begin) {
2092                 os << subst(lyxrc.language_command_begin, "$$lang",
2093                              params.language->babel())
2094                     << endl;
2095                 texrow.newline();
2096         }
2097
2098         latexParagraphs(os, &*(paragraphs.begin()), 0, texrow);
2099
2100         // add this just in case after all the paragraphs
2101         os << endl;
2102         texrow.newline();
2103
2104         if (!lyxrc.language_auto_end) {
2105                 os << subst(lyxrc.language_command_end, "$$lang",
2106                              params.language->babel())
2107                     << endl;
2108                 texrow.newline();
2109         }
2110
2111         if (!only_body) {
2112                 os << "\\end{document}\n";
2113                 texrow.newline();
2114
2115                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2116         } else {
2117                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2118                                      << endl;
2119         }
2120
2121         // Just to be sure. (Asger)
2122         texrow.newline();
2123
2124         lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2125         lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2126
2127         // we want this to be true outside previews (for insetexternal)
2128         niceFile = true;
2129 }
2130
2131
2132 //
2133 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2134 //
2135 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2136                              Paragraph * endpar, TexRow & texrow,
2137                              bool moving_arg) const
2138 {
2139         bool was_title = false;
2140         bool already_title = false;
2141
2142         // if only_body
2143         while (par != endpar) {
2144                 Inset * in = par->inInset();
2145                 // well we have to check if we are in an inset with unlimited
2146                 // length (all in one row) if that is true then we don't allow
2147                 // any special options in the paragraph and also we don't allow
2148                 // any environment other then "Standard" to be valid!
2149                 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2150                         LyXLayout_ptr const & layout = par->layout();
2151
2152                         if (layout->intitle) {
2153                                 if (already_title) {
2154                                         lyxerr <<"Error in latexParagraphs: You"
2155                                                 " should not mix title layouts"
2156                                                 " with normal ones." << endl;
2157                                 } else
2158                                         was_title = true;
2159                         } else if (was_title && !already_title) {
2160                                 ofs << "\\maketitle\n";
2161                                 texrow.newline();
2162                                 already_title = true;
2163                                 was_title = false;
2164                         }
2165
2166                         if (layout->isEnvironment() ||
2167                                 !par->params().leftIndent().zero())
2168                         {
2169                                 par = par->TeXEnvironment(this, params, ofs, texrow);
2170                         } else {
2171                                 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2172                         }
2173                 } else {
2174                         par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2175                 }
2176         }
2177         // It might be that we only have a title in this document
2178         if (was_title && !already_title) {
2179                 ofs << "\\maketitle\n";
2180                 texrow.newline();
2181         }
2182 }
2183
2184
2185 bool Buffer::isLatex() const
2186 {
2187         return params.getLyXTextClass().outputType() == LATEX;
2188 }
2189
2190
2191 bool Buffer::isLinuxDoc() const
2192 {
2193         return params.getLyXTextClass().outputType() == LINUXDOC;
2194 }
2195
2196
2197 bool Buffer::isLiterate() const
2198 {
2199         return params.getLyXTextClass().outputType() == LITERATE;
2200 }
2201
2202
2203 bool Buffer::isDocBook() const
2204 {
2205         return params.getLyXTextClass().outputType() == DOCBOOK;
2206 }
2207
2208
2209 bool Buffer::isSGML() const
2210 {
2211         LyXTextClass const & tclass = params.getLyXTextClass();
2212
2213         return tclass.outputType() == LINUXDOC ||
2214                tclass.outputType() == DOCBOOK;
2215 }
2216
2217
2218 int Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2219                          string const & latexname) const
2220 {
2221         if (!latexname.empty() && latexname != "!-- --") {
2222                 if (!mixcont)
2223                         os << string(" ",depth);
2224                 os << "<" << latexname << ">";
2225         }
2226
2227         if (!mixcont)
2228                 os << endl;
2229
2230         return mixcont?0:1;
2231 }
2232
2233
2234 int Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2235                           string const & latexname) const
2236 {
2237         if (!latexname.empty() && latexname != "!-- --") {
2238                 if (!mixcont)
2239                         os << endl << string(" ",depth);
2240                 os << "</" << latexname << ">";
2241         }
2242
2243         if (!mixcont)
2244                 os << endl;
2245
2246         return mixcont?0:1;
2247 }
2248
2249
2250 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2251 {
2252         ofstream ofs(fname.c_str());
2253
2254         if (!ofs) {
2255                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2256                 return;
2257         }
2258
2259         niceFile = nice; // this will be used by included files.
2260
2261         LaTeXFeatures features(params);
2262
2263         validate(features);
2264
2265         texrow.reset();
2266
2267         LyXTextClass const & tclass = params.getLyXTextClass();
2268
2269         string top_element = tclass.latexname();
2270
2271         if (!body_only) {
2272                 ofs << "<!doctype linuxdoc system";
2273
2274                 string preamble = params.preamble;
2275                 const string name = nice ? ChangeExtension(filename_, ".sgml")
2276                          : fname;
2277                 preamble += features.getIncludedFiles(name);
2278                 preamble += features.getLyXSGMLEntities();
2279
2280                 if (!preamble.empty()) {
2281                         ofs << " [ " << preamble << " ]";
2282                 }
2283                 ofs << ">\n\n";
2284
2285                 if (params.options.empty())
2286                         sgmlOpenTag(ofs, 0, false, top_element);
2287                 else {
2288                         string top = top_element;
2289                         top += " ";
2290                         top += params.options;
2291                         sgmlOpenTag(ofs, 0, false, top);
2292                 }
2293         }
2294
2295         ofs << "<!-- "  << lyx_docversion
2296             << " created this file. For more info see http://www.lyx.org/"
2297             << " -->\n";
2298
2299         Paragraph::depth_type depth = 0; // paragraph depth
2300         Paragraph * par = &*(paragraphs.begin());
2301         string item_name;
2302         vector<string> environment_stack(5);
2303
2304         while (par) {
2305                 LyXLayout_ptr const & style = par->layout();
2306                 // treat <toc> as a special case for compatibility with old code
2307                 if (par->isInset(0)) {
2308                         Inset * inset = par->getInset(0);
2309                         Inset::Code lyx_code = inset->lyxCode();
2310                         if (lyx_code == Inset::TOC_CODE) {
2311                                 string const temp = "toc";
2312                                 sgmlOpenTag(ofs, depth, false, temp);
2313
2314                                 par = par->next();
2315                                 continue;
2316                         }
2317                 }
2318
2319                 // environment tag closing
2320                 for (; depth > par->params().depth(); --depth) {
2321                         sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2322                         environment_stack[depth].erase();
2323                 }
2324
2325                 // write opening SGML tags
2326                 switch (style->latextype) {
2327                 case LATEX_PARAGRAPH:
2328                         if (depth == par->params().depth()
2329                            && !environment_stack[depth].empty()) {
2330                                 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2331                                 environment_stack[depth].erase();
2332                                 if (depth)
2333                                         --depth;
2334                                 else
2335                                         ofs << "</p>";
2336                         }
2337                         sgmlOpenTag(ofs, depth, false, style->latexname());
2338                         break;
2339
2340                 case LATEX_COMMAND:
2341                         if (depth!= 0)
2342                                 sgmlError(par, 0,
2343                                           _("Error : Wrong depth for"
2344                                             " LatexType Command.\n"));
2345
2346                         if (!environment_stack[depth].empty()) {
2347                                 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2348                                 ofs << "</p>";
2349                         }
2350
2351                         environment_stack[depth].erase();
2352                         sgmlOpenTag(ofs, depth, false, style->latexname());
2353                         break;
2354
2355                 case LATEX_ENVIRONMENT:
2356                 case LATEX_ITEM_ENVIRONMENT:
2357                 {
2358                         string const & latexname = style->latexname();
2359
2360                         if (depth == par->params().depth()
2361                             && environment_stack[depth] != latexname) {
2362                                 sgmlCloseTag(ofs, depth, false,
2363                                              environment_stack[depth]);
2364                                 environment_stack[depth].erase();
2365                         }
2366                         if (depth < par->params().depth()) {
2367                                depth = par->params().depth();
2368                                environment_stack[depth].erase();
2369                         }
2370                         if (environment_stack[depth] != latexname) {
2371                                 if (depth == 0) {
2372                                         sgmlOpenTag(ofs, depth, false, "p");
2373                                 }
2374                                 sgmlOpenTag(ofs, depth, false, latexname);
2375
2376                                 if (environment_stack.size() == depth + 1)
2377                                         environment_stack.push_back("!-- --");
2378                                 environment_stack[depth] = latexname;
2379                         }
2380
2381                         if (style->latexparam() == "CDATA")
2382                                 ofs << "<![CDATA[";
2383
2384                         if (style->latextype == LATEX_ENVIRONMENT) break;
2385
2386                         if (style->labeltype == LABEL_MANUAL)
2387                                 item_name = "tag";
2388                         else
2389                                 item_name = "item";
2390
2391                         sgmlOpenTag(ofs, depth + 1, false, item_name);
2392                 }
2393                 break;
2394
2395                 default:
2396                         sgmlOpenTag(ofs, depth, false, style->latexname());
2397                         break;
2398                 }
2399
2400                 simpleLinuxDocOnePar(ofs, par, depth);
2401
2402                 par = par->next();
2403
2404                 ofs << "\n";
2405                 // write closing SGML tags
2406                 switch (style->latextype) {
2407                 case LATEX_COMMAND:
2408                         break;
2409                 case LATEX_ENVIRONMENT:
2410                 case LATEX_ITEM_ENVIRONMENT:
2411                         if (style->latexparam() == "CDATA")
2412                                 ofs << "]]>";
2413                         break;
2414                 default:
2415                         sgmlCloseTag(ofs, depth, false, style->latexname());
2416                         break;
2417                 }
2418         }
2419
2420         // Close open tags
2421         for (int i = depth; i >= 0; --i)
2422                 sgmlCloseTag(ofs, depth, false, environment_stack[i]);
2423
2424         if (!body_only) {
2425                 ofs << "\n\n";
2426                 sgmlCloseTag(ofs, 0, false, top_element);
2427         }
2428
2429         ofs.close();
2430         // How to check for successful close
2431
2432         // we want this to be true outside previews (for insetexternal)
2433         niceFile = true;
2434 }
2435
2436
2437 // checks, if newcol chars should be put into this line
2438 // writes newline, if necessary.
2439 namespace {
2440
2441 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2442                           string::size_type newcol)
2443 {
2444         colcount += newcol;
2445         if (colcount > lyxrc.ascii_linelen) {
2446                 os << "\n";
2447                 colcount = newcol; // assume write after this call
2448         }
2449 }
2450
2451 enum PAR_TAG {
2452         NONE=0,
2453         TT = 1,
2454         SF = 2,
2455         BF = 4,
2456         IT = 8,
2457         SL = 16,
2458         EM = 32
2459 };
2460
2461
2462 string tag_name(PAR_TAG const & pt) {
2463         switch (pt) {
2464         case NONE: return "!-- --";
2465         case TT: return "tt";
2466         case SF: return "sf";
2467         case BF: return "bf";
2468         case IT: return "it";
2469         case SL: return "sl";
2470         case EM: return "em";
2471         }
2472         return "";
2473 }
2474
2475
2476 inline
2477 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2478 {
2479         p1 = static_cast<PAR_TAG>(p1 | p2);
2480 }
2481
2482
2483 inline
2484 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2485 {
2486         p1 = static_cast<PAR_TAG>(p1 & ~p2);
2487 }
2488
2489 } // anon
2490
2491
2492 // Handle internal paragraph parsing -- layout already processed.
2493 void Buffer::simpleLinuxDocOnePar(ostream & os,
2494         Paragraph * par,
2495         Paragraph::depth_type /*depth*/)
2496 {
2497         LyXLayout_ptr const & style = par->layout();
2498
2499         string::size_type char_line_count = 5;     // Heuristic choice ;-)
2500
2501         // gets paragraph main font
2502         LyXFont font_old;
2503         bool desc_on;
2504         if (style->labeltype == LABEL_MANUAL) {
2505                 font_old = style->labelfont;
2506                 desc_on = true;
2507         } else {
2508                 font_old = style->font;
2509                 desc_on = false;
2510         }
2511
2512         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2513         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2514         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
2515         bool is_em = false;
2516
2517         stack<PAR_TAG> tag_state;
2518         // parsing main loop
2519         for (pos_type i = 0; i < par->size(); ++i) {
2520
2521                 PAR_TAG tag_close = NONE;
2522                 list < PAR_TAG > tag_open;
2523
2524                 LyXFont const font = par->getFont(params, i);
2525
2526                 if (font_old.family() != font.family()) {
2527                         switch (family_type) {
2528                         case LyXFont::SANS_FAMILY:
2529                                 tag_close |= SF;
2530                                 break;
2531                         case LyXFont::TYPEWRITER_FAMILY:
2532                                 tag_close |= TT;
2533                                 break;
2534                         default:
2535                                 break;
2536                         }
2537
2538                         family_type = font.family();
2539
2540                         switch (family_type) {
2541                         case LyXFont::SANS_FAMILY:
2542                                 tag_open.push_back(SF);
2543                                 break;
2544                         case LyXFont::TYPEWRITER_FAMILY:
2545                                 tag_open.push_back(TT);
2546                                 break;
2547                         default:
2548                                 break;
2549                         }
2550                 }
2551
2552                 if (font_old.series() != font.series()) {
2553                         switch (series_type) {
2554                         case LyXFont::BOLD_SERIES:
2555                                 tag_close |= BF;
2556                                 break;
2557                         default:
2558                                 break;
2559                         }
2560
2561                         series_type = font.series();
2562
2563                         switch (series_type) {
2564                         case LyXFont::BOLD_SERIES:
2565                                 tag_open.push_back(BF);
2566                                 break;
2567                         default:
2568                                 break;
2569                         }
2570
2571                 }
2572
2573                 if (font_old.shape() != font.shape()) {
2574                         switch (shape_type) {
2575                         case LyXFont::ITALIC_SHAPE:
2576                                 tag_close |= IT;
2577                                 break;
2578                         case LyXFont::SLANTED_SHAPE:
2579                                 tag_close |= SL;
2580                                 break;
2581                         default:
2582                                 break;
2583                         }
2584
2585                         shape_type = font.shape();
2586
2587                         switch (shape_type) {
2588                         case LyXFont::ITALIC_SHAPE:
2589                                 tag_open.push_back(IT);
2590                                 break;
2591                         case LyXFont::SLANTED_SHAPE:
2592                                 tag_open.push_back(SL);
2593                                 break;
2594                         default:
2595                                 break;
2596                         }
2597                 }
2598                 // handle <em> tag
2599                 if (font_old.emph() != font.emph()) {
2600                         if (font.emph() == LyXFont::ON) {
2601                                 tag_open.push_back(EM);
2602                                 is_em = true;
2603                         }
2604                         else if (is_em) {
2605                                 tag_close |= EM;
2606                                 is_em = false;
2607                         }
2608                 }
2609
2610                 list < PAR_TAG > temp;
2611                 while (!tag_state.empty() && tag_close) {
2612                         PAR_TAG k =  tag_state.top();
2613                         tag_state.pop();
2614                         os << "</" << tag_name(k) << ">";
2615                         if (tag_close & k)
2616                                 reset(tag_close,k);
2617                         else
2618                                 temp.push_back(k);
2619                 }
2620
2621                 for(list< PAR_TAG >::const_iterator j = temp.begin();
2622                     j != temp.end(); ++j) {
2623                         tag_state.push(*j);
2624                         os << "<" << tag_name(*j) << ">";
2625                 }
2626
2627                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2628                     j != tag_open.end(); ++j) {
2629                         tag_state.push(*j);
2630                         os << "<" << tag_name(*j) << ">";
2631                 }
2632
2633                 char c = par->getChar(i);
2634
2635                 if (c == Paragraph::META_INSET) {
2636                         Inset * inset = par->getInset(i);
2637                         inset->linuxdoc(this, os);
2638                         font_old = font;
2639                         continue;
2640                 }
2641
2642                 if (style->latexparam() == "CDATA") {
2643                         // "TeX"-Mode on == > SGML-Mode on.
2644                         if (c != '\0')
2645                                 os << c;
2646                         ++char_line_count;
2647                 } else {
2648                         bool ws;
2649                         string str;
2650                         boost::tie(ws, str) = sgml::escapeChar(c);
2651                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2652                                 // in freespacing mode, spaces are
2653                                 // non-breaking characters
2654                                 if (desc_on) {// if char is ' ' then...
2655
2656                                         ++char_line_count;
2657                                         sgmlLineBreak(os, char_line_count, 6);
2658                                         os << "</tag>";
2659                                         desc_on = false;
2660                                 } else  {
2661                                         sgmlLineBreak(os, char_line_count, 1);
2662                                         os << c;
2663                                 }
2664                         } else {
2665                                 os << str;
2666                                 char_line_count += str.length();
2667                         }
2668                 }
2669                 font_old = font;
2670         }
2671
2672         while (!tag_state.empty()) {
2673                 os << "</" << tag_name(tag_state.top()) << ">";
2674                 tag_state.pop();
2675         }
2676
2677         // resets description flag correctly
2678         if (desc_on) {
2679                 // <tag> not closed...
2680                 sgmlLineBreak(os, char_line_count, 6);
2681                 os << "</tag>";
2682         }
2683 }
2684
2685
2686 // Print an error message.
2687 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2688         string const & /*message*/) const
2689 {
2690 #ifdef WITH_WARNINGS
2691 #warning This is wrong we cannot insert an inset like this!!!
2692         // I guess this was Jose' so I explain you more or less why this
2693         // is wrong. This way you insert something in the paragraph and
2694         // don't tell it to LyXText (row rebreaking and undo handling!!!)
2695         // I deactivate this code, have a look at BufferView::insertErrors
2696         // how you should do this correctly! (Jug 20020315)
2697 #endif
2698 #if 0
2699         // insert an error marker in text
2700         InsetError * new_inset = new InsetError(message);
2701         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2702                          params.language));
2703 #endif
2704 }
2705
2706
2707 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2708 {
2709         ofstream ofs(fname.c_str());
2710         if (!ofs) {
2711                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2712                 return;
2713         }
2714
2715         Paragraph * par = &*(paragraphs.begin());
2716
2717         niceFile = nice; // this will be used by Insetincludes.
2718
2719         LaTeXFeatures features(params);
2720         validate(features);
2721
2722         texrow.reset();
2723
2724         LyXTextClass const & tclass = params.getLyXTextClass();
2725         string top_element = tclass.latexname();
2726
2727         if (!only_body) {
2728                 ofs << "<!DOCTYPE " << top_element
2729                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2730
2731                 string preamble = params.preamble;
2732                 const string name = nice ? ChangeExtension(filename_, ".sgml")
2733                          : fname;
2734                 preamble += features.getIncludedFiles(name);
2735                 preamble += features.getLyXSGMLEntities();
2736
2737                 if (!preamble.empty()) {
2738                         ofs << "\n [ " << preamble << " ]";
2739                 }
2740                 ofs << ">\n\n";
2741         }
2742
2743         string top = top_element;
2744         top += " lang=\"";
2745         top += params.language->code();
2746         top += "\"";
2747
2748         if (!params.options.empty()) {
2749                 top += " ";
2750                 top += params.options;
2751         }
2752         sgmlOpenTag(ofs, 0, false, top);
2753
2754         ofs << "<!-- DocBook file was created by " << lyx_docversion
2755             << "\n  See http://www.lyx.org/ for more information -->\n";
2756
2757         vector<string> environment_stack(10);
2758         vector<string> environment_inner(10);
2759         vector<string> command_stack(10);
2760
2761         bool command_flag = false;
2762         Paragraph::depth_type command_depth = 0;
2763         Paragraph::depth_type command_base = 0;
2764         Paragraph::depth_type cmd_depth = 0;
2765         Paragraph::depth_type depth = 0; // paragraph depth
2766
2767         string item_name;
2768         string command_name;
2769
2770         while (par) {
2771                 string sgmlparam;
2772                 string c_depth;
2773                 string c_params;
2774                 int desc_on = 0; // description mode
2775
2776                 LyXLayout_ptr const & style = par->layout();
2777
2778                 // environment tag closing
2779                 for (; depth > par->params().depth(); --depth) {
2780                         if (environment_inner[depth] != "!-- --") {
2781                                 item_name = "listitem";
2782                                 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2783                                 if (environment_inner[depth] == "varlistentry")
2784                                         sgmlCloseTag(ofs, depth+command_depth, false, environment_inner[depth]);
2785                         }
2786                         sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2787                         environment_stack[depth].erase();
2788                         environment_inner[depth].erase();
2789                 }
2790
2791                 if (depth == par->params().depth()
2792                    && environment_stack[depth] != style->latexname()
2793                    && !environment_stack[depth].empty()) {
2794                         if (environment_inner[depth] != "!-- --") {
2795                                 item_name= "listitem";
2796                                 sgmlCloseTag(ofs, command_depth+depth, false, item_name);
2797                                 if (environment_inner[depth] == "varlistentry")
2798                                         sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2799                         }
2800
2801                         sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2802
2803                         environment_stack[depth].erase();
2804                         environment_inner[depth].erase();
2805                 }
2806
2807                 // Write opening SGML tags.
2808                 switch (style->latextype) {
2809                 case LATEX_PARAGRAPH:
2810                         sgmlOpenTag(ofs, depth + command_depth,
2811                                     false, style->latexname());
2812                         break;
2813
2814                 case LATEX_COMMAND:
2815                         if (depth != 0)
2816                                 sgmlError(par, 0,
2817                                           _("Error : Wrong depth for "
2818                                             "LatexType Command.\n"));
2819
2820                         command_name = style->latexname();
2821
2822                         sgmlparam = style->latexparam();
2823                         c_params = split(sgmlparam, c_depth,'|');
2824
2825                         cmd_depth = lyx::atoi(c_depth);
2826
2827                         if (command_flag) {
2828                                 if (cmd_depth < command_base) {
2829                                         for (Paragraph::depth_type j = command_depth;
2830                                              j >= command_base; --j) {
2831                                                 sgmlCloseTag(ofs, j, false, command_stack[j]);
2832                                                 ofs << endl;
2833                                         }
2834                                         command_depth = command_base = cmd_depth;
2835                                 } else if (cmd_depth <= command_depth) {
2836                                         for (int j = command_depth;
2837                                              j >= int(cmd_depth); --j) {
2838                                                 sgmlCloseTag(ofs, j, false, command_stack[j]);
2839                                                 ofs << endl;
2840                                         }
2841                                         command_depth = cmd_depth;
2842                                 } else
2843                                         command_depth = cmd_depth;
2844                         } else {
2845                                 command_depth = command_base = cmd_depth;
2846                                 command_flag = true;
2847                         }
2848                         if (command_stack.size() == command_depth + 1)
2849                                 command_stack.push_back(string());
2850                         command_stack[command_depth] = command_name;
2851
2852                         // treat label as a special case for
2853                         // more WYSIWYM handling.
2854                         // This is a hack while paragraphs can't have
2855                         // attributes, like id in this case.
2856                         if (par->isInset(0)) {
2857                                 Inset * inset = par->getInset(0);
2858                                 Inset::Code lyx_code = inset->lyxCode();
2859                                 if (lyx_code == Inset::LABEL_CODE) {
2860                                         command_name += " id=\"";
2861                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
2862                                         command_name += "\"";
2863                                         desc_on = 3;
2864                                 }
2865                         }
2866
2867                         sgmlOpenTag(ofs, depth + command_depth, false, command_name);
2868
2869                         item_name = c_params.empty()?"title":c_params;
2870                         sgmlOpenTag(ofs, depth + 1 + command_depth, false, item_name);
2871                         break;
2872
2873                 case LATEX_ENVIRONMENT:
2874                 case LATEX_ITEM_ENVIRONMENT:
2875                         if (depth < par->params().depth()) {
2876                                 depth = par->params().depth();
2877                                 environment_stack[depth].erase();
2878                         }
2879
2880                         if (environment_stack[depth] != style->latexname()) {
2881                                 if (environment_stack.size() == depth + 1) {
2882                                         environment_stack.push_back("!-- --");
2883                                         environment_inner.push_back("!-- --");
2884                                 }
2885                                 environment_stack[depth] = style->latexname();
2886                                 environment_inner[depth] = "!-- --";
2887                                 sgmlOpenTag(ofs, depth + command_depth, false, environment_stack[depth]);
2888                         } else {
2889                                 if (environment_inner[depth] != "!-- --") {
2890                                         item_name= "listitem";
2891                                         sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2892                                         if (environment_inner[depth] == "varlistentry")
2893                                                 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2894                                 }
2895                         }
2896
2897                         if (style->latextype == LATEX_ENVIRONMENT) {
2898                                 if (!style->latexparam().empty()) {
2899                                         if (style->latexparam() == "CDATA")
2900                                                 ofs << "<![CDATA[";
2901                                         else
2902                                                 sgmlOpenTag(ofs, depth + command_depth, false, style->latexparam());
2903                                 }
2904                                 break;
2905                         }
2906
2907                         desc_on = (style->labeltype == LABEL_MANUAL);
2908
2909                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2910                         sgmlOpenTag(ofs, depth + 1 + command_depth,
2911                                     false, environment_inner[depth]);
2912
2913                         item_name = desc_on ? "term" : "para";
2914                         sgmlOpenTag(ofs, depth + 1 + command_depth,
2915                                     false, item_name);
2916                         break;
2917                 default:
2918                         sgmlOpenTag(ofs, depth + command_depth,
2919                                     false, style->latexname());
2920                         break;
2921                 }
2922
2923                 simpleDocBookOnePar(ofs, par, desc_on,
2924                                     depth + 1 + command_depth);
2925                 par = par->next();
2926
2927                 string end_tag;
2928                 // write closing SGML tags
2929                 switch (style->latextype) {
2930                 case LATEX_COMMAND:
2931                         end_tag = c_params.empty() ? "title" : c_params;
2932                         sgmlCloseTag(ofs, depth + command_depth,
2933                                      false, end_tag);
2934                         break;
2935                 case LATEX_ENVIRONMENT:
2936                         if (!style->latexparam().empty()) {
2937                                 if (style->latexparam() == "CDATA")
2938                                         ofs << "]]>";
2939                                 else
2940                                         sgmlCloseTag(ofs, depth + command_depth, false, style->latexparam());
2941                         }
2942                         break;
2943                 case LATEX_ITEM_ENVIRONMENT:
2944                         if (desc_on == 1) break;
2945                         end_tag= "para";
2946                         sgmlCloseTag(ofs, depth + 1 + command_depth, false, end_tag);
2947                         break;
2948                 case LATEX_PARAGRAPH:
2949                         sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2950                         break;
2951                 default:
2952                         sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2953                         break;
2954                 }
2955         }
2956
2957         // Close open tags
2958         for (int d = depth; d >= 0; --d) {
2959                 if (!environment_stack[depth].empty()) {
2960                         if (environment_inner[depth] != "!-- --") {
2961                                 item_name = "listitem";
2962                                 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2963                                if (environment_inner[depth] == "varlistentry")
2964                                        sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2965                         }
2966
2967                         sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2968                 }
2969         }
2970
2971         for (int j = command_depth; j >= 0 ; --j)
2972                 if (!command_stack[j].empty()) {
2973                         sgmlCloseTag(ofs, j, false, command_stack[j]);
2974                         ofs << endl;
2975                 }
2976
2977         ofs << "\n\n";
2978         sgmlCloseTag(ofs, 0, false, top_element);
2979
2980         ofs.close();
2981         // How to check for successful close
2982
2983         // we want this to be true outside previews (for insetexternal)
2984         niceFile = true;
2985 }
2986
2987
2988 void Buffer::simpleDocBookOnePar(ostream & os,
2989                                  Paragraph * par, int & desc_on,
2990                                  Paragraph::depth_type depth) const
2991 {
2992         bool emph_flag = false;
2993
2994         LyXLayout_ptr const & style = par->layout();
2995
2996         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2997
2998         int char_line_count = depth;
2999         //if (!style.free_spacing)
3000         //      os << string(depth,' ');
3001
3002         // parsing main loop
3003         for (pos_type i = 0; i < par->size(); ++i) {
3004                 LyXFont font = par->getFont(params, i);
3005
3006                 // handle <emphasis> tag
3007                 if (font_old.emph() != font.emph()) {
3008                         if (font.emph() == LyXFont::ON) {
3009                                 if (style->latexparam() == "CDATA")
3010                                         os << "]]>";
3011                                 os << "<emphasis>";
3012                                 if (style->latexparam() == "CDATA")
3013                                         os << "<![CDATA[";
3014                                 emph_flag = true;
3015                         } else if (i) {
3016                                 if (style->latexparam() == "CDATA")
3017                                         os << "]]>";
3018                                 os << "</emphasis>";
3019                                 if (style->latexparam() == "CDATA")
3020                                         os << "<![CDATA[";
3021                                 emph_flag = false;
3022                         }
3023                 }
3024
3025
3026                 if (par->isInset(i)) {
3027                         Inset * inset = par->getInset(i);
3028                         // don't print the inset in position 0 if desc_on == 3 (label)
3029                         if (i || desc_on != 3) {
3030                                 if (style->latexparam() == "CDATA")
3031                                         os << "]]>";
3032                                 inset->docbook(this, os, false);
3033                                 if (style->latexparam() == "CDATA")
3034                                         os << "<![CDATA[";
3035                         }
3036                 } else {
3037                         char c = par->getChar(i);
3038                         bool ws;
3039                         string str;
3040                         boost::tie(ws, str) = sgml::escapeChar(c);
3041
3042                         if (style->pass_thru) {
3043                                 os << c;
3044                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3045                                         os << str;
3046                         } else if (desc_on ==1) {
3047                                 ++char_line_count;
3048                                 os << "\n</term><listitem><para>";
3049                                 desc_on = 2;
3050                         } else {
3051                                 os << ' ';
3052                         }
3053                 }
3054                 font_old = font;
3055         }
3056
3057         if (emph_flag) {
3058                 if (style->latexparam() == "CDATA")
3059                         os << "]]>";
3060                 os << "</emphasis>";
3061                 if (style->latexparam() == "CDATA")
3062                         os << "<![CDATA[";
3063         }
3064
3065         // resets description flag correctly
3066         if (desc_on == 1) {
3067                 // <term> not closed...
3068                 os << "</term>\n<listitem><para>&nbsp;</para>";
3069         }
3070         if (style->free_spacing)
3071                 os << '\n';
3072 }
3073
3074
3075 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3076 // Other flags: -wall -v0 -x
3077 int Buffer::runChktex()
3078 {
3079         if (!users->text) return 0;
3080
3081         users->owner()->prohibitInput();
3082
3083         // get LaTeX-Filename
3084         string const name = getLatexName();
3085         string path = filePath();
3086
3087         string const org_path = path;
3088         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3089                 path = tmppath;
3090         }
3091
3092         Path p(path); // path to LaTeX file
3093         users->owner()->message(_("Running chktex..."));
3094
3095         // Remove all error insets
3096         bool const removedErrorInsets = users->removeAutoInsets();
3097
3098         // Generate the LaTeX file if neccessary
3099         makeLaTeXFile(name, org_path, false);
3100
3101         TeXErrors terr;
3102         Chktex chktex(lyxrc.chktex_command, name, filePath());
3103         int res = chktex.run(terr); // run chktex
3104
3105         if (res == -1) {
3106                 Alert::alert(_("chktex did not work!"),
3107                            _("Could not run with file:"), name);
3108         } else if (res > 0) {
3109                 // Insert all errors as errors boxes
3110                 users->insertErrors(terr);
3111         }
3112
3113         // if we removed error insets before we ran chktex or if we inserted
3114         // error insets after we ran chktex, this must be run:
3115         if (removedErrorInsets || res) {
3116 #warning repaint needed here, or do you mean update() ?
3117                 users->repaint();
3118                 users->fitCursor();
3119         }
3120         users->owner()->allowInput();
3121
3122         return res;
3123 }
3124
3125
3126 void Buffer::validate(LaTeXFeatures & features) const
3127 {
3128         LyXTextClass const & tclass = params.getLyXTextClass();
3129
3130         // AMS Style is at document level
3131         if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3132                 features.require("amsmath");
3133
3134         for_each(paragraphs.begin(), paragraphs.end(),
3135                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3136
3137         // the bullet shapes are buffer level not paragraph level
3138         // so they are tested here
3139         for (int i = 0; i < 4; ++i) {
3140                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3141                         int const font = params.user_defined_bullets[i].getFont();
3142                         if (font == 0) {
3143                                 int const c = params
3144                                         .user_defined_bullets[i]
3145                                         .getCharacter();
3146                                 if (c == 16
3147                                    || c == 17
3148                                    || c == 25
3149                                    || c == 26
3150                                    || c == 31) {
3151                                         features.require("latexsym");
3152                                 }
3153                         } else if (font == 1) {
3154                                 features.require("amssymb");
3155                         } else if ((font >= 2 && font <= 5)) {
3156                                 features.require("pifont");
3157                         }
3158                 }
3159         }
3160
3161         if (lyxerr.debugging(Debug::LATEX)) {
3162                 features.showStruct();
3163         }
3164 }
3165
3166
3167 vector<string> const Buffer::getLabelList() const
3168 {
3169         /// if this is a child document and the parent is already loaded
3170         /// Use the parent's list instead  [ale990407]
3171         if (!params.parentname.empty()
3172             && bufferlist.exists(params.parentname)) {
3173                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3174                 if (tmp)
3175                         return tmp->getLabelList();
3176         }
3177
3178         vector<string> label_list;
3179         for (inset_iterator it = inset_const_iterator_begin();
3180              it != inset_const_iterator_end(); ++it) {
3181                 vector<string> const l = it->getLabelList();
3182                 label_list.insert(label_list.end(), l.begin(), l.end());
3183         }
3184         return label_list;
3185 }
3186
3187
3188 // This is also a buffer property (ale)
3189 vector<pair<string, string> > const Buffer::getBibkeyList() const
3190 {
3191         typedef pair<string, string> StringPair;
3192         /// if this is a child document and the parent is already loaded
3193         /// Use the parent's list instead  [ale990412]
3194         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3195                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3196                 if (tmp)
3197                         return tmp->getBibkeyList();
3198         }
3199
3200         vector<StringPair> keys;
3201         ParagraphList::iterator pit = paragraphs.begin();
3202         ParagraphList::iterator pend = paragraphs.end();
3203         for (; pit != pend; ++pit) {
3204                 if (pit->bibkey) {
3205                         string const key = pit->bibkey->getContents();
3206                         string const opt = pit->bibkey->getOptions();
3207                         string const ref = pit->asString(this, false);
3208                         string const info = opt + "TheBibliographyRef" + ref;
3209
3210                         keys.push_back(StringPair(key, info));
3211                 }
3212         }
3213
3214         if (!keys.empty())
3215                 return keys;
3216
3217         // Might be either using bibtex or a child has bibliography
3218         for (inset_iterator it = inset_const_iterator_begin();
3219                 it != inset_const_iterator_end(); ++it) {
3220                 // Search for Bibtex or Include inset
3221                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
3222                         vector<StringPair> tmp =
3223                                 static_cast<InsetBibtex &>(*it).getKeys(this);
3224                         keys.insert(keys.end(), tmp.begin(), tmp.end());
3225                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3226                         vector<StringPair> const tmp =
3227                                 static_cast<InsetInclude &>(*it).getKeys();
3228                         keys.insert(keys.end(), tmp.begin(), tmp.end());
3229                 }
3230         }
3231
3232         return keys;
3233 }
3234
3235
3236 bool Buffer::isDepClean(string const & name) const
3237 {
3238         DEPCLEAN * item = dep_clean;
3239         while (item && item->master != name)
3240                 item = item->next;
3241         if (!item) return true;
3242         return item->clean;
3243 }
3244
3245
3246 void Buffer::markDepClean(string const & name)
3247 {
3248         if (!dep_clean) {
3249                 dep_clean = new DEPCLEAN;
3250                 dep_clean->clean = true;
3251                 dep_clean->master = name;
3252                 dep_clean->next = 0;
3253         } else {
3254                 DEPCLEAN * item = dep_clean;
3255                 while (item && item->master != name)
3256                         item = item->next;
3257                 if (item) {
3258                         item->clean = true;
3259                 } else {
3260                         item = new DEPCLEAN;
3261                         item->clean = true;
3262                         item->master = name;
3263                         item->next = 0;
3264                 }
3265         }
3266 }
3267
3268
3269 bool Buffer::dispatch(string const & command, bool * result)
3270 {
3271         // Split command string into command and argument
3272         string cmd;
3273         string line = ltrim(command);
3274         string const arg = trim(split(line, cmd, ' '));
3275
3276         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3277 }
3278
3279
3280 bool Buffer::dispatch(int action, string const & argument, bool * result)
3281 {
3282         bool dispatched = true;
3283
3284         switch (action) {
3285                 case LFUN_EXPORT: {
3286                         bool const tmp = Exporter::Export(this, argument, false);
3287                         if (result)
3288                                 *result = tmp;
3289                         break;
3290                 }
3291
3292                 default:
3293                         dispatched = false;
3294         }
3295         return dispatched;
3296 }
3297
3298
3299 void Buffer::resizeInsets(BufferView * bv)
3300 {
3301         /// then remove all LyXText in text-insets
3302         for_each(paragraphs.begin(), paragraphs.end(),
3303                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3304 }
3305
3306
3307 void Buffer::redraw()
3308 {
3309 #warning repaint needed here, or do you mean update() ?
3310         users->repaint();
3311         users->fitCursor();
3312 }
3313
3314
3315 void Buffer::changeLanguage(Language const * from, Language const * to)
3316 {
3317
3318         ParIterator end = par_iterator_end();
3319         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3320                 (*it)->changeLanguage(params, from, to);
3321 }
3322
3323
3324 bool Buffer::isMultiLingual()
3325 {
3326         ParIterator end = par_iterator_end();
3327         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3328                 if ((*it)->isMultiLingual(params))
3329                         return true;
3330
3331         return false;
3332 }
3333
3334
3335 void Buffer::inset_iterator::setParagraph()
3336 {
3337         while (pit != pend) {
3338                 it = pit->insetlist.begin();
3339                 if (it != pit->insetlist.end())
3340                         return;
3341                 ++pit;
3342         }
3343 }
3344
3345
3346 Inset * Buffer::getInsetFromID(int id_arg) const
3347 {
3348         for (inset_iterator it = inset_const_iterator_begin();
3349                  it != inset_const_iterator_end(); ++it)
3350         {
3351                 if (it->id() == id_arg)
3352                         return &(*it);
3353                 Inset * in = it->getInsetFromID(id_arg);
3354                 if (in)
3355                         return in;
3356         }
3357         return 0;
3358 }
3359
3360
3361 Paragraph * Buffer::getParFromID(int id) const
3362 {
3363         if (id < 0)
3364                 return 0;
3365
3366         ParagraphList::iterator it = paragraphs.begin();
3367         ParagraphList::iterator end = paragraphs.end();
3368         for (; it != end; ++it) {
3369                 if (it->id() == id) {
3370                         return &*it;
3371                 }
3372                 Paragraph * tmp = it->getParFromID(id);
3373                 if (tmp) {
3374                         return tmp;
3375                 }
3376         }
3377         return 0;
3378 }
3379
3380
3381 ParIterator Buffer::par_iterator_begin()
3382 {
3383         return ParIterator(&*(paragraphs.begin()));
3384 }
3385
3386
3387 ParIterator Buffer::par_iterator_end()
3388 {
3389         return ParIterator();
3390 }
3391
3392
3393 void Buffer::addUser(BufferView * u)
3394 {
3395         users = u;
3396 }
3397
3398
3399 void Buffer::delUser(BufferView *)
3400 {
3401         users = 0;
3402 }
3403
3404
3405 Language const * Buffer::getLanguage() const
3406 {
3407         return params.language;
3408 }
3409
3410
3411 bool Buffer::isClean() const
3412 {
3413         return lyx_clean;
3414 }
3415
3416
3417 bool Buffer::isBakClean() const
3418 {
3419         return bak_clean;
3420 }
3421
3422
3423 void Buffer::markClean() const
3424 {
3425         if (!lyx_clean) {
3426                 lyx_clean = true;
3427                 updateTitles();
3428         }
3429         // if the .lyx file has been saved, we don't need an
3430         // autosave
3431         bak_clean = true;
3432 }
3433
3434
3435 void Buffer::markBakClean()
3436 {
3437         bak_clean = true;
3438 }
3439
3440
3441 void Buffer::setUnnamed(bool flag)
3442 {
3443         unnamed = flag;
3444 }
3445
3446
3447 bool Buffer::isUnnamed()
3448 {
3449         return unnamed;
3450 }
3451
3452
3453 void Buffer::markDirty()
3454 {
3455         if (lyx_clean) {
3456                 lyx_clean = false;
3457                 updateTitles();
3458         }
3459         bak_clean = false;
3460         DEPCLEAN * tmp = dep_clean;
3461         while (tmp) {
3462                 tmp->clean = false;
3463                 tmp = tmp->next;
3464         }
3465 }
3466
3467
3468 string const & Buffer::fileName() const
3469 {
3470         return filename_;
3471 }
3472
3473
3474 string const & Buffer::filePath() const
3475 {
3476         return filepath_;
3477 }
3478
3479
3480 bool Buffer::isReadonly() const
3481 {
3482         return read_only;
3483 }
3484
3485
3486 BufferView * Buffer::getUser() const
3487 {
3488         return users;
3489 }
3490
3491
3492 void Buffer::setParentName(string const & name)
3493 {
3494         params.parentname = name;
3495 }
3496
3497
3498 Buffer::inset_iterator::inset_iterator()
3499         : pit(0), pend(0)
3500 {}
3501
3502
3503 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3504         : pit(p), pend(e)
3505 {
3506         setParagraph();
3507 }
3508
3509
3510 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3511 {
3512         if (pit != pend) {
3513                 ++it;
3514                 if (it == pit->insetlist.end()) {
3515                         ++pit;
3516                         setParagraph();
3517                 }
3518         }
3519         return *this;
3520 }
3521
3522
3523 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3524 {
3525         inset_iterator tmp = *this;
3526         ++*this;
3527         return tmp;
3528 }
3529
3530
3531 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3532 {
3533         return *it.getInset();
3534 }
3535
3536
3537 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3538 {
3539         return it.getInset();
3540 }
3541
3542
3543 Paragraph * Buffer::inset_iterator::getPar()
3544 {
3545         return &(*pit);
3546 }
3547
3548
3549 lyx::pos_type Buffer::inset_iterator::getPos() const
3550 {
3551         return it.getPos();
3552 }
3553
3554
3555 bool operator==(Buffer::inset_iterator const & iter1,
3556                 Buffer::inset_iterator const & iter2)
3557 {
3558         return iter1.pit == iter2.pit
3559                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3560 }
3561
3562
3563 bool operator!=(Buffer::inset_iterator const & iter1,
3564                 Buffer::inset_iterator const & iter2)
3565 {
3566         return !(iter1 == iter2);
3567 }