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