]> git.lyx.org Git - lyx.git/blob - src/buffer.C
small tweak
[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 #include "buffer.h"
18 #include "bufferlist.h"
19 #include "LyXAction.h"
20 #include "lyxrc.h"
21 #include "lyxlex.h"
22 #include "tex-strings.h"
23 #include "layout.h"
24 #include "bufferview_funcs.h"
25 #include "lyxfont.h"
26 #include "version.h"
27 #include "LaTeX.h"
28 #include "Chktex.h"
29 #include "debug.h"
30 #include "LaTeXFeatures.h"
31 #include "lyxtext.h"
32 #include "gettext.h"
33 #include "language.h"
34 #include "exporter.h"
35 #include "Lsstream.h"
36 #include "format.h"
37 #include "BufferView.h"
38 #include "ParagraphParameters.h"
39 #include "iterators.h"
40 #include "lyxtextclasslist.h"
41 #include "sgml.h"
42 #include "paragraph_funcs.h"
43 #include "author.h"
44
45 #include "frontends/LyXView.h"
46
47 #include "mathed/formulamacro.h"
48 #include "mathed/formula.h"
49
50 #include "insets/inset.h"
51 #include "insets/inseterror.h"
52 #include "insets/insethfill.h"
53 #include "insets/insetlabel.h"
54 #include "insets/insetref.h"
55 #include "insets/inseturl.h"
56 #include "insets/insetnote.h"
57 #include "insets/insetquotes.h"
58 #include "insets/insetlatexaccent.h"
59 #include "insets/insetbibitem.h"
60 #include "insets/insetbibtex.h"
61 #include "insets/insetcite.h"
62 #include "insets/insetexternal.h"
63 #include "insets/insetindex.h"
64 #include "insets/insetinclude.h"
65 #include "insets/insettoc.h"
66 #include "insets/insetparent.h"
67 #include "insets/insetspecialchar.h"
68 #include "insets/insettext.h"
69 #include "insets/insetert.h"
70 #include "insets/insetgraphics.h"
71 #include "insets/insetfoot.h"
72 #include "insets/insetmarginal.h"
73 #include "insets/insetoptarg.h"
74 #include "insets/insetminipage.h"
75 #include "insets/insetfloat.h"
76 #include "insets/insetwrap.h"
77 #include "insets/insettabular.h"
78 #if 0
79 #include "insets/insettheorem.h"
80 #include "insets/insetlist.h"
81 #endif
82 #include "insets/insetcaption.h"
83 #include "insets/insetfloatlist.h"
84
85 #include "frontends/Dialogs.h"
86 #include "frontends/Alert.h"
87
88 #include "graphics/Previews.h"
89
90 #include "support/textutils.h"
91 #include "support/filetools.h"
92 #include "support/path.h"
93 #include "support/os.h"
94 #include "support/lyxlib.h"
95 #include "support/FileInfo.h"
96 #include "support/lyxmanip.h"
97 #include "support/lyxtime.h"
98
99 #include <boost/bind.hpp>
100 #include <boost/tuple/tuple.hpp>
101 #include "BoostFormat.h"
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::stack;
136 using std::list;
137 using std::for_each;
138
139 using lyx::pos_type;
140 using lyx::textclass_type;
141
142 // all these externs should eventually be removed.
143 extern BufferList bufferlist;
144
145 namespace {
146
147 const int LYX_FORMAT = 222;
148
149 } // namespace anon
150
151 Buffer::Buffer(string const & file, bool ronly)
152         : niceFile(true), lyx_clean(true), bak_clean(true),
153           unnamed(false), read_only(ronly),
154           filename_(file), users(0)
155 {
156         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
157         filepath_ = OnlyPath(file);
158         lyxvc.buffer(this);
159         if (read_only || lyxrc.use_tempdir) {
160                 tmppath = CreateBufferTmpDir();
161         } else {
162                 tmppath.erase();
163         }
164
165         // set initial author
166         authors().record(Author(lyxrc.user_name, lyxrc.user_email));
167 }
168
169
170 Buffer::~Buffer()
171 {
172         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
173         // here the buffer should take care that it is
174         // saved properly, before it goes into the void.
175
176         // make sure that views using this buffer
177         // forgets it.
178         if (users)
179                 users->buffer(0);
180
181         if (!tmppath.empty()) {
182                 DestroyBufferTmpDir(tmppath);
183         }
184
185         paragraphs.clear();
186
187         // Remove any previewed LaTeX snippets assocoated with this buffer.
188         grfx::Previews::get().removeLoader(this);
189 }
190
191
192 string const Buffer::getLatexName(bool no_path) const
193 {
194         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
195         if (no_path)
196                 return OnlyFilename(name);
197         else
198                 return name;
199 }
200
201
202 pair<Buffer::LogType, string> const Buffer::getLogName() const
203 {
204         string const filename = getLatexName(false);
205
206         if (filename.empty())
207                 return make_pair(Buffer::latexlog, string());
208
209         string path = OnlyPath(filename);
210
211         if (lyxrc.use_tempdir || !IsDirWriteable(path))
212                 path = tmppath;
213
214         string const fname = AddName(path,
215                                      OnlyFilename(ChangeExtension(filename,
216                                                                   ".log")));
217         string const bname =
218                 AddName(path, OnlyFilename(
219                         ChangeExtension(filename,
220                                         formats.extension("literate") + ".out")));
221
222         // If no Latex log or Build log is newer, show Build log
223
224         FileInfo const f_fi(fname);
225         FileInfo const b_fi(bname);
226
227         if (b_fi.exist() &&
228             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
229                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
230                 return make_pair(Buffer::buildlog, bname);
231         }
232         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
233         return make_pair(Buffer::latexlog, fname);
234 }
235
236
237 void Buffer::setReadonly(bool flag)
238 {
239         if (read_only != flag) {
240                 read_only = flag;
241                 updateTitles();
242                 users->owner()->getDialogs().updateBufferDependent(false);
243         }
244 }
245
246
247 AuthorList & Buffer::authors()
248 {
249         return params.authorlist;
250 }
251
252
253 /// Update window titles of all users
254 // Should work on a list
255 void Buffer::updateTitles() const
256 {
257         if (users)
258                 users->owner()->updateWindowTitle();
259 }
260
261
262 /// Reset autosave timer of all users
263 // Should work on a list
264 void Buffer::resetAutosaveTimers() const
265 {
266         if (users)
267                 users->owner()->resetAutosaveTimer();
268 }
269
270
271 void Buffer::setFileName(string const & newfile)
272 {
273         filename_ = MakeAbsPath(newfile);
274         filepath_ = OnlyPath(filename_);
275         setReadonly(IsFileWriteable(filename_) == 0);
276         updateTitles();
277 }
278
279
280 // We'll remove this later. (Lgb)
281 namespace {
282
283 #ifdef WITH_WARNINGS
284 #warning this is never set to != 0 !!! - remove ?
285 #endif
286 int unknown_layouts;
287
288 void unknownClass(string const & unknown)
289 {
290         string msg =
291 #if USE_BOOST_FORMAT
292                 boost::io::str(boost::format(
293                         _("The document uses an unknown textclass \"%1$s\".")) % unknown)
294                 + _("-- substituting default.");
295 #else
296                 _("The document uses an unknown textclass ")
297                 + unknown + _("-- substituting default.");
298 #endif
299         Alert::alert(_("Textclass error"), msg);
300 }
301
302 } // anon
303
304 int Buffer::readHeader(LyXLex & lex)
305 {
306         int unknown_tokens = 0;
307
308         while (lex.isOK()) {
309                 lex.nextToken();
310                 string const token = lex.getString();
311
312                 if (token.empty())
313                         continue;
314
315                 if (token == "\\end_header")
316                         break;
317
318                 lyxerr[Debug::PARSER] << "Handling header token: `"
319                                       << token << '\'' << endl;
320
321                 string unknown = params.readToken(lex, token);
322                 if (!unknown.empty()) {
323                         if (unknown[0] != '\\') {
324                                 unknownClass(unknown);
325                         } else {
326                         ++unknown_tokens;
327                         }
328                 }
329         }
330         return unknown_tokens;
331 }
332
333
334 // candidate for move to BufferView
335 // (at least some parts in the beginning of the func)
336 //
337 // Uwe C. Schroeder
338 // changed to be public and have one parameter
339 // if par = 0 normal behavior
340 // else insert behavior
341 // Returns false if "\the_end" is not read (Asger)
342 bool Buffer::readBody(LyXLex & lex, Paragraph * par)
343 {
344         unknown_layouts = 0;
345         int unknown_tokens = 0;
346
347         int pos = 0;
348         Paragraph::depth_type depth = 0;
349         bool the_end_read = false;
350
351         Paragraph * first_par = 0;
352         LyXFont font(LyXFont::ALL_INHERIT, params.language);
353
354         if (!par) {
355                 // New document
356                 par = new Paragraph;
357                 par->layout(params.getLyXTextClass().defaultLayout());
358                 // mark the first paragraph
359                 if (params.tracking_changes)
360                         par->trackChanges();
361
362                 unknown_tokens += readHeader(lex);
363
364                 if (!params.getLyXTextClass().load()) {
365 #if USE_BOOST_FORMAT
366                         Alert::alert(_("Textclass Loading Error!"),
367                                    boost::io::str(boost::format(_("Can't load textclass %1$s")) %
368                                    params.getLyXTextClass().name()),
369                                    _("-- substituting default."));
370 #else
371                         Alert::alert(_("Textclass Loading Error!"),
372                                      _("Can't load textclass ")
373                                      + params.getLyXTextClass().name(),
374                                      _("-- substituting default."));
375 #endif
376                         params.textclass = 0;
377                 }
378         } else {
379                 // We are inserting into an existing document
380                 users->text->breakParagraph(users, paragraphs);
381                 first_par = users->text->ownerParagraph();
382                 pos = 0;
383                 markDirty();
384
385                 // We don't want to adopt the parameters from the
386                 // document we insert, so read them into a temporary buffer
387                 // and then discard it
388
389                 Buffer tmpbuf("", false);
390                 tmpbuf.readHeader(lex);
391         }
392
393         while (lex.isOK()) {
394                 lex.nextToken();
395                 string const token = lex.getString();
396
397                 if (token.empty())
398                         continue;
399
400                 lyxerr[Debug::PARSER] << "Handling token: `"
401                                       << token << '\'' << endl;
402
403                 if (token == "\\the_end") {
404                         the_end_read = true;
405                         continue;
406                 }
407
408                 unknown_tokens += readToken(lex, par, first_par,
409                                             token, pos, depth, font);
410         }
411
412         if (!first_par)
413                 first_par = par;
414
415         paragraphs.set(first_par);
416
417         if (unknown_layouts > 0) {
418                 string s = _("Couldn't set the layout for ");
419                 if (unknown_layouts == 1) {
420                         s += _("one paragraph");
421                 } else {
422                         s += tostr(unknown_layouts);
423                         s += _(" paragraphs");
424                 }
425 #if USE_BOOST_FORMAT
426                 Alert::alert(_("Textclass Loading Error!"), s,
427                            boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
428 #else
429                 Alert::alert(_("Textclass Loading Error!"), s,
430                              _("When reading ") + fileName());
431 #endif
432         }
433
434         if (unknown_tokens > 0) {
435                 string s = _("Encountered ");
436                 if (unknown_tokens == 1) {
437                         s += _("one unknown token");
438                 } else {
439                         s += tostr(unknown_tokens);
440                         s += _(" unknown tokens");
441                 }
442 #if USE_BOOST_FORMAT
443                 Alert::alert(_("Textclass Loading Error!"), s,
444                            boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
445 #else
446                 Alert::alert(_("Textclass Loading Error!"), s,
447                              _("When reading ") +  fileName());
448 #endif
449         }
450
451         return the_end_read;
452 }
453
454
455 int
456 Buffer::readToken(LyXLex & lex, Paragraph *& par,
457                                    Paragraph *& first_par,
458                                    string const & token, int & pos,
459                                    Paragraph::depth_type & depth,
460                                    LyXFont & font
461         )
462 {
463         static Change current_change;
464         int unknown = 0;
465
466         // The order of the tags tested may seem unnatural, but this
467         // has been done in order to reduce the number of string
468         // comparisons needed to recognize a given token. This leads
469         // on large documents like UserGuide to a reduction of a
470         // factor 5! (JMarc)
471         if (token[0] != '\\') {
472                 for (string::const_iterator cit = token.begin();
473                      cit != token.end(); ++cit) {
474                         par->insertChar(pos, (*cit), font, current_change);
475                         ++pos;
476                 }
477         } else if (token == "\\layout") {
478                 // reset the font as we start a new layout and if the font is
479                 // not ALL_INHERIT,document_language then it will be set to the
480                 // right values after this tag (Jug 20020420)
481                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
482
483                 lex.eatLine();
484                 string layoutname = lex.getString();
485
486                 LyXTextClass const & tclass = params.getLyXTextClass();
487
488                 if (layoutname.empty()) {
489                         layoutname = tclass.defaultLayoutName();
490                 }
491                 bool hasLayout = tclass.hasLayout(layoutname);
492                 if (!hasLayout) {
493                         lyxerr << "Layout '" << layoutname << "' does not"
494                                << " exist in textclass '" << tclass.name()
495                                << "'." << endl;
496                         lyxerr << "Trying to use default layout instead."
497                                << endl;
498                         layoutname = tclass.defaultLayoutName();
499                 }
500
501 #ifdef USE_CAPTION
502                 // The is the compability reading of layout caption.
503                 // It can be removed in LyX version 1.3.0. (Lgb)
504                 if (compare_ascii_no_case(layoutname, "caption") == 0) {
505                         // We expect that the par we are now working on is
506                         // really inside a InsetText inside a InsetFloat.
507                         // We also know that captions can only be
508                         // one paragraph. (Lgb)
509
510                         // We should now read until the next "\layout"
511                         // is reached.
512                         // This is probably not good enough, what if the
513                         // caption is the last par in the document (Lgb)
514                         istream & ist = lex.getStream();
515                         stringstream ss;
516                         string line;
517                         int begin = 0;
518                         while (true) {
519                                 getline(ist, line);
520                                 if (prefixIs(line, "\\layout")) {
521                                         lex.pushToken(line);
522                                         break;
523                                 }
524                                 if (prefixIs(line, "\\begin_inset"))
525                                         ++begin;
526                                 if (prefixIs(line, "\\end_inset")) {
527                                         if (begin)
528                                                 --begin;
529                                         else {
530                                                 lex.pushToken(line);
531                                                 break;
532                                         }
533                                 }
534
535                                 ss << line << '\n';
536                         }
537                         // Now we should have the whole layout in ss
538                         // we should now be able to give this to the
539                         // caption inset.
540                         ss << "\\end_inset\n";
541
542                         // This seems like a bug in stringstream.
543                         // We really should be able to use ss
544                         // directly. (Lgb)
545                         istringstream is(ss.str());
546                         LyXLex tmplex(0, 0);
547                         tmplex.setStream(is);
548                         Inset * inset = new InsetCaption;
549                         inset->Read(this, tmplex);
550                         par->InsertInset(pos, inset, font);
551                         ++pos;
552                 } else {
553 #endif
554                         if (!first_par)
555                                 first_par = par;
556                         else {
557                                 par = new Paragraph(par);
558                                 par->layout(params.getLyXTextClass().defaultLayout());
559                                 if (params.tracking_changes)
560                                         par->trackChanges();
561                         }
562                         pos = 0;
563                         par->layout(params.getLyXTextClass()[layoutname]);
564                         // Test whether the layout is obsolete.
565                         LyXLayout_ptr const & layout = par->layout();
566                         if (!layout->obsoleted_by().empty())
567                                 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
568                         par->params().depth(depth);
569 #if USE_CAPTION
570                 }
571 #endif
572
573         } else if (token == "\\end_inset") {
574                 lyxerr << "Solitary \\end_inset in line " << lex.getLineNo() << "\n"
575                        << "Missing \\begin_inset?.\n";
576                 // Simply ignore this. The insets do not have
577                 // to read this.
578                 // But insets should read it, it is a part of
579                 // the inset isn't it? Lgb.
580         } else if (token == "\\begin_inset") {
581                 readInset(lex, par, pos, font, current_change);
582         } else if (token == "\\family") {
583                 lex.next();
584                 font.setLyXFamily(lex.getString());
585         } else if (token == "\\series") {
586                 lex.next();
587                 font.setLyXSeries(lex.getString());
588         } else if (token == "\\shape") {
589                 lex.next();
590                 font.setLyXShape(lex.getString());
591         } else if (token == "\\size") {
592                 lex.next();
593                 font.setLyXSize(lex.getString());
594         } else if (token == "\\lang") {
595                 lex.next();
596                 string const tok = lex.getString();
597                 Language const * lang = languages.getLanguage(tok);
598                 if (lang) {
599                         font.setLanguage(lang);
600                 } else {
601                         font.setLanguage(params.language);
602                         lex.printError("Unknown language `$$Token'");
603                 }
604         } else if (token == "\\numeric") {
605                 lex.next();
606                 font.setNumber(font.setLyXMisc(lex.getString()));
607         } else if (token == "\\emph") {
608                 lex.next();
609                 font.setEmph(font.setLyXMisc(lex.getString()));
610         } else if (token == "\\bar") {
611                 lex.next();
612                 string const tok = lex.getString();
613                 // This is dirty, but gone with LyX3. (Asger)
614                 if (tok == "under")
615                         font.setUnderbar(LyXFont::ON);
616                 else if (tok == "no")
617                         font.setUnderbar(LyXFont::OFF);
618                 else if (tok == "default")
619                         font.setUnderbar(LyXFont::INHERIT);
620                 else
621                         lex.printError("Unknown bar font flag "
622                                        "`$$Token'");
623         } else if (token == "\\noun") {
624                 lex.next();
625                 font.setNoun(font.setLyXMisc(lex.getString()));
626         } else if (token == "\\color") {
627                 lex.next();
628                 font.setLyXColor(lex.getString());
629         } else if (token == "\\SpecialChar") {
630                 LyXLayout_ptr const & layout = par->layout();
631
632                 // Insets don't make sense in a free-spacing context! ---Kayvan
633                 if (layout->free_spacing || par->isFreeSpacing()) {
634                         if (lex.isOK()) {
635                                 lex.next();
636                                 string const next_token = lex.getString();
637                                 if (next_token == "\\-") {
638                                         par->insertChar(pos, '-', font, current_change);
639                                 } else if (next_token == "~") {
640                                         par->insertChar(pos, ' ', font, current_change);
641                                 } else {
642                                         lex.printError("Token `$$Token' "
643                                                        "is in free space "
644                                                        "paragraph layout!");
645                                         --pos;
646                                 }
647                         }
648                 } else {
649                         Inset * inset = new InsetSpecialChar;
650                         inset->read(this, lex);
651                         par->insertInset(pos, inset, font, current_change);
652                 }
653                 ++pos;
654         } else if (token == "\\i") {
655                 Inset * inset = new InsetLatexAccent;
656                 inset->read(this, lex);
657                 par->insertInset(pos, inset, font, current_change);
658                 ++pos;
659         } else if (token == "\\backslash") {
660                 par->insertChar(pos, '\\', font, current_change);
661                 ++pos;
662         } else if (token == "\\begin_deeper") {
663                 ++depth;
664         } else if (token == "\\end_deeper") {
665                 if (!depth) {
666                         lex.printError("\\end_deeper: "
667                                        "depth is already null");
668                 }
669                 else
670                         --depth;
671         } else if (token == "\\noindent") {
672                 par->params().noindent(true);
673         } else if (token == "\\leftindent") {
674                 lex.nextToken();
675                 LyXLength value(lex.getString());
676                 par->params().leftIndent(value);
677         } else if (token == "\\fill_top") {
678                 par->params().spaceTop(VSpace(VSpace::VFILL));
679         } else if (token == "\\fill_bottom") {
680                 par->params().spaceBottom(VSpace(VSpace::VFILL));
681         } else if (token == "\\line_top") {
682                 par->params().lineTop(true);
683         } else if (token == "\\line_bottom") {
684                 par->params().lineBottom(true);
685         } else if (token == "\\pagebreak_top") {
686                 par->params().pagebreakTop(true);
687         } else if (token == "\\pagebreak_bottom") {
688                 par->params().pagebreakBottom(true);
689         } else if (token == "\\start_of_appendix") {
690                 par->params().startOfAppendix(true);
691         } else if (token == "\\paragraph_spacing") {
692                 lex.next();
693                 string const tmp = rtrim(lex.getString());
694                 if (tmp == "single") {
695                         par->params().spacing(Spacing(Spacing::Single));
696                 } else if (tmp == "onehalf") {
697                         par->params().spacing(Spacing(Spacing::Onehalf));
698                 } else if (tmp == "double") {
699                         par->params().spacing(Spacing(Spacing::Double));
700                 } else if (tmp == "other") {
701                         lex.next();
702                         par->params().spacing(Spacing(Spacing::Other,
703                                          lex.getFloat()));
704                 } else {
705                         lex.printError("Unknown spacing token: '$$Token'");
706                 }
707         } else if (token == "\\align") {
708                 int tmpret = lex.findToken(string_align);
709                 if (tmpret == -1)
710                         ++tmpret;
711                 int const tmpret2 = int(pow(2.0, tmpret));
712                 par->params().align(LyXAlignment(tmpret2));
713         } else if (token == "\\added_space_top") {
714                 lex.nextToken();
715                 VSpace value = VSpace(lex.getString());
716                 // only add the length when value > 0 or
717                 // with option keep
718                 if ((value.length().len().value() != 0) ||
719                     value.keep() ||
720                     (value.kind() != VSpace::LENGTH))
721                         par->params().spaceTop(value);
722         } else if (token == "\\added_space_bottom") {
723                 lex.nextToken();
724                 VSpace value = VSpace(lex.getString());
725                 // only add the length when value > 0 or
726                 // with option keep
727                 if ((value.length().len().value() != 0) ||
728                    value.keep() ||
729                     (value.kind() != VSpace::LENGTH))
730                         par->params().spaceBottom(value);
731         } else if (token == "\\labelwidthstring") {
732                 lex.eatLine();
733                 par->params().labelWidthString(lex.getString());
734                 // do not delete this token, it is still needed!
735         } else if (token == "\\newline") {
736                 par->insertChar(pos, Paragraph::META_NEWLINE, font, current_change);
737                 ++pos;
738         } else if (token == "\\LyXTable") {
739                 Inset * inset = new InsetTabular(*this);
740                 inset->read(this, lex);
741                 par->insertInset(pos, inset, font, current_change);
742                 ++pos;
743         } else if (token == "\\bibitem") {  // ale970302
744                 InsetCommandParams p("bibitem", "dummy");
745                 InsetBibitem * inset = new InsetBibitem(p);
746                 inset->read(this, lex);
747                 par->insertInset(pos, inset, font, current_change);
748                 ++pos;
749         } else if (token == "\\hfill") {
750                 par->insertInset(pos, new InsetHFill(),
751                         LyXFont(LyXFont::ALL_INHERIT, params.language));
752                 ++pos;
753         } else if (token == "\\change_unchanged") {
754                 // Hack ! Needed for empty paragraphs :/
755                 if (!pos)
756                         par->cleanChanges();
757                 current_change = Change(Change::UNCHANGED);
758         } else if (token == "\\change_inserted") {
759                 lex.nextToken();
760                 istringstream istr(lex.getString());
761                 int aid;
762                 lyx::time_type ct;
763                 istr >> aid;
764                 istr >> ct;
765                 current_change = Change(Change::INSERTED, params.author_ids[aid], ct);
766         } else if (token == "\\change_deleted") {
767                 lex.nextToken();
768                 istringstream istr(lex.getString());
769                 int aid;
770                 lyx::time_type ct;
771                 istr >> aid;
772                 istr >> ct;
773                 current_change = Change(Change::DELETED, params.author_ids[aid], ct);
774         } else {
775                 // This should be insurance for the future: (Asger)
776                 ++unknown;
777                 lex.eatLine();
778 #if USE_BOOST_FORMAT
779                 boost::format fmt(_("Unknown token: %1$s %2$s\n"));
780                 fmt % token % lex.text();
781                 string const s = fmt.str();
782 #else
783                 string const s = _("Unknown token: ") + token
784                         + ' ' + lex.text() + '\n';
785 #endif
786                 // we can do this here this way because we're actually reading
787                 // the buffer and don't care about LyXText right now.
788                 InsetError * new_inset = new InsetError(s);
789                 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
790                                  params.language));
791
792         }
793
794         return unknown;
795 }
796
797
798 // needed to insert the selection
799 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
800                                  LyXFont const & fn,string const & str)
801 {
802         LyXLayout_ptr const & layout = par->layout();
803
804         LyXFont font = fn;
805
806         par->checkInsertChar(font);
807         // insert the string, don't insert doublespace
808         bool space_inserted = true;
809         bool autobreakrows = !par->inInset() ||
810                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
811         for(string::const_iterator cit = str.begin();
812             cit != str.end(); ++cit) {
813                 if (*cit == '\n') {
814                         if (autobreakrows && (!par->empty() || layout->keepempty)) {
815                                 breakParagraph(params, paragraphs, par, pos,
816                                                layout->isEnvironment());
817                                 par = par->next();
818                                 pos = 0;
819                                 space_inserted = true;
820                         } else {
821                                 continue;
822                         }
823                         // do not insert consecutive spaces if !free_spacing
824                 } else if ((*cit == ' ' || *cit == '\t') &&
825                            space_inserted && !layout->free_spacing &&
826                                    !par->isFreeSpacing())
827                 {
828                         continue;
829                 } else if (*cit == '\t') {
830                         if (!layout->free_spacing && !par->isFreeSpacing()) {
831                                 // tabs are like spaces here
832                                 par->insertChar(pos, ' ', font);
833                                 ++pos;
834                                 space_inserted = true;
835                         } else {
836                                 const pos_type nb = 8 - pos % 8;
837                                 for (pos_type a = 0; a < nb ; ++a) {
838                                         par->insertChar(pos, ' ', font);
839                                         ++pos;
840                                 }
841                                 space_inserted = true;
842                         }
843                 } else if (!IsPrintable(*cit)) {
844                         // Ignore unprintables
845                         continue;
846                 } else {
847                         // just insert the character
848                         par->insertChar(pos, *cit, font);
849                         ++pos;
850                         space_inserted = (*cit == ' ');
851                 }
852
853         }
854 }
855
856
857 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
858                        int & pos, LyXFont & font, Change current_change)
859 {
860         // consistency check
861         if (lex.getString() != "\\begin_inset") {
862                 lyxerr << "Buffer::readInset: Consistency check failed."
863                        << endl;
864         }
865
866         Inset * inset = 0;
867
868         lex.next();
869         string const tmptok = lex.getString();
870
871         // test the different insets
872         if (tmptok == "LatexCommand") {
873                 InsetCommandParams inscmd;
874                 inscmd.read(lex);
875
876                 string const cmdName = inscmd.getCmdName();
877
878                 // This strange command allows LyX to recognize "natbib" style
879                 // citations: citet, citep, Citet etc.
880                 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
881                         inset = new InsetCitation(inscmd);
882                 } else if (cmdName == "bibitem") {
883                         lex.printError("Wrong place for bibitem");
884                         inset = new InsetBibitem(inscmd);
885                 } else if (cmdName == "BibTeX") {
886                         inset = new InsetBibtex(inscmd);
887                 } else if (cmdName == "index") {
888                         inset = new InsetIndex(inscmd);
889                 } else if (cmdName == "include") {
890                         inset = new InsetInclude(inscmd, *this);
891                 } else if (cmdName == "label") {
892                         inset = new InsetLabel(inscmd);
893                 } else if (cmdName == "url"
894                            || cmdName == "htmlurl") {
895                         inset = new InsetUrl(inscmd);
896                 } else if (cmdName == "ref"
897                            || cmdName == "pageref"
898                            || cmdName == "vref"
899                            || cmdName == "vpageref"
900                            || cmdName == "prettyref") {
901                         if (!inscmd.getOptions().empty()
902                             || !inscmd.getContents().empty()) {
903                                 inset = new InsetRef(inscmd, *this);
904                         }
905                 } else if (cmdName == "tableofcontents") {
906                         inset = new InsetTOC(inscmd);
907                 } else if (cmdName == "listofalgorithms") {
908                         inset = new InsetFloatList("algorithm");
909                 } else if (cmdName == "listoffigures") {
910                         inset = new InsetFloatList("figure");
911                 } else if (cmdName == "listoftables") {
912                         inset = new InsetFloatList("table");
913                 } else if (cmdName == "printindex") {
914                         inset = new InsetPrintIndex(inscmd);
915                 } else if (cmdName == "lyxparent") {
916                         inset = new InsetParent(inscmd, *this);
917                 }
918         } else {
919                 if (tmptok == "Quotes") {
920                         inset = new InsetQuotes;
921                 } else if (tmptok == "External") {
922                         inset = new InsetExternal;
923                 } else if (tmptok == "FormulaMacro") {
924                         inset = new InsetFormulaMacro;
925                 } else if (tmptok == "Formula") {
926                         inset = new InsetFormula;
927                 } else if (tmptok == "Graphics") {
928                         inset = new InsetGraphics;
929                 } else if (tmptok == "Note") {
930                         inset = new InsetNote(params);
931                 } else if (tmptok == "Include") {
932                         InsetCommandParams p("Include");
933                         inset = new InsetInclude(p, *this);
934                 } else if (tmptok == "ERT") {
935                         inset = new InsetERT(params);
936                 } else if (tmptok == "Tabular") {
937                         inset = new InsetTabular(*this);
938                 } else if (tmptok == "Text") {
939                         inset = new InsetText(params);
940                 } else if (tmptok == "Foot") {
941                         inset = new InsetFoot(params);
942                 } else if (tmptok == "Marginal") {
943                         inset = new InsetMarginal(params);
944                 } else if (tmptok == "OptArg") {
945                         inset = new InsetOptArg(params);
946                 } else if (tmptok == "Minipage") {
947                         inset = new InsetMinipage(params);
948                 } else if (tmptok == "Float") {
949                         lex.next();
950                         string tmptok = lex.getString();
951                         inset = new InsetFloat(params, tmptok);
952                 } else if (tmptok == "Wrap") {
953                         lex.next();
954                         string tmptok = lex.getString();
955                         inset = new InsetWrap(params, tmptok);
956 #if 0
957                 } else if (tmptok == "List") {
958                         inset = new InsetList;
959                 } else if (tmptok == "Theorem") {
960                         inset = new InsetList;
961 #endif
962                 } else if (tmptok == "Caption") {
963                         inset = new InsetCaption(params);
964                 } else if (tmptok == "FloatList") {
965                         inset = new InsetFloatList;
966                 }
967
968                 if (inset)
969                         inset->read(this, lex);
970         }
971
972         if (inset) {
973                 par->insertInset(pos, inset, font, current_change);
974                 ++pos;
975         }
976 }
977
978
979 bool Buffer::readFile(LyXLex & lex, string const & filename, Paragraph * par)
980 {
981         if (lex.isOK()) {
982                 lex.next();
983                 string const token(lex.getString());
984                 if (token == "\\lyxformat") { // the first token _must_ be...
985                         lex.eatLine();
986                         string tmp_format = lex.getString();
987                         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
988                         // if present remove ".," from string.
989                         string::size_type dot = tmp_format.find_first_of(".,");
990                         //lyxerr << "           dot found at " << dot << endl;
991                         if (dot != string::npos)
992                                 tmp_format.erase(dot, 1);
993                         file_format = strToInt(tmp_format);
994                         //lyxerr << "format: " << file_format << endl;
995                         if (file_format == LYX_FORMAT) {
996                                 // current format
997                         } else if (file_format > LYX_FORMAT) {
998                                 // future format
999                                 Alert::alert(_("Warning!"),
1000                                         _("The file was created with a newer version of "
1001                                         "LyX. This is likely to cause problems."));
1002
1003                         } else if (file_format < LYX_FORMAT) {
1004                                 // old formats
1005                                 if (file_format < 200) {
1006                                         Alert::alert(_("ERROR!"),
1007                                                    _("Old LyX file format found. "
1008                                                      "Use LyX 0.10.x to read this!"));
1009                                         return false;
1010                                 } else if (!filename.empty()) {
1011                                         string command =
1012                                                 LibFileSearch("lyx2lyx", "lyx2lyx");
1013                                         if (command.empty()) {
1014                                                 Alert::alert(_("ERROR!"),
1015                                                              _("Can't find conversion script."));
1016                                                 return false;
1017                                         }
1018                                         command += " -t"
1019                                                 +tostr(LYX_FORMAT) + ' '
1020                                                 + QuoteName(filename);
1021                                         lyxerr[Debug::INFO] << "Running '"
1022                                                             << command << '\''
1023                                                             << endl;
1024                                         cmd_ret const ret = RunCommand(command);
1025                                         if (ret.first) {
1026                                                 Alert::alert(_("ERROR!"),
1027                                                              _("An error occured while "
1028                                                                "running the conversion script."));
1029                                                 return false;
1030                                         }
1031                                         istringstream is(STRCONV(ret.second));
1032                                         LyXLex tmplex(0, 0);
1033                                         tmplex.setStream(is);
1034                                         return readFile(tmplex, string(), par);
1035                                 } else {
1036                                         // This code is reached if lyx2lyx failed (for
1037                                         // some reason) to change the file format of
1038                                         // the file.
1039                                         lyx::Assert(false);
1040                                         return false;
1041                                 }
1042                         }
1043                         bool the_end = readBody(lex, par);
1044                         params.setPaperStuff();
1045
1046                         if (!the_end) {
1047                                 Alert::alert(_("Warning!"),
1048                                            _("Reading of document is not complete"),
1049                                            _("Maybe the document is truncated"));
1050                         }
1051                         return true;
1052                 } else { // "\\lyxformat" not found
1053                         Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1054                 }
1055         } else
1056                 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1057         return false;
1058 }
1059
1060
1061 // Should probably be moved to somewhere else: BufferView? LyXView?
1062 bool Buffer::save() const
1063 {
1064         // We don't need autosaves in the immediate future. (Asger)
1065         resetAutosaveTimers();
1066
1067         // make a backup
1068         string s;
1069         if (lyxrc.make_backup) {
1070                 s = fileName() + '~';
1071                 if (!lyxrc.backupdir_path.empty())
1072                         s = AddName(lyxrc.backupdir_path,
1073                                     subst(os::slashify_path(s),'/','!'));
1074
1075                 // Rename is the wrong way of making a backup,
1076                 // this is the correct way.
1077                 /* truss cp fil fil2:
1078                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1079                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1080                    open("LyXVC.lyx", O_RDONLY)                     = 3
1081                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1082                    fstat(4, 0xEFFFF508)                            = 0
1083                    fstat(3, 0xEFFFF508)                            = 0
1084                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1085                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1086                    read(3, 0xEFFFD4A0, 8192)                       = 0
1087                    close(4)                                        = 0
1088                    close(3)                                        = 0
1089                    chmod("LyXVC3.lyx", 0100644)                    = 0
1090                    lseek(0, 0, SEEK_CUR)                           = 46440
1091                    _exit(0)
1092                 */
1093
1094                 // Should probably have some more error checking here.
1095                 // Doing it this way, also makes the inodes stay the same.
1096                 // This is still not a very good solution, in particular we
1097                 // might loose the owner of the backup.
1098                 FileInfo finfo(fileName());
1099                 if (finfo.exist()) {
1100                         mode_t fmode = finfo.getMode();
1101                         struct utimbuf times = {
1102                                 finfo.getAccessTime(),
1103                                 finfo.getModificationTime() };
1104
1105                         ifstream ifs(fileName().c_str());
1106                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1107                         if (ifs && ofs) {
1108                                 ofs << ifs.rdbuf();
1109                                 ifs.close();
1110                                 ofs.close();
1111                                 ::chmod(s.c_str(), fmode);
1112
1113                                 if (::utime(s.c_str(), &times)) {
1114                                         lyxerr << "utime error." << endl;
1115                                 }
1116                         } else {
1117                                 lyxerr << "LyX was not able to make "
1118                                         "backup copy. Beware." << endl;
1119                         }
1120                 }
1121         }
1122
1123         if (writeFile(fileName())) {
1124                 markClean();
1125                 removeAutosaveFile(fileName());
1126         } else {
1127                 // Saving failed, so backup is not backup
1128                 if (lyxrc.make_backup) {
1129                         lyx::rename(s, fileName());
1130                 }
1131                 return false;
1132         }
1133         return true;
1134 }
1135
1136
1137 bool Buffer::writeFile(string const & fname) const
1138 {
1139         if (read_only && (fname == fileName())) {
1140                 return false;
1141         }
1142
1143         FileInfo finfo(fname);
1144         if (finfo.exist() && !finfo.writable()) {
1145                 return false;
1146         }
1147
1148         ofstream ofs(fname.c_str());
1149         if (!ofs) {
1150                 return false;
1151         }
1152
1153 #ifdef HAVE_LOCALE
1154         // Use the standard "C" locale for file output.
1155         ofs.imbue(std::locale::classic());
1156 #endif
1157
1158         // The top of the file should not be written by params.
1159
1160         // write out a comment in the top of the file
1161         ofs << '#' << lyx_docversion
1162             << " created this file. For more info see http://www.lyx.org/\n"
1163             << "\\lyxformat " << LYX_FORMAT << "\n";
1164
1165         // now write out the buffer paramters.
1166         params.writeFile(ofs);
1167
1168         ofs << "\\end_header\n";
1169
1170         Paragraph::depth_type depth = 0;
1171
1172         // this will write out all the paragraphs
1173         // using recursive descent.
1174         ParagraphList::iterator pit = paragraphs.begin();
1175         ParagraphList::iterator pend = paragraphs.end();
1176         for (; pit != pend; ++pit)
1177                 pit->write(this, ofs, params, depth);
1178
1179         // Write marker that shows file is complete
1180         ofs << "\n\\the_end" << endl;
1181
1182         ofs.close();
1183
1184         // how to check if close went ok?
1185         // Following is an attempt... (BE 20001011)
1186
1187         // good() returns false if any error occured, including some
1188         //        formatting error.
1189         // bad()  returns true if something bad happened in the buffer,
1190         //        which should include file system full errors.
1191
1192         bool status = true;
1193         if (!ofs.good()) {
1194                 status = false;
1195 #if 0
1196                 if (ofs.bad()) {
1197                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1198                 } else {
1199                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1200                                << endl;
1201                 }
1202 #endif
1203         }
1204
1205         return status;
1206 }
1207
1208
1209 namespace {
1210
1211 pair<int, string> const addDepth(int depth, int ldepth)
1212 {
1213         int d = depth * 2;
1214         if (ldepth > depth)
1215                 d += (ldepth - depth) * 2;
1216         return make_pair(d, string(d, ' '));
1217 }
1218
1219 }
1220
1221
1222 string const Buffer::asciiParagraph(Paragraph const & par,
1223                                     unsigned int linelen,
1224                                     bool noparbreak) const
1225 {
1226         ostringstream buffer;
1227         Paragraph::depth_type depth = 0;
1228         int ltype = 0;
1229         Paragraph::depth_type ltype_depth = 0;
1230         bool ref_printed = false;
1231 //      if (!par->previous()) {
1232 #if 0
1233         // begins or ends a deeper area ?
1234         if (depth != par->params().depth()) {
1235                 if (par->params().depth() > depth) {
1236                         while (par->params().depth() > depth) {
1237                                 ++depth;
1238                         }
1239                 } else {
1240                         while (par->params().depth() < depth) {
1241                                 --depth;
1242                         }
1243                 }
1244         }
1245 #else
1246         depth = par.params().depth();
1247 #endif
1248
1249         // First write the layout
1250         string const & tmp = par.layout()->name();
1251         if (compare_no_case(tmp, "itemize") == 0) {
1252                 ltype = 1;
1253                 ltype_depth = depth + 1;
1254         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1255                 ltype = 2;
1256                 ltype_depth = depth + 1;
1257         } else if (contains(ascii_lowercase(tmp), "ection")) {
1258                 ltype = 3;
1259                 ltype_depth = depth + 1;
1260         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1261                 ltype = 4;
1262                 ltype_depth = depth + 1;
1263         } else if (compare_ascii_no_case(tmp, "description") == 0) {
1264                 ltype = 5;
1265                 ltype_depth = depth + 1;
1266         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1267                 ltype = 6;
1268                 ltype_depth = 0;
1269         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1270                 ltype = 7;
1271                 ltype_depth = 0;
1272         } else {
1273                 ltype = 0;
1274                 ltype_depth = 0;
1275         }
1276
1277         /* maybe some vertical spaces */
1278
1279         /* the labelwidthstring used in lists */
1280
1281         /* some lines? */
1282
1283         /* some pagebreaks? */
1284
1285         /* noindent ? */
1286
1287         /* what about the alignment */
1288 //      } else {
1289 //              lyxerr << "Should this ever happen?" << endl;
1290 //      }
1291
1292         // linelen <= 0 is special and means we don't have paragraph breaks
1293
1294         string::size_type currlinelen = 0;
1295
1296         if (!noparbreak) {
1297                 if (linelen > 0)
1298                         buffer << "\n\n";
1299
1300                 buffer << string(depth * 2, ' ');
1301                 currlinelen += depth * 2;
1302
1303                 //--
1304                 // we should probably change to the paragraph language in the
1305                 // gettext here (if possible) so that strings are outputted in
1306                 // the correct language! (20012712 Jug)
1307                 //--
1308                 switch (ltype) {
1309                 case 0: // Standard
1310                 case 4: // (Sub)Paragraph
1311                 case 5: // Description
1312                         break;
1313                 case 6: // Abstract
1314                         if (linelen > 0) {
1315                                 buffer << _("Abstract") << "\n\n";
1316                                 currlinelen = 0;
1317                         } else {
1318                                 string const abst = _("Abstract: ");
1319                                 buffer << abst;
1320                                 currlinelen += abst.length();
1321                         }
1322                         break;
1323                 case 7: // Bibliography
1324                         if (!ref_printed) {
1325                                 if (linelen > 0) {
1326                                         buffer << _("References") << "\n\n";
1327                                         currlinelen = 0;
1328                                 } else {
1329                                         string const refs = _("References: ");
1330                                         buffer << refs;
1331                                         currlinelen += refs.length();
1332                                 }
1333
1334                                 ref_printed = true;
1335                         }
1336                         break;
1337                 default:
1338                 {
1339                         string const parlab = par.params().labelString();
1340                         buffer << parlab << ' ';
1341                         currlinelen += parlab.length() + 1;
1342                 }
1343                 break;
1344
1345                 }
1346         }
1347
1348         if (!currlinelen) {
1349                 pair<int, string> p = addDepth(depth, ltype_depth);
1350                 buffer << p.second;
1351                 currlinelen += p.first;
1352         }
1353
1354         // this is to change the linebreak to do it by word a bit more
1355         // intelligent hopefully! (only in the case where we have a
1356         // max linelength!) (Jug)
1357
1358         string word;
1359
1360         for (pos_type i = 0; i < par.size(); ++i) {
1361                 char c = par.getUChar(params, i);
1362                 switch (c) {
1363                 case Paragraph::META_INSET:
1364                 {
1365                         Inset const * inset = par.getInset(i);
1366                         if (inset) {
1367                                 if (linelen > 0) {
1368                                         buffer << word;
1369                                         currlinelen += word.length();
1370                                         word.erase();
1371                                 }
1372                                 if (inset->ascii(this, buffer, linelen)) {
1373                                         // to be sure it breaks paragraph
1374                                         currlinelen += linelen;
1375                                 }
1376                         }
1377                 }
1378                 break;
1379
1380                 case Paragraph::META_NEWLINE:
1381                         if (linelen > 0) {
1382                                 buffer << word << "\n";
1383                                 word.erase();
1384
1385                                 pair<int, string> p = addDepth(depth,
1386                                                                ltype_depth);
1387                                 buffer << p.second;
1388                                 currlinelen = p.first;
1389                         }
1390                         break;
1391
1392                 default:
1393                         if (c == ' ') {
1394                                 if (linelen > 0 &&
1395                                     currlinelen + word.length() > linelen - 10) {
1396                                         buffer << "\n";
1397                                         pair<int, string> p = addDepth(depth, ltype_depth);
1398                                         buffer << p.second;
1399                                         currlinelen = p.first;
1400                                 }
1401
1402                                 buffer << word << ' ';
1403                                 currlinelen += word.length() + 1;
1404                                 word.erase();
1405
1406                         } else {
1407                                 if (c != '\0') {
1408                                         word += c;
1409                                 } else {
1410                                         lyxerr[Debug::INFO] <<
1411                                                 "writeAsciiFile: NULL char in structure." << endl;
1412                                 }
1413                                 if ((linelen > 0) &&
1414                                         (currlinelen + word.length()) > linelen)
1415                                 {
1416                                         buffer << "\n";
1417
1418                                         pair<int, string> p =
1419                                                 addDepth(depth, ltype_depth);
1420                                         buffer << p.second;
1421                                         currlinelen = p.first;
1422                                 }
1423                         }
1424                         break;
1425                 }
1426         }
1427         buffer << word;
1428         return STRCONV(buffer.str());
1429 }
1430
1431
1432 void Buffer::writeFileAscii(string const & fname, int linelen)
1433 {
1434         ofstream ofs(fname.c_str());
1435         if (!ofs) {
1436                 Alert::err_alert(_("Error: Cannot write file:"), fname);
1437                 return;
1438         }
1439         writeFileAscii(ofs, linelen);
1440 }
1441
1442
1443 void Buffer::writeFileAscii(ostream & os, int linelen)
1444 {
1445         ParagraphList::iterator beg = paragraphs.begin();
1446         ParagraphList::iterator end = paragraphs.end();
1447         ParagraphList::iterator it = beg;
1448         for (; it != end; ++it) {
1449                 os << asciiParagraph(*it, linelen, it == beg);
1450         }
1451         os << "\n";
1452 }
1453
1454
1455
1456 void Buffer::makeLaTeXFile(string const & fname,
1457                            string const & original_path,
1458                            bool nice, bool only_body, bool only_preamble)
1459 {
1460         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1461
1462         ofstream ofs(fname.c_str());
1463         if (!ofs) {
1464                 Alert::err_alert(_("Error: Cannot open file: "), fname);
1465                 return;
1466         }
1467
1468         makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1469
1470         ofs.close();
1471         if (ofs.fail()) {
1472                 lyxerr << "File was not closed properly." << endl;
1473         }
1474 }
1475
1476
1477 void Buffer::makeLaTeXFile(ostream & os,
1478                            string const & original_path,
1479                            bool nice, bool only_body, bool only_preamble)
1480 {
1481         niceFile = nice; // this will be used by Insetincludes.
1482
1483         // validate the buffer.
1484         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1485         LaTeXFeatures features(params);
1486         validate(features);
1487         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1488
1489         texrow.reset();
1490         // The starting paragraph of the coming rows is the
1491         // first paragraph of the document. (Asger)
1492         texrow.start(&*(paragraphs.begin()), 0);
1493
1494         if (!only_body && nice) {
1495                 os << "%% " << lyx_docversion << " created this file.  "
1496                         "For more info, see http://www.lyx.org/.\n"
1497                         "%% Do not edit unless you really know what "
1498                         "you are doing.\n";
1499                 texrow.newline();
1500                 texrow.newline();
1501         }
1502         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1503         // There are a few differences between nice LaTeX and usual files:
1504         // usual is \batchmode and has a
1505         // special input@path to allow the including of figures
1506         // with either \input or \includegraphics (what figinsets do).
1507         // input@path is set when the actual parameter
1508         // original_path is set. This is done for usual tex-file, but not
1509         // for nice-latex-file. (Matthias 250696)
1510         if (!only_body) {
1511                 if (!nice) {
1512                         // code for usual, NOT nice-latex-file
1513                         os << "\\batchmode\n"; // changed
1514                         // from \nonstopmode
1515                         texrow.newline();
1516                 }
1517                 if (!original_path.empty()) {
1518                         string inputpath = os::external_path(original_path);
1519                         subst(inputpath, "~", "\\string~");
1520                         os << "\\makeatletter\n"
1521                             << "\\def\\input@path{{"
1522                             << inputpath << "/}}\n"
1523                             << "\\makeatother\n";
1524                         texrow.newline();
1525                         texrow.newline();
1526                         texrow.newline();
1527                 }
1528
1529                 // Write the preamble
1530                 params.writeLaTeX(os, features, texrow);
1531
1532                 if (only_preamble)
1533                         return;
1534
1535                 // make the body.
1536                 os << "\\begin{document}\n";
1537                 texrow.newline();
1538         } // only_body
1539         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1540
1541         if (!lyxrc.language_auto_begin) {
1542                 os << subst(lyxrc.language_command_begin, "$$lang",
1543                              params.language->babel())
1544                     << endl;
1545                 texrow.newline();
1546         }
1547
1548         latexParagraphs(this, paragraphs, paragraphs.begin(), paragraphs.end(), os, texrow);
1549
1550         // add this just in case after all the paragraphs
1551         os << endl;
1552         texrow.newline();
1553
1554         if (!lyxrc.language_auto_end) {
1555                 os << subst(lyxrc.language_command_end, "$$lang",
1556                              params.language->babel())
1557                     << endl;
1558                 texrow.newline();
1559         }
1560
1561         if (!only_body) {
1562                 os << "\\end{document}\n";
1563                 texrow.newline();
1564
1565                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1566         } else {
1567                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1568                                      << endl;
1569         }
1570
1571         // Just to be sure. (Asger)
1572         texrow.newline();
1573
1574         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1575         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1576                             << '.' << endl;
1577
1578         // we want this to be true outside previews (for insetexternal)
1579         niceFile = true;
1580 }
1581
1582
1583 bool Buffer::isLatex() const
1584 {
1585         return params.getLyXTextClass().outputType() == LATEX;
1586 }
1587
1588
1589 bool Buffer::isLinuxDoc() const
1590 {
1591         return params.getLyXTextClass().outputType() == LINUXDOC;
1592 }
1593
1594
1595 bool Buffer::isLiterate() const
1596 {
1597         return params.getLyXTextClass().outputType() == LITERATE;
1598 }
1599
1600
1601 bool Buffer::isDocBook() const
1602 {
1603         return params.getLyXTextClass().outputType() == DOCBOOK;
1604 }
1605
1606
1607 bool Buffer::isSGML() const
1608 {
1609         LyXTextClass const & tclass = params.getLyXTextClass();
1610
1611         return tclass.outputType() == LINUXDOC ||
1612                tclass.outputType() == DOCBOOK;
1613 }
1614
1615
1616 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1617 {
1618         ofstream ofs(fname.c_str());
1619
1620         if (!ofs) {
1621                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
1622                 return;
1623         }
1624
1625         niceFile = nice; // this will be used by included files.
1626
1627         LaTeXFeatures features(params);
1628
1629         validate(features);
1630
1631         texrow.reset();
1632
1633         LyXTextClass const & tclass = params.getLyXTextClass();
1634
1635         string top_element = tclass.latexname();
1636
1637         if (!body_only) {
1638                 ofs << "<!doctype linuxdoc system";
1639
1640                 string preamble = params.preamble;
1641                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1642                          : fname;
1643                 preamble += features.getIncludedFiles(name);
1644                 preamble += features.getLyXSGMLEntities();
1645
1646                 if (!preamble.empty()) {
1647                         ofs << " [ " << preamble << " ]";
1648                 }
1649                 ofs << ">\n\n";
1650
1651                 if (params.options.empty())
1652                         sgml::openTag(ofs, 0, false, top_element);
1653                 else {
1654                         string top = top_element;
1655                         top += ' ';
1656                         top += params.options;
1657                         sgml::openTag(ofs, 0, false, top);
1658                 }
1659         }
1660
1661         ofs << "<!-- "  << lyx_docversion
1662             << " created this file. For more info see http://www.lyx.org/"
1663             << " -->\n";
1664
1665         Paragraph::depth_type depth = 0; // paragraph depth
1666         Paragraph * par = &*(paragraphs.begin());
1667         string item_name;
1668         vector<string> environment_stack(5);
1669
1670         while (par) {
1671                 LyXLayout_ptr const & style = par->layout();
1672                 // treat <toc> as a special case for compatibility with old code
1673                 if (par->isInset(0)) {
1674                         Inset * inset = par->getInset(0);
1675                         Inset::Code lyx_code = inset->lyxCode();
1676                         if (lyx_code == Inset::TOC_CODE) {
1677                                 string const temp = "toc";
1678                                 sgml::openTag(ofs, depth, false, temp);
1679
1680                                 par = par->next();
1681                                 continue;
1682                         }
1683                 }
1684
1685                 // environment tag closing
1686                 for (; depth > par->params().depth(); --depth) {
1687                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1688                         environment_stack[depth].erase();
1689                 }
1690
1691                 // write opening SGML tags
1692                 switch (style->latextype) {
1693                 case LATEX_PARAGRAPH:
1694                         if (depth == par->params().depth()
1695                            && !environment_stack[depth].empty()) {
1696                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1697                                 environment_stack[depth].erase();
1698                                 if (depth)
1699                                         --depth;
1700                                 else
1701                                         ofs << "</p>";
1702                         }
1703                         sgml::openTag(ofs, depth, false, style->latexname());
1704                         break;
1705
1706                 case LATEX_COMMAND:
1707                         if (depth!= 0)
1708                                 sgmlError(par, 0,
1709                                           _("Error: Wrong depth for LatexType Command.\n"));
1710
1711                         if (!environment_stack[depth].empty()) {
1712                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1713                                 ofs << "</p>";
1714                         }
1715
1716                         environment_stack[depth].erase();
1717                         sgml::openTag(ofs, depth, false, style->latexname());
1718                         break;
1719
1720                 case LATEX_ENVIRONMENT:
1721                 case LATEX_ITEM_ENVIRONMENT:
1722                 case LATEX_BIB_ENVIRONMENT:
1723                 {
1724                         string const & latexname = style->latexname();
1725
1726                         if (depth == par->params().depth()
1727                             && environment_stack[depth] != latexname) {
1728                                 sgml::closeTag(ofs, depth, false,
1729                                              environment_stack[depth]);
1730                                 environment_stack[depth].erase();
1731                         }
1732                         if (depth < par->params().depth()) {
1733                                depth = par->params().depth();
1734                                environment_stack[depth].erase();
1735                         }
1736                         if (environment_stack[depth] != latexname) {
1737                                 if (depth == 0) {
1738                                         sgml::openTag(ofs, depth, false, "p");
1739                                 }
1740                                 sgml::openTag(ofs, depth, false, latexname);
1741
1742                                 if (environment_stack.size() == depth + 1)
1743                                         environment_stack.push_back("!-- --");
1744                                 environment_stack[depth] = latexname;
1745                         }
1746
1747                         if (style->latexparam() == "CDATA")
1748                                 ofs << "<![CDATA[";
1749
1750                         if (style->latextype == LATEX_ENVIRONMENT) break;
1751
1752                         if (style->labeltype == LABEL_MANUAL)
1753                                 item_name = "tag";
1754                         else
1755                                 item_name = "item";
1756
1757                         sgml::openTag(ofs, depth + 1, false, item_name);
1758                 }
1759                 break;
1760
1761                 default:
1762                         sgml::openTag(ofs, depth, false, style->latexname());
1763                         break;
1764                 }
1765
1766                 simpleLinuxDocOnePar(ofs, par, depth);
1767
1768                 par = par->next();
1769
1770                 ofs << "\n";
1771                 // write closing SGML tags
1772                 switch (style->latextype) {
1773                 case LATEX_COMMAND:
1774                         break;
1775                 case LATEX_ENVIRONMENT:
1776                 case LATEX_ITEM_ENVIRONMENT:
1777                 case LATEX_BIB_ENVIRONMENT:
1778                         if (style->latexparam() == "CDATA")
1779                                 ofs << "]]>";
1780                         break;
1781                 default:
1782                         sgml::closeTag(ofs, depth, false, style->latexname());
1783                         break;
1784                 }
1785         }
1786
1787         // Close open tags
1788         for (int i = depth; i >= 0; --i)
1789                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1790
1791         if (!body_only) {
1792                 ofs << "\n\n";
1793                 sgml::closeTag(ofs, 0, false, top_element);
1794         }
1795
1796         ofs.close();
1797         // How to check for successful close
1798
1799         // we want this to be true outside previews (for insetexternal)
1800         niceFile = true;
1801 }
1802
1803
1804 // checks, if newcol chars should be put into this line
1805 // writes newline, if necessary.
1806 namespace {
1807
1808 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1809                           string::size_type newcol)
1810 {
1811         colcount += newcol;
1812         if (colcount > lyxrc.ascii_linelen) {
1813                 os << "\n";
1814                 colcount = newcol; // assume write after this call
1815         }
1816 }
1817
1818 enum PAR_TAG {
1819         NONE=0,
1820         TT = 1,
1821         SF = 2,
1822         BF = 4,
1823         IT = 8,
1824         SL = 16,
1825         EM = 32
1826 };
1827
1828
1829 string tag_name(PAR_TAG const & pt) {
1830         switch (pt) {
1831         case NONE: return "!-- --";
1832         case TT: return "tt";
1833         case SF: return "sf";
1834         case BF: return "bf";
1835         case IT: return "it";
1836         case SL: return "sl";
1837         case EM: return "em";
1838         }
1839         return "";
1840 }
1841
1842
1843 inline
1844 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1845 {
1846         p1 = static_cast<PAR_TAG>(p1 | p2);
1847 }
1848
1849
1850 inline
1851 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1852 {
1853         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1854 }
1855
1856 } // anon
1857
1858
1859 // Handle internal paragraph parsing -- layout already processed.
1860 void Buffer::simpleLinuxDocOnePar(ostream & os,
1861         Paragraph * par,
1862         Paragraph::depth_type /*depth*/)
1863 {
1864         LyXLayout_ptr const & style = par->layout();
1865
1866         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1867
1868         // gets paragraph main font
1869         LyXFont font_old;
1870         bool desc_on;
1871         if (style->labeltype == LABEL_MANUAL) {
1872                 font_old = style->labelfont;
1873                 desc_on = true;
1874         } else {
1875                 font_old = style->font;
1876                 desc_on = false;
1877         }
1878
1879         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1880         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1881         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1882         bool is_em = false;
1883
1884         stack<PAR_TAG> tag_state;
1885         // parsing main loop
1886         for (pos_type i = 0; i < par->size(); ++i) {
1887
1888                 PAR_TAG tag_close = NONE;
1889                 list < PAR_TAG > tag_open;
1890
1891                 LyXFont const font = par->getFont(params, i);
1892
1893                 if (font_old.family() != font.family()) {
1894                         switch (family_type) {
1895                         case LyXFont::SANS_FAMILY:
1896                                 tag_close |= SF;
1897                                 break;
1898                         case LyXFont::TYPEWRITER_FAMILY:
1899                                 tag_close |= TT;
1900                                 break;
1901                         default:
1902                                 break;
1903                         }
1904
1905                         family_type = font.family();
1906
1907                         switch (family_type) {
1908                         case LyXFont::SANS_FAMILY:
1909                                 tag_open.push_back(SF);
1910                                 break;
1911                         case LyXFont::TYPEWRITER_FAMILY:
1912                                 tag_open.push_back(TT);
1913                                 break;
1914                         default:
1915                                 break;
1916                         }
1917                 }
1918
1919                 if (font_old.series() != font.series()) {
1920                         switch (series_type) {
1921                         case LyXFont::BOLD_SERIES:
1922                                 tag_close |= BF;
1923                                 break;
1924                         default:
1925                                 break;
1926                         }
1927
1928                         series_type = font.series();
1929
1930                         switch (series_type) {
1931                         case LyXFont::BOLD_SERIES:
1932                                 tag_open.push_back(BF);
1933                                 break;
1934                         default:
1935                                 break;
1936                         }
1937
1938                 }
1939
1940                 if (font_old.shape() != font.shape()) {
1941                         switch (shape_type) {
1942                         case LyXFont::ITALIC_SHAPE:
1943                                 tag_close |= IT;
1944                                 break;
1945                         case LyXFont::SLANTED_SHAPE:
1946                                 tag_close |= SL;
1947                                 break;
1948                         default:
1949                                 break;
1950                         }
1951
1952                         shape_type = font.shape();
1953
1954                         switch (shape_type) {
1955                         case LyXFont::ITALIC_SHAPE:
1956                                 tag_open.push_back(IT);
1957                                 break;
1958                         case LyXFont::SLANTED_SHAPE:
1959                                 tag_open.push_back(SL);
1960                                 break;
1961                         default:
1962                                 break;
1963                         }
1964                 }
1965                 // handle <em> tag
1966                 if (font_old.emph() != font.emph()) {
1967                         if (font.emph() == LyXFont::ON) {
1968                                 tag_open.push_back(EM);
1969                                 is_em = true;
1970                         }
1971                         else if (is_em) {
1972                                 tag_close |= EM;
1973                                 is_em = false;
1974                         }
1975                 }
1976
1977                 list < PAR_TAG > temp;
1978                 while (!tag_state.empty() && tag_close) {
1979                         PAR_TAG k =  tag_state.top();
1980                         tag_state.pop();
1981                         os << "</" << tag_name(k) << '>';
1982                         if (tag_close & k)
1983                                 reset(tag_close,k);
1984                         else
1985                                 temp.push_back(k);
1986                 }
1987
1988                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1989                     j != temp.end(); ++j) {
1990                         tag_state.push(*j);
1991                         os << '<' << tag_name(*j) << '>';
1992                 }
1993
1994                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1995                     j != tag_open.end(); ++j) {
1996                         tag_state.push(*j);
1997                         os << '<' << tag_name(*j) << '>';
1998                 }
1999
2000                 char c = par->getChar(i);
2001
2002                 if (c == Paragraph::META_INSET) {
2003                         Inset * inset = par->getInset(i);
2004                         inset->linuxdoc(this, os);
2005                         font_old = font;
2006                         continue;
2007                 }
2008
2009                 if (style->latexparam() == "CDATA") {
2010                         // "TeX"-Mode on == > SGML-Mode on.
2011                         if (c != '\0')
2012                                 os << c;
2013                         ++char_line_count;
2014                 } else {
2015                         bool ws;
2016                         string str;
2017                         boost::tie(ws, str) = sgml::escapeChar(c);
2018                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2019                                 // in freespacing mode, spaces are
2020                                 // non-breaking characters
2021                                 if (desc_on) {// if char is ' ' then...
2022
2023                                         ++char_line_count;
2024                                         sgmlLineBreak(os, char_line_count, 6);
2025                                         os << "</tag>";
2026                                         desc_on = false;
2027                                 } else  {
2028                                         sgmlLineBreak(os, char_line_count, 1);
2029                                         os << c;
2030                                 }
2031                         } else {
2032                                 os << str;
2033                                 char_line_count += str.length();
2034                         }
2035                 }
2036                 font_old = font;
2037         }
2038
2039         while (!tag_state.empty()) {
2040                 os << "</" << tag_name(tag_state.top()) << '>';
2041                 tag_state.pop();
2042         }
2043
2044         // resets description flag correctly
2045         if (desc_on) {
2046                 // <tag> not closed...
2047                 sgmlLineBreak(os, char_line_count, 6);
2048                 os << "</tag>";
2049         }
2050 }
2051
2052
2053 // Print an error message.
2054 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2055         string const & /*message*/) const
2056 {
2057 #ifdef WITH_WARNINGS
2058 #warning This is wrong we cannot insert an inset like this!!!
2059         // I guess this was Jose' so I explain you more or less why this
2060         // is wrong. This way you insert something in the paragraph and
2061         // don't tell it to LyXText (row rebreaking and undo handling!!!)
2062         // I deactivate this code, have a look at BufferView::insertErrors
2063         // how you should do this correctly! (Jug 20020315)
2064 #endif
2065 #if 0
2066         // insert an error marker in text
2067         InsetError * new_inset = new InsetError(message);
2068         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2069                          params.language));
2070 #endif
2071 }
2072
2073
2074 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2075 {
2076         ofstream ofs(fname.c_str());
2077         if (!ofs) {
2078                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2079                 return;
2080         }
2081
2082         Paragraph * par = &*(paragraphs.begin());
2083
2084         niceFile = nice; // this will be used by Insetincludes.
2085
2086         LaTeXFeatures features(params);
2087         validate(features);
2088
2089         texrow.reset();
2090
2091         LyXTextClass const & tclass = params.getLyXTextClass();
2092         string top_element = tclass.latexname();
2093
2094         if (!only_body) {
2095                 ofs << "<!DOCTYPE " << top_element
2096                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2097
2098                 string preamble = params.preamble;
2099                 const string name = nice ? ChangeExtension(filename_, ".sgml")
2100                          : fname;
2101                 preamble += features.getIncludedFiles(name);
2102                 preamble += features.getLyXSGMLEntities();
2103
2104                 if (!preamble.empty()) {
2105                         ofs << "\n [ " << preamble << " ]";
2106                 }
2107                 ofs << ">\n\n";
2108         }
2109
2110         string top = top_element;
2111         top += " lang=\"";
2112         top += params.language->code();
2113         top += '"';
2114
2115         if (!params.options.empty()) {
2116                 top += ' ';
2117                 top += params.options;
2118         }
2119         sgml::openTag(ofs, 0, false, top);
2120
2121         ofs << "<!-- DocBook file was created by " << lyx_docversion
2122             << "\n  See http://www.lyx.org/ for more information -->\n";
2123
2124         vector<string> environment_stack(10);
2125         vector<string> environment_inner(10);
2126         vector<string> command_stack(10);
2127
2128         bool command_flag = false;
2129         Paragraph::depth_type command_depth = 0;
2130         Paragraph::depth_type command_base = 0;
2131         Paragraph::depth_type cmd_depth = 0;
2132         Paragraph::depth_type depth = 0; // paragraph depth
2133
2134         string item_name;
2135         string command_name;
2136
2137         while (par) {
2138                 string sgmlparam;
2139                 string c_depth;
2140                 string c_params;
2141                 int desc_on = 0; // description mode
2142
2143                 LyXLayout_ptr const & style = par->layout();
2144
2145                 // environment tag closing
2146                 for (; depth > par->params().depth(); --depth) {
2147                         if (environment_inner[depth] != "!-- --") {
2148                                 item_name = "listitem";
2149                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2150                                 if (environment_inner[depth] == "varlistentry")
2151                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
2152                         }
2153                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2154                         environment_stack[depth].erase();
2155                         environment_inner[depth].erase();
2156                 }
2157
2158                 if (depth == par->params().depth()
2159                    && environment_stack[depth] != style->latexname()
2160                    && !environment_stack[depth].empty()) {
2161                         if (environment_inner[depth] != "!-- --") {
2162                                 item_name= "listitem";
2163                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
2164                                 if (environment_inner[depth] == "varlistentry")
2165                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2166                         }
2167
2168                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2169
2170                         environment_stack[depth].erase();
2171                         environment_inner[depth].erase();
2172                 }
2173
2174                 // Write opening SGML tags.
2175                 switch (style->latextype) {
2176                 case LATEX_PARAGRAPH:
2177                         sgml::openTag(ofs, depth + command_depth,
2178                                     false, style->latexname());
2179                         break;
2180
2181                 case LATEX_COMMAND:
2182                         if (depth != 0)
2183                                 sgmlError(par, 0,
2184                                           _("Error: Wrong depth for LatexType Command.\n"));
2185
2186                         command_name = style->latexname();
2187
2188                         sgmlparam = style->latexparam();
2189                         c_params = split(sgmlparam, c_depth,'|');
2190
2191                         cmd_depth = lyx::atoi(c_depth);
2192
2193                         if (command_flag) {
2194                                 if (cmd_depth < command_base) {
2195                                         for (Paragraph::depth_type j = command_depth;
2196                                              j >= command_base; --j) {
2197                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
2198                                                 ofs << endl;
2199                                         }
2200                                         command_depth = command_base = cmd_depth;
2201                                 } else if (cmd_depth <= command_depth) {
2202                                         for (int j = command_depth;
2203                                              j >= int(cmd_depth); --j) {
2204                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
2205                                                 ofs << endl;
2206                                         }
2207                                         command_depth = cmd_depth;
2208                                 } else
2209                                         command_depth = cmd_depth;
2210                         } else {
2211                                 command_depth = command_base = cmd_depth;
2212                                 command_flag = true;
2213                         }
2214                         if (command_stack.size() == command_depth + 1)
2215                                 command_stack.push_back(string());
2216                         command_stack[command_depth] = command_name;
2217
2218                         // treat label as a special case for
2219                         // more WYSIWYM handling.
2220                         // This is a hack while paragraphs can't have
2221                         // attributes, like id in this case.
2222                         if (par->isInset(0)) {
2223                                 Inset * inset = par->getInset(0);
2224                                 Inset::Code lyx_code = inset->lyxCode();
2225                                 if (lyx_code == Inset::LABEL_CODE) {
2226                                         command_name += " id=\"";
2227                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
2228                                         command_name += '"';
2229                                         desc_on = 3;
2230                                 }
2231                         }
2232
2233                         sgml::openTag(ofs, depth + command_depth, false, command_name);
2234
2235                         item_name = c_params.empty() ? "title" : c_params;
2236                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
2237                         break;
2238
2239                 case LATEX_ENVIRONMENT:
2240                 case LATEX_ITEM_ENVIRONMENT:
2241                         if (depth < par->params().depth()) {
2242                                 depth = par->params().depth();
2243                                 environment_stack[depth].erase();
2244                         }
2245
2246                         if (environment_stack[depth] != style->latexname()) {
2247                                 if (environment_stack.size() == depth + 1) {
2248                                         environment_stack.push_back("!-- --");
2249                                         environment_inner.push_back("!-- --");
2250                                 }
2251                                 environment_stack[depth] = style->latexname();
2252                                 environment_inner[depth] = "!-- --";
2253                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
2254                         } else {
2255                                 if (environment_inner[depth] != "!-- --") {
2256                                         item_name= "listitem";
2257                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
2258                                         if (environment_inner[depth] == "varlistentry")
2259                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2260                                 }
2261                         }
2262
2263                         if (style->latextype == LATEX_ENVIRONMENT) {
2264                                 if (!style->latexparam().empty()) {
2265                                         if (style->latexparam() == "CDATA")
2266                                                 ofs << "<![CDATA[";
2267                                         else
2268                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
2269                                 }
2270                                 break;
2271                         }
2272
2273                         desc_on = (style->labeltype == LABEL_MANUAL);
2274
2275                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2276                         sgml::openTag(ofs, depth + 1 + command_depth,
2277                                     false, environment_inner[depth]);
2278
2279                         item_name = desc_on ? "term" : "para";
2280                         sgml::openTag(ofs, depth + 1 + command_depth,
2281                                     false, item_name);
2282                         break;
2283                 default:
2284                         sgml::openTag(ofs, depth + command_depth,
2285                                     false, style->latexname());
2286                         break;
2287                 }
2288
2289                 simpleDocBookOnePar(ofs, par, desc_on,
2290                                     depth + 1 + command_depth);
2291                 par = par->next();
2292
2293                 string end_tag;
2294                 // write closing SGML tags
2295                 switch (style->latextype) {
2296                 case LATEX_COMMAND:
2297                         end_tag = c_params.empty() ? "title" : c_params;
2298                         sgml::closeTag(ofs, depth + command_depth,
2299                                      false, end_tag);
2300                         break;
2301                 case LATEX_ENVIRONMENT:
2302                         if (!style->latexparam().empty()) {
2303                                 if (style->latexparam() == "CDATA")
2304                                         ofs << "]]>";
2305                                 else
2306                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
2307                         }
2308                         break;
2309                 case LATEX_ITEM_ENVIRONMENT:
2310                         if (desc_on == 1) break;
2311                         end_tag = "para";
2312                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
2313                         break;
2314                 case LATEX_PARAGRAPH:
2315                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2316                         break;
2317                 default:
2318                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2319                         break;
2320                 }
2321         }
2322
2323         // Close open tags
2324         for (int d = depth; d >= 0; --d) {
2325                 if (!environment_stack[depth].empty()) {
2326                         if (environment_inner[depth] != "!-- --") {
2327                                 item_name = "listitem";
2328                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2329                                if (environment_inner[depth] == "varlistentry")
2330                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2331                         }
2332
2333                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2334                 }
2335         }
2336
2337         for (int j = command_depth; j >= 0 ; --j)
2338                 if (!command_stack[j].empty()) {
2339                         sgml::closeTag(ofs, j, false, command_stack[j]);
2340                         ofs << endl;
2341                 }
2342
2343         ofs << "\n\n";
2344         sgml::closeTag(ofs, 0, false, top_element);
2345
2346         ofs.close();
2347         // How to check for successful close
2348
2349         // we want this to be true outside previews (for insetexternal)
2350         niceFile = true;
2351 }
2352
2353
2354 void Buffer::simpleDocBookOnePar(ostream & os,
2355                                  Paragraph * par, int & desc_on,
2356                                  Paragraph::depth_type depth) const
2357 {
2358         bool emph_flag = false;
2359
2360         LyXLayout_ptr const & style = par->layout();
2361
2362         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2363
2364         int char_line_count = depth;
2365         //if (!style.free_spacing)
2366         //      os << string(depth,' ');
2367
2368         // parsing main loop
2369         for (pos_type i = 0; i < par->size(); ++i) {
2370                 LyXFont font = par->getFont(params, i);
2371
2372                 // handle <emphasis> tag
2373                 if (font_old.emph() != font.emph()) {
2374                         if (font.emph() == LyXFont::ON) {
2375                                 if (style->latexparam() == "CDATA")
2376                                         os << "]]>";
2377                                 os << "<emphasis>";
2378                                 if (style->latexparam() == "CDATA")
2379                                         os << "<![CDATA[";
2380                                 emph_flag = true;
2381                         } else if (i) {
2382                                 if (style->latexparam() == "CDATA")
2383                                         os << "]]>";
2384                                 os << "</emphasis>";
2385                                 if (style->latexparam() == "CDATA")
2386                                         os << "<![CDATA[";
2387                                 emph_flag = false;
2388                         }
2389                 }
2390
2391
2392                 if (par->isInset(i)) {
2393                         Inset * inset = par->getInset(i);
2394                         // don't print the inset in position 0 if desc_on == 3 (label)
2395                         if (i || desc_on != 3) {
2396                                 if (style->latexparam() == "CDATA")
2397                                         os << "]]>";
2398                                 inset->docbook(this, os, false);
2399                                 if (style->latexparam() == "CDATA")
2400                                         os << "<![CDATA[";
2401                         }
2402                 } else {
2403                         char c = par->getChar(i);
2404                         bool ws;
2405                         string str;
2406                         boost::tie(ws, str) = sgml::escapeChar(c);
2407
2408                         if (style->pass_thru) {
2409                                 os << c;
2410                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
2411                                         os << str;
2412                         } else if (desc_on ==1) {
2413                                 ++char_line_count;
2414                                 os << "\n</term><listitem><para>";
2415                                 desc_on = 2;
2416                         } else {
2417                                 os << ' ';
2418                         }
2419                 }
2420                 font_old = font;
2421         }
2422
2423         if (emph_flag) {
2424                 if (style->latexparam() == "CDATA")
2425                         os << "]]>";
2426                 os << "</emphasis>";
2427                 if (style->latexparam() == "CDATA")
2428                         os << "<![CDATA[";
2429         }
2430
2431         // resets description flag correctly
2432         if (desc_on == 1) {
2433                 // <term> not closed...
2434                 os << "</term>\n<listitem><para>&nbsp;</para>";
2435         }
2436         if (style->free_spacing)
2437                 os << '\n';
2438 }
2439
2440
2441 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2442 // Other flags: -wall -v0 -x
2443 int Buffer::runChktex()
2444 {
2445         if (!users->text) return 0;
2446
2447         users->owner()->busy(true);
2448
2449         // get LaTeX-Filename
2450         string const name = getLatexName();
2451         string path = filePath();
2452
2453         string const org_path = path;
2454         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2455                 path = tmppath;
2456         }
2457
2458         Path p(path); // path to LaTeX file
2459         users->owner()->message(_("Running chktex..."));
2460
2461         // Remove all error insets
2462         bool const removedErrorInsets = users->removeAutoInsets();
2463
2464         // Generate the LaTeX file if neccessary
2465         makeLaTeXFile(name, org_path, false);
2466
2467         TeXErrors terr;
2468         Chktex chktex(lyxrc.chktex_command, name, filePath());
2469         int res = chktex.run(terr); // run chktex
2470
2471         if (res == -1) {
2472                 Alert::alert(_("chktex did not work!"),
2473                            _("Could not run with file:"), name);
2474         } else if (res > 0) {
2475                 // Insert all errors as errors boxes
2476                 users->insertErrors(terr);
2477         }
2478
2479         // if we removed error insets before we ran chktex or if we inserted
2480         // error insets after we ran chktex, this must be run:
2481         if (removedErrorInsets || res) {
2482 #warning repaint needed here, or do you mean update() ?
2483                 users->repaint();
2484                 users->fitCursor();
2485         }
2486         users->owner()->busy(false);
2487
2488         return res;
2489 }
2490
2491
2492 void Buffer::validate(LaTeXFeatures & features) const
2493 {
2494         LyXTextClass const & tclass = params.getLyXTextClass();
2495
2496         if (params.tracking_changes) {
2497                 features.require("dvipost");
2498                 features.require("color");
2499         }
2500
2501         // AMS Style is at document level
2502         if (params.use_amsmath == BufferParams::AMS_ON
2503             || tclass.provides(LyXTextClass::amsmath))
2504                 features.require("amsmath");
2505
2506         for_each(paragraphs.begin(), paragraphs.end(),
2507                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2508
2509         // the bullet shapes are buffer level not paragraph level
2510         // so they are tested here
2511         for (int i = 0; i < 4; ++i) {
2512                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2513                         int const font = params.user_defined_bullets[i].getFont();
2514                         if (font == 0) {
2515                                 int const c = params
2516                                         .user_defined_bullets[i]
2517                                         .getCharacter();
2518                                 if (c == 16
2519                                    || c == 17
2520                                    || c == 25
2521                                    || c == 26
2522                                    || c == 31) {
2523                                         features.require("latexsym");
2524                                 }
2525                         } else if (font == 1) {
2526                                 features.require("amssymb");
2527                         } else if ((font >= 2 && font <= 5)) {
2528                                 features.require("pifont");
2529                         }
2530                 }
2531         }
2532
2533         if (lyxerr.debugging(Debug::LATEX)) {
2534                 features.showStruct();
2535         }
2536 }
2537
2538
2539 vector<string> const Buffer::getLabelList() const
2540 {
2541         /// if this is a child document and the parent is already loaded
2542         /// Use the parent's list instead  [ale990407]
2543         if (!params.parentname.empty()
2544             && bufferlist.exists(params.parentname)) {
2545                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2546                 if (tmp)
2547                         return tmp->getLabelList();
2548         }
2549
2550         vector<string> label_list;
2551         for (inset_iterator it = inset_const_iterator_begin();
2552              it != inset_const_iterator_end(); ++it) {
2553                 vector<string> const l = it->getLabelList();
2554                 label_list.insert(label_list.end(), l.begin(), l.end());
2555         }
2556         return label_list;
2557 }
2558
2559
2560 // This is also a buffer property (ale)
2561 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2562 {
2563         /// if this is a child document and the parent is already loaded
2564         /// use the parent's list instead  [ale990412]
2565         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2566                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2567                 if (tmp) {
2568                         tmp->fillWithBibKeys(keys);
2569                         return;
2570                 }
2571         }
2572
2573         for (inset_iterator it = inset_const_iterator_begin();
2574                 it != inset_const_iterator_end(); ++it) {
2575                 if (it->lyxCode() == Inset::BIBTEX_CODE)
2576                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2577                 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2578                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2579                 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2580                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2581                         string const key = bib.getContents();
2582                         string const opt = bib.getOptions();
2583                         string const ref; // = pit->asString(this, false);
2584                         string const info = opt + "TheBibliographyRef" + ref;
2585                         keys.push_back(pair<string, string>(key, info));
2586                 }
2587         }
2588 }
2589
2590
2591 bool Buffer::isDepClean(string const & name) const
2592 {
2593         DepClean::const_iterator it = dep_clean_.find(name);
2594         if (it == dep_clean_.end())
2595                 return true;
2596         return it->second;
2597 }
2598
2599
2600 void Buffer::markDepClean(string const & name)
2601 {
2602         dep_clean_[name] = true;
2603 }
2604
2605
2606 bool Buffer::dispatch(string const & command, bool * result)
2607 {
2608         // Split command string into command and argument
2609         string cmd;
2610         string line = ltrim(command);
2611         string const arg = trim(split(line, cmd, ' '));
2612
2613         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2614 }
2615
2616
2617 bool Buffer::dispatch(int action, string const & argument, bool * result)
2618 {
2619         bool dispatched = true;
2620
2621         switch (action) {
2622                 case LFUN_EXPORT: {
2623                         bool const tmp = Exporter::Export(this, argument, false);
2624                         if (result)
2625                                 *result = tmp;
2626                         break;
2627                 }
2628
2629                 default:
2630                         dispatched = false;
2631         }
2632         return dispatched;
2633 }
2634
2635
2636 void Buffer::resizeInsets(BufferView * bv)
2637 {
2638         /// then remove all LyXText in text-insets
2639         for_each(paragraphs.begin(), paragraphs.end(),
2640                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2641 }
2642
2643
2644 void Buffer::redraw()
2645 {
2646 #warning repaint needed here, or do you mean update() ?
2647         users->repaint();
2648         users->fitCursor();
2649 }
2650
2651
2652 void Buffer::changeLanguage(Language const * from, Language const * to)
2653 {
2654
2655         ParIterator end = par_iterator_end();
2656         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2657                 (*it)->changeLanguage(params, from, to);
2658 }
2659
2660
2661 bool Buffer::isMultiLingual()
2662 {
2663         ParIterator end = par_iterator_end();
2664         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2665                 if ((*it)->isMultiLingual(params))
2666                         return true;
2667
2668         return false;
2669 }
2670
2671
2672 void Buffer::inset_iterator::setParagraph()
2673 {
2674         while (pit != pend) {
2675                 it = pit->insetlist.begin();
2676                 if (it != pit->insetlist.end())
2677                         return;
2678                 ++pit;
2679         }
2680 }
2681
2682
2683 Inset * Buffer::getInsetFromID(int id_arg) const
2684 {
2685         for (inset_iterator it = inset_const_iterator_begin();
2686                  it != inset_const_iterator_end(); ++it)
2687         {
2688                 if (it->id() == id_arg)
2689                         return &(*it);
2690                 Inset * in = it->getInsetFromID(id_arg);
2691                 if (in)
2692                         return in;
2693         }
2694         return 0;
2695 }
2696
2697
2698 Paragraph * Buffer::getParFromID(int id) const
2699 {
2700         if (id < 0)
2701                 return 0;
2702
2703         // why should we allow < 0 ??
2704         //lyx::Assert(id >= 0);
2705
2706         ParConstIterator it(par_iterator_begin());
2707         ParConstIterator end(par_iterator_end());
2708
2709         for (; it != end; ++it) {
2710                 // go on then, show me how to remove
2711                 // the cast
2712                 if ((*it)->id() == id) {
2713                         return const_cast<Paragraph*>(*it);
2714                 }
2715         }
2716
2717         return 0;
2718 }
2719
2720
2721 ParIterator Buffer::par_iterator_begin()
2722 {
2723         return ParIterator(&*(paragraphs.begin()));
2724 }
2725
2726
2727 ParIterator Buffer::par_iterator_end()
2728 {
2729         return ParIterator();
2730 }
2731
2732 ParConstIterator Buffer::par_iterator_begin() const
2733 {
2734         return ParConstIterator(&*(paragraphs.begin()));
2735 }
2736
2737
2738 ParConstIterator Buffer::par_iterator_end() const
2739 {
2740         return ParConstIterator();
2741 }
2742
2743
2744
2745 void Buffer::addUser(BufferView * u)
2746 {
2747         users = u;
2748 }
2749
2750
2751 void Buffer::delUser(BufferView *)
2752 {
2753         users = 0;
2754 }
2755
2756
2757 Language const * Buffer::getLanguage() const
2758 {
2759         return params.language;
2760 }
2761
2762
2763 bool Buffer::isClean() const
2764 {
2765         return lyx_clean;
2766 }
2767
2768
2769 bool Buffer::isBakClean() const
2770 {
2771         return bak_clean;
2772 }
2773
2774
2775 void Buffer::markClean() const
2776 {
2777         if (!lyx_clean) {
2778                 lyx_clean = true;
2779                 updateTitles();
2780         }
2781         // if the .lyx file has been saved, we don't need an
2782         // autosave
2783         bak_clean = true;
2784 }
2785
2786
2787 void Buffer::markBakClean()
2788 {
2789         bak_clean = true;
2790 }
2791
2792
2793 void Buffer::setUnnamed(bool flag)
2794 {
2795         unnamed = flag;
2796 }
2797
2798
2799 bool Buffer::isUnnamed()
2800 {
2801         return unnamed;
2802 }
2803
2804
2805 void Buffer::markDirty()
2806 {
2807         if (lyx_clean) {
2808                 lyx_clean = false;
2809                 updateTitles();
2810         }
2811         bak_clean = false;
2812
2813         DepClean::iterator it = dep_clean_.begin();
2814         DepClean::const_iterator const end = dep_clean_.end();
2815
2816         for (; it != end; ++it) {
2817                 it->second = false;
2818         }
2819 }
2820
2821
2822 string const & Buffer::fileName() const
2823 {
2824         return filename_;
2825 }
2826
2827
2828 string const & Buffer::filePath() const
2829 {
2830         return filepath_;
2831 }
2832
2833
2834 bool Buffer::isReadonly() const
2835 {
2836         return read_only;
2837 }
2838
2839
2840 BufferView * Buffer::getUser() const
2841 {
2842         return users;
2843 }
2844
2845
2846 void Buffer::setParentName(string const & name)
2847 {
2848         params.parentname = name;
2849 }
2850
2851
2852 Buffer::inset_iterator::inset_iterator()
2853         : pit(0), pend(0)
2854 {}
2855
2856
2857 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2858         : pit(p), pend(e)
2859 {
2860         setParagraph();
2861 }
2862
2863
2864 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2865 {
2866         if (pit != pend) {
2867                 ++it;
2868                 if (it == pit->insetlist.end()) {
2869                         ++pit;
2870                         setParagraph();
2871                 }
2872         }
2873         return *this;
2874 }
2875
2876
2877 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2878 {
2879         inset_iterator tmp = *this;
2880         ++*this;
2881         return tmp;
2882 }
2883
2884
2885 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2886 {
2887         return *it.getInset();
2888 }
2889
2890
2891 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2892 {
2893         return it.getInset();
2894 }
2895
2896
2897 Paragraph * Buffer::inset_iterator::getPar()
2898 {
2899         return &(*pit);
2900 }
2901
2902
2903 lyx::pos_type Buffer::inset_iterator::getPos() const
2904 {
2905         return it.getPos();
2906 }
2907
2908
2909 bool operator==(Buffer::inset_iterator const & iter1,
2910                 Buffer::inset_iterator const & iter2)
2911 {
2912         return iter1.pit == iter2.pit
2913                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2914 }
2915
2916
2917 bool operator!=(Buffer::inset_iterator const & iter1,
2918                 Buffer::inset_iterator const & iter2)
2919 {
2920         return !(iter1 == iter2);
2921 }