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