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