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