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