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