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