]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
afe016b70c44e714f90fd67783728f15e41b965b
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Buffer.h"
15
16 #include "Author.h"
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "Bullet.h"
24 #include "Chktex.h"
25 #include "Converter.h"
26 #include "Counters.h"
27 #include "DocIterator.h"
28 #include "Encoding.h"
29 #include "ErrorList.h"
30 #include "Exporter.h"
31 #include "Format.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LaTeX.h"
38 #include "Layout.h"
39 #include "Lexer.h"
40 #include "LyXAction.h"
41 #include "LyX.h"
42 #include "LyXRC.h"
43 #include "LyXVC.h"
44 #include "output_docbook.h"
45 #include "output.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
53 #include "sgml.h"
54 #include "TexRow.h"
55 #include "TexStream.h"
56 #include "Text.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
59 #include "Undo.h"
60 #include "VCBackend.h"
61 #include "version.h"
62 #include "WordList.h"
63
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
68
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
72
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
76
77 #include "graphics/Previews.h"
78
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
96
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
99
100 #include <algorithm>
101 #include <fstream>
102 #include <iomanip>
103 #include <map>
104 #include <sstream>
105 #include <stack>
106 #include <vector>
107
108 using namespace std;
109 using namespace lyx::support;
110
111 namespace lyx {
112
113 namespace Alert = frontend::Alert;
114 namespace os = support::os;
115
116 namespace {
117
118 int const LYX_FORMAT = 335;
119
120 typedef map<string, bool> DepClean;
121 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
122
123 } // namespace anon
124
125 class Buffer::Impl
126 {
127 public:
128         Impl(Buffer & parent, FileName const & file, bool readonly);
129
130         ~Impl()
131         {
132                 if (wa_) {
133                         wa_->closeAll();
134                         delete wa_;
135                 }
136         }
137         
138         BufferParams params;
139         LyXVC lyxvc;
140         FileName temppath;
141         mutable TexRow texrow;
142         Buffer const * parent_buffer;
143
144         /// need to regenerate .tex?
145         DepClean dep_clean;
146
147         /// is save needed?
148         mutable bool lyx_clean;
149
150         /// is autosave needed?
151         mutable bool bak_clean;
152
153         /// is this a unnamed file (New...)?
154         bool unnamed;
155
156         /// buffer is r/o
157         bool read_only;
158
159         /// name of the file the buffer is associated with.
160         FileName filename;
161
162         /** Set to true only when the file is fully loaded.
163          *  Used to prevent the premature generation of previews
164          *  and by the citation inset.
165          */
166         bool file_fully_loaded;
167
168         ///
169         mutable TocBackend toc_backend;
170
171         /// macro tables
172         typedef pair<DocIterator, MacroData> ScopeMacro;
173         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
174         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
175         /// map from the macro name to the position map,
176         /// which maps the macro definition position to the scope and the MacroData.
177         NamePositionScopeMacroMap macros;
178         bool macro_lock;
179         
180         /// positions of child buffers in the buffer
181         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
182         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
183         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
184         /// position of children buffers in this buffer
185         BufferPositionMap children_positions;
186         /// map from children inclusion positions to their scope and their buffer
187         PositionScopeBufferMap position_to_children;
188
189         /// Container for all sort of Buffer dependant errors.
190         map<string, ErrorList> errorLists;
191
192         /// timestamp and checksum used to test if the file has been externally
193         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
194         time_t timestamp_;
195         unsigned long checksum_;
196
197         ///
198         frontend::WorkAreaManager * wa_;
199
200         ///
201         Undo undo_;
202
203         /// A cache for the bibfiles (including bibfiles of loaded child
204         /// documents), needed for appropriate update of natbib labels.
205         mutable support::FileNameList bibfilesCache_;
206
207         /// 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                 case LFUN_BRANCH_ACTIVATE:
1432                 case LFUN_BRANCH_DEACTIVATE: {
1433                         BranchList & branchList = params().branchlist();
1434                         docstring const branchName = func.argument();
1435                         Branch * branch = branchList.find(branchName);
1436                         if (!branch)
1437                                 LYXERR0("Branch " << branchName << " does not exist.");
1438                         else 
1439                                 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1440                         if (result)
1441                                 *result = true;
1442                 }
1443
1444                 default:
1445                         dispatched = false;
1446         }
1447         return dispatched;
1448 }
1449
1450
1451 void Buffer::changeLanguage(Language const * from, Language const * to)
1452 {
1453         LASSERT(from, /**/);
1454         LASSERT(to, /**/);
1455
1456         for_each(par_iterator_begin(),
1457                  par_iterator_end(),
1458                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1459 }
1460
1461
1462 bool Buffer::isMultiLingual() const
1463 {
1464         ParConstIterator end = par_iterator_end();
1465         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1466                 if (it->isMultiLingual(params()))
1467                         return true;
1468
1469         return false;
1470 }
1471
1472
1473 DocIterator Buffer::getParFromID(int const id) const
1474 {
1475         if (id < 0) {
1476                 // John says this is called with id == -1 from undo
1477                 lyxerr << "getParFromID(), id: " << id << endl;
1478                 return doc_iterator_end(inset());
1479         }
1480
1481         for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1482                 if (it.paragraph().id() == id)
1483                         return it;
1484
1485         return doc_iterator_end(inset());
1486 }
1487
1488
1489 bool Buffer::hasParWithID(int const id) const
1490 {
1491         return !getParFromID(id).atEnd();
1492 }
1493
1494
1495 ParIterator Buffer::par_iterator_begin()
1496 {
1497         return ParIterator(doc_iterator_begin(inset()));
1498 }
1499
1500
1501 ParIterator Buffer::par_iterator_end()
1502 {
1503         return ParIterator(doc_iterator_end(inset()));
1504 }
1505
1506
1507 ParConstIterator Buffer::par_iterator_begin() const
1508 {
1509         return lyx::par_const_iterator_begin(inset());
1510 }
1511
1512
1513 ParConstIterator Buffer::par_iterator_end() const
1514 {
1515         return lyx::par_const_iterator_end(inset());
1516 }
1517
1518
1519 Language const * Buffer::language() const
1520 {
1521         return params().language;
1522 }
1523
1524
1525 docstring const Buffer::B_(string const & l10n) const
1526 {
1527         return params().B_(l10n);
1528 }
1529
1530
1531 bool Buffer::isClean() const
1532 {
1533         return d->lyx_clean;
1534 }
1535
1536
1537 bool Buffer::isBakClean() const
1538 {
1539         return d->bak_clean;
1540 }
1541
1542
1543 bool Buffer::isExternallyModified(CheckMethod method) const
1544 {
1545         LASSERT(d->filename.exists(), /**/);
1546         // if method == timestamp, check timestamp before checksum
1547         return (method == checksum_method 
1548                 || d->timestamp_ != d->filename.lastModified())
1549                 && d->checksum_ != d->filename.checksum();
1550 }
1551
1552
1553 void Buffer::saveCheckSum(FileName const & file) const
1554 {
1555         if (file.exists()) {
1556                 d->timestamp_ = file.lastModified();
1557                 d->checksum_ = file.checksum();
1558         } else {
1559                 // in the case of save to a new file.
1560                 d->timestamp_ = 0;
1561                 d->checksum_ = 0;
1562         }
1563 }
1564
1565
1566 void Buffer::markClean() const
1567 {
1568         if (!d->lyx_clean) {
1569                 d->lyx_clean = true;
1570                 updateTitles();
1571         }
1572         // if the .lyx file has been saved, we don't need an
1573         // autosave
1574         d->bak_clean = true;
1575 }
1576
1577
1578 void Buffer::markBakClean() const
1579 {
1580         d->bak_clean = true;
1581 }
1582
1583
1584 void Buffer::setUnnamed(bool flag)
1585 {
1586         d->unnamed = flag;
1587 }
1588
1589
1590 bool Buffer::isUnnamed() const
1591 {
1592         return d->unnamed;
1593 }
1594
1595
1596 // FIXME: this function should be moved to buffer_pimpl.C
1597 void Buffer::markDirty()
1598 {
1599         if (d->lyx_clean) {
1600                 d->lyx_clean = false;
1601                 updateTitles();
1602         }
1603         d->bak_clean = false;
1604
1605         DepClean::iterator it = d->dep_clean.begin();
1606         DepClean::const_iterator const end = d->dep_clean.end();
1607
1608         for (; it != end; ++it)
1609                 it->second = false;
1610 }
1611
1612
1613 FileName Buffer::fileName() const
1614 {
1615         return d->filename;
1616 }
1617
1618
1619 string Buffer::absFileName() const
1620 {
1621         return d->filename.absFilename();
1622 }
1623
1624
1625 string Buffer::filePath() const
1626 {
1627         return d->filename.onlyPath().absFilename() + "/";
1628 }
1629
1630
1631 bool Buffer::isReadonly() const
1632 {
1633         return d->read_only;
1634 }
1635
1636
1637 void Buffer::setParent(Buffer const * buffer)
1638 {
1639         // Avoids recursive include.
1640         d->parent_buffer = buffer == this ? 0 : buffer;
1641         updateMacros();
1642 }
1643
1644
1645 Buffer const * Buffer::parent()
1646 {
1647         return d->parent_buffer;
1648 }
1649
1650
1651 Buffer const * Buffer::masterBuffer() const
1652 {
1653         if (!d->parent_buffer)
1654                 return this;
1655         
1656         return d->parent_buffer->masterBuffer();
1657 }
1658
1659
1660 template<typename M>
1661 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1662 {
1663         if (m.empty())
1664                 return m.end();
1665
1666         typename M::iterator it = m.lower_bound(x);
1667         if (it == m.begin())
1668                 return m.end();
1669
1670         it--;
1671         return it;      
1672 }
1673
1674
1675 MacroData const * Buffer::getBufferMacro(docstring const & name, 
1676                                          DocIterator const & pos) const
1677 {
1678         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1679
1680         // if paragraphs have no macro context set, pos will be empty
1681         if (pos.empty())
1682                 return 0;
1683
1684         // we haven't found anything yet
1685         DocIterator bestPos = par_iterator_begin();
1686         MacroData const * bestData = 0;
1687         
1688         // find macro definitions for name
1689         Impl::NamePositionScopeMacroMap::iterator nameIt
1690         = d->macros.find(name);
1691         if (nameIt != d->macros.end()) {
1692                 // find last definition in front of pos or at pos itself
1693                 Impl::PositionScopeMacroMap::const_iterator it
1694                 = greatest_below(nameIt->second, pos);
1695                 if (it != nameIt->second.end()) {
1696                         while (true) {
1697                                 // scope ends behind pos?
1698                                 if (pos < it->second.first) {
1699                                         // Looks good, remember this. If there
1700                                         // is no external macro behind this,
1701                                         // we found the right one already.
1702                                         bestPos = it->first;
1703                                         bestData = &it->second.second;
1704                                         break;
1705                                 }
1706                                 
1707                                 // try previous macro if there is one
1708                                 if (it == nameIt->second.begin())
1709                                         break;
1710                                 it--;
1711                         }
1712                 }
1713         }
1714
1715         // find macros in included files
1716         Impl::PositionScopeBufferMap::const_iterator it
1717         = greatest_below(d->position_to_children, pos);
1718         if (it == d->position_to_children.end())
1719                 // no children before
1720                 return bestData;
1721
1722         while (true) {
1723                 // do we know something better (i.e. later) already?
1724                 if (it->first < bestPos )
1725                         break;
1726
1727                 // scope ends behind pos?
1728                 if (pos < it->second.first) {
1729                         // look for macro in external file
1730                         d->macro_lock = true;
1731                         MacroData const * data
1732                         = it->second.second->getMacro(name, false);
1733                         d->macro_lock = false;
1734                         if (data) {
1735                                 bestPos = it->first;
1736                                 bestData = data;
1737                                 break;
1738                         }
1739                 }
1740
1741                 // try previous file if there is one
1742                 if (it == d->position_to_children.begin())
1743                         break;
1744                 --it;
1745         }
1746                 
1747         // return the best macro we have found
1748         return bestData;
1749 }
1750
1751
1752 MacroData const * Buffer::getMacro(docstring const & name,
1753         DocIterator const & pos, bool global) const
1754 {
1755         if (d->macro_lock)
1756                 return 0;       
1757
1758         // query buffer macros
1759         MacroData const * data = getBufferMacro(name, pos);
1760         if (data != 0)
1761                 return data;
1762
1763         // If there is a master buffer, query that
1764         if (d->parent_buffer) {
1765                 d->macro_lock = true;
1766                 MacroData const * macro = d->parent_buffer->getMacro(
1767                         name, *this, false);
1768                 d->macro_lock = false;
1769                 if (macro)
1770                         return macro;
1771         }
1772
1773         if (global) {
1774                 data = MacroTable::globalMacros().get(name);
1775                 if (data != 0)
1776                         return data;
1777         }
1778
1779         return 0;
1780 }
1781
1782
1783 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1784 {
1785         // set scope end behind the last paragraph
1786         DocIterator scope = par_iterator_begin();
1787         scope.pit() = scope.lastpit() + 1;
1788
1789         return getMacro(name, scope, global);
1790 }
1791
1792
1793 MacroData const * Buffer::getMacro(docstring const & name,
1794         Buffer const & child, bool global) const
1795 {
1796         // look where the child buffer is included first
1797         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1798         if (it == d->children_positions.end())
1799                 return 0;
1800
1801         // check for macros at the inclusion position
1802         return getMacro(name, it->second, global);
1803 }
1804
1805
1806 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1807 {
1808         pit_type lastpit = it.lastpit();
1809
1810         // look for macros in each paragraph
1811         while (it.pit() <= lastpit) {
1812                 Paragraph & par = it.paragraph();
1813
1814                 // iterate over the insets of the current paragraph
1815                 InsetList const & insets = par.insetList();
1816                 InsetList::const_iterator iit = insets.begin();
1817                 InsetList::const_iterator end = insets.end();
1818                 for (; iit != end; ++iit) {
1819                         it.pos() = iit->pos;
1820                         
1821                         // is it a nested text inset?
1822                         if (iit->inset->asInsetText()) {
1823                                 // Inset needs its own scope?
1824                                 InsetText const * itext 
1825                                 = iit->inset->asInsetText();
1826                                 bool newScope = itext->isMacroScope();
1827
1828                                 // scope which ends just behind the inset       
1829                                 DocIterator insetScope = it;
1830                                 ++insetScope.pos();
1831
1832                                 // collect macros in inset
1833                                 it.push_back(CursorSlice(*iit->inset));
1834                                 updateMacros(it, newScope ? insetScope : scope);
1835                                 it.pop_back();
1836                                 continue;
1837                         }
1838                                               
1839                         // is it an external file?
1840                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
1841                                 // get buffer of external file
1842                                 InsetCommand const & inset 
1843                                         = static_cast<InsetCommand const &>(*iit->inset);
1844                                 InsetCommandParams const & ip = inset.params();
1845                                 d->macro_lock = true;
1846                                 Buffer * child = loadIfNeeded(*this, ip);
1847                                 d->macro_lock = false;
1848                                 if (!child)
1849                                         continue;                               
1850
1851                                 // register its position, but only when it is
1852                                 // included first in the buffer
1853                                 if (d->children_positions.find(child)
1854                                         == d->children_positions.end())
1855                                         d->children_positions[child] = it;
1856                                                                                                 
1857                                 // register child with its scope
1858                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1859                                 continue;
1860                         }
1861
1862                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
1863                                 continue;
1864                         
1865                         // get macro data
1866                         MathMacroTemplate & macroTemplate
1867                         = static_cast<MathMacroTemplate &>(*iit->inset);
1868                         MacroContext mc(*this, it);
1869                         macroTemplate.updateToContext(mc);
1870
1871                         // valid?
1872                         bool valid = macroTemplate.validMacro();
1873                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
1874                         // then the BufferView's cursor will be invalid in
1875                         // some cases which leads to crashes.
1876                         if (!valid)
1877                                 continue;
1878
1879                         // register macro
1880                         d->macros[macroTemplate.name()][it] =
1881                                 Impl::ScopeMacro(scope, MacroData(*this, it));
1882                 }
1883
1884                 // next paragraph
1885                 it.pit()++;
1886                 it.pos() = 0;
1887         }
1888 }
1889
1890
1891 void Buffer::updateMacros() const
1892 {
1893         if (d->macro_lock)
1894                 return;
1895
1896         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1897
1898         // start with empty table
1899         d->macros.clear();
1900         d->children_positions.clear();
1901         d->position_to_children.clear();
1902
1903         // Iterate over buffer, starting with first paragraph
1904         // The scope must be bigger than any lookup DocIterator
1905         // later. For the global lookup, lastpit+1 is used, hence
1906         // we use lastpit+2 here.
1907         DocIterator it = par_iterator_begin();
1908         DocIterator outerScope = it;
1909         outerScope.pit() = outerScope.lastpit() + 2;
1910         updateMacros(it, outerScope);
1911 }
1912
1913
1914 void Buffer::updateMacroInstances() const
1915 {
1916         LYXERR(Debug::MACROS, "updateMacroInstances for "
1917                 << d->filename.onlyFileName());
1918         DocIterator it = doc_iterator_begin(inset());
1919         DocIterator end = doc_iterator_end(inset());
1920         for (; it != end; it.forwardPos()) {
1921                 // look for MathData cells in InsetMathNest insets
1922                 Inset * inset = it.nextInset();
1923                 if (!inset)
1924                         continue;
1925
1926                 InsetMath * minset = inset->asInsetMath();
1927                 if (!minset)
1928                         continue;
1929
1930                 // update macro in all cells of the InsetMathNest
1931                 DocIterator::idx_type n = minset->nargs();
1932                 MacroContext mc = MacroContext(*this, it);
1933                 for (DocIterator::idx_type i = 0; i < n; ++i) {
1934                         MathData & data = minset->cell(i);
1935                         data.updateMacros(0, mc);
1936                 }
1937         }
1938 }
1939
1940
1941 void Buffer::listMacroNames(MacroNameSet & macros) const
1942 {
1943         if (d->macro_lock)
1944                 return;
1945
1946         d->macro_lock = true;
1947         
1948         // loop over macro names
1949         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1950         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1951         for (; nameIt != nameEnd; ++nameIt)
1952                 macros.insert(nameIt->first);
1953
1954         // loop over children
1955         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1956         Impl::BufferPositionMap::iterator end = d->children_positions.end();
1957         for (; it != end; ++it)
1958                 it->first->listMacroNames(macros);
1959
1960         // call parent
1961         if (d->parent_buffer)
1962                 d->parent_buffer->listMacroNames(macros);
1963
1964         d->macro_lock = false;  
1965 }
1966
1967
1968 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1969 {
1970         if (!d->parent_buffer)
1971                 return;
1972         
1973         MacroNameSet names;
1974         d->parent_buffer->listMacroNames(names);
1975         
1976         // resolve macros
1977         MacroNameSet::iterator it = names.begin();
1978         MacroNameSet::iterator end = names.end();
1979         for (; it != end; ++it) {
1980                 // defined?
1981                 MacroData const * data = 
1982                 d->parent_buffer->getMacro(*it, *this, false);
1983                 if (data) {
1984                         macros.insert(data);
1985                         
1986                         // we cannot access the original MathMacroTemplate anymore
1987                         // here to calls validate method. So we do its work here manually.
1988                         // FIXME: somehow make the template accessible here.
1989                         if (data->optionals() > 0)
1990                                 features.require("xargs");
1991                 }
1992         }
1993 }
1994
1995
1996 Buffer::References & Buffer::references(docstring const & label)
1997 {
1998         if (d->parent_buffer)
1999                 return const_cast<Buffer *>(masterBuffer())->references(label);
2000
2001         RefCache::iterator it = d->ref_cache_.find(label);
2002         if (it != d->ref_cache_.end())
2003                 return it->second.second;
2004
2005         static InsetLabel const * dummy_il = 0;
2006         static References const dummy_refs;
2007         it = d->ref_cache_.insert(
2008                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2009         return it->second.second;
2010 }
2011
2012
2013 Buffer::References const & Buffer::references(docstring const & label) const
2014 {
2015         return const_cast<Buffer *>(this)->references(label);
2016 }
2017
2018
2019 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2020 {
2021         masterBuffer()->d->ref_cache_[label].first = il;
2022 }
2023
2024
2025 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2026 {
2027         return masterBuffer()->d->ref_cache_[label].first;
2028 }
2029
2030
2031 void Buffer::clearReferenceCache() const
2032 {
2033         if (!d->parent_buffer)
2034                 d->ref_cache_.clear();
2035 }
2036
2037
2038 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2039         InsetCode code)
2040 {
2041         //FIXME: This does not work for child documents yet.
2042         LASSERT(code == CITE_CODE, /**/);
2043         // Check if the label 'from' appears more than once
2044         vector<docstring> labels;
2045         string paramName;
2046         BiblioInfo const & keys = masterBibInfo();
2047         BiblioInfo::const_iterator bit  = keys.begin();
2048         BiblioInfo::const_iterator bend = keys.end();
2049
2050         for (; bit != bend; ++bit)
2051                 // FIXME UNICODE
2052                 labels.push_back(bit->first);
2053         paramName = "key";
2054
2055         if (count(labels.begin(), labels.end(), from) > 1)
2056                 return;
2057
2058         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2059                 if (it->lyxCode() == code) {
2060                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2061                         docstring const oldValue = inset.getParam(paramName);
2062                         if (oldValue == from)
2063                                 inset.setParam(paramName, to);
2064                 }
2065         }
2066 }
2067
2068
2069 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2070         pit_type par_end, bool full_source)
2071 {
2072         OutputParams runparams(&params().encoding());
2073         runparams.nice = true;
2074         runparams.flavor = OutputParams::LATEX;
2075         runparams.linelen = lyxrc.plaintext_linelen;
2076         // No side effect of file copying and image conversion
2077         runparams.dryrun = true;
2078
2079         d->texrow.reset();
2080         if (full_source) {
2081                 os << "% " << _("Preview source code") << "\n\n";
2082                 d->texrow.newline();
2083                 d->texrow.newline();
2084                 if (isLatex())
2085                         writeLaTeXSource(os, filePath(), runparams, true, true);
2086                 else
2087                         writeDocBookSource(os, absFileName(), runparams, false);
2088         } else {
2089                 runparams.par_begin = par_begin;
2090                 runparams.par_end = par_end;
2091                 if (par_begin + 1 == par_end) {
2092                         os << "% "
2093                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2094                            << "\n\n";
2095                 } else {
2096                         os << "% "
2097                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2098                                         convert<docstring>(par_begin),
2099                                         convert<docstring>(par_end - 1))
2100                            << "\n\n";
2101                 }
2102                 d->texrow.newline();
2103                 d->texrow.newline();
2104                 // output paragraphs
2105                 if (isLatex())
2106                         latexParagraphs(*this, text(), os, d->texrow, runparams);
2107                 else
2108                         // DocBook
2109                         docbookParagraphs(paragraphs(), *this, os, runparams);
2110         }
2111 }
2112
2113
2114 ErrorList & Buffer::errorList(string const & type) const
2115 {
2116         static ErrorList emptyErrorList;
2117         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2118         if (I == d->errorLists.end())
2119                 return emptyErrorList;
2120
2121         return I->second;
2122 }
2123
2124
2125 void Buffer::structureChanged() const
2126 {
2127         if (gui_)
2128                 gui_->structureChanged();
2129 }
2130
2131
2132 void Buffer::errors(string const & err) const
2133 {
2134         if (gui_)
2135                 gui_->errors(err);
2136 }
2137
2138
2139 void Buffer::message(docstring const & msg) const
2140 {
2141         if (gui_)
2142                 gui_->message(msg);
2143 }
2144
2145
2146 void Buffer::setBusy(bool on) const
2147 {
2148         if (gui_)
2149                 gui_->setBusy(on);
2150 }
2151
2152
2153 void Buffer::setReadOnly(bool on) const
2154 {
2155         if (d->wa_)
2156                 d->wa_->setReadOnly(on);
2157 }
2158
2159
2160 void Buffer::updateTitles() const
2161 {
2162         if (d->wa_)
2163                 d->wa_->updateTitles();
2164 }
2165
2166
2167 void Buffer::resetAutosaveTimers() const
2168 {
2169         if (gui_)
2170                 gui_->resetAutosaveTimers();
2171 }
2172
2173
2174 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2175 {
2176         gui_ = gui;
2177 }
2178
2179
2180
2181 namespace {
2182
2183 class AutoSaveBuffer : public ForkedProcess {
2184 public:
2185         ///
2186         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2187                 : buffer_(buffer), fname_(fname) {}
2188         ///
2189         virtual boost::shared_ptr<ForkedProcess> clone() const
2190         {
2191                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2192         }
2193         ///
2194         int start()
2195         {
2196                 command_ = to_utf8(bformat(_("Auto-saving %1$s"), 
2197                                                  from_utf8(fname_.absFilename())));
2198                 return run(DontWait);
2199         }
2200 private:
2201         ///
2202         virtual int generateChild();
2203         ///
2204         Buffer const & buffer_;
2205         FileName fname_;
2206 };
2207
2208
2209 int AutoSaveBuffer::generateChild()
2210 {
2211         // tmp_ret will be located (usually) in /tmp
2212         // will that be a problem?
2213         // Note that this calls ForkedCalls::fork(), so it's
2214         // ok cross-platform.
2215         pid_t const pid = fork();
2216         // If you want to debug the autosave
2217         // you should set pid to -1, and comment out the fork.
2218         if (pid != 0 && pid != -1)
2219                 return pid;
2220
2221         // pid = -1 signifies that lyx was unable
2222         // to fork. But we will do the save
2223         // anyway.
2224         bool failed = false;
2225         FileName const tmp_ret = FileName::tempName("lyxauto");
2226         if (!tmp_ret.empty()) {
2227                 buffer_.writeFile(tmp_ret);
2228                 // assume successful write of tmp_ret
2229                 if (!tmp_ret.moveTo(fname_))
2230                         failed = true;
2231         } else
2232                 failed = true;
2233
2234         if (failed) {
2235                 // failed to write/rename tmp_ret so try writing direct
2236                 if (!buffer_.writeFile(fname_)) {
2237                         // It is dangerous to do this in the child,
2238                         // but safe in the parent, so...
2239                         if (pid == -1) // emit message signal.
2240                                 buffer_.message(_("Autosave failed!"));
2241                 }
2242         }
2243
2244         if (pid == 0) // we are the child so...
2245                 _exit(0);
2246
2247         return pid;
2248 }
2249
2250 } // namespace anon
2251
2252
2253 // Perfect target for a thread...
2254 void Buffer::autoSave() const
2255 {
2256         if (isBakClean() || isReadonly()) {
2257                 // We don't save now, but we'll try again later
2258                 resetAutosaveTimers();
2259                 return;
2260         }
2261
2262         // emit message signal.
2263         message(_("Autosaving current document..."));
2264
2265         // create autosave filename
2266         string fname = filePath();
2267         fname += '#';
2268         fname += d->filename.onlyFileName();
2269         fname += '#';
2270
2271         AutoSaveBuffer autosave(*this, FileName(fname));
2272         autosave.start();
2273
2274         markBakClean();
2275         resetAutosaveTimers();
2276 }
2277
2278
2279 string Buffer::bufferFormat() const
2280 {
2281         if (isDocBook())
2282                 return "docbook";
2283         if (isLiterate())
2284                 return "literate";
2285         return "latex";
2286 }
2287
2288
2289 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2290         string & result_file) const
2291 {
2292         string backend_format;
2293         OutputParams runparams(&params().encoding());
2294         runparams.flavor = OutputParams::LATEX;
2295         runparams.linelen = lyxrc.plaintext_linelen;
2296         vector<string> backs = backends();
2297         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2298                 // Get shortest path to format
2299                 Graph::EdgePath path;
2300                 for (vector<string>::const_iterator it = backs.begin();
2301                      it != backs.end(); ++it) {
2302                         Graph::EdgePath p = theConverters().getPath(*it, format);
2303                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2304                                 backend_format = *it;
2305                                 path = p;
2306                         }
2307                 }
2308                 if (!path.empty())
2309                         runparams.flavor = theConverters().getFlavor(path);
2310                 else {
2311                         Alert::error(_("Couldn't export file"),
2312                                 bformat(_("No information for exporting the format %1$s."),
2313                                    formats.prettyName(format)));
2314                         return false;
2315                 }
2316         } else {
2317                 backend_format = format;
2318                 // FIXME: Don't hardcode format names here, but use a flag
2319                 if (backend_format == "pdflatex")
2320                         runparams.flavor = OutputParams::PDFLATEX;
2321         }
2322
2323         string filename = latexName(false);
2324         filename = addName(temppath(), filename);
2325         filename = changeExtension(filename,
2326                                    formats.extension(backend_format));
2327
2328         // fix macros
2329         updateMacroInstances();
2330
2331         // Plain text backend
2332         if (backend_format == "text")
2333                 writePlaintextFile(*this, FileName(filename), runparams);
2334         // no backend
2335         else if (backend_format == "lyx")
2336                 writeFile(FileName(filename));
2337         // Docbook backend
2338         else if (isDocBook()) {
2339                 runparams.nice = !put_in_tempdir;
2340                 makeDocBookFile(FileName(filename), runparams);
2341         }
2342         // LaTeX backend
2343         else if (backend_format == format) {
2344                 runparams.nice = true;
2345                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2346                         return false;
2347         } else if (!lyxrc.tex_allows_spaces
2348                    && contains(filePath(), ' ')) {
2349                 Alert::error(_("File name error"),
2350                            _("The directory path to the document cannot contain spaces."));
2351                 return false;
2352         } else {
2353                 runparams.nice = false;
2354                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2355                         return false;
2356         }
2357
2358         string const error_type = (format == "program")
2359                 ? "Build" : bufferFormat();
2360         string const ext = formats.extension(format);
2361         FileName const tmp_result_file(changeExtension(filename, ext));
2362         bool const success = theConverters().convert(this, FileName(filename),
2363                 tmp_result_file, FileName(absFileName()), backend_format, format,
2364                 errorList(error_type));
2365         // Emit the signal to show the error list.
2366         if (format != backend_format)
2367                 errors(error_type);
2368         if (!success)
2369                 return false;
2370
2371         if (put_in_tempdir) {
2372                 result_file = tmp_result_file.absFilename();
2373                 return true;
2374         }
2375
2376         result_file = changeExtension(absFileName(), ext);
2377         // We need to copy referenced files (e. g. included graphics
2378         // if format == "dvi") to the result dir.
2379         vector<ExportedFile> const files =
2380                 runparams.exportdata->externalFiles(format);
2381         string const dest = onlyPath(result_file);
2382         CopyStatus status = SUCCESS;
2383         for (vector<ExportedFile>::const_iterator it = files.begin();
2384                 it != files.end() && status != CANCEL; ++it) {
2385                 string const fmt = formats.getFormatFromFile(it->sourceName);
2386                 status = copyFile(fmt, it->sourceName,
2387                         makeAbsPath(it->exportName, dest),
2388                         it->exportName, status == FORCE);
2389         }
2390         if (status == CANCEL) {
2391                 message(_("Document export cancelled."));
2392         } else if (tmp_result_file.exists()) {
2393                 // Finally copy the main file
2394                 status = copyFile(format, tmp_result_file,
2395                         FileName(result_file), result_file,
2396                         status == FORCE);
2397                 message(bformat(_("Document exported as %1$s "
2398                         "to file `%2$s'"),
2399                         formats.prettyName(format),
2400                         makeDisplayPath(result_file)));
2401         } else {
2402                 // This must be a dummy converter like fax (bug 1888)
2403                 message(bformat(_("Document exported as %1$s"),
2404                         formats.prettyName(format)));
2405         }
2406
2407         return true;
2408 }
2409
2410
2411 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2412 {
2413         string result_file;
2414         return doExport(format, put_in_tempdir, result_file);
2415 }
2416
2417
2418 bool Buffer::preview(string const & format) const
2419 {
2420         string result_file;
2421         if (!doExport(format, true, result_file))
2422                 return false;
2423         return formats.view(*this, FileName(result_file), format);
2424 }
2425
2426
2427 bool Buffer::isExportable(string const & format) const
2428 {
2429         vector<string> backs = backends();
2430         for (vector<string>::const_iterator it = backs.begin();
2431              it != backs.end(); ++it)
2432                 if (theConverters().isReachable(*it, format))
2433                         return true;
2434         return false;
2435 }
2436
2437
2438 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2439 {
2440         vector<string> backs = backends();
2441         vector<Format const *> result =
2442                 theConverters().getReachable(backs[0], only_viewable, true);
2443         for (vector<string>::const_iterator it = backs.begin() + 1;
2444              it != backs.end(); ++it) {
2445                 vector<Format const *>  r =
2446                         theConverters().getReachable(*it, only_viewable, false);
2447                 result.insert(result.end(), r.begin(), r.end());
2448         }
2449         return result;
2450 }
2451
2452
2453 vector<string> Buffer::backends() const
2454 {
2455         vector<string> v;
2456         if (params().baseClass()->isTeXClassAvailable()) {
2457                 v.push_back(bufferFormat());
2458                 // FIXME: Don't hardcode format names here, but use a flag
2459                 if (v.back() == "latex")
2460                         v.push_back("pdflatex");
2461         }
2462         v.push_back("text");
2463         v.push_back("lyx");
2464         return v;
2465 }
2466
2467
2468 bool Buffer::readFileHelper(FileName const & s)
2469 {
2470         // File information about normal file
2471         if (!s.exists()) {
2472                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2473                 docstring text = bformat(_("The specified document\n%1$s"
2474                                                      "\ncould not be read."), file);
2475                 Alert::error(_("Could not read document"), text);
2476                 return false;
2477         }
2478
2479         // Check if emergency save file exists and is newer.
2480         FileName const e(s.absFilename() + ".emergency");
2481
2482         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2483                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2484                 docstring const text =
2485                         bformat(_("An emergency save of the document "
2486                                   "%1$s exists.\n\n"
2487                                                "Recover emergency save?"), file);
2488                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2489                                       _("&Recover"),  _("&Load Original"),
2490                                       _("&Cancel")))
2491                 {
2492                 case 0:
2493                         // the file is not saved if we load the emergency file.
2494                         markDirty();
2495                         return readFile(e);
2496                 case 1:
2497                         break;
2498                 default:
2499                         return false;
2500                 }
2501         }
2502
2503         // Now check if autosave file is newer.
2504         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2505
2506         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2507                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2508                 docstring const text =
2509                         bformat(_("The backup of the document "
2510                                   "%1$s is newer.\n\nLoad the "
2511                                                "backup instead?"), file);
2512                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2513                                       _("&Load backup"), _("Load &original"),
2514                                       _("&Cancel") ))
2515                 {
2516                 case 0:
2517                         // the file is not saved if we load the autosave file.
2518                         markDirty();
2519                         return readFile(a);
2520                 case 1:
2521                         // Here we delete the autosave
2522                         a.removeFile();
2523                         break;
2524                 default:
2525                         return false;
2526                 }
2527         }
2528         return readFile(s);
2529 }
2530
2531
2532 bool Buffer::loadLyXFile(FileName const & s)
2533 {
2534         if (s.isReadableFile()) {
2535                 if (readFileHelper(s)) {
2536                         lyxvc().file_found_hook(s);
2537                         if (!s.isWritable())
2538                                 setReadonly(true);
2539                         return true;
2540                 }
2541         } else {
2542                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2543                 // Here we probably should run
2544                 if (LyXVC::file_not_found_hook(s)) {
2545                         docstring const text =
2546                                 bformat(_("Do you want to retrieve the document"
2547                                                        " %1$s from version control?"), file);
2548                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2549                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2550
2551                         if (ret == 0) {
2552                                 // How can we know _how_ to do the checkout?
2553                                 // With the current VC support it has to be,
2554                                 // a RCS file since CVS do not have special ,v files.
2555                                 RCS::retrieve(s);
2556                                 return loadLyXFile(s);
2557                         }
2558                 }
2559         }
2560         return false;
2561 }
2562
2563
2564 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2565 {
2566         TeXErrors::Errors::const_iterator cit = terr.begin();
2567         TeXErrors::Errors::const_iterator end = terr.end();
2568
2569         for (; cit != end; ++cit) {
2570                 int id_start = -1;
2571                 int pos_start = -1;
2572                 int errorRow = cit->error_in_line;
2573                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2574                                                        pos_start);
2575                 int id_end = -1;
2576                 int pos_end = -1;
2577                 do {
2578                         ++errorRow;
2579                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2580                 } while (found && id_start == id_end && pos_start == pos_end);
2581
2582                 errorList.push_back(ErrorItem(cit->error_desc,
2583                         cit->error_text, id_start, pos_start, pos_end));
2584         }
2585 }
2586
2587
2588 } // namespace lyx