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