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