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