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