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