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