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