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