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