]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Sanitize the way we use abort() and exit(). With this commit, we should never crash...
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Buffer.h"
15
16 #include "Author.h"
17 #include "BiblioInfo.h"
18 #include "BranchList.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "Bullet.h"
23 #include "Chktex.h"
24 #include "Converter.h"
25 #include "Counters.h"
26 #include "DocIterator.h"
27 #include "EmbeddedFiles.h"
28 #include "Encoding.h"
29 #include "ErrorList.h"
30 #include "Exporter.h"
31 #include "Format.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LaTeX.h"
38 #include "Layout.h"
39 #include "Lexer.h"
40 #include "LyXAction.h"
41 #include "LyX.h"
42 #include "LyXRC.h"
43 #include "LyXVC.h"
44 #include "output_docbook.h"
45 #include "output.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
53 #include "Session.h"
54 #include "sgml.h"
55 #include "TexRow.h"
56 #include "TexStream.h"
57 #include "TextClassList.h"
58 #include "Text.h"
59 #include "TocBackend.h"
60 #include "Undo.h"
61 #include "VCBackend.h"
62 #include "version.h"
63
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
68
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
72
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
76
77 #include "graphics/Previews.h"
78
79 #include "support/convert.h"
80 #include "support/debug.h"
81 #include "support/FileFilterList.h"
82 #include "support/FileNameList.h"
83 #include "support/filetools.h"
84 #include "support/ForkedCalls.h"
85 #include "support/gettext.h"
86 #include "support/gzstream.h"
87 #include "support/lstrings.h"
88 #include "support/lyxalgo.h"
89 #include "support/lyxlib.h"
90 #include "support/os.h"
91 #include "support/Path.h"
92 #include "support/textutils.h"
93 #include "support/types.h"
94 #include "support/FileZipListDir.h"
95
96 #if !defined (HAVE_FORK)
97 # define fork() -1
98 #endif
99
100 #include <boost/bind.hpp>
101 #include <boost/shared_ptr.hpp>
102
103 #include <algorithm>
104 #include <iomanip>
105 #include <stack>
106 #include <stdlib.h>
107 #include <sstream>
108 #include <fstream>
109
110 using namespace std;
111 using namespace lyx::support;
112
113 namespace lyx {
114
115 namespace Alert = frontend::Alert;
116 namespace os = support::os;
117
118 namespace {
119
120 int const LYX_FORMAT = 308; // Uwe: Serbian-Latin
121
122 } // namespace anon
123
124
125 typedef map<string, bool> DepClean;
126
127 class Buffer::Impl
128 {
129 public:
130         Impl(Buffer & parent, FileName const & file, bool readonly);
131
132         ~Impl()
133         {
134                 if (wa_) {
135                         wa_->closeAll();
136                         delete wa_;
137                 }
138         }
139         
140         BufferParams params;
141         LyXVC lyxvc;
142         string temppath;
143         mutable TexRow texrow;
144         Buffer const * parent_buffer;
145
146         /// need to regenerate .tex?
147         DepClean dep_clean;
148
149         /// is save needed?
150         mutable bool lyx_clean;
151
152         /// is autosave needed?
153         mutable bool bak_clean;
154
155         /// is this a unnamed file (New...)?
156         bool unnamed;
157
158         /// buffer is r/o
159         bool read_only;
160
161         /// name of the file the buffer is associated with.
162         FileName filename;
163
164         /** Set to true only when the file is fully loaded.
165          *  Used to prevent the premature generation of previews
166          *  and by the citation inset.
167          */
168         bool file_fully_loaded;
169
170         /// our Text that should be wrapped in an InsetText
171         InsetText inset;
172
173         ///
174         mutable TocBackend toc_backend;
175
176         /// macro table
177         typedef map<unsigned int, MacroData, greater<int> > PositionToMacroMap;
178         typedef map<docstring, PositionToMacroMap> NameToPositionMacroMap;
179         NameToPositionMacroMap macros;
180
181         /// Container for all sort of Buffer dependant errors.
182         map<string, ErrorList> errorLists;
183
184         /// all embedded files of this buffer
185         EmbeddedFiles embedded_files;
186
187         /// timestamp and checksum used to test if the file has been externally
188         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
189         time_t timestamp_;
190         unsigned long checksum_;
191
192         ///
193         frontend::WorkAreaManager * wa_;
194
195         ///
196         Undo undo_;
197
198         /// A cache for the bibfiles (including bibfiles of loaded child
199         /// documents), needed for appropriate update of natbib labels.
200         mutable FileNameList bibfilesCache_;
201 };
202
203
204 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
205         : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
206           read_only(readonly_), filename(file), file_fully_loaded(false),
207           inset(params), toc_backend(&parent), embedded_files(&parent),
208           timestamp_(0), checksum_(0), wa_(0), undo_(parent)
209 {
210         inset.setAutoBreakRows(true);
211         lyxvc.setBuffer(&parent);
212         temppath = createBufferTmpDir();
213
214         // FIXME: And now do something if temppath == string(), because we
215         // assume from now on that temppath points to a valid temp dir.
216         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
217
218         if (use_gui)
219                 wa_ = new frontend::WorkAreaManager;
220 }
221
222
223 Buffer::Buffer(string const & file, bool readonly)
224         : d(new Impl(*this, FileName(file), readonly)), gui_(0)
225 {
226         LYXERR(Debug::INFO, "Buffer::Buffer()");
227 }
228
229
230 Buffer::~Buffer()
231 {
232         LYXERR(Debug::INFO, "Buffer::~Buffer()");
233         // here the buffer should take care that it is
234         // saved properly, before it goes into the void.
235
236         // GuiView already destroyed
237         gui_ = 0;
238
239         Buffer const * master = masterBuffer();
240         if (master != this && use_gui)
241                 // We are closing buf which was a child document so we
242                 // must update the labels and section numbering of its master
243                 // Buffer.
244                 updateLabels(*master);
245
246         resetChildDocuments(false);
247
248         if (!temppath().empty() && !FileName(temppath()).destroyDirectory()) {
249                 Alert::warning(_("Could not remove temporary directory"),
250                         bformat(_("Could not remove the temporary directory %1$s"),
251                         from_utf8(temppath())));
252         }
253
254         // Remove any previewed LaTeX snippets associated with this buffer.
255         graphics::Previews::get().removeLoader(*this);
256
257         delete d;
258 }
259
260
261 void Buffer::changed() const
262 {
263         if (d->wa_)
264                 d->wa_->redrawAll();
265 }
266
267
268 frontend::WorkAreaManager & Buffer::workAreaManager() const
269 {
270         BOOST_ASSERT(d->wa_);
271         return *d->wa_;
272 }
273
274
275 Text & Buffer::text() const
276 {
277         return const_cast<Text &>(d->inset.text_);
278 }
279
280
281 Inset & Buffer::inset() const
282 {
283         return const_cast<InsetText &>(d->inset);
284 }
285
286
287 BufferParams & Buffer::params()
288 {
289         return d->params;
290 }
291
292
293 BufferParams const & Buffer::params() const
294 {
295         return d->params;
296 }
297
298
299 ParagraphList & Buffer::paragraphs()
300 {
301         return text().paragraphs();
302 }
303
304
305 ParagraphList const & Buffer::paragraphs() const
306 {
307         return text().paragraphs();
308 }
309
310
311 LyXVC & Buffer::lyxvc()
312 {
313         return d->lyxvc;
314 }
315
316
317 LyXVC const & Buffer::lyxvc() const
318 {
319         return d->lyxvc;
320 }
321
322
323 string const & Buffer::temppath() const
324 {
325         return d->temppath;
326 }
327
328
329 TexRow const & Buffer::texrow() const
330 {
331         return d->texrow;
332 }
333
334
335 TocBackend & Buffer::tocBackend() const
336 {
337         return d->toc_backend;
338 }
339
340
341 EmbeddedFiles & Buffer::embeddedFiles()
342 {
343         return d->embedded_files;
344 }
345
346
347 EmbeddedFiles const & Buffer::embeddedFiles() const
348 {
349         return d->embedded_files;
350 }
351
352
353 Undo & Buffer::undo()
354 {
355         return d->undo_;
356 }
357
358
359 string Buffer::latexName(bool const no_path) const
360 {
361         FileName latex_name = makeLatexName(d->filename);
362         return no_path ? latex_name.onlyFileName()
363                 : latex_name.absFilename();
364 }
365
366
367 string Buffer::logName(LogType * type) const
368 {
369         string const filename = latexName(false);
370
371         if (filename.empty()) {
372                 if (type)
373                         *type = latexlog;
374                 return string();
375         }
376
377         string const path = temppath();
378
379         FileName const fname(addName(temppath(),
380                                      onlyFilename(changeExtension(filename,
381                                                                   ".log"))));
382         FileName const bname(
383                 addName(path, onlyFilename(
384                         changeExtension(filename,
385                                         formats.extension("literate") + ".out"))));
386
387         // If no Latex log or Build log is newer, show Build log
388
389         if (bname.exists() &&
390             (!fname.exists() || fname.lastModified() < bname.lastModified())) {
391                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
392                 if (type)
393                         *type = buildlog;
394                 return bname.absFilename();
395         }
396         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
397         if (type)
398                         *type = latexlog;
399         return fname.absFilename();
400 }
401
402
403 void Buffer::setReadonly(bool const flag)
404 {
405         if (d->read_only != flag) {
406                 d->read_only = flag;
407                 setReadOnly(flag);
408         }
409 }
410
411
412 void Buffer::setFileName(string const & newfile)
413 {
414         d->filename = makeAbsPath(newfile);
415         setReadonly(d->filename.isReadOnly());
416         updateTitles();
417 }
418
419
420 int Buffer::readHeader(Lexer & lex)
421 {
422         int unknown_tokens = 0;
423         int line = -1;
424         int begin_header_line = -1;
425
426         // Initialize parameters that may be/go lacking in header:
427         params().branchlist().clear();
428         params().preamble.erase();
429         params().options.erase();
430         params().float_placement.erase();
431         params().paperwidth.erase();
432         params().paperheight.erase();
433         params().leftmargin.erase();
434         params().rightmargin.erase();
435         params().topmargin.erase();
436         params().bottommargin.erase();
437         params().headheight.erase();
438         params().headsep.erase();
439         params().footskip.erase();
440         params().listings_params.clear();
441         params().clearLayoutModules();
442         params().pdfoptions().clear();
443         
444         for (int i = 0; i < 4; ++i) {
445                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
446                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
447         }
448
449         ErrorList & errorList = d->errorLists["Parse"];
450
451         while (lex.isOK()) {
452                 lex.next();
453                 string const token = lex.getString();
454
455                 if (token.empty())
456                         continue;
457
458                 if (token == "\\end_header")
459                         break;
460
461                 ++line;
462                 if (token == "\\begin_header") {
463                         begin_header_line = line;
464                         continue;
465                 }
466
467                 LYXERR(Debug::PARSER, "Handling document header token: `"
468                                       << token << '\'');
469
470                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
471                 if (!unknown.empty()) {
472                         if (unknown[0] != '\\' && token == "\\textclass") {
473                                 Alert::warning(_("Unknown document class"),
474                        bformat(_("Using the default document class, because the "
475                                               "class %1$s is unknown."), from_utf8(unknown)));
476                         } else {
477                                 ++unknown_tokens;
478                                 docstring const s = bformat(_("Unknown token: "
479                                                                         "%1$s %2$s\n"),
480                                                          from_utf8(token),
481                                                          lex.getDocString());
482                                 errorList.push_back(ErrorItem(_("Document header error"),
483                                         s, -1, 0, 0));
484                         }
485                 }
486         }
487         if (begin_header_line) {
488                 docstring const s = _("\\begin_header is missing");
489                 errorList.push_back(ErrorItem(_("Document header error"),
490                         s, -1, 0, 0));
491         }
492
493         return unknown_tokens;
494 }
495
496
497 // Uwe C. Schroeder
498 // changed to be public and have one parameter
499 // Returns false if "\end_document" is not read (Asger)
500 bool Buffer::readDocument(Lexer & lex)
501 {
502         ErrorList & errorList = d->errorLists["Parse"];
503         errorList.clear();
504
505         lex.next();
506         string const token = lex.getString();
507         if (token != "\\begin_document") {
508                 docstring const s = _("\\begin_document is missing");
509                 errorList.push_back(ErrorItem(_("Document header error"),
510                         s, -1, 0, 0));
511         }
512
513         // we are reading in a brand new document
514         BOOST_ASSERT(paragraphs().empty());
515
516         readHeader(lex);
517         TextClass const & baseClass = textclasslist[params().getBaseClass()];
518         if (!baseClass.load(filePath())) {
519                 string theclass = baseClass.name();
520                 Alert::error(_("Can't load document class"), bformat(
521                         _("Using the default document class, because the "
522                                      "class %1$s could not be loaded."), from_utf8(theclass)));
523                 params().setBaseClass(defaultTextclass());
524         }
525
526         if (params().outputChanges) {
527                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
528                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
529                                   LaTeXFeatures::isAvailable("xcolor");
530
531                 if (!dvipost && !xcolorsoul) {
532                         Alert::warning(_("Changes not shown in LaTeX output"),
533                                        _("Changes will not be highlighted in LaTeX output, "
534                                          "because neither dvipost nor xcolor/soul are installed.\n"
535                                          "Please install these packages or redefine "
536                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
537                 } else if (!xcolorsoul) {
538                         Alert::warning(_("Changes not shown in LaTeX output"),
539                                        _("Changes will not be highlighted in LaTeX output "
540                                          "when using pdflatex, because xcolor and soul are not installed.\n"
541                                          "Please install both packages or redefine "
542                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
543                 }
544         }
545
546         // read main text
547         bool const res = text().read(*this, lex, errorList);
548         for_each(text().paragraphs().begin(),
549                  text().paragraphs().end(),
550                  bind(&Paragraph::setInsetOwner, _1, &inset()));
551
552         return res;
553 }
554
555
556 // needed to insert the selection
557 void Buffer::insertStringAsLines(ParagraphList & pars,
558         pit_type & pit, pos_type & pos,
559         Font const & fn, docstring const & str, bool autobreakrows)
560 {
561         Font font = fn;
562
563         // insert the string, don't insert doublespace
564         bool space_inserted = true;
565         for (docstring::const_iterator cit = str.begin();
566             cit != str.end(); ++cit) {
567                 Paragraph & par = pars[pit];
568                 if (*cit == '\n') {
569                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
570                                 breakParagraph(params(), pars, pit, pos,
571                                                par.layout()->isEnvironment());
572                                 ++pit;
573                                 pos = 0;
574                                 space_inserted = true;
575                         } else {
576                                 continue;
577                         }
578                         // do not insert consecutive spaces if !free_spacing
579                 } else if ((*cit == ' ' || *cit == '\t') &&
580                            space_inserted && !par.isFreeSpacing()) {
581                         continue;
582                 } else if (*cit == '\t') {
583                         if (!par.isFreeSpacing()) {
584                                 // tabs are like spaces here
585                                 par.insertChar(pos, ' ', font, params().trackChanges);
586                                 ++pos;
587                                 space_inserted = true;
588                         } else {
589                                 const pos_type n = 8 - pos % 8;
590                                 for (pos_type i = 0; i < n; ++i) {
591                                         par.insertChar(pos, ' ', font, params().trackChanges);
592                                         ++pos;
593                                 }
594                                 space_inserted = true;
595                         }
596                 } else if (!isPrintable(*cit)) {
597                         // Ignore unprintables
598                         continue;
599                 } else {
600                         // just insert the character
601                         par.insertChar(pos, *cit, font, params().trackChanges);
602                         ++pos;
603                         space_inserted = (*cit == ' ');
604                 }
605
606         }
607 }
608
609
610 bool Buffer::readString(string const & s)
611 {
612         params().compressed = false;
613
614         // remove dummy empty par
615         paragraphs().clear();
616         Lexer lex(0, 0);
617         istringstream is(s);
618         lex.setStream(is);
619         FileName const name = FileName::tempName();
620         switch (readFile(lex, name, true)) {
621         case failure:
622                 return false;
623         case wrongversion: {
624                 // We need to call lyx2lyx, so write the input to a file
625                 ofstream os(name.toFilesystemEncoding().c_str());
626                 os << s;
627                 os.close();
628                 return readFile(name);
629         }
630         case success:
631                 break;
632         }
633
634         return true;
635 }
636
637
638 bool Buffer::readFile(FileName const & filename)
639 {
640         FileName fname(filename);
641         // Check if the file is compressed.
642         string format = filename.guessFormatFromContents();
643         if (format == "zip") {
644                 // decompress to a temp directory
645                 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
646                 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
647                 //
648                 FileName lyxfile(addName(temppath(), "content.lyx"));
649                 // if both manifest.txt and file.lyx exist, this is am embedded file
650                 if (lyxfile.exists()) {
651                         params().embedded = true;
652                         fname = lyxfile;
653                 }
654         }
655         // The embedded lyx file can also be compressed, for backward compatibility
656         format = fname.guessFormatFromContents();
657         if (format == "gzip" || format == "zip" || format == "compress")
658                 params().compressed = true;
659
660         // remove dummy empty par
661         paragraphs().clear();
662         Lexer lex(0, 0);
663         lex.setFile(fname);
664         if (readFile(lex, fname) != success)
665                 return false;
666
667         return true;
668 }
669
670
671 bool Buffer::isFullyLoaded() const
672 {
673         return d->file_fully_loaded;
674 }
675
676
677 void Buffer::setFullyLoaded(bool value)
678 {
679         d->file_fully_loaded = value;
680 }
681
682
683 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
684                 bool fromstring)
685 {
686         BOOST_ASSERT(!filename.empty());
687
688         if (!lex.isOK()) {
689                 Alert::error(_("Document could not be read"),
690                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
691                 return failure;
692         }
693
694         lex.next();
695         string const token = lex.getString();
696
697         if (!lex) {
698                 Alert::error(_("Document could not be read"),
699                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
700                 return failure;
701         }
702
703         // the first token _must_ be...
704         if (token != "\\lyxformat") {
705                 lyxerr << "Token: " << token << endl;
706
707                 Alert::error(_("Document format failure"),
708                              bformat(_("%1$s is not a LyX document."),
709                                        from_utf8(filename.absFilename())));
710                 return failure;
711         }
712
713         lex.next();
714         string tmp_format = lex.getString();
715         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
716         // if present remove ".," from string.
717         string::size_type dot = tmp_format.find_first_of(".,");
718         //lyxerr << "           dot found at " << dot << endl;
719         if (dot != string::npos)
720                         tmp_format.erase(dot, 1);
721         int const file_format = convert<int>(tmp_format);
722         //lyxerr << "format: " << file_format << endl;
723
724         // save timestamp and checksum of the original disk file, making sure
725         // to not overwrite them with those of the file created in the tempdir
726         // when it has to be converted to the current format.
727         if (!d->checksum_) {
728                 // Save the timestamp and checksum of disk file. If filename is an
729                 // emergency file, save the timestamp and checksum of the original lyx file
730                 // because isExternallyModified will check for this file. (BUG4193)
731                 string diskfile = filename.absFilename();
732                 if (suffixIs(diskfile, ".emergency"))
733                         diskfile = diskfile.substr(0, diskfile.size() - 10);
734                 saveCheckSum(FileName(diskfile));
735         }
736
737         if (file_format != LYX_FORMAT) {
738
739                 if (fromstring)
740                         // lyx2lyx would fail
741                         return wrongversion;
742
743                 FileName const tmpfile = FileName::tempName();
744                 if (tmpfile.empty()) {
745                         Alert::error(_("Conversion failed"),
746                                      bformat(_("%1$s is from a different"
747                                               " version of LyX, but a temporary"
748                                               " file for converting it could"
749                                                             " not be created."),
750                                               from_utf8(filename.absFilename())));
751                         return failure;
752                 }
753                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
754                 if (lyx2lyx.empty()) {
755                         Alert::error(_("Conversion script not found"),
756                                      bformat(_("%1$s is from a different"
757                                                " version of LyX, but the"
758                                                " conversion script lyx2lyx"
759                                                             " could not be found."),
760                                                from_utf8(filename.absFilename())));
761                         return failure;
762                 }
763                 ostringstream command;
764                 command << os::python()
765                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
766                         << " -t " << convert<string>(LYX_FORMAT)
767                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
768                         << ' ' << quoteName(filename.toFilesystemEncoding());
769                 string const command_str = command.str();
770
771                 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
772
773                 cmd_ret const ret = runCommand(command_str);
774                 if (ret.first != 0) {
775                         Alert::error(_("Conversion script failed"),
776                                      bformat(_("%1$s is from a different version"
777                                               " of LyX, but the lyx2lyx script"
778                                                             " failed to convert it."),
779                                               from_utf8(filename.absFilename())));
780                         return failure;
781                 } else {
782                         bool const ret = readFile(tmpfile);
783                         // Do stuff with tmpfile name and buffer name here.
784                         return ret ? success : failure;
785                 }
786
787         }
788
789         if (readDocument(lex)) {
790                 Alert::error(_("Document format failure"),
791                              bformat(_("%1$s ended unexpectedly, which means"
792                                                     " that it is probably corrupted."),
793                                        from_utf8(filename.absFilename())));
794         }
795
796         d->file_fully_loaded = true;
797         return success;
798 }
799
800
801 // Should probably be moved to somewhere else: BufferView? LyXView?
802 bool Buffer::save() const
803 {
804         // We don't need autosaves in the immediate future. (Asger)
805         resetAutosaveTimers();
806
807         string const encodedFilename = d->filename.toFilesystemEncoding();
808
809         FileName backupName;
810         bool madeBackup = false;
811
812         // make a backup if the file already exists
813         if (lyxrc.make_backup && fileName().exists()) {
814                 backupName = FileName(absFileName() + '~');
815                 if (!lyxrc.backupdir_path.empty()) {
816                         string const mangledName =
817                                 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
818                         backupName = FileName(addName(lyxrc.backupdir_path,
819                                                       mangledName));
820                 }
821                 if (fileName().copyTo(backupName)) {
822                         madeBackup = true;
823                 } else {
824                         Alert::error(_("Backup failure"),
825                                      bformat(_("Cannot create backup file %1$s.\n"
826                                                "Please check whether the directory exists and is writeable."),
827                                              from_utf8(backupName.absFilename())));
828                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
829                 }
830         }
831
832         // ask if the disk file has been externally modified (use checksum method)
833         if (fileName().exists() && isExternallyModified(checksum_method)) {
834                 docstring const file = makeDisplayPath(absFileName(), 20);
835                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
836                                                              "you want to overwrite this file?"), file);
837                 int const ret = Alert::prompt(_("Overwrite modified file?"),
838                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
839                 if (ret == 1)
840                         return false;
841         }
842
843         if (writeFile(d->filename)) {
844                 markClean();
845                 return true;
846         } else {
847                 // Saving failed, so backup is not backup
848                 if (madeBackup)
849                         backupName.moveTo(d->filename);
850                 return false;
851         }
852 }
853
854
855 bool Buffer::writeFile(FileName const & fname) const
856 {
857         if (d->read_only && fname == d->filename)
858                 return false;
859
860         bool retval = false;
861
862         FileName content;
863         if (params().embedded)
864                 // first write the .lyx file to the temporary directory
865                 content = FileName(addName(temppath(), "content.lyx"));
866         else
867                 content = fname;
868
869         docstring const str = bformat(_("Saving document %1$s..."),
870                 makeDisplayPath(content.absFilename()));
871         message(str);
872
873         if (params().compressed) {
874                 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
875                 retval = ofs && write(ofs);
876         } else {
877                 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
878                 retval = ofs && write(ofs);
879         }
880
881         if (!retval) {
882                 message(str + _(" could not write file!."));
883                 return false;
884         }
885
886         removeAutosaveFile(d->filename.absFilename());
887         saveCheckSum(d->filename);
888         message(str + _(" done."));
889
890         if (!params().embedded)
891                 return true;
892
893         message(str + _(" writing embedded files!."));
894         // if embedding is enabled, write file.lyx and all the embedded files
895         // to the zip file fname.
896         if (!d->embedded_files.writeFile(fname)) {
897                 message(str + _(" could not write embedded files!."));
898                 return false;
899         }
900         message(str + _(" error while writing embedded files."));
901         return true;
902 }
903
904
905 bool Buffer::write(ostream & ofs) const
906 {
907 #ifdef HAVE_LOCALE
908         // Use the standard "C" locale for file output.
909         ofs.imbue(locale::classic());
910 #endif
911
912         // The top of the file should not be written by params().
913
914         // write out a comment in the top of the file
915         ofs << "#LyX " << lyx_version
916             << " created this file. For more info see http://www.lyx.org/\n"
917             << "\\lyxformat " << LYX_FORMAT << "\n"
918             << "\\begin_document\n";
919
920
921         /// For each author, set 'used' to true if there is a change
922         /// by this author in the document; otherwise set it to 'false'.
923         AuthorList::Authors::const_iterator a_it = params().authors().begin();
924         AuthorList::Authors::const_iterator a_end = params().authors().end();
925         for (; a_it != a_end; ++a_it)
926                 a_it->second.setUsed(false);
927
928         ParIterator const end = par_iterator_end();
929         ParIterator it = par_iterator_begin();
930         for ( ; it != end; ++it)
931                 it->checkAuthors(params().authors());
932
933         // now write out the buffer parameters.
934         ofs << "\\begin_header\n";
935         params().writeFile(ofs);
936         ofs << "\\end_header\n";
937
938         // write the text
939         ofs << "\n\\begin_body\n";
940         text().write(*this, ofs);
941         ofs << "\n\\end_body\n";
942
943         // Write marker that shows file is complete
944         ofs << "\\end_document" << endl;
945
946         // Shouldn't really be needed....
947         //ofs.close();
948
949         // how to check if close went ok?
950         // Following is an attempt... (BE 20001011)
951
952         // good() returns false if any error occured, including some
953         //        formatting error.
954         // bad()  returns true if something bad happened in the buffer,
955         //        which should include file system full errors.
956
957         bool status = true;
958         if (!ofs) {
959                 status = false;
960                 lyxerr << "File was not closed properly." << endl;
961         }
962
963         return status;
964 }
965
966
967 bool Buffer::makeLaTeXFile(FileName const & fname,
968                            string const & original_path,
969                            OutputParams const & runparams,
970                            bool output_preamble, bool output_body) const
971 {
972         string const encoding = runparams.encoding->iconvName();
973         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
974
975         odocfstream ofs;
976         try { ofs.reset(encoding); }
977         catch (iconv_codecvt_facet_exception & e) {
978                 lyxerr << "Caught iconv exception: " << e.what() << endl;
979                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
980                         "verify that the support software for your encoding (%1$s) is "
981                         "properly installed"), from_ascii(encoding)));
982                 return false;
983         }
984         if (!openFileWrite(ofs, fname))
985                 return false;
986
987         //TexStream ts(ofs.rdbuf(), &texrow());
988
989         bool failed_export = false;
990         try {
991                 d->texrow.reset();
992                 writeLaTeXSource(ofs, original_path,
993                       runparams, output_preamble, output_body);
994         }
995         catch (iconv_codecvt_facet_exception & e) {
996                 lyxerr << "Caught iconv exception: " << e.what() << endl;
997                 failed_export = true;
998         }
999         catch (exception const & e) {
1000                 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1001                 failed_export = true;
1002         }
1003         catch (...) {
1004                 lyxerr << "Caught some really weird exception..." << endl;
1005                 LyX::cref().exit(1);
1006         }
1007
1008         ofs.close();
1009         if (ofs.fail()) {
1010                 failed_export = true;
1011                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1012         }
1013
1014         if (failed_export) {
1015                 Alert::error(_("Encoding error"),
1016                         _("Some characters of your document are probably not "
1017                         "representable in the chosen encoding.\n"
1018                         "Changing the document encoding to utf8 could help."));
1019                 return false;
1020         }
1021         return true;
1022 }
1023
1024
1025 void Buffer::writeLaTeXSource(odocstream & os,
1026                            string const & original_path,
1027                            OutputParams const & runparams_in,
1028                            bool const output_preamble, bool const output_body) const
1029 {
1030         OutputParams runparams = runparams_in;
1031
1032         // validate the buffer.
1033         LYXERR(Debug::LATEX, "  Validating buffer...");
1034         LaTeXFeatures features(*this, params(), runparams);
1035         validate(features);
1036         LYXERR(Debug::LATEX, "  Buffer validation done.");
1037
1038         // The starting paragraph of the coming rows is the
1039         // first paragraph of the document. (Asger)
1040         if (output_preamble && runparams.nice) {
1041                 os << "%% LyX " << lyx_version << " created this file.  "
1042                         "For more info, see http://www.lyx.org/.\n"
1043                         "%% Do not edit unless you really know what "
1044                         "you are doing.\n";
1045                 d->texrow.newline();
1046                 d->texrow.newline();
1047         }
1048         LYXERR(Debug::INFO, "lyx document header finished");
1049         // There are a few differences between nice LaTeX and usual files:
1050         // usual is \batchmode and has a
1051         // special input@path to allow the including of figures
1052         // with either \input or \includegraphics (what figinsets do).
1053         // input@path is set when the actual parameter
1054         // original_path is set. This is done for usual tex-file, but not
1055         // for nice-latex-file. (Matthias 250696)
1056         // Note that input@path is only needed for something the user does
1057         // in the preamble, included .tex files or ERT, files included by
1058         // LyX work without it.
1059         if (output_preamble) {
1060                 if (!runparams.nice) {
1061                         // code for usual, NOT nice-latex-file
1062                         os << "\\batchmode\n"; // changed
1063                         // from \nonstopmode
1064                         d->texrow.newline();
1065                 }
1066                 if (!original_path.empty()) {
1067                         // FIXME UNICODE
1068                         // We don't know the encoding of inputpath
1069                         docstring const inputpath = from_utf8(latex_path(original_path));
1070                         os << "\\makeatletter\n"
1071                            << "\\def\\input@path{{"
1072                            << inputpath << "/}}\n"
1073                            << "\\makeatother\n";
1074                         d->texrow.newline();
1075                         d->texrow.newline();
1076                         d->texrow.newline();
1077                 }
1078
1079                 // Write the preamble
1080                 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1081
1082                 if (!output_body)
1083                         return;
1084
1085                 // make the body.
1086                 os << "\\begin{document}\n";
1087                 d->texrow.newline();
1088         } // output_preamble
1089
1090         d->texrow.start(paragraphs().begin()->id(), 0);
1091         
1092         LYXERR(Debug::INFO, "preamble finished, now the body.");
1093
1094         // if we are doing a real file with body, even if this is the
1095         // child of some other buffer, let's cut the link here.
1096         // This happens for example if only a child document is printed.
1097         Buffer const * save_parent = 0;
1098         if (output_preamble) {
1099                 save_parent = d->parent_buffer;
1100                 d->parent_buffer = 0;
1101         }
1102
1103         loadChildDocuments();
1104
1105         // the real stuff
1106         latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1107
1108         // Restore the parenthood if needed
1109         if (output_preamble)
1110                 d->parent_buffer = save_parent;
1111
1112         // add this just in case after all the paragraphs
1113         os << endl;
1114         d->texrow.newline();
1115
1116         if (output_preamble) {
1117                 os << "\\end{document}\n";
1118                 d->texrow.newline();
1119                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1120         } else {
1121                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1122         }
1123         runparams_in.encoding = runparams.encoding;
1124
1125         // Just to be sure. (Asger)
1126         d->texrow.newline();
1127
1128         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1129         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1130 }
1131
1132
1133 bool Buffer::isLatex() const
1134 {
1135         return params().getTextClass().outputType() == LATEX;
1136 }
1137
1138
1139 bool Buffer::isLiterate() const
1140 {
1141         return params().getTextClass().outputType() == LITERATE;
1142 }
1143
1144
1145 bool Buffer::isDocBook() const
1146 {
1147         return params().getTextClass().outputType() == DOCBOOK;
1148 }
1149
1150
1151 void Buffer::makeDocBookFile(FileName const & fname,
1152                               OutputParams const & runparams,
1153                               bool const body_only) const
1154 {
1155         LYXERR(Debug::LATEX, "makeDocBookFile...");
1156
1157         //ofstream ofs;
1158         odocfstream ofs;
1159         if (!openFileWrite(ofs, fname))
1160                 return;
1161
1162         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1163
1164         ofs.close();
1165         if (ofs.fail())
1166                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1167 }
1168
1169
1170 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1171                              OutputParams const & runparams,
1172                              bool const only_body) const
1173 {
1174         LaTeXFeatures features(*this, params(), runparams);
1175         validate(features);
1176
1177         d->texrow.reset();
1178
1179         TextClass const & tclass = params().getTextClass();
1180         string const top_element = tclass.latexname();
1181
1182         if (!only_body) {
1183                 if (runparams.flavor == OutputParams::XML)
1184                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1185
1186                 // FIXME UNICODE
1187                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1188
1189                 // FIXME UNICODE
1190                 if (! tclass.class_header().empty())
1191                         os << from_ascii(tclass.class_header());
1192                 else if (runparams.flavor == OutputParams::XML)
1193                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1194                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1195                 else
1196                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1197
1198                 docstring preamble = from_utf8(params().preamble);
1199                 if (runparams.flavor != OutputParams::XML ) {
1200                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1201                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1202                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1203                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1204                 }
1205
1206                 string const name = runparams.nice
1207                         ? changeExtension(absFileName(), ".sgml") : fname;
1208                 preamble += features.getIncludedFiles(name);
1209                 preamble += features.getLyXSGMLEntities();
1210
1211                 if (!preamble.empty()) {
1212                         os << "\n [ " << preamble << " ]";
1213                 }
1214                 os << ">\n\n";
1215         }
1216
1217         string top = top_element;
1218         top += " lang=\"";
1219         if (runparams.flavor == OutputParams::XML)
1220                 top += params().language->code();
1221         else
1222                 top += params().language->code().substr(0,2);
1223         top += '"';
1224
1225         if (!params().options.empty()) {
1226                 top += ' ';
1227                 top += params().options;
1228         }
1229
1230         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1231             << " file was created by LyX " << lyx_version
1232             << "\n  See http://www.lyx.org/ for more information -->\n";
1233
1234         params().getTextClass().counters().reset();
1235
1236         loadChildDocuments();
1237
1238         sgml::openTag(os, top);
1239         os << '\n';
1240         docbookParagraphs(paragraphs(), *this, os, runparams);
1241         sgml::closeTag(os, top_element);
1242 }
1243
1244
1245 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1246 // Other flags: -wall -v0 -x
1247 int Buffer::runChktex()
1248 {
1249         setBusy(true);
1250
1251         // get LaTeX-Filename
1252         FileName const path(temppath());
1253         string const name = addName(path.absFilename(), latexName());
1254         string const org_path = filePath();
1255
1256         PathChanger p(path); // path to LaTeX file
1257         message(_("Running chktex..."));
1258
1259         // Generate the LaTeX file if neccessary
1260         OutputParams runparams(&params().encoding());
1261         runparams.flavor = OutputParams::LATEX;
1262         runparams.nice = false;
1263         makeLaTeXFile(FileName(name), org_path, runparams);
1264
1265         TeXErrors terr;
1266         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1267         int const res = chktex.run(terr); // run chktex
1268
1269         if (res == -1) {
1270                 Alert::error(_("chktex failure"),
1271                              _("Could not run chktex successfully."));
1272         } else if (res > 0) {
1273                 ErrorList & errlist = d->errorLists["ChkTeX"];
1274                 errlist.clear();
1275                 bufferErrors(terr, errlist);
1276         }
1277
1278         setBusy(false);
1279
1280         errors("ChkTeX");
1281
1282         return res;
1283 }
1284
1285
1286 void Buffer::validate(LaTeXFeatures & features) const
1287 {
1288         params().validate(features);
1289
1290         loadChildDocuments();
1291
1292         for_each(paragraphs().begin(), paragraphs().end(),
1293                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1294
1295         if (lyxerr.debugging(Debug::LATEX)) {
1296                 features.showStruct();
1297         }
1298 }
1299
1300
1301 void Buffer::getLabelList(vector<docstring> & list) const
1302 {
1303         /// if this is a child document and the parent is already loaded
1304         /// Use the parent's list instead  [ale990407]
1305         Buffer const * tmp = masterBuffer();
1306         if (!tmp) {
1307                 lyxerr << "masterBuffer() failed!" << endl;
1308                 BOOST_ASSERT(tmp);
1309         }
1310         if (tmp != this) {
1311                 tmp->getLabelList(list);
1312                 return;
1313         }
1314
1315         loadChildDocuments();
1316
1317         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1318                 it.nextInset()->getLabelList(*this, list);
1319 }
1320
1321
1322 void Buffer::updateBibfilesCache() const
1323 {
1324         // if this is a child document and the parent is already loaded
1325         // update the parent's cache instead
1326         Buffer const * tmp = masterBuffer();
1327         BOOST_ASSERT(tmp);
1328         if (tmp != this) {
1329                 tmp->updateBibfilesCache();
1330                 return;
1331         }
1332
1333         d->bibfilesCache_.clear();
1334         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1335                 if (it->lyxCode() == BIBTEX_CODE) {
1336                         InsetBibtex const & inset =
1337                                 static_cast<InsetBibtex const &>(*it);
1338                         FileNameList const bibfiles = inset.getFiles(*this);
1339                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1340                                 bibfiles.begin(),
1341                                 bibfiles.end());
1342                 } else if (it->lyxCode() == INCLUDE_CODE) {
1343                         InsetInclude & inset =
1344                                 static_cast<InsetInclude &>(*it);
1345                         inset.updateBibfilesCache(*this);
1346                         FileNameList const & bibfiles =
1347                                         inset.getBibfilesCache(*this);
1348                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1349                                 bibfiles.begin(),
1350                                 bibfiles.end());
1351                 }
1352         }
1353 }
1354
1355
1356 FileNameList const & Buffer::getBibfilesCache() const
1357 {
1358         // if this is a child document and the parent is already loaded
1359         // use the parent's cache instead
1360         Buffer const * tmp = masterBuffer();
1361         BOOST_ASSERT(tmp);
1362         if (tmp != this)
1363                 return tmp->getBibfilesCache();
1364
1365         // We update the cache when first used instead of at loading time.
1366         if (d->bibfilesCache_.empty())
1367                 const_cast<Buffer *>(this)->updateBibfilesCache();
1368
1369         return d->bibfilesCache_;
1370 }
1371
1372
1373 bool Buffer::isDepClean(string const & name) const
1374 {
1375         DepClean::const_iterator const it = d->dep_clean.find(name);
1376         if (it == d->dep_clean.end())
1377                 return true;
1378         return it->second;
1379 }
1380
1381
1382 void Buffer::markDepClean(string const & name)
1383 {
1384         d->dep_clean[name] = true;
1385 }
1386
1387
1388 bool Buffer::dispatch(string const & command, bool * result)
1389 {
1390         return dispatch(lyxaction.lookupFunc(command), result);
1391 }
1392
1393
1394 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1395 {
1396         bool dispatched = true;
1397
1398         switch (func.action) {
1399                 case LFUN_BUFFER_EXPORT: {
1400                         bool const tmp = doExport(to_utf8(func.argument()), false);
1401                         if (result)
1402                                 *result = tmp;
1403                         break;
1404                 }
1405
1406                 default:
1407                         dispatched = false;
1408         }
1409         return dispatched;
1410 }
1411
1412
1413 void Buffer::changeLanguage(Language const * from, Language const * to)
1414 {
1415         BOOST_ASSERT(from);
1416         BOOST_ASSERT(to);
1417
1418         for_each(par_iterator_begin(),
1419                  par_iterator_end(),
1420                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1421 }
1422
1423
1424 bool Buffer::isMultiLingual() const
1425 {
1426         ParConstIterator end = par_iterator_end();
1427         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1428                 if (it->isMultiLingual(params()))
1429                         return true;
1430
1431         return false;
1432 }
1433
1434
1435 ParIterator Buffer::getParFromID(int const id) const
1436 {
1437         ParConstIterator it = par_iterator_begin();
1438         ParConstIterator const end = par_iterator_end();
1439
1440         if (id < 0) {
1441                 // John says this is called with id == -1 from undo
1442                 lyxerr << "getParFromID(), id: " << id << endl;
1443                 return end;
1444         }
1445
1446         for (; it != end; ++it)
1447                 if (it->id() == id)
1448                         return it;
1449
1450         return end;
1451 }
1452
1453
1454 bool Buffer::hasParWithID(int const id) const
1455 {
1456         ParConstIterator const it = getParFromID(id);
1457         return it != par_iterator_end();
1458 }
1459
1460
1461 ParIterator Buffer::par_iterator_begin()
1462 {
1463         return lyx::par_iterator_begin(inset());
1464 }
1465
1466
1467 ParIterator Buffer::par_iterator_end()
1468 {
1469         return lyx::par_iterator_end(inset());
1470 }
1471
1472
1473 ParConstIterator Buffer::par_iterator_begin() const
1474 {
1475         return lyx::par_const_iterator_begin(inset());
1476 }
1477
1478
1479 ParConstIterator Buffer::par_iterator_end() const
1480 {
1481         return lyx::par_const_iterator_end(inset());
1482 }
1483
1484
1485 Language const * Buffer::language() const
1486 {
1487         return params().language;
1488 }
1489
1490
1491 docstring const Buffer::B_(string const & l10n) const
1492 {
1493         return params().B_(l10n);
1494 }
1495
1496
1497 bool Buffer::isClean() const
1498 {
1499         return d->lyx_clean;
1500 }
1501
1502
1503 bool Buffer::isBakClean() const
1504 {
1505         return d->bak_clean;
1506 }
1507
1508
1509 bool Buffer::isExternallyModified(CheckMethod method) const
1510 {
1511         BOOST_ASSERT(d->filename.exists());
1512         // if method == timestamp, check timestamp before checksum
1513         return (method == checksum_method 
1514                 || d->timestamp_ != d->filename.lastModified())
1515                 && d->checksum_ != d->filename.checksum();
1516 }
1517
1518
1519 void Buffer::saveCheckSum(FileName const & file) const
1520 {
1521         if (file.exists()) {
1522                 d->timestamp_ = file.lastModified();
1523                 d->checksum_ = file.checksum();
1524         } else {
1525                 // in the case of save to a new file.
1526                 d->timestamp_ = 0;
1527                 d->checksum_ = 0;
1528         }
1529 }
1530
1531
1532 void Buffer::markClean() const
1533 {
1534         if (!d->lyx_clean) {
1535                 d->lyx_clean = true;
1536                 updateTitles();
1537         }
1538         // if the .lyx file has been saved, we don't need an
1539         // autosave
1540         d->bak_clean = true;
1541 }
1542
1543
1544 void Buffer::markBakClean() const
1545 {
1546         d->bak_clean = true;
1547 }
1548
1549
1550 void Buffer::setUnnamed(bool flag)
1551 {
1552         d->unnamed = flag;
1553 }
1554
1555
1556 bool Buffer::isUnnamed() const
1557 {
1558         return d->unnamed;
1559 }
1560
1561
1562 // FIXME: this function should be moved to buffer_pimpl.C
1563 void Buffer::markDirty()
1564 {
1565         if (d->lyx_clean) {
1566                 d->lyx_clean = false;
1567                 updateTitles();
1568         }
1569         d->bak_clean = false;
1570
1571         DepClean::iterator it = d->dep_clean.begin();
1572         DepClean::const_iterator const end = d->dep_clean.end();
1573
1574         for (; it != end; ++it)
1575                 it->second = false;
1576 }
1577
1578
1579 FileName Buffer::fileName() const
1580 {
1581         return d->filename;
1582 }
1583
1584
1585 string Buffer::absFileName() const
1586 {
1587         return d->filename.absFilename();
1588 }
1589
1590
1591 string Buffer::filePath() const
1592 {
1593         return d->filename.onlyPath().absFilename();
1594 }
1595
1596
1597 bool Buffer::isReadonly() const
1598 {
1599         return d->read_only;
1600 }
1601
1602
1603 void Buffer::setParent(Buffer const * buffer)
1604 {
1605         // Avoids recursive include.
1606         d->parent_buffer = buffer == this ? 0 : buffer;
1607 }
1608
1609
1610 Buffer const * Buffer::parent()
1611 {
1612         return d->parent_buffer;
1613 }
1614
1615
1616 Buffer const * Buffer::masterBuffer() const
1617 {
1618         if (!d->parent_buffer)
1619                 return this;
1620         
1621         return d->parent_buffer->masterBuffer();
1622 }
1623
1624
1625 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1626 {
1627         Impl::PositionToMacroMap::iterator it;
1628         it = d->macros[name].upper_bound(par.macrocontextPosition());
1629         if (it != d->macros[name].end())
1630                 return true;
1631
1632         // If there is a master buffer, query that
1633         Buffer const * master = masterBuffer();
1634         if (master && master != this)
1635                 return master->hasMacro(name);
1636
1637         return MacroTable::globalMacros().has(name);
1638 }
1639
1640
1641 bool Buffer::hasMacro(docstring const & name) const
1642 {
1643         if( !d->macros[name].empty() )
1644                 return true;
1645
1646         // If there is a master buffer, query that
1647         Buffer const * master = masterBuffer();
1648         if (master && master != this)
1649                 return master->hasMacro(name);
1650
1651         return MacroTable::globalMacros().has(name);
1652 }
1653
1654
1655 MacroData const & Buffer::getMacro(docstring const & name,
1656         Paragraph const & par) const
1657 {
1658         Impl::PositionToMacroMap::iterator it;
1659         it = d->macros[name].upper_bound(par.macrocontextPosition());
1660         if( it != d->macros[name].end() )
1661                 return it->second;
1662
1663         // If there is a master buffer, query that
1664         Buffer const * master = masterBuffer();
1665         if (master && master != this)
1666                 return master->getMacro(name);
1667
1668         return MacroTable::globalMacros().get(name);
1669 }
1670
1671
1672 MacroData const & Buffer::getMacro(docstring const & name) const
1673 {
1674         Impl::PositionToMacroMap::iterator it;
1675         it = d->macros[name].begin();
1676         if( it != d->macros[name].end() )
1677                 return it->second;
1678
1679         // If there is a master buffer, query that
1680         Buffer const * master = masterBuffer();
1681         if (master && master != this)
1682                 return master->getMacro(name);
1683
1684         return MacroTable::globalMacros().get(name);
1685 }
1686
1687
1688 void Buffer::updateMacros()
1689 {
1690         // start with empty table
1691         d->macros = Impl::NameToPositionMacroMap();
1692
1693         // Iterate over buffer
1694         ParagraphList & pars = text().paragraphs();
1695         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1696                 // set position again
1697                 pars[i].setMacrocontextPosition(i);
1698
1699                 //lyxerr << "searching main par " << i
1700                 //      << " for macro definitions" << endl;
1701                 InsetList const & insets = pars[i].insetList();
1702                 InsetList::const_iterator it = insets.begin();
1703                 InsetList::const_iterator end = insets.end();
1704                 for ( ; it != end; ++it) {
1705                         if (it->inset->lyxCode() != MATHMACRO_CODE)
1706                                 continue;
1707                         
1708                         // get macro data
1709                         MathMacroTemplate const & macroTemplate
1710                         = static_cast<MathMacroTemplate const &>(*it->inset);
1711
1712                         // valid?
1713                         if (macroTemplate.validMacro()) {
1714                                 MacroData macro = macroTemplate.asMacroData();
1715
1716                                 // redefinition?
1717                                 // call hasMacro here instead of directly querying mc to
1718                                 // also take the master document into consideration
1719                                 macro.setRedefinition(hasMacro(macroTemplate.name()));
1720
1721                                 // register macro (possibly overwrite the previous one of this paragraph)
1722                                 d->macros[macroTemplate.name()][i] = macro;
1723                         }
1724                 }
1725         }
1726 }
1727
1728
1729 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1730         InsetCode code)
1731 {
1732         //FIXME: This does not work for child documents yet.
1733         BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1734         // Check if the label 'from' appears more than once
1735         vector<docstring> labels;
1736
1737         string paramName;
1738         if (code == CITE_CODE) {
1739                 BiblioInfo keys;
1740                 keys.fillWithBibKeys(this);
1741                 BiblioInfo::const_iterator bit  = keys.begin();
1742                 BiblioInfo::const_iterator bend = keys.end();
1743
1744                 for (; bit != bend; ++bit)
1745                         // FIXME UNICODE
1746                         labels.push_back(bit->first);
1747                 paramName = "key";
1748         } else {
1749                 getLabelList(labels);
1750                 paramName = "reference";
1751         }
1752
1753         if (count(labels.begin(), labels.end(), from) > 1)
1754                 return;
1755
1756         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1757                 if (it->lyxCode() == code) {
1758                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
1759                         docstring const oldValue = inset.getParam(paramName);
1760                         if (oldValue == from)
1761                                 inset.setParam(paramName, to);
1762                 }
1763         }
1764 }
1765
1766
1767 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1768         pit_type par_end, bool full_source)
1769 {
1770         OutputParams runparams(&params().encoding());
1771         runparams.nice = true;
1772         runparams.flavor = OutputParams::LATEX;
1773         runparams.linelen = lyxrc.plaintext_linelen;
1774         // No side effect of file copying and image conversion
1775         runparams.dryrun = true;
1776
1777         d->texrow.reset();
1778         if (full_source) {
1779                 os << "% " << _("Preview source code") << "\n\n";
1780                 d->texrow.newline();
1781                 d->texrow.newline();
1782                 if (isLatex())
1783                         writeLaTeXSource(os, filePath(), runparams, true, true);
1784                 else {
1785                         writeDocBookSource(os, absFileName(), runparams, false);
1786                 }
1787         } else {
1788                 runparams.par_begin = par_begin;
1789                 runparams.par_end = par_end;
1790                 if (par_begin + 1 == par_end)
1791                         os << "% "
1792                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1793                            << "\n\n";
1794                 else
1795                         os << "% "
1796                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1797                                         convert<docstring>(par_begin),
1798                                         convert<docstring>(par_end - 1))
1799                            << "\n\n";
1800                 d->texrow.newline();
1801                 d->texrow.newline();
1802                 // output paragraphs
1803                 if (isLatex()) {
1804                         latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1805                 } else {
1806                         // DocBook
1807                         docbookParagraphs(paragraphs(), *this, os, runparams);
1808                 }
1809         }
1810 }
1811
1812
1813 ErrorList & Buffer::errorList(string const & type) const
1814 {
1815         static ErrorList emptyErrorList;
1816         map<string, ErrorList>::iterator I = d->errorLists.find(type);
1817         if (I == d->errorLists.end())
1818                 return emptyErrorList;
1819
1820         return I->second;
1821 }
1822
1823
1824 void Buffer::structureChanged() const
1825 {
1826         if (gui_)
1827                 gui_->structureChanged();
1828 }
1829
1830
1831 void Buffer::errors(string const & err) const
1832 {
1833         if (gui_)
1834                 gui_->errors(err);
1835 }
1836
1837
1838 void Buffer::message(docstring const & msg) const
1839 {
1840         if (gui_)
1841                 gui_->message(msg);
1842 }
1843
1844
1845 void Buffer::setBusy(bool on) const
1846 {
1847         if (gui_)
1848                 gui_->setBusy(on);
1849 }
1850
1851
1852 void Buffer::setReadOnly(bool on) const
1853 {
1854         if (d->wa_)
1855                 d->wa_->setReadOnly(on);
1856 }
1857
1858
1859 void Buffer::updateTitles() const
1860 {
1861         if (d->wa_)
1862                 d->wa_->updateTitles();
1863 }
1864
1865
1866 void Buffer::resetAutosaveTimers() const
1867 {
1868         if (gui_)
1869                 gui_->resetAutosaveTimers();
1870 }
1871
1872
1873 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1874 {
1875         gui_ = gui;
1876 }
1877
1878
1879
1880 namespace {
1881
1882 class AutoSaveBuffer : public ForkedProcess {
1883 public:
1884         ///
1885         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1886                 : buffer_(buffer), fname_(fname) {}
1887         ///
1888         virtual boost::shared_ptr<ForkedProcess> clone() const
1889         {
1890                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1891         }
1892         ///
1893         int start()
1894         {
1895                 command_ = to_utf8(bformat(_("Auto-saving %1$s"), 
1896                                                  from_utf8(fname_.absFilename())));
1897                 return run(DontWait);
1898         }
1899 private:
1900         ///
1901         virtual int generateChild();
1902         ///
1903         Buffer const & buffer_;
1904         FileName fname_;
1905 };
1906
1907
1908 #if !defined (HAVE_FORK)
1909 # define fork() -1
1910 #endif
1911
1912 int AutoSaveBuffer::generateChild()
1913 {
1914         // tmp_ret will be located (usually) in /tmp
1915         // will that be a problem?
1916         pid_t const pid = fork();
1917         // If you want to debug the autosave
1918         // you should set pid to -1, and comment out the fork.
1919         if (pid == 0 || pid == -1) {
1920                 // pid = -1 signifies that lyx was unable
1921                 // to fork. But we will do the save
1922                 // anyway.
1923                 bool failed = false;
1924
1925                 FileName const tmp_ret = FileName::tempName("lyxauto");
1926                 if (!tmp_ret.empty()) {
1927                         buffer_.writeFile(tmp_ret);
1928                         // assume successful write of tmp_ret
1929                         if (!tmp_ret.moveTo(fname_)) {
1930                                 failed = true;
1931                                 // most likely couldn't move between
1932                                 // filesystems unless write of tmp_ret
1933                                 // failed so remove tmp file (if it
1934                                 // exists)
1935                                 tmp_ret.removeFile();
1936                         }
1937                 } else {
1938                         failed = true;
1939                 }
1940
1941                 if (failed) {
1942                         // failed to write/rename tmp_ret so try writing direct
1943                         if (!buffer_.writeFile(fname_)) {
1944                                 // It is dangerous to do this in the child,
1945                                 // but safe in the parent, so...
1946                                 if (pid == -1) // emit message signal.
1947                                         buffer_.message(_("Autosave failed!"));
1948                         }
1949                 }
1950                 if (pid == 0) { // we are the child so...
1951                         _exit(0);
1952                 }
1953         }
1954         return pid;
1955 }
1956
1957 } // namespace anon
1958
1959
1960 // Perfect target for a thread...
1961 void Buffer::autoSave() const
1962 {
1963         if (isBakClean() || isReadonly()) {
1964                 // We don't save now, but we'll try again later
1965                 resetAutosaveTimers();
1966                 return;
1967         }
1968
1969         // emit message signal.
1970         message(_("Autosaving current document..."));
1971
1972         // create autosave filename
1973         string fname = filePath();
1974         fname += '#';
1975         fname += d->filename.onlyFileName();
1976         fname += '#';
1977
1978         AutoSaveBuffer autosave(*this, FileName(fname));
1979         autosave.start();
1980
1981         markBakClean();
1982         resetAutosaveTimers();
1983 }
1984
1985
1986 void Buffer::resetChildDocuments(bool close_them) const
1987 {
1988         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1989                 if (it->lyxCode() != INCLUDE_CODE)
1990                         continue;
1991                 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
1992                 InsetCommandParams const & ip = inset.params();
1993
1994                 resetParentBuffer(this, ip, close_them);
1995         }
1996
1997         if (use_gui && masterBuffer() == this)
1998                 updateLabels(*this);
1999 }
2000
2001
2002 void Buffer::loadChildDocuments() const
2003 {
2004         bool parse_error = false;
2005                 
2006         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2007                 if (it->lyxCode() != INCLUDE_CODE)
2008                         continue;
2009                 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2010                 InsetCommandParams const & ip = inset.params();
2011                 Buffer * child = loadIfNeeded(*this, ip);
2012                 if (!child)
2013                         continue;
2014                 parse_error |= !child->errorList("Parse").empty();
2015                 child->loadChildDocuments();
2016         }
2017
2018         if (use_gui && masterBuffer() == this)
2019                 updateLabels(*this);
2020 }
2021
2022
2023 string Buffer::bufferFormat() const
2024 {
2025         if (isDocBook())
2026                 return "docbook";
2027         if (isLiterate())
2028                 return "literate";
2029         return "latex";
2030 }
2031
2032
2033 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2034         string & result_file) const
2035 {
2036         string backend_format;
2037         OutputParams runparams(&params().encoding());
2038         runparams.flavor = OutputParams::LATEX;
2039         runparams.linelen = lyxrc.plaintext_linelen;
2040         vector<string> backs = backends();
2041         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2042                 // Get shortest path to format
2043                 Graph::EdgePath path;
2044                 for (vector<string>::const_iterator it = backs.begin();
2045                      it != backs.end(); ++it) {
2046                         Graph::EdgePath p = theConverters().getPath(*it, format);
2047                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2048                                 backend_format = *it;
2049                                 path = p;
2050                         }
2051                 }
2052                 if (!path.empty())
2053                         runparams.flavor = theConverters().getFlavor(path);
2054                 else {
2055                         Alert::error(_("Couldn't export file"),
2056                                 bformat(_("No information for exporting the format %1$s."),
2057                                    formats.prettyName(format)));
2058                         return false;
2059                 }
2060         } else {
2061                 backend_format = format;
2062                 // FIXME: Don't hardcode format names here, but use a flag
2063                 if (backend_format == "pdflatex")
2064                         runparams.flavor = OutputParams::PDFLATEX;
2065         }
2066
2067         string filename = latexName(false);
2068         filename = addName(temppath(), filename);
2069         filename = changeExtension(filename,
2070                                    formats.extension(backend_format));
2071
2072         // Plain text backend
2073         if (backend_format == "text")
2074                 writePlaintextFile(*this, FileName(filename), runparams);
2075         // no backend
2076         else if (backend_format == "lyx")
2077                 writeFile(FileName(filename));
2078         // Docbook backend
2079         else if (isDocBook()) {
2080                 runparams.nice = !put_in_tempdir;
2081                 makeDocBookFile(FileName(filename), runparams);
2082         }
2083         // LaTeX backend
2084         else if (backend_format == format) {
2085                 runparams.nice = true;
2086                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2087                         return false;
2088         } else if (!lyxrc.tex_allows_spaces
2089                    && contains(filePath(), ' ')) {
2090                 Alert::error(_("File name error"),
2091                            _("The directory path to the document cannot contain spaces."));
2092                 return false;
2093         } else {
2094                 runparams.nice = false;
2095                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2096                         return false;
2097         }
2098
2099         string const error_type = (format == "program")
2100                 ? "Build" : bufferFormat();
2101         string const ext = formats.extension(format);
2102         FileName const tmp_result_file(changeExtension(filename, ext));
2103         bool const success = theConverters().convert(this, FileName(filename),
2104                 tmp_result_file, FileName(absFileName()), backend_format, format,
2105                 errorList(error_type));
2106         // Emit the signal to show the error list.
2107         if (format != backend_format)
2108                 errors(error_type);
2109         if (!success)
2110                 return false;
2111
2112         if (put_in_tempdir)
2113                 result_file = tmp_result_file.absFilename();
2114         else {
2115                 result_file = changeExtension(absFileName(), ext);
2116                 // We need to copy referenced files (e. g. included graphics
2117                 // if format == "dvi") to the result dir.
2118                 vector<ExportedFile> const files =
2119                         runparams.exportdata->externalFiles(format);
2120                 string const dest = onlyPath(result_file);
2121                 CopyStatus status = SUCCESS;
2122                 for (vector<ExportedFile>::const_iterator it = files.begin();
2123                                 it != files.end() && status != CANCEL; ++it) {
2124                         string const fmt =
2125                                 formats.getFormatFromFile(it->sourceName);
2126                         status = copyFile(fmt, it->sourceName,
2127                                           makeAbsPath(it->exportName, dest),
2128                                           it->exportName, status == FORCE);
2129                 }
2130                 if (status == CANCEL) {
2131                         message(_("Document export cancelled."));
2132                 } else if (tmp_result_file.exists()) {
2133                         // Finally copy the main file
2134                         status = copyFile(format, tmp_result_file,
2135                                           FileName(result_file), result_file,
2136                                           status == FORCE);
2137                         message(bformat(_("Document exported as %1$s "
2138                                                                "to file `%2$s'"),
2139                                                 formats.prettyName(format),
2140                                                 makeDisplayPath(result_file)));
2141                 } else {
2142                         // This must be a dummy converter like fax (bug 1888)
2143                         message(bformat(_("Document exported as %1$s"),
2144                                                 formats.prettyName(format)));
2145                 }
2146         }
2147
2148         return true;
2149 }
2150
2151
2152 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2153 {
2154         string result_file;
2155         return doExport(format, put_in_tempdir, result_file);
2156 }
2157
2158
2159 bool Buffer::preview(string const & format) const
2160 {
2161         string result_file;
2162         if (!doExport(format, true, result_file))
2163                 return false;
2164         return formats.view(*this, FileName(result_file), format);
2165 }
2166
2167
2168 bool Buffer::isExportable(string const & format) const
2169 {
2170         vector<string> backs = backends();
2171         for (vector<string>::const_iterator it = backs.begin();
2172              it != backs.end(); ++it)
2173                 if (theConverters().isReachable(*it, format))
2174                         return true;
2175         return false;
2176 }
2177
2178
2179 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2180 {
2181         vector<string> backs = backends();
2182         vector<Format const *> result =
2183                 theConverters().getReachable(backs[0], only_viewable, true);
2184         for (vector<string>::const_iterator it = backs.begin() + 1;
2185              it != backs.end(); ++it) {
2186                 vector<Format const *>  r =
2187                         theConverters().getReachable(*it, only_viewable, false);
2188                 result.insert(result.end(), r.begin(), r.end());
2189         }
2190         return result;
2191 }
2192
2193
2194 vector<string> Buffer::backends() const
2195 {
2196         vector<string> v;
2197         if (params().getTextClass().isTeXClassAvailable()) {
2198                 v.push_back(bufferFormat());
2199                 // FIXME: Don't hardcode format names here, but use a flag
2200                 if (v.back() == "latex")
2201                         v.push_back("pdflatex");
2202         }
2203         v.push_back("text");
2204         v.push_back("lyx");
2205         return v;
2206 }
2207
2208
2209 bool Buffer::readFileHelper(FileName const & s)
2210 {
2211         // File information about normal file
2212         if (!s.exists()) {
2213                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2214                 docstring text = bformat(_("The specified document\n%1$s"
2215                                                      "\ncould not be read."), file);
2216                 Alert::error(_("Could not read document"), text);
2217                 return false;
2218         }
2219
2220         // Check if emergency save file exists and is newer.
2221         FileName const e(s.absFilename() + ".emergency");
2222
2223         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2224                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2225                 docstring const text =
2226                         bformat(_("An emergency save of the document "
2227                                   "%1$s exists.\n\n"
2228                                                "Recover emergency save?"), file);
2229                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2230                                       _("&Recover"),  _("&Load Original"),
2231                                       _("&Cancel")))
2232                 {
2233                 case 0:
2234                         // the file is not saved if we load the emergency file.
2235                         markDirty();
2236                         return readFile(e);
2237                 case 1:
2238                         break;
2239                 default:
2240                         return false;
2241                 }
2242         }
2243
2244         // Now check if autosave file is newer.
2245         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2246
2247         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2248                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2249                 docstring const text =
2250                         bformat(_("The backup of the document "
2251                                   "%1$s is newer.\n\nLoad the "
2252                                                "backup instead?"), file);
2253                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2254                                       _("&Load backup"), _("Load &original"),
2255                                       _("&Cancel") ))
2256                 {
2257                 case 0:
2258                         // the file is not saved if we load the autosave file.
2259                         markDirty();
2260                         return readFile(a);
2261                 case 1:
2262                         // Here we delete the autosave
2263                         a.removeFile();
2264                         break;
2265                 default:
2266                         return false;
2267                 }
2268         }
2269         return readFile(s);
2270 }
2271
2272
2273 bool Buffer::loadLyXFile(FileName const & s)
2274 {
2275         if (s.isReadableFile()) {
2276                 if (readFileHelper(s)) {
2277                         lyxvc().file_found_hook(s);
2278                         if (!s.isWritable())
2279                                 setReadonly(true);
2280                         return true;
2281                 }
2282         } else {
2283                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2284                 // Here we probably should run
2285                 if (LyXVC::file_not_found_hook(s)) {
2286                         docstring const text =
2287                                 bformat(_("Do you want to retrieve the document"
2288                                                        " %1$s from version control?"), file);
2289                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2290                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2291
2292                         if (ret == 0) {
2293                                 // How can we know _how_ to do the checkout?
2294                                 // With the current VC support it has to be,
2295                                 // a RCS file since CVS do not have special ,v files.
2296                                 RCS::retrieve(s);
2297                                 return loadLyXFile(s);
2298                         }
2299                 }
2300         }
2301         return false;
2302 }
2303
2304
2305 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2306 {
2307         TeXErrors::Errors::const_iterator cit = terr.begin();
2308         TeXErrors::Errors::const_iterator end = terr.end();
2309
2310         for (; cit != end; ++cit) {
2311                 int id_start = -1;
2312                 int pos_start = -1;
2313                 int errorRow = cit->error_in_line;
2314                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2315                                                        pos_start);
2316                 int id_end = -1;
2317                 int pos_end = -1;
2318                 do {
2319                         ++errorRow;
2320                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2321                 } while (found && id_start == id_end && pos_start == pos_end);
2322
2323                 errorList.push_back(ErrorItem(cit->error_desc,
2324                         cit->error_text, id_start, pos_start, pos_end));
2325         }
2326 }
2327
2328 } // namespace lyx