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