]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
start using FileName::exists()
[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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Buffer.h"
14
15 #include "Author.h"
16 #include "BiblioInfo.h"
17 #include "BranchList.h"
18 #include "buffer_funcs.h"
19 #include "BufferList.h"
20 #include "BufferParams.h"
21 #include "Counters.h"
22 #include "Bullet.h"
23 #include "Chktex.h"
24 #include "debug.h"
25 #include "DocIterator.h"
26 #include "Encoding.h"
27 #include "ErrorList.h"
28 #include "Exporter.h"
29 #include "Format.h"
30 #include "FuncRequest.h"
31 #include "gettext.h"
32 #include "InsetIterator.h"
33 #include "InsetList.h"
34 #include "Language.h"
35 #include "LaTeX.h"
36 #include "LaTeXFeatures.h"
37 #include "Layout.h"
38 #include "LyXAction.h"
39 #include "Lexer.h"
40 #include "Text.h"
41 #include "LyX.h"
42 #include "LyXRC.h"
43 #include "LyXVC.h"
44 #include "Messages.h"
45 #include "output.h"
46 #include "output_docbook.h"
47 #include "output_latex.h"
48 #include "Paragraph.h"
49 #include "paragraph_funcs.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "Session.h"
53 #include "sgml.h"
54 #include "TexRow.h"
55 #include "TextClassList.h"
56 #include "TexStream.h"
57 #include "TocBackend.h"
58 #include "Undo.h"
59 #include "version.h"
60 #include "EmbeddedFiles.h"
61 #include "PDFOptions.h"
62
63 #include "insets/InsetBibitem.h"
64 #include "insets/InsetBibtex.h"
65 #include "insets/InsetInclude.h"
66 #include "insets/InsetText.h"
67
68 #include "mathed/MathMacroTemplate.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathSupport.h"
71
72 #include "frontends/alert.h"
73 #include "frontends/Delegates.h"
74 #include "frontends/WorkAreaManager.h"
75 #include "frontends/FileDialog.h"
76
77 #include "graphics/Previews.h"
78
79 #include "support/types.h"
80 #include "support/lyxalgo.h"
81 #include "support/FileFilterList.h"
82 #include "support/filetools.h"
83 #include "support/Forkedcall.h"
84 #include "support/fs_extras.h"
85 #include "support/gzstream.h"
86 #include "support/lyxlib.h"
87 #include "support/os.h"
88 #include "support/Path.h"
89 #include "support/textutils.h"
90 #include "support/convert.h"
91
92 #if !defined (HAVE_FORK)
93 # define fork() -1
94 #endif
95
96 #include <boost/bind.hpp>
97 #include <boost/filesystem/exception.hpp>
98 #include <boost/filesystem/operations.hpp>
99 #include <boost/shared_ptr.hpp>
100
101 #include <algorithm>
102 #include <iomanip>
103 #include <stack>
104 #include <sstream>
105 #include <fstream>
106
107 using std::endl;
108 using std::for_each;
109 using std::make_pair;
110
111 using std::ios;
112 using std::map;
113 using std::ostream;
114 using std::ostringstream;
115 using std::ofstream;
116 using std::ifstream;
117 using std::pair;
118 using std::stack;
119 using std::vector;
120 using std::string;
121 using std::time_t;
122
123 namespace lyx {
124
125 using support::addName;
126 using support::bformat;
127 using support::changeExtension;
128 using support::cmd_ret;
129 using support::createBufferTmpDir;
130 using support::destroyDir;
131 using support::FileName;
132 using support::getFormatFromContents;
133 using support::libFileSearch;
134 using support::latex_path;
135 using support::ltrim;
136 using support::makeAbsPath;
137 using support::makeDisplayPath;
138 using support::makeLatexName;
139 using support::onlyFilename;
140 using support::onlyPath;
141 using support::quoteName;
142 using support::removeAutosaveFile;
143 using support::rename;
144 using support::runCommand;
145 using support::split;
146 using support::subst;
147 using support::tempName;
148 using support::trim;
149 using support::sum;
150 using support::suffixIs;
151
152 namespace Alert = frontend::Alert;
153 namespace os = support::os;
154 namespace fs = boost::filesystem;
155
156 namespace {
157
158 int const LYX_FORMAT = 295; //Uwe: htmlurl, href
159
160 } // namespace anon
161
162
163 typedef std::map<string, bool> DepClean;
164
165 class Buffer::Impl
166 {
167 public:
168         Impl(Buffer & parent, FileName const & file, bool readonly);
169         
170         BufferParams params;
171         LyXVC lyxvc;
172         string temppath;
173         TexRow texrow;
174
175         /// need to regenerate .tex?
176         DepClean dep_clean;
177
178         /// is save needed?
179         mutable bool lyx_clean;
180
181         /// is autosave needed?
182         mutable bool bak_clean;
183
184         /// is this a unnamed file (New...)?
185         bool unnamed;
186
187         /// buffer is r/o
188         bool read_only;
189
190         /// name of the file the buffer is associated with.
191         FileName filename;
192
193         /** Set to true only when the file is fully loaded.
194          *  Used to prevent the premature generation of previews
195          *  and by the citation inset.
196          */
197         bool file_fully_loaded;
198
199         /// our Text that should be wrapped in an InsetText
200         InsetText inset;
201
202         ///
203         MacroTable macros;
204
205         ///
206         TocBackend toc_backend;
207
208         /// Container for all sort of Buffer dependant errors.
209         map<string, ErrorList> errorLists;
210
211         /// all embedded files of this buffer
212         EmbeddedFiles embedded_files;
213
214         /// timestamp and checksum used to test if the file has been externally
215         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
216         time_t timestamp_;
217         unsigned long checksum_;
218
219         ///
220         frontend::WorkAreaManager * wa_;
221
222         ///
223         Undo undo_;
224 };
225
226
227 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
228         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
229           filename(file), file_fully_loaded(false), inset(params),
230           toc_backend(&parent), embedded_files(&parent), timestamp_(0),
231           checksum_(0), wa_(0), undo_(parent)
232 {
233         inset.setAutoBreakRows(true);
234         lyxvc.buffer(&parent);
235         temppath = createBufferTmpDir();
236         params.filepath = onlyPath(file.absFilename());
237         // FIXME: And now do something if temppath == string(), because we
238         // assume from now on that temppath points to a valid temp dir.
239         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
240
241         if (use_gui)
242                 wa_ = new frontend::WorkAreaManager;
243 }
244
245
246 Buffer::Buffer(string const & file, bool readonly)
247         : pimpl_(new Impl(*this, FileName(file), readonly)), gui_(0)
248 {
249         LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
250 }
251
252
253 Buffer::~Buffer()
254 {
255         LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
256         // here the buffer should take care that it is
257         // saved properly, before it goes into the void.
258
259         Buffer * master = getMasterBuffer();
260         if (master != this && use_gui)
261                 // We are closing buf which was a child document so we
262                 // must update the labels and section numbering of its master
263                 // Buffer.
264                 updateLabels(*master);
265
266         if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
267                 Alert::warning(_("Could not remove temporary directory"),
268                         bformat(_("Could not remove the temporary directory %1$s"),
269                         from_utf8(temppath())));
270         }
271
272         // Remove any previewed LaTeX snippets associated with this buffer.
273         graphics::Previews::get().removeLoader(*this);
274
275         if (pimpl_->wa_) {
276                 pimpl_->wa_->closeAll();
277                 delete pimpl_->wa_;
278         }
279         delete pimpl_;
280 }
281
282
283 void Buffer::changed() const
284 {
285         if (pimpl_->wa_)
286                 pimpl_->wa_->redrawAll();
287 }
288
289
290 frontend::WorkAreaManager & Buffer::workAreaManager() const
291 {
292         BOOST_ASSERT(pimpl_->wa_);
293         return *pimpl_->wa_;
294 }
295
296
297 Text & Buffer::text() const
298 {
299         return const_cast<Text &>(pimpl_->inset.text_);
300 }
301
302
303 Inset & Buffer::inset() const
304 {
305         return const_cast<InsetText &>(pimpl_->inset);
306 }
307
308
309 BufferParams & Buffer::params()
310 {
311         return pimpl_->params;
312 }
313
314
315 BufferParams const & Buffer::params() const
316 {
317         return pimpl_->params;
318 }
319
320
321 ParagraphList & Buffer::paragraphs()
322 {
323         return text().paragraphs();
324 }
325
326
327 ParagraphList const & Buffer::paragraphs() const
328 {
329         return text().paragraphs();
330 }
331
332
333 LyXVC & Buffer::lyxvc()
334 {
335         return pimpl_->lyxvc;
336 }
337
338
339 LyXVC const & Buffer::lyxvc() const
340 {
341         return pimpl_->lyxvc;
342 }
343
344
345 string const & Buffer::temppath() const
346 {
347         return pimpl_->temppath;
348 }
349
350
351 TexRow & Buffer::texrow()
352 {
353         return pimpl_->texrow;
354 }
355
356
357 TexRow const & Buffer::texrow() const
358 {
359         return pimpl_->texrow;
360 }
361
362
363 TocBackend & Buffer::tocBackend()
364 {
365         return pimpl_->toc_backend;
366 }
367
368
369 TocBackend const & Buffer::tocBackend() const
370 {
371         return pimpl_->toc_backend;
372 }
373
374
375 EmbeddedFiles & Buffer::embeddedFiles()
376 {
377         return pimpl_->embedded_files;
378 }
379
380
381 EmbeddedFiles const & Buffer::embeddedFiles() const
382 {
383         return pimpl_->embedded_files;
384 }
385
386 Undo & Buffer::undo()
387 {
388         return pimpl_->undo_;
389 }
390
391
392
393 string const Buffer::getLatexName(bool const no_path) const
394 {
395         string const name = changeExtension(makeLatexName(fileName()), ".tex");
396         return no_path ? onlyFilename(name) : name;
397 }
398
399
400 pair<Buffer::LogType, string> const Buffer::getLogName() const
401 {
402         string const filename = getLatexName(false);
403
404         if (filename.empty())
405                 return make_pair(Buffer::latexlog, string());
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 << endl;
422                 return make_pair(Buffer::buildlog, bname.absFilename());
423         }
424         LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
425         return make_pair(Buffer::latexlog, fname.absFilename());
426 }
427
428
429 void Buffer::setReadonly(bool const flag)
430 {
431         if (pimpl_->read_only != flag) {
432                 pimpl_->read_only = flag;
433                 readonly(flag);
434         }
435 }
436
437
438 void Buffer::setFileName(string const & newfile)
439 {
440         pimpl_->filename = makeAbsPath(newfile);
441         params().filepath = onlyPath(pimpl_->filename.absFilename());
442         setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
443         updateTitles();
444 }
445
446
447 // We'll remove this later. (Lgb)
448 namespace {
449
450 void unknownClass(string const & unknown)
451 {
452         Alert::warning(_("Unknown document class"),
453                        bformat(_("Using the default document class, because the "
454                                               "class %1$s is unknown."), from_utf8(unknown)));
455 }
456
457 } // anon
458
459
460 int Buffer::readHeader(Lexer & lex)
461 {
462         int unknown_tokens = 0;
463         int line = -1;
464         int begin_header_line = -1;
465
466         // Initialize parameters that may be/go lacking in header:
467         params().branchlist().clear();
468         params().preamble.erase();
469         params().options.erase();
470         params().float_placement.erase();
471         params().paperwidth.erase();
472         params().paperheight.erase();
473         params().leftmargin.erase();
474         params().rightmargin.erase();
475         params().topmargin.erase();
476         params().bottommargin.erase();
477         params().headheight.erase();
478         params().headsep.erase();
479         params().footskip.erase();
480         params().listings_params.clear();
481         params().clearLayoutModules();
482         params().pdfoptions().clear();
483         
484         for (int i = 0; i < 4; ++i) {
485                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
486                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
487         }
488
489         ErrorList & errorList = pimpl_->errorLists["Parse"];
490
491         while (lex.isOK()) {
492                 lex.next();
493                 string const token = lex.getString();
494
495                 if (token.empty())
496                         continue;
497
498                 if (token == "\\end_header")
499                         break;
500
501                 ++line;
502                 if (token == "\\begin_header") {
503                         begin_header_line = line;
504                         continue;
505                 }
506
507                 LYXERR(Debug::PARSER) << "Handling document header token: `"
508                                       << token << '\'' << endl;
509
510                 string unknown = params().readToken(lex, token);
511                 if (!unknown.empty()) {
512                         if (unknown[0] != '\\' && token == "\\textclass") {
513                                 unknownClass(unknown);
514                         } else {
515                                 ++unknown_tokens;
516                                 docstring const s = bformat(_("Unknown token: "
517                                                                         "%1$s %2$s\n"),
518                                                          from_utf8(token),
519                                                          lex.getDocString());
520                                 errorList.push_back(ErrorItem(_("Document header error"),
521                                         s, -1, 0, 0));
522                         }
523                 }
524         }
525         if (begin_header_line) {
526                 docstring const s = _("\\begin_header is missing");
527                 errorList.push_back(ErrorItem(_("Document header error"),
528                         s, -1, 0, 0));
529         }
530
531         return unknown_tokens;
532 }
533
534
535 // Uwe C. Schroeder
536 // changed to be public and have one parameter
537 // Returns false if "\end_document" is not read (Asger)
538 bool Buffer::readDocument(Lexer & lex)
539 {
540         ErrorList & errorList = pimpl_->errorLists["Parse"];
541         errorList.clear();
542
543         lex.next();
544         string const token = lex.getString();
545         if (token != "\\begin_document") {
546                 docstring const s = _("\\begin_document is missing");
547                 errorList.push_back(ErrorItem(_("Document header error"),
548                         s, -1, 0, 0));
549         }
550
551         // we are reading in a brand new document
552         BOOST_ASSERT(paragraphs().empty());
553
554         readHeader(lex);
555         TextClass const & baseClass = textclasslist[params().getBaseClass()];
556         if (!baseClass.load(filePath())) {
557                 string theclass = baseClass.name();
558                 Alert::error(_("Can't load document class"), bformat(
559                         _("Using the default document class, because the "
560                                      "class %1$s could not be loaded."), from_utf8(theclass)));
561                 params().setBaseClass(defaultTextclass());
562         }
563
564         if (params().outputChanges) {
565                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
566                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
567                                   LaTeXFeatures::isAvailable("xcolor");
568
569                 if (!dvipost && !xcolorsoul) {
570                         Alert::warning(_("Changes not shown in LaTeX output"),
571                                        _("Changes will not be highlighted in LaTeX output, "
572                                          "because neither dvipost nor xcolor/soul are installed.\n"
573                                          "Please install these packages or redefine "
574                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
575                 } else if (!xcolorsoul) {
576                         Alert::warning(_("Changes not shown in LaTeX output"),
577                                        _("Changes will not be highlighted in LaTeX output "
578                                          "when using pdflatex, because xcolor and soul are not installed.\n"
579                                          "Please install both packages or redefine "
580                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
581                 }
582         }
583         // read manifest after header
584         embeddedFiles().readManifest(lex, errorList);   
585
586         // read main text
587         bool const res = text().read(*this, lex, errorList);
588         for_each(text().paragraphs().begin(),
589                  text().paragraphs().end(),
590                  bind(&Paragraph::setInsetOwner, _1, &inset()));
591
592         return res;
593 }
594
595
596 // needed to insert the selection
597 void Buffer::insertStringAsLines(ParagraphList & pars,
598         pit_type & pit, pos_type & pos,
599         Font const & fn, docstring const & str, bool autobreakrows)
600 {
601         Font font = fn;
602
603         // insert the string, don't insert doublespace
604         bool space_inserted = true;
605         for (docstring::const_iterator cit = str.begin();
606             cit != str.end(); ++cit) {
607                 Paragraph & par = pars[pit];
608                 if (*cit == '\n') {
609                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
610                                 breakParagraph(params(), pars, pit, pos,
611                                                par.layout()->isEnvironment());
612                                 ++pit;
613                                 pos = 0;
614                                 space_inserted = true;
615                         } else {
616                                 continue;
617                         }
618                         // do not insert consecutive spaces if !free_spacing
619                 } else if ((*cit == ' ' || *cit == '\t') &&
620                            space_inserted && !par.isFreeSpacing()) {
621                         continue;
622                 } else if (*cit == '\t') {
623                         if (!par.isFreeSpacing()) {
624                                 // tabs are like spaces here
625                                 par.insertChar(pos, ' ', font, params().trackChanges);
626                                 ++pos;
627                                 space_inserted = true;
628                         } else {
629                                 const pos_type n = 8 - pos % 8;
630                                 for (pos_type i = 0; i < n; ++i) {
631                                         par.insertChar(pos, ' ', font, params().trackChanges);
632                                         ++pos;
633                                 }
634                                 space_inserted = true;
635                         }
636                 } else if (!isPrintable(*cit)) {
637                         // Ignore unprintables
638                         continue;
639                 } else {
640                         // just insert the character
641                         par.insertChar(pos, *cit, font, params().trackChanges);
642                         ++pos;
643                         space_inserted = (*cit == ' ');
644                 }
645
646         }
647 }
648
649
650 bool Buffer::readString(std::string const & s)
651 {
652         params().compressed = false;
653
654         // remove dummy empty par
655         paragraphs().clear();
656         Lexer lex(0, 0);
657         std::istringstream is(s);
658         lex.setStream(is);
659         FileName const name(tempName());
660         switch (readFile(lex, name, true)) {
661         case failure:
662                 return false;
663         case wrongversion: {
664                 // We need to call lyx2lyx, so write the input to a file
665                 std::ofstream os(name.toFilesystemEncoding().c_str());
666                 os << s;
667                 os.close();
668                 return readFile(name);
669         }
670         case success:
671                 break;
672         }
673
674         return true;
675 }
676
677
678 bool Buffer::readFile(FileName const & filename)
679 {
680         FileName fname(filename);
681         // Check if the file is compressed.
682         string format = getFormatFromContents(filename);
683         if (format == "zip") {
684                 // decompress to a temp directory
685                 LYXERR(Debug::FILES) << filename << " is in zip format. Unzip to " << temppath() << endl;
686                 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
687                 //
688                 FileName lyxfile(addName(temppath(), "content.lyx"));
689                 // if both manifest.txt and file.lyx exist, this is am embedded file
690                 if (lyxfile.exists()) {
691                         params().embedded = true;
692                         fname = lyxfile;
693                 }
694         }
695         // The embedded lyx file can also be compressed, for backward compatibility
696         format = getFormatFromContents(fname);
697         if (format == "gzip" || format == "zip" || format == "compress") {
698                 params().compressed = true;
699         }
700
701         // remove dummy empty par
702         paragraphs().clear();
703         Lexer lex(0, 0);
704         lex.setFile(fname);
705         if (readFile(lex, fname) != success)
706                 return false;
707
708         return true;
709 }
710
711
712 bool Buffer::fully_loaded() const
713 {
714         return pimpl_->file_fully_loaded;
715 }
716
717
718 void Buffer::fully_loaded(bool const value)
719 {
720         pimpl_->file_fully_loaded = value;
721 }
722
723
724 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
725                 bool fromstring)
726 {
727         BOOST_ASSERT(!filename.empty());
728
729         if (!lex.isOK()) {
730                 Alert::error(_("Document could not be read"),
731                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
732                 return failure;
733         }
734
735         lex.next();
736         string const token = lex.getString();
737
738         if (!lex) {
739                 Alert::error(_("Document could not be read"),
740                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
741                 return failure;
742         }
743
744         // the first token _must_ be...
745         if (token != "\\lyxformat") {
746                 lyxerr << "Token: " << token << endl;
747
748                 Alert::error(_("Document format failure"),
749                              bformat(_("%1$s is not a LyX document."),
750                                        from_utf8(filename.absFilename())));
751                 return failure;
752         }
753
754         lex.next();
755         string tmp_format = lex.getString();
756         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
757         // if present remove ".," from string.
758         string::size_type dot = tmp_format.find_first_of(".,");
759         //lyxerr << "           dot found at " << dot << endl;
760         if (dot != string::npos)
761                         tmp_format.erase(dot, 1);
762         int const file_format = convert<int>(tmp_format);
763         //lyxerr << "format: " << file_format << endl;
764
765         // save timestamp and checksum of the original disk file, making sure
766         // to not overwrite them with those of the file created in the tempdir
767         // when it has to be converted to the current format.
768         if (!pimpl_->checksum_) {
769                 // Save the timestamp and checksum of disk file. If filename is an
770                 // emergency file, save the timestamp and sum of the original lyx file
771                 // because isExternallyModified will check for this file. (BUG4193)
772                 string diskfile = filename.toFilesystemEncoding();
773                 if (suffixIs(diskfile, ".emergency"))
774                         diskfile = diskfile.substr(0, diskfile.size() - 10);
775                 saveCheckSum(diskfile);
776         }
777
778         if (file_format != LYX_FORMAT) {
779
780                 if (fromstring)
781                         // lyx2lyx would fail
782                         return wrongversion;
783
784                 FileName const tmpfile(tempName());
785                 if (tmpfile.empty()) {
786                         Alert::error(_("Conversion failed"),
787                                      bformat(_("%1$s is from a different"
788                                               " version of LyX, but a temporary"
789                                               " file for converting it could"
790                                                             " not be created."),
791                                               from_utf8(filename.absFilename())));
792                         return failure;
793                 }
794                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
795                 if (lyx2lyx.empty()) {
796                         Alert::error(_("Conversion script not found"),
797                                      bformat(_("%1$s is from a different"
798                                                " version of LyX, but the"
799                                                " conversion script lyx2lyx"
800                                                             " could not be found."),
801                                                from_utf8(filename.absFilename())));
802                         return failure;
803                 }
804                 ostringstream command;
805                 command << os::python()
806                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
807                         << " -t " << convert<string>(LYX_FORMAT)
808                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
809                         << ' ' << quoteName(filename.toFilesystemEncoding());
810                 string const command_str = command.str();
811
812                 LYXERR(Debug::INFO) << "Running '"
813                                     << command_str << '\''
814                                     << endl;
815
816                 cmd_ret const ret = runCommand(command_str);
817                 if (ret.first != 0) {
818                         Alert::error(_("Conversion script failed"),
819                                      bformat(_("%1$s is from a different version"
820                                               " of LyX, but the lyx2lyx script"
821                                                             " failed to convert it."),
822                                               from_utf8(filename.absFilename())));
823                         return failure;
824                 } else {
825                         bool const ret = readFile(tmpfile);
826                         // Do stuff with tmpfile name and buffer name here.
827                         return ret ? success : failure;
828                 }
829
830         }
831
832         if (readDocument(lex)) {
833                 Alert::error(_("Document format failure"),
834                              bformat(_("%1$s ended unexpectedly, which means"
835                                                     " that it is probably corrupted."),
836                                        from_utf8(filename.absFilename())));
837         }
838
839         //lyxerr << "removing " << MacroTable::localMacros().size()
840         //      << " temporary macro entries" << endl;
841         //MacroTable::localMacros().clear();
842
843         pimpl_->file_fully_loaded = true;
844         return success;
845 }
846
847
848 // Should probably be moved to somewhere else: BufferView? LyXView?
849 bool Buffer::save() const
850 {
851         // We don't need autosaves in the immediate future. (Asger)
852         resetAutosaveTimers();
853
854         string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
855
856         FileName backupName;
857         bool madeBackup = false;
858
859         // make a backup if the file already exists
860         if (lyxrc.make_backup && fs::exists(encodedFilename)) {
861                 backupName = FileName(fileName() + '~');
862                 if (!lyxrc.backupdir_path.empty())
863                         backupName = FileName(addName(lyxrc.backupdir_path,
864                                               subst(os::internal_path(backupName.absFilename()), '/', '!')));
865
866                 try {
867                         fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
868                         madeBackup = true;
869                 } catch (fs::filesystem_error const & fe) {
870                         Alert::error(_("Backup failure"),
871                                      bformat(_("Cannot create backup file %1$s.\n"
872                                                "Please check whether the directory exists and is writeable."),
873                                              from_utf8(backupName.absFilename())));
874                         LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
875                 }
876         }
877
878         // ask if the disk file has been externally modified (use checksum method)
879         if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
880                 docstring const file = makeDisplayPath(fileName(), 20);
881                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
882                                                              "you want to overwrite this file?"), file);
883                 int const ret = Alert::prompt(_("Overwrite modified file?"),
884                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
885                 if (ret == 1)
886                         return false;
887         }
888
889         if (writeFile(pimpl_->filename)) {
890                 markClean();
891                 removeAutosaveFile(fileName());
892                 saveCheckSum(pimpl_->filename.toFilesystemEncoding());
893                 return true;
894         } else {
895                 // Saving failed, so backup is not backup
896                 if (madeBackup)
897                         rename(backupName, pimpl_->filename);
898                 return false;
899         }
900 }
901
902
903 bool Buffer::writeFile(FileName const & fname) const
904 {
905         if (pimpl_->read_only && fname == pimpl_->filename)
906                 return false;
907
908         bool retval = false;
909
910         FileName content;
911         if (params().embedded)
912                 // first write the .lyx file to the temporary directory
913                 content = FileName(addName(temppath(), "content.lyx"));
914         else
915                 content = fname;
916         
917         if (params().compressed) {
918                 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
919                 if (!ofs)
920                         return false;
921
922                 retval = write(ofs);
923         } else {
924                 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
925                 if (!ofs)
926                         return false;
927
928                 retval = write(ofs);
929         }
930
931         if (retval && params().embedded) {
932                 // write file.lyx and all the embedded files to the zip file fname
933                 // if embedding is enabled
934                 return pimpl_->embedded_files.writeFile(fname);
935         }
936         return retval;
937 }
938
939
940 bool Buffer::write(ostream & ofs) const
941 {
942 #ifdef HAVE_LOCALE
943         // Use the standard "C" locale for file output.
944         ofs.imbue(std::locale::classic());
945 #endif
946
947         // The top of the file should not be written by params().
948
949         // write out a comment in the top of the file
950         ofs << "#LyX " << lyx_version
951             << " created this file. For more info see http://www.lyx.org/\n"
952             << "\\lyxformat " << LYX_FORMAT << "\n"
953             << "\\begin_document\n";
954
955
956         /// For each author, set 'used' to true if there is a change
957         /// by this author in the document; otherwise set it to 'false'.
958         AuthorList::Authors::const_iterator a_it = params().authors().begin();
959         AuthorList::Authors::const_iterator a_end = params().authors().end();
960         for (; a_it != a_end; ++a_it)
961                 a_it->second.used(false);
962
963         ParIterator const end = par_iterator_end();
964         ParIterator it = par_iterator_begin();
965         for ( ; it != end; ++it)
966                 it->checkAuthors(params().authors());
967
968         // now write out the buffer parameters.
969         ofs << "\\begin_header\n";
970         params().writeFile(ofs);
971         ofs << "\\end_header\n";
972
973         // write the manifest after header
974         ofs << "\n\\begin_manifest\n";
975         pimpl_->embedded_files.update();
976         embeddedFiles().writeManifest(ofs);
977         ofs << "\\end_manifest\n";
978
979         // write the text
980         ofs << "\n\\begin_body\n";
981         text().write(*this, ofs);
982         ofs << "\n\\end_body\n";
983
984         // Write marker that shows file is complete
985         ofs << "\\end_document" << endl;
986
987         // Shouldn't really be needed....
988         //ofs.close();
989
990         // how to check if close went ok?
991         // Following is an attempt... (BE 20001011)
992
993         // good() returns false if any error occured, including some
994         //        formatting error.
995         // bad()  returns true if something bad happened in the buffer,
996         //        which should include file system full errors.
997
998         bool status = true;
999         if (!ofs) {
1000                 status = false;
1001                 lyxerr << "File was not closed properly." << endl;
1002         }
1003
1004         return status;
1005 }
1006
1007
1008 bool Buffer::makeLaTeXFile(FileName const & fname,
1009                            string const & original_path,
1010                            OutputParams const & runparams,
1011                            bool output_preamble, bool output_body)
1012 {
1013         string const encoding = runparams.encoding->iconvName();
1014         LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
1015                 << encoding << "..." << endl;
1016
1017         odocfstream ofs(encoding);
1018         if (!openFileWrite(ofs, fname))
1019                 return false;
1020
1021         //TexStream ts(ofs.rdbuf(), &texrow());
1022
1023         bool failed_export = false;
1024         try {
1025                 texrow().reset();
1026                 writeLaTeXSource(ofs, original_path,
1027                       runparams, output_preamble, output_body);
1028         }
1029         catch (iconv_codecvt_facet_exception & e) {
1030                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1031                 failed_export = true;
1032         }
1033         catch (std::exception const & e) {
1034                 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1035                 failed_export = true;
1036         }
1037         catch (...) {
1038                 lyxerr << "Caught some really weird exception..." << endl;
1039                 LyX::cref().emergencyCleanup();
1040                 abort();
1041         }
1042
1043         ofs.close();
1044         if (ofs.fail()) {
1045                 failed_export = true;
1046                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1047         }
1048
1049         if (failed_export) {
1050                 Alert::error(_("Encoding error"),
1051                         _("Some characters of your document are probably not "
1052                         "representable in the chosen encoding.\n"
1053                         "Changing the document encoding to utf8 could help."));
1054                 return false;
1055         }
1056         return true;
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)
1064 {
1065         OutputParams runparams = runparams_in;
1066
1067         // validate the buffer.
1068         LYXERR(Debug::LATEX) << "  Validating buffer..." << endl;
1069         LaTeXFeatures features(*this, params(), runparams);
1070         validate(features);
1071         LYXERR(Debug::LATEX) << "  Buffer validation done." << endl;
1072
1073         // The starting paragraph of the coming rows is the
1074         // first paragraph of the document. (Asger)
1075         if (output_preamble && runparams.nice) {
1076                 os << "%% LyX " << lyx_version << " created this file.  "
1077                         "For more info, see http://www.lyx.org/.\n"
1078                         "%% Do not edit unless you really know what "
1079                         "you are doing.\n";
1080                 texrow().newline();
1081                 texrow().newline();
1082         }
1083         LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1084         // There are a few differences between nice LaTeX and usual files:
1085         // usual is \batchmode and has a
1086         // special input@path to allow the including of figures
1087         // with either \input or \includegraphics (what figinsets do).
1088         // input@path is set when the actual parameter
1089         // original_path is set. This is done for usual tex-file, but not
1090         // for nice-latex-file. (Matthias 250696)
1091         // Note that input@path is only needed for something the user does
1092         // in the preamble, included .tex files or ERT, files included by
1093         // LyX work without it.
1094         if (output_preamble) {
1095                 if (!runparams.nice) {
1096                         // code for usual, NOT nice-latex-file
1097                         os << "\\batchmode\n"; // changed
1098                         // from \nonstopmode
1099                         texrow().newline();
1100                 }
1101                 if (!original_path.empty()) {
1102                         // FIXME UNICODE
1103                         // We don't know the encoding of inputpath
1104                         docstring const inputpath = from_utf8(latex_path(original_path));
1105                         os << "\\makeatletter\n"
1106                            << "\\def\\input@path{{"
1107                            << inputpath << "/}}\n"
1108                            << "\\makeatother\n";
1109                         texrow().newline();
1110                         texrow().newline();
1111                         texrow().newline();
1112                 }
1113
1114                 // Write the preamble
1115                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1116
1117                 if (!output_body)
1118                         return;
1119
1120                 // make the body.
1121                 os << "\\begin{document}\n";
1122                 texrow().newline();
1123         } // output_preamble
1124
1125         texrow().start(paragraphs().begin()->id(), 0);
1126         
1127         LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1128
1129         if (!lyxrc.language_auto_begin &&
1130             !params().language->babel().empty()) {
1131                 // FIXME UNICODE
1132                 os << from_utf8(subst(lyxrc.language_command_begin,
1133                                            "$$lang",
1134                                            params().language->babel()))
1135                    << '\n';
1136                 texrow().newline();
1137         }
1138
1139         Encoding const & encoding = params().encoding();
1140         if (encoding.package() == Encoding::CJK) {
1141                 // Open a CJK environment, since in contrast to the encodings
1142                 // handled by inputenc the document encoding is not set in
1143                 // the preamble if it is handled by CJK.sty.
1144                 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1145                    << "}{}\n";
1146                 texrow().newline();
1147         }
1148
1149         // if we are doing a real file with body, even if this is the
1150         // child of some other buffer, let's cut the link here.
1151         // This happens for example if only a child document is printed.
1152         string save_parentname;
1153         if (output_preamble) {
1154                 save_parentname = params().parentname;
1155                 params().parentname.erase();
1156         }
1157
1158         loadChildDocuments(*this);
1159
1160         // the real stuff
1161         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1162
1163         // Restore the parenthood if needed
1164         if (output_preamble)
1165                 params().parentname = save_parentname;
1166
1167         // add this just in case after all the paragraphs
1168         os << endl;
1169         texrow().newline();
1170
1171         if (encoding.package() == Encoding::CJK) {
1172                 // Close the open CJK environment.
1173                 // latexParagraphs will have opened one even if the last text
1174                 // was not CJK.
1175                 os << "\\end{CJK}\n";
1176                 texrow().newline();
1177         }
1178
1179         if (!lyxrc.language_auto_end &&
1180             !params().language->babel().empty()) {
1181                 os << from_utf8(subst(lyxrc.language_command_end,
1182                                            "$$lang",
1183                                            params().language->babel()))
1184                    << '\n';
1185                 texrow().newline();
1186         }
1187
1188         if (output_preamble) {
1189                 os << "\\end{document}\n";
1190                 texrow().newline();
1191
1192                 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1193         } else {
1194                 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1195                                      << endl;
1196         }
1197         runparams_in.encoding = runparams.encoding;
1198
1199         // Just to be sure. (Asger)
1200         texrow().newline();
1201
1202         LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1203         LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1204                             << '.' << endl;
1205 }
1206
1207
1208 bool Buffer::isLatex() const
1209 {
1210         return params().getTextClass().outputType() == LATEX;
1211 }
1212
1213
1214 bool Buffer::isLiterate() const
1215 {
1216         return params().getTextClass().outputType() == LITERATE;
1217 }
1218
1219
1220 bool Buffer::isDocBook() const
1221 {
1222         return params().getTextClass().outputType() == DOCBOOK;
1223 }
1224
1225
1226 void Buffer::makeDocBookFile(FileName const & fname,
1227                               OutputParams const & runparams,
1228                               bool const body_only)
1229 {
1230         LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1231
1232         //ofstream ofs;
1233         odocfstream ofs;
1234         if (!openFileWrite(ofs, fname))
1235                 return;
1236
1237         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1238
1239         ofs.close();
1240         if (ofs.fail())
1241                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1242 }
1243
1244
1245 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1246                              OutputParams const & runparams,
1247                              bool const only_body)
1248 {
1249         LaTeXFeatures features(*this, params(), runparams);
1250         validate(features);
1251
1252         texrow().reset();
1253
1254         TextClass const & tclass = params().getTextClass();
1255         string const top_element = tclass.latexname();
1256
1257         if (!only_body) {
1258                 if (runparams.flavor == OutputParams::XML)
1259                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1260
1261                 // FIXME UNICODE
1262                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1263
1264                 // FIXME UNICODE
1265                 if (! tclass.class_header().empty())
1266                         os << from_ascii(tclass.class_header());
1267                 else if (runparams.flavor == OutputParams::XML)
1268                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1269                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1270                 else
1271                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1272
1273                 docstring preamble = from_utf8(params().preamble);
1274                 if (runparams.flavor != OutputParams::XML ) {
1275                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1276                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1277                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1278                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1279                 }
1280
1281                 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1282                          : fname;
1283                 preamble += features.getIncludedFiles(name);
1284                 preamble += features.getLyXSGMLEntities();
1285
1286                 if (!preamble.empty()) {
1287                         os << "\n [ " << preamble << " ]";
1288                 }
1289                 os << ">\n\n";
1290         }
1291
1292         string top = top_element;
1293         top += " lang=\"";
1294         if (runparams.flavor == OutputParams::XML)
1295                 top += params().language->code();
1296         else
1297                 top += params().language->code().substr(0,2);
1298         top += '"';
1299
1300         if (!params().options.empty()) {
1301                 top += ' ';
1302                 top += params().options;
1303         }
1304
1305         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1306             << " file was created by LyX " << lyx_version
1307             << "\n  See http://www.lyx.org/ for more information -->\n";
1308
1309         params().getTextClass().counters().reset();
1310
1311         loadChildDocuments(*this);
1312
1313         sgml::openTag(os, top);
1314         os << '\n';
1315         docbookParagraphs(paragraphs(), *this, os, runparams);
1316         sgml::closeTag(os, top_element);
1317 }
1318
1319
1320 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1321 // Other flags: -wall -v0 -x
1322 int Buffer::runChktex()
1323 {
1324         busy(true);
1325
1326         // get LaTeX-Filename
1327         FileName const path(temppath());
1328         string const name = addName(path.absFilename(), getLatexName());
1329         string const org_path = filePath();
1330
1331         support::Path p(path); // path to LaTeX file
1332         message(_("Running chktex..."));
1333
1334         // Generate the LaTeX file if neccessary
1335         OutputParams runparams(&params().encoding());
1336         runparams.flavor = OutputParams::LATEX;
1337         runparams.nice = false;
1338         makeLaTeXFile(FileName(name), org_path, runparams);
1339
1340         TeXErrors terr;
1341         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1342         int const res = chktex.run(terr); // run chktex
1343
1344         if (res == -1) {
1345                 Alert::error(_("chktex failure"),
1346                              _("Could not run chktex successfully."));
1347         } else if (res > 0) {
1348                 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1349                 // Clear out old errors
1350                 errorList.clear();
1351                 // Fill-in the error list with the TeX errors
1352                 bufferErrors(*this, terr, errorList);
1353         }
1354
1355         busy(false);
1356
1357         errors("ChkTeX");
1358
1359         return res;
1360 }
1361
1362
1363 void Buffer::validate(LaTeXFeatures & features) const
1364 {
1365         TextClass const & tclass = params().getTextClass();
1366
1367         if (params().outputChanges) {
1368                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1369                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1370                                   LaTeXFeatures::isAvailable("xcolor");
1371
1372                 if (features.runparams().flavor == OutputParams::LATEX) {
1373                         if (dvipost) {
1374                                 features.require("ct-dvipost");
1375                                 features.require("dvipost");
1376                         } else if (xcolorsoul) {
1377                                 features.require("ct-xcolor-soul");
1378                                 features.require("soul");
1379                                 features.require("xcolor");
1380                         } else {
1381                                 features.require("ct-none");
1382                         }
1383                 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1384                         if (xcolorsoul) {
1385                                 features.require("ct-xcolor-soul");
1386                                 features.require("soul");
1387                                 features.require("xcolor");
1388                                 features.require("pdfcolmk"); // improves color handling in PDF output
1389                         } else {
1390                                 features.require("ct-none");
1391                         }
1392                 }
1393         }
1394
1395         // AMS Style is at document level
1396         if (params().use_amsmath == BufferParams::package_on
1397             || tclass.provides("amsmath"))
1398                 features.require("amsmath");
1399         if (params().use_esint == BufferParams::package_on)
1400                 features.require("esint");
1401
1402         loadChildDocuments(*this);
1403
1404         for_each(paragraphs().begin(), paragraphs().end(),
1405                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1406
1407         // the bullet shapes are buffer level not paragraph level
1408         // so they are tested here
1409         for (int i = 0; i < 4; ++i) {
1410                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1411                         int const font = params().user_defined_bullet(i).getFont();
1412                         if (font == 0) {
1413                                 int const c = params()
1414                                         .user_defined_bullet(i)
1415                                         .getCharacter();
1416                                 if (c == 16
1417                                    || c == 17
1418                                    || c == 25
1419                                    || c == 26
1420                                    || c == 31) {
1421                                         features.require("latexsym");
1422                                 }
1423                         } else if (font == 1) {
1424                                 features.require("amssymb");
1425                         } else if ((font >= 2 && font <= 5)) {
1426                                 features.require("pifont");
1427                         }
1428                 }
1429         }
1430
1431         if (lyxerr.debugging(Debug::LATEX)) {
1432                 features.showStruct();
1433         }
1434 }
1435
1436
1437 void Buffer::getLabelList(vector<docstring> & list) const
1438 {
1439         /// if this is a child document and the parent is already loaded
1440         /// Use the parent's list instead  [ale990407]
1441         Buffer const * tmp = getMasterBuffer();
1442         if (!tmp) {
1443                 lyxerr << "getMasterBuffer() failed!" << endl;
1444                 BOOST_ASSERT(tmp);
1445         }
1446         if (tmp != this) {
1447                 tmp->getLabelList(list);
1448                 return;
1449         }
1450
1451         loadChildDocuments(*this);
1452
1453         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1454                 it.nextInset()->getLabelList(*this, list);
1455 }
1456
1457
1458 void Buffer::updateBibfilesCache()
1459 {
1460         // if this is a child document and the parent is already loaded
1461         // update the parent's cache instead
1462         Buffer * tmp = getMasterBuffer();
1463         BOOST_ASSERT(tmp);
1464         if (tmp != this) {
1465                 tmp->updateBibfilesCache();
1466                 return;
1467         }
1468
1469         bibfilesCache_.clear();
1470         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1471                 if (it->lyxCode() == BIBTEX_CODE) {
1472                         InsetBibtex const & inset =
1473                                 static_cast<InsetBibtex const &>(*it);
1474                         vector<FileName> const bibfiles = inset.getFiles(*this);
1475                         bibfilesCache_.insert(bibfilesCache_.end(),
1476                                 bibfiles.begin(),
1477                                 bibfiles.end());
1478                 } else if (it->lyxCode() == INCLUDE_CODE) {
1479                         InsetInclude & inset =
1480                                 static_cast<InsetInclude &>(*it);
1481                         inset.updateBibfilesCache(*this);
1482                         vector<FileName> const & bibfiles =
1483                                         inset.getBibfilesCache(*this);
1484                         bibfilesCache_.insert(bibfilesCache_.end(),
1485                                 bibfiles.begin(),
1486                                 bibfiles.end());
1487                 }
1488         }
1489 }
1490
1491
1492 vector<FileName> const & Buffer::getBibfilesCache() const
1493 {
1494         // if this is a child document and the parent is already loaded
1495         // use the parent's cache instead
1496         Buffer const * tmp = getMasterBuffer();
1497         BOOST_ASSERT(tmp);
1498         if (tmp != this)
1499                 return tmp->getBibfilesCache();
1500
1501         // We update the cache when first used instead of at loading time.
1502         if (bibfilesCache_.empty())
1503                 const_cast<Buffer *>(this)->updateBibfilesCache();
1504
1505         return bibfilesCache_;
1506 }
1507
1508
1509 bool Buffer::isDepClean(string const & name) const
1510 {
1511         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1512         if (it == pimpl_->dep_clean.end())
1513                 return true;
1514         return it->second;
1515 }
1516
1517
1518 void Buffer::markDepClean(string const & name)
1519 {
1520         pimpl_->dep_clean[name] = true;
1521 }
1522
1523
1524 bool Buffer::dispatch(string const & command, bool * result)
1525 {
1526         return dispatch(lyxaction.lookupFunc(command), result);
1527 }
1528
1529
1530 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1531 {
1532         bool dispatched = true;
1533
1534         switch (func.action) {
1535                 case LFUN_BUFFER_EXPORT: {
1536                         bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1537                         if (result)
1538                                 *result = tmp;
1539                         break;
1540                 }
1541
1542                 default:
1543                         dispatched = false;
1544         }
1545         return dispatched;
1546 }
1547
1548
1549 void Buffer::changeLanguage(Language const * from, Language const * to)
1550 {
1551         BOOST_ASSERT(from);
1552         BOOST_ASSERT(to);
1553
1554         for_each(par_iterator_begin(),
1555                  par_iterator_end(),
1556                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1557 }
1558
1559
1560 bool Buffer::isMultiLingual() const
1561 {
1562         ParConstIterator end = par_iterator_end();
1563         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1564                 if (it->isMultiLingual(params()))
1565                         return true;
1566
1567         return false;
1568 }
1569
1570
1571 ParIterator Buffer::getParFromID(int const id) const
1572 {
1573         ParConstIterator it = par_iterator_begin();
1574         ParConstIterator const end = par_iterator_end();
1575
1576         if (id < 0) {
1577                 // John says this is called with id == -1 from undo
1578                 lyxerr << "getParFromID(), id: " << id << endl;
1579                 return end;
1580         }
1581
1582         for (; it != end; ++it)
1583                 if (it->id() == id)
1584                         return it;
1585
1586         return end;
1587 }
1588
1589
1590 bool Buffer::hasParWithID(int const id) const
1591 {
1592         ParConstIterator const it = getParFromID(id);
1593         return it != par_iterator_end();
1594 }
1595
1596
1597 ParIterator Buffer::par_iterator_begin()
1598 {
1599         return lyx::par_iterator_begin(inset());
1600 }
1601
1602
1603 ParIterator Buffer::par_iterator_end()
1604 {
1605         return lyx::par_iterator_end(inset());
1606 }
1607
1608
1609 ParConstIterator Buffer::par_iterator_begin() const
1610 {
1611         return lyx::par_const_iterator_begin(inset());
1612 }
1613
1614
1615 ParConstIterator Buffer::par_iterator_end() const
1616 {
1617         return lyx::par_const_iterator_end(inset());
1618 }
1619
1620
1621 Language const * Buffer::getLanguage() const
1622 {
1623         return params().language;
1624 }
1625
1626
1627 docstring const Buffer::B_(string const & l10n) const
1628 {
1629         return params().B_(l10n);
1630 }
1631
1632
1633 bool Buffer::isClean() const
1634 {
1635         return pimpl_->lyx_clean;
1636 }
1637
1638
1639 bool Buffer::isBakClean() const
1640 {
1641         return pimpl_->bak_clean;
1642 }
1643
1644
1645 bool Buffer::isExternallyModified(CheckMethod method) const
1646 {
1647         BOOST_ASSERT(pimpl_->filename.exists());
1648         // if method == timestamp, check timestamp before checksum
1649         return (method == checksum_method 
1650                 || pimpl_->timestamp_ != pimpl_->filename.lastModified())
1651                 && pimpl_->checksum_ != sum(pimpl_->filename);
1652 }
1653
1654
1655 void Buffer::saveCheckSum(string const & file) const
1656 {
1657         if (fs::exists(file)) {
1658                 pimpl_->timestamp_ = fs::last_write_time(file);
1659                 pimpl_->checksum_ = sum(FileName(file));
1660         } else {
1661                 // in the case of save to a new file.
1662                 pimpl_->timestamp_ = 0;
1663                 pimpl_->checksum_ = 0;
1664         }
1665 }
1666
1667
1668 void Buffer::markClean() const
1669 {
1670         if (!pimpl_->lyx_clean) {
1671                 pimpl_->lyx_clean = true;
1672                 updateTitles();
1673         }
1674         // if the .lyx file has been saved, we don't need an
1675         // autosave
1676         pimpl_->bak_clean = true;
1677 }
1678
1679
1680 void Buffer::markBakClean() const
1681 {
1682         pimpl_->bak_clean = true;
1683 }
1684
1685
1686 void Buffer::setUnnamed(bool flag)
1687 {
1688         pimpl_->unnamed = flag;
1689 }
1690
1691
1692 bool Buffer::isUnnamed() const
1693 {
1694         return pimpl_->unnamed;
1695 }
1696
1697
1698 // FIXME: this function should be moved to buffer_pimpl.C
1699 void Buffer::markDirty()
1700 {
1701         if (pimpl_->lyx_clean) {
1702                 pimpl_->lyx_clean = false;
1703                 updateTitles();
1704         }
1705         pimpl_->bak_clean = false;
1706
1707         DepClean::iterator it = pimpl_->dep_clean.begin();
1708         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1709
1710         for (; it != end; ++it)
1711                 it->second = false;
1712 }
1713
1714
1715 string const Buffer::fileName() const
1716 {
1717         return pimpl_->filename.absFilename();
1718 }
1719
1720
1721 string const & Buffer::filePath() const
1722 {
1723         return params().filepath;
1724 }
1725
1726
1727 bool Buffer::isReadonly() const
1728 {
1729         return pimpl_->read_only;
1730 }
1731
1732
1733 void Buffer::setParentName(string const & name)
1734 {
1735         if (name == pimpl_->filename.absFilename())
1736                 // Avoids recursive include.
1737                 params().parentname.clear();
1738         else
1739                 params().parentname = name;
1740 }
1741
1742
1743 Buffer const * Buffer::getMasterBuffer() const
1744 {
1745         if (!params().parentname.empty()
1746             && theBufferList().exists(params().parentname)) {
1747                 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1748                 //We need to check if the parent is us...
1749                 //FIXME RECURSIVE INCLUDE
1750                 //This is not sufficient, since recursive includes could be downstream.
1751                 if (buf && buf != this)
1752                         return buf->getMasterBuffer();
1753         }
1754
1755         return this;
1756 }
1757
1758
1759 Buffer * Buffer::getMasterBuffer()
1760 {
1761         if (!params().parentname.empty()
1762             && theBufferList().exists(params().parentname)) {
1763                 Buffer * buf = theBufferList().getBuffer(params().parentname);
1764                 //We need to check if the parent is us...
1765                 //FIXME RECURSIVE INCLUDE
1766                 //This is not sufficient, since recursive includes could be downstream.
1767                 if (buf && buf != this)
1768                         return buf->getMasterBuffer();
1769         }
1770
1771         return this;
1772 }
1773
1774
1775 MacroData const & Buffer::getMacro(docstring const & name) const
1776 {
1777         return pimpl_->macros.get(name);
1778 }
1779
1780
1781 bool Buffer::hasMacro(docstring const & name) const
1782 {
1783         return pimpl_->macros.has(name);
1784 }
1785
1786
1787 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1788 {
1789         MacroTable::globalMacros().insert(name, data);
1790         pimpl_->macros.insert(name, data);
1791 }
1792
1793
1794 void Buffer::buildMacros()
1795 {
1796         // Start with global table.
1797         pimpl_->macros = MacroTable::globalMacros();
1798
1799         // Now add our own.
1800         ParagraphList const & pars = text().paragraphs();
1801         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1802                 //lyxerr << "searching main par " << i
1803                 //      << " for macro definitions" << std::endl;
1804                 InsetList const & insets = pars[i].insetList();
1805                 InsetList::const_iterator it = insets.begin();
1806                 InsetList::const_iterator end = insets.end();
1807                 for ( ; it != end; ++it) {
1808                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1809                         if (it->inset->lyxCode() == MATHMACRO_CODE) {
1810                                 MathMacroTemplate const & mac
1811                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1812                                 insertMacro(mac.name(), mac.asMacroData());
1813                         }
1814                 }
1815         }
1816 }
1817
1818
1819 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1820         InsetCode code)
1821 {
1822         //FIXME: This does not work for child documents yet.
1823         BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1824         // Check if the label 'from' appears more than once
1825         vector<docstring> labels;
1826
1827         if (code == CITE_CODE) {
1828                 BiblioInfo keys;
1829                 keys.fillWithBibKeys(this);
1830                 BiblioInfo::const_iterator bit  = keys.begin();
1831                 BiblioInfo::const_iterator bend = keys.end();
1832
1833                 for (; bit != bend; ++bit)
1834                         // FIXME UNICODE
1835                         labels.push_back(bit->first);
1836         } else
1837                 getLabelList(labels);
1838
1839         if (std::count(labels.begin(), labels.end(), from) > 1)
1840                 return;
1841
1842         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1843                 if (it->lyxCode() == code) {
1844                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
1845                         inset.replaceContents(to_utf8(from), to_utf8(to));
1846                 }
1847         }
1848 }
1849
1850
1851 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1852         pit_type par_end, bool full_source)
1853 {
1854         OutputParams runparams(&params().encoding());
1855         runparams.nice = true;
1856         runparams.flavor = OutputParams::LATEX;
1857         runparams.linelen = lyxrc.plaintext_linelen;
1858         // No side effect of file copying and image conversion
1859         runparams.dryrun = true;
1860
1861         texrow().reset();
1862         if (full_source) {
1863                 os << "% " << _("Preview source code") << "\n\n";
1864                 texrow().newline();
1865                 texrow().newline();
1866                 if (isLatex())
1867                         writeLaTeXSource(os, filePath(), runparams, true, true);
1868                 else {
1869                         writeDocBookSource(os, fileName(), runparams, false);
1870                 }
1871         } else {
1872                 runparams.par_begin = par_begin;
1873                 runparams.par_end = par_end;
1874                 if (par_begin + 1 == par_end)
1875                         os << "% "
1876                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1877                            << "\n\n";
1878                 else
1879                         os << "% "
1880                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1881                                         convert<docstring>(par_begin),
1882                                         convert<docstring>(par_end - 1))
1883                            << "\n\n";
1884                 texrow().newline();
1885                 texrow().newline();
1886                 // output paragraphs
1887                 if (isLatex()) {
1888                         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1889                 } else {
1890                         // DocBook
1891                         docbookParagraphs(paragraphs(), *this, os, runparams);
1892                 }
1893         }
1894 }
1895
1896
1897 ErrorList const & Buffer::errorList(string const & type) const
1898 {
1899         static ErrorList const emptyErrorList;
1900         std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1901         if (I == pimpl_->errorLists.end())
1902                 return emptyErrorList;
1903
1904         return I->second;
1905 }
1906
1907
1908 ErrorList & Buffer::errorList(string const & type)
1909 {
1910         return pimpl_->errorLists[type];
1911 }
1912
1913
1914 void Buffer::structureChanged() const
1915 {
1916         if (gui_)
1917                 gui_->structureChanged();
1918 }
1919
1920
1921 void Buffer::embeddingChanged() const
1922 {
1923         if (gui_)
1924                 gui_->embeddingChanged();
1925 }
1926
1927
1928 void Buffer::errors(std::string const & err) const
1929 {
1930         if (gui_)
1931                 gui_->errors(err);
1932 }
1933
1934
1935 void Buffer::message(docstring const & msg) const
1936 {
1937         if (gui_)
1938                 gui_->message(msg);
1939 }
1940
1941
1942 void Buffer::busy(bool on) const
1943 {
1944         if (gui_)
1945                 gui_->busy(on);
1946 }
1947
1948
1949 void Buffer::readonly(bool on) const
1950 {
1951         if (gui_)
1952                 gui_->readonly(on);
1953 }
1954
1955
1956 void Buffer::updateTitles() const
1957 {
1958         if (gui_)
1959                 gui_->updateTitles();
1960 }
1961
1962
1963 void Buffer::resetAutosaveTimers() const
1964 {
1965         if (gui_)
1966                 gui_->resetAutosaveTimers();
1967 }
1968
1969
1970 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1971 {
1972         gui_ = gui;
1973 }
1974
1975
1976
1977 namespace {
1978
1979 class AutoSaveBuffer : public support::ForkedProcess {
1980 public:
1981         ///
1982         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1983                 : buffer_(buffer), fname_(fname) {}
1984         ///
1985         virtual boost::shared_ptr<ForkedProcess> clone() const
1986         {
1987                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1988         }
1989         ///
1990         int start()
1991         {
1992                 command_ = to_utf8(bformat(_("Auto-saving %1$s"), 
1993                                                  from_utf8(fname_.absFilename())));
1994                 return run(DontWait);
1995         }
1996 private:
1997         ///
1998         virtual int generateChild();
1999         ///
2000         Buffer const & buffer_;
2001         FileName fname_;
2002 };
2003
2004
2005 #if !defined (HAVE_FORK)
2006 # define fork() -1
2007 #endif
2008
2009 int AutoSaveBuffer::generateChild()
2010 {
2011         // tmp_ret will be located (usually) in /tmp
2012         // will that be a problem?
2013         pid_t const pid = fork();
2014         // If you want to debug the autosave
2015         // you should set pid to -1, and comment out the fork.
2016         if (pid == 0 || pid == -1) {
2017                 // pid = -1 signifies that lyx was unable
2018                 // to fork. But we will do the save
2019                 // anyway.
2020                 bool failed = false;
2021
2022                 FileName const tmp_ret(tempName(FileName(), "lyxauto"));
2023                 if (!tmp_ret.empty()) {
2024                         buffer_.writeFile(tmp_ret);
2025                         // assume successful write of tmp_ret
2026                         if (!rename(tmp_ret, fname_)) {
2027                                 failed = true;
2028                                 // most likely couldn't move between
2029                                 // filesystems unless write of tmp_ret
2030                                 // failed so remove tmp file (if it
2031                                 // exists)
2032                                 unlink(tmp_ret);
2033                         }
2034                 } else {
2035                         failed = true;
2036                 }
2037
2038                 if (failed) {
2039                         // failed to write/rename tmp_ret so try writing direct
2040                         if (!buffer_.writeFile(fname_)) {
2041                                 // It is dangerous to do this in the child,
2042                                 // but safe in the parent, so...
2043                                 if (pid == -1) // emit message signal.
2044                                         buffer_.message(_("Autosave failed!"));
2045                         }
2046                 }
2047                 if (pid == 0) { // we are the child so...
2048                         _exit(0);
2049                 }
2050         }
2051         return pid;
2052 }
2053
2054 } // namespace anon
2055
2056
2057 // Perfect target for a thread...
2058 void Buffer::autoSave() const
2059 {
2060         if (isBakClean() || isReadonly()) {
2061                 // We don't save now, but we'll try again later
2062                 resetAutosaveTimers();
2063                 return;
2064         }
2065
2066         // emit message signal.
2067         message(_("Autosaving current document..."));
2068
2069         // create autosave filename
2070         string fname = filePath();
2071         fname += '#';
2072         fname += onlyFilename(fileName());
2073         fname += '#';
2074
2075         AutoSaveBuffer autosave(*this, FileName(fname));
2076         autosave.start();
2077
2078         markBakClean();
2079         resetAutosaveTimers();
2080 }
2081
2082
2083 /** Write a buffer to a new file name and rename the buffer
2084     according to the new file name.
2085
2086     This function is e.g. used by menu callbacks and
2087     LFUN_BUFFER_WRITE_AS.
2088
2089     If 'newname' is empty (the default), the user is asked via a
2090     dialog for the buffer's new name and location.
2091
2092     If 'newname' is non-empty and has an absolute path, that is used.
2093     Otherwise the base directory of the buffer is used as the base
2094     for any relative path in 'newname'.
2095 */
2096
2097 bool Buffer::writeAs(string const & newname)
2098 {
2099         string fname = fileName();
2100         string const oldname = fname;
2101
2102         if (newname.empty()) {  /// No argument? Ask user through dialog
2103
2104                 // FIXME UNICODE
2105                 FileDialog fileDlg(_("Choose a filename to save document as"),
2106                                    LFUN_BUFFER_WRITE_AS,
2107                                    make_pair(_("Documents|#o#O"), 
2108                                              from_utf8(lyxrc.document_path)),
2109                                    make_pair(_("Templates|#T#t"), 
2110                                              from_utf8(lyxrc.template_path)));
2111
2112                 if (!support::isLyXFilename(fname))
2113                         fname += ".lyx";
2114
2115                 support::FileFilterList const filter(_("LyX Documents (*.lyx)"));
2116
2117                 FileDialog::Result result =
2118                         fileDlg.save(from_utf8(onlyPath(fname)),
2119                                      filter,
2120                                      from_utf8(onlyFilename(fname)));
2121
2122                 if (result.first == FileDialog::Later)
2123                         return false;
2124
2125                 fname = to_utf8(result.second);
2126
2127                 if (fname.empty())
2128                         return false;
2129
2130                 // Make sure the absolute filename ends with appropriate suffix
2131                 fname = makeAbsPath(fname).absFilename();
2132                 if (!support::isLyXFilename(fname))
2133                         fname += ".lyx";
2134
2135         } else 
2136                 fname = makeAbsPath(newname, onlyPath(oldname)).absFilename();
2137
2138         if (FileName(fname).exists()) {
2139                 docstring const file = makeDisplayPath(fname, 30);
2140                 docstring text = bformat(_("The document %1$s already "
2141                                            "exists.\n\nDo you want to "
2142                                            "overwrite that document?"), 
2143                                          file);
2144                 int const ret = Alert::prompt(_("Overwrite document?"),
2145                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
2146
2147                 if (ret == 1)
2148                         return false;
2149         }
2150
2151         // Ok, change the name of the buffer
2152         setFileName(fname);
2153         markDirty();
2154         bool unnamed = isUnnamed();
2155         setUnnamed(false);
2156         saveCheckSum(fname);
2157
2158         if (!menuWrite()) {
2159                 setFileName(oldname);
2160                 setUnnamed(unnamed);
2161                 saveCheckSum(oldname);
2162                 return false;
2163         }
2164
2165         removeAutosaveFile(oldname);
2166         return true;
2167 }
2168
2169
2170 bool Buffer::menuWrite()
2171 {
2172         if (save()) {
2173                 LyX::ref().session().lastFiles().add(FileName(fileName()));
2174                 return true;
2175         }
2176
2177         // FIXME: we don't tell the user *WHY* the save failed !!
2178
2179         docstring const file = makeDisplayPath(fileName(), 30);
2180
2181         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2182                                    "Do you want to rename the document and "
2183                                    "try again?"), file);
2184         int const ret = Alert::prompt(_("Rename and save?"),
2185                 text, 0, 1, _("&Rename"), _("&Cancel"));
2186
2187         if (ret != 0)
2188                 return false;
2189
2190         return writeAs();
2191 }
2192
2193
2194 } // namespace lyx