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