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