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