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