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