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