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