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