3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
24 #include "errorlist.h"
27 #include "funcrequest.h"
29 #include "insetiterator.h"
32 #include "LaTeXFeatures.h"
33 #include "LyXAction.h"
41 #include "output_docbook.h"
42 #include "output_latex.h"
43 #include "output_linuxdoc.h"
44 #include "paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "pariterator.h"
53 #include "insets/insetbibitem.h"
54 #include "insets/insetbibtex.h"
55 #include "insets/insetinclude.h"
56 #include "insets/insettext.h"
58 #include "mathed/math_macrotemplate.h"
59 #include "mathed/math_macrotable.h"
60 #include "mathed/math_support.h"
62 #include "frontends/Alert.h"
64 #include "graphics/Previews.h"
66 #include "support/FileInfo.h"
67 #include "support/filetools.h"
68 #include "support/gzstream.h"
69 #include "support/lyxlib.h"
70 #include "support/os.h"
71 #include "support/path.h"
72 #include "support/textutils.h"
73 #include "support/tostr.h"
75 #include <boost/bind.hpp>
87 using lyx::support::AddName;
88 using lyx::support::atoi;
89 using lyx::support::bformat;
90 using lyx::support::ChangeExtension;
91 using lyx::support::cmd_ret;
92 using lyx::support::createBufferTmpDir;
93 using lyx::support::destroyDir;
94 using lyx::support::FileInfo;
95 using lyx::support::FileInfo;
96 using lyx::support::getFormatFromContents;
97 using lyx::support::IsDirWriteable;
98 using lyx::support::IsFileWriteable;
99 using lyx::support::LibFileSearch;
100 using lyx::support::ltrim;
101 using lyx::support::MakeAbsPath;
102 using lyx::support::MakeDisplayPath;
103 using lyx::support::MakeLatexName;
104 using lyx::support::OnlyFilename;
105 using lyx::support::OnlyPath;
106 using lyx::support::Path;
107 using lyx::support::QuoteName;
108 using lyx::support::removeAutosaveFile;
109 using lyx::support::rename;
110 using lyx::support::RunCommand;
111 using lyx::support::split;
112 using lyx::support::strToInt;
113 using lyx::support::subst;
114 using lyx::support::tempName;
115 using lyx::support::trim;
117 namespace os = lyx::support::os;
121 using std::make_pair;
127 using std::ostringstream;
135 // all these externs should eventually be removed.
136 extern BufferList bufferlist;
140 const int LYX_FORMAT = 237;
145 typedef std::map<string, bool> DepClean;
149 Impl(Buffer & parent, string const & file, bool readonly);
151 limited_stack<Undo> undostack;
152 limited_stack<Undo> redostack;
158 /// need to regenerate .tex?
162 mutable bool lyx_clean;
164 /// is autosave needed?
165 mutable bool bak_clean;
167 /// is this a unnamed file (New...)?
173 /// name of the file the buffer is associated with.
176 /// The path to the document file.
179 boost::scoped_ptr<Messages> messages;
181 /** Set to true only when the file is fully loaded.
182 * Used to prevent the premature generation of previews
183 * and by the citation inset.
185 bool file_fully_loaded;
187 /// our LyXText that should be wrapped in an InsetText
195 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
196 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
197 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
200 lyxvc.buffer(&parent);
201 temppath = createBufferTmpDir();
202 // FIXME: And now do something if temppath == string(), because we
203 // assume from now on that temppath points to a valid temp dir.
204 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
208 Buffer::Buffer(string const & file, bool ronly)
209 : pimpl_(new Impl(*this, file, ronly))
211 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
217 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
218 // here the buffer should take care that it is
219 // saved properly, before it goes into the void.
223 if (!temppath().empty() && destroyDir(temppath()) != 0) {
224 Alert::warning(_("Could not remove temporary directory"),
225 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
228 // Remove any previewed LaTeX snippets associated with this buffer.
229 lyx::graphics::Previews::get().removeLoader(*this);
233 LyXText & Buffer::text() const
235 return const_cast<LyXText &>(pimpl_->inset.text_);
239 InsetBase & Buffer::inset() const
241 return const_cast<InsetText &>(pimpl_->inset);
245 limited_stack<Undo> & Buffer::undostack()
247 return pimpl_->undostack;
251 limited_stack<Undo> const & Buffer::undostack() const
253 return pimpl_->undostack;
257 limited_stack<Undo> & Buffer::redostack()
259 return pimpl_->redostack;
263 limited_stack<Undo> const & Buffer::redostack() const
265 return pimpl_->redostack;
269 BufferParams & Buffer::params()
271 return pimpl_->params;
275 BufferParams const & Buffer::params() const
277 return pimpl_->params;
281 ParagraphList & Buffer::paragraphs()
283 return text().paragraphs();
287 ParagraphList const & Buffer::paragraphs() const
289 return text().paragraphs();
293 LyXVC & Buffer::lyxvc()
295 return pimpl_->lyxvc;
299 LyXVC const & Buffer::lyxvc() const
301 return pimpl_->lyxvc;
305 string const & Buffer::temppath() const
307 return pimpl_->temppath;
311 TexRow & Buffer::texrow()
313 return pimpl_->texrow;
317 TexRow const & Buffer::texrow() const
319 return pimpl_->texrow;
323 string const Buffer::getLatexName(bool no_path) const
325 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
326 return no_path ? OnlyFilename(name) : name;
330 pair<Buffer::LogType, string> const Buffer::getLogName() const
332 string const filename = getLatexName(false);
334 if (filename.empty())
335 return make_pair(Buffer::latexlog, string());
337 string const path = temppath();
339 string const fname = AddName(path,
340 OnlyFilename(ChangeExtension(filename,
343 AddName(path, OnlyFilename(
344 ChangeExtension(filename,
345 formats.extension("literate") + ".out")));
347 // If no Latex log or Build log is newer, show Build log
349 FileInfo const f_fi(fname);
350 FileInfo const b_fi(bname);
353 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
354 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
355 return make_pair(Buffer::buildlog, bname);
357 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
358 return make_pair(Buffer::latexlog, fname);
362 void Buffer::setReadonly(bool flag)
364 if (pimpl_->read_only != flag) {
365 pimpl_->read_only = flag;
371 void Buffer::setFileName(string const & newfile)
373 pimpl_->filename = MakeAbsPath(newfile);
374 pimpl_->filepath = OnlyPath(pimpl_->filename);
375 setReadonly(IsFileWriteable(pimpl_->filename) == 0);
380 // We'll remove this later. (Lgb)
383 void unknownClass(string const & unknown)
385 Alert::warning(_("Unknown document class"),
386 bformat(_("Using the default document class, because the "
387 "class %1$s is unknown."), unknown));
393 int Buffer::readHeader(LyXLex & lex)
395 int unknown_tokens = 0;
397 int begin_header_line = -1;
401 string const token = lex.getString();
406 if (token == "\\end_header")
410 if (token == "\\begin_header") {
411 begin_header_line = line;
415 lyxerr[Debug::PARSER] << "Handling header token: `"
416 << token << '\'' << endl;
418 string unknown = params().readToken(lex, token);
419 if (!unknown.empty()) {
420 if (unknown[0] != '\\' and token == "\\textclass") {
421 unknownClass(unknown);
424 string const s = bformat(_("Unknown token: "
428 error(ErrorItem(_("Header error"), s,
433 if (begin_header_line) {
434 string const s = _("\\begin_header is missing");
435 error(ErrorItem(_("Header error"), s, -1, 0, 0));
437 return unknown_tokens;
442 // changed to be public and have one parameter
443 // Returns false if "\end_document" is not read (Asger)
444 bool Buffer::readDocument(LyXLex & lex)
447 string const token = lex.getString();
448 if (token != "\\begin_document") {
449 string const s = _("\\begin_document is missing");
450 error(ErrorItem(_("Header error"), s, -1, 0, 0));
453 if (paragraphs().empty()) {
455 if (!params().getLyXTextClass().load()) {
456 string theclass = params().getLyXTextClass().name();
457 Alert::error(_("Can't load document class"), bformat(
458 "Using the default document class, because the "
459 " class %1$s could not be loaded.", theclass));
460 params().textclass = 0;
463 // We don't want to adopt the parameters from the
464 // document we insert, so read them into a temporary buffer
465 // and then discard it
467 Buffer tmpbuf("", false);
468 tmpbuf.readHeader(lex);
471 return text().read(*this, lex);
475 // needed to insert the selection
476 void Buffer::insertStringAsLines(ParagraphList & pars,
477 par_type & par, pos_type & pos,
478 LyXFont const & fn, string const & str)
480 LyXLayout_ptr const & layout = pars[par].layout();
484 pars[par].checkInsertChar(font);
485 // insert the string, don't insert doublespace
486 bool space_inserted = true;
487 bool autobreakrows = pars[par].autoBreakRows();
488 for (string::const_iterator cit = str.begin();
489 cit != str.end(); ++cit) {
491 if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
492 breakParagraph(params(), paragraphs(), par, pos,
493 layout->isEnvironment());
496 space_inserted = true;
500 // do not insert consecutive spaces if !free_spacing
501 } else if ((*cit == ' ' || *cit == '\t') &&
502 space_inserted && !pars[par].isFreeSpacing()) {
504 } else if (*cit == '\t') {
505 if (!pars[par].isFreeSpacing()) {
506 // tabs are like spaces here
507 pars[par].insertChar(pos, ' ', font);
509 space_inserted = true;
511 const pos_type n = 8 - pos % 8;
512 for (pos_type i = 0; i < n; ++i) {
513 pars[par].insertChar(pos, ' ', font);
516 space_inserted = true;
518 } else if (!IsPrintable(*cit)) {
519 // Ignore unprintables
522 // just insert the character
523 pars[par].insertChar(pos, *cit, font);
525 space_inserted = (*cit == ' ');
532 bool Buffer::readFile(string const & filename)
534 // Check if the file is compressed.
535 string const format = getFormatFromContents(filename);
536 if (format == "gzip" || format == "zip" || format == "compress") {
537 params().compressed = true;
540 // remove dummy empty par
541 paragraphs().clear();
542 bool ret = readFile(filename, paragraphs().size());
544 // After we have read a file, we must ensure that the buffer
545 // language is set and used in the gui.
546 // If you know of a better place to put this, please tell me. (Lgb)
547 updateDocLang(params().language);
553 bool Buffer::readFile(string const & filename, par_type pit)
556 lex.setFile(filename);
557 return readFile(lex, filename, pit);
561 bool Buffer::fully_loaded() const
563 return pimpl_->file_fully_loaded;
567 void Buffer::fully_loaded(bool value)
569 pimpl_->file_fully_loaded = value;
573 bool Buffer::readFile(LyXLex & lex, string const & filename, par_type pit)
575 BOOST_ASSERT(!filename.empty());
578 Alert::error(_("Document could not be read"),
579 bformat(_("%1$s could not be read."), filename));
584 string const token(lex.getString());
587 Alert::error(_("Document could not be read"),
588 bformat(_("%1$s could not be read."), filename));
592 // the first token _must_ be...
593 if (token != "\\lyxformat") {
594 lyxerr << "Token: " << token << endl;
596 Alert::error(_("Document format failure"),
597 bformat(_("%1$s is not a LyX document."),
603 string tmp_format = lex.getString();
604 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
605 // if present remove ".," from string.
606 string::size_type dot = tmp_format.find_first_of(".,");
607 //lyxerr << " dot found at " << dot << endl;
608 if (dot != string::npos)
609 tmp_format.erase(dot, 1);
610 int file_format = strToInt(tmp_format);
611 //lyxerr << "format: " << file_format << endl;
613 if (file_format != LYX_FORMAT) {
614 string const tmpfile = tempName();
615 if (tmpfile.empty()) {
616 Alert::error(_("Conversion failed"),
617 bformat(_("%1$s is from an earlier"
618 " version of LyX, but a temporary"
619 " file for converting it could"
624 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
625 if (command.empty()) {
626 Alert::error(_("Conversion script not found"),
627 bformat(_("%1$s is from an earlier"
628 " version of LyX, but the"
629 " conversion script lyx2lyx"
630 " could not be found."),
636 + " -o " + tmpfile + ' '
637 + QuoteName(filename);
638 lyxerr[Debug::INFO] << "Running '"
641 cmd_ret const ret = RunCommand(command);
642 if (ret.first != 0) {
643 Alert::error(_("Conversion script failed"),
644 bformat(_("%1$s is from an earlier version"
645 " of LyX, but the lyx2lyx script"
646 " failed to convert it."),
650 bool ret = readFile(tmpfile, pit);
651 // Do stuff with tmpfile name and buffer name here.
657 if (readDocument(lex)) {
658 Alert::error(_("Document format failure"),
659 bformat(_("%1$s ended unexpectedly, which means"
660 " that it is probably corrupted."),
664 //lyxerr << "removing " << MacroTable::localMacros().size()
665 // << " temporary macro entries" << endl;
666 //MacroTable::localMacros().clear();
667 params().setPaperStuff();
669 pimpl_->file_fully_loaded = true;
674 // Should probably be moved to somewhere else: BufferView? LyXView?
675 bool Buffer::save() const
677 // We don't need autosaves in the immediate future. (Asger)
678 resetAutosaveTimers();
682 if (lyxrc.make_backup) {
683 s = fileName() + '~';
684 if (!lyxrc.backupdir_path.empty())
685 s = AddName(lyxrc.backupdir_path,
686 subst(os::slashify_path(s),'/','!'));
688 // Rename is the wrong way of making a backup,
689 // this is the correct way.
690 /* truss cp fil fil2:
691 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
692 stat("LyXVC.lyx", 0xEFFFF688) = 0
693 open("LyXVC.lyx", O_RDONLY) = 3
694 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
695 fstat(4, 0xEFFFF508) = 0
696 fstat(3, 0xEFFFF508) = 0
697 read(3, " # T h i s f i l e w".., 8192) = 5579
698 write(4, " # T h i s f i l e w".., 5579) = 5579
699 read(3, 0xEFFFD4A0, 8192) = 0
702 chmod("LyXVC3.lyx", 0100644) = 0
703 lseek(0, 0, SEEK_CUR) = 46440
707 // Should probably have some more error checking here.
708 // Doing it this way, also makes the inodes stay the same.
709 // This is still not a very good solution, in particular we
710 // might loose the owner of the backup.
711 FileInfo finfo(fileName());
713 mode_t fmode = finfo.getMode();
714 struct utimbuf times = {
715 finfo.getAccessTime(),
716 finfo.getModificationTime() };
718 ifstream ifs(fileName().c_str());
719 ofstream ofs(s.c_str(), ios::out|ios::trunc);
724 ::chmod(s.c_str(), fmode);
726 if (::utime(s.c_str(), ×)) {
727 lyxerr << "utime error." << endl;
730 lyxerr << "LyX was not able to make "
731 "backup copy. Beware." << endl;
736 if (writeFile(fileName())) {
738 removeAutosaveFile(fileName());
740 // Saving failed, so backup is not backup
741 if (lyxrc.make_backup)
742 rename(s, fileName());
749 bool Buffer::writeFile(string const & fname) const
751 if (pimpl_->read_only && fname == fileName())
754 FileInfo finfo(fname);
755 if (finfo.exist() && !finfo.writable())
760 if (params().compressed) {
761 gz::ogzstream ofs(fname.c_str());
765 retval = do_writeFile(ofs);
768 ofstream ofs(fname.c_str());
772 retval = do_writeFile(ofs);
779 bool Buffer::do_writeFile(ostream & ofs) const
782 // Use the standard "C" locale for file output.
783 ofs.imbue(std::locale::classic());
786 // The top of the file should not be written by params().
788 // write out a comment in the top of the file
789 ofs << "#LyX " << lyx_version
790 << " created this file. For more info see http://www.lyx.org/\n"
791 << "\\lyxformat " << LYX_FORMAT << "\n"
792 << "\\begin_document\n";
794 // now write out the buffer parameters.
795 ofs << "\\begin_header\n";
796 params().writeFile(ofs);
797 ofs << "\\end_header\n";
800 ofs << "\n\\begin_body\n";
801 text().write(*this, ofs);
802 ofs << "\n\\end_body\n";
804 // Write marker that shows file is complete
805 ofs << "\\end_document" << endl;
807 // Shouldn't really be needed....
810 // how to check if close went ok?
811 // Following is an attempt... (BE 20001011)
813 // good() returns false if any error occured, including some
815 // bad() returns true if something bad happened in the buffer,
816 // which should include file system full errors.
821 lyxerr << "File was not closed properly." << endl;
828 void Buffer::makeLaTeXFile(string const & fname,
829 string const & original_path,
830 OutputParams const & runparams,
831 bool output_preamble, bool output_body)
833 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
836 if (!openFileWrite(ofs, fname))
839 makeLaTeXFile(ofs, original_path,
840 runparams, output_preamble, output_body);
844 lyxerr << "File '" << fname << "' was not closed properly." << endl;
848 void Buffer::makeLaTeXFile(ostream & os,
849 string const & original_path,
850 OutputParams const & runparams_in,
851 bool output_preamble, bool output_body)
853 OutputParams runparams = runparams_in;
855 // validate the buffer.
856 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
857 LaTeXFeatures features(*this, params(), runparams.nice);
859 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
863 // The starting paragraph of the coming rows is the
864 // first paragraph of the document. (Asger)
865 texrow().start(paragraphs().begin()->id(), 0);
867 if (output_preamble && runparams.nice) {
868 os << "%% LyX " << lyx_version << " created this file. "
869 "For more info, see http://www.lyx.org/.\n"
870 "%% Do not edit unless you really know what "
875 lyxerr[Debug::INFO] << "lyx header finished" << endl;
876 // There are a few differences between nice LaTeX and usual files:
877 // usual is \batchmode and has a
878 // special input@path to allow the including of figures
879 // with either \input or \includegraphics (what figinsets do).
880 // input@path is set when the actual parameter
881 // original_path is set. This is done for usual tex-file, but not
882 // for nice-latex-file. (Matthias 250696)
883 // Note that input@path is only needed for something the user does
884 // in the preamble, included .tex files or ERT, files included by
885 // LyX work without it.
886 if (output_preamble) {
887 if (!runparams.nice) {
888 // code for usual, NOT nice-latex-file
889 os << "\\batchmode\n"; // changed
893 if (!original_path.empty()) {
894 string inputpath = os::external_path(original_path);
895 subst(inputpath, "~", "\\string~");
896 os << "\\makeatletter\n"
897 << "\\def\\input@path{{"
898 << inputpath << "/}}\n"
899 << "\\makeatother\n";
905 // Write the preamble
906 runparams.use_babel = params().writeLaTeX(os, features, texrow());
912 os << "\\begin{document}\n";
915 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
917 if (!lyxrc.language_auto_begin) {
918 os << subst(lyxrc.language_command_begin, "$$lang",
919 params().language->babel())
924 // if we are doing a real file with body, even if this is the
925 // child of some other buffer, let's cut the link here.
926 // This happens for example if only a child document is printed.
927 string save_parentname;
928 if (output_preamble) {
929 save_parentname = params().parentname;
930 params().parentname.erase();
934 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
936 // Restore the parenthood if needed
938 params().parentname = save_parentname;
940 // add this just in case after all the paragraphs
944 if (!lyxrc.language_auto_end) {
945 os << subst(lyxrc.language_command_end, "$$lang",
946 params().language->babel())
951 if (output_preamble) {
952 os << "\\end{document}\n";
955 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
957 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
961 // Just to be sure. (Asger)
964 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
965 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
970 bool Buffer::isLatex() const
972 return params().getLyXTextClass().outputType() == LATEX;
976 bool Buffer::isLinuxDoc() const
978 return params().getLyXTextClass().outputType() == LINUXDOC;
982 bool Buffer::isLiterate() const
984 return params().getLyXTextClass().outputType() == LITERATE;
988 bool Buffer::isDocBook() const
990 return params().getLyXTextClass().outputType() == DOCBOOK;
994 bool Buffer::isSGML() const
996 LyXTextClass const & tclass = params().getLyXTextClass();
998 return tclass.outputType() == LINUXDOC ||
999 tclass.outputType() == DOCBOOK;
1003 void Buffer::makeLinuxDocFile(string const & fname,
1004 OutputParams const & runparams,
1008 if (!openFileWrite(ofs, fname))
1011 LaTeXFeatures features(*this, params(), runparams.nice);
1016 LyXTextClass const & tclass = params().getLyXTextClass();
1018 string top_element = tclass.latexname();
1021 ofs << tclass.class_header();
1023 string preamble = params().preamble;
1024 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1026 preamble += features.getIncludedFiles(name);
1027 preamble += features.getLyXSGMLEntities();
1029 if (!preamble.empty()) {
1030 ofs << " [ " << preamble << " ]";
1034 if (params().options.empty())
1035 sgml::openTag(ofs, top_element);
1037 string top = top_element;
1039 top += params().options;
1040 sgml::openTag(ofs, top);
1044 ofs << "<!-- LyX " << lyx_version
1045 << " created this file. For more info see http://www.lyx.org/"
1048 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1052 sgml::closeTag(ofs, top_element);
1057 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1061 void Buffer::makeDocBookFile(string const & fname,
1062 OutputParams const & runparams,
1066 if (!openFileWrite(ofs, fname))
1069 LaTeXFeatures features(*this, params(), runparams.nice);
1074 LyXTextClass const & tclass = params().getLyXTextClass();
1075 string top_element = tclass.latexname();
1078 if (runparams.flavor == OutputParams::XML)
1079 ofs << "<?xml version=\"1.0\" encoding=\""
1080 << params().language->encoding()->Name() << "\"?>\n";
1082 ofs << "<!DOCTYPE " << top_element << " ";
1084 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1085 else if (runparams.flavor == OutputParams::XML)
1086 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1087 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1089 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1091 string preamble = params().preamble;
1092 if (runparams.flavor != OutputParams::XML ) {
1093 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1094 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1095 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1096 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1099 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1101 preamble += features.getIncludedFiles(name);
1102 preamble += features.getLyXSGMLEntities();
1104 if (!preamble.empty()) {
1105 ofs << "\n [ " << preamble << " ]";
1110 string top = top_element;
1112 if (runparams.flavor == OutputParams::XML)
1113 top += params().language->code();
1115 top += params().language->code().substr(0,2);
1118 if (!params().options.empty()) {
1120 top += params().options;
1123 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1124 << " file was created by LyX " << lyx_version
1125 << "\n See http://www.lyx.org/ for more information -->\n";
1127 params().getLyXTextClass().counters().reset();
1129 sgml::openTag(ofs, top);
1131 docbookParagraphs(paragraphs(), *this, ofs, runparams);
1132 sgml::closeTag(ofs, top_element);
1136 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1140 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1141 // Other flags: -wall -v0 -x
1142 int Buffer::runChktex()
1146 // get LaTeX-Filename
1147 string const name = getLatexName();
1148 string const path = temppath();
1149 string const org_path = filePath();
1151 Path p(path); // path to LaTeX file
1152 message(_("Running chktex..."));
1154 // Generate the LaTeX file if neccessary
1155 OutputParams runparams;
1156 runparams.flavor = OutputParams::LATEX;
1157 runparams.nice = false;
1158 makeLaTeXFile(name, org_path, runparams);
1161 Chktex chktex(lyxrc.chktex_command, name, filePath());
1162 int res = chktex.run(terr); // run chktex
1165 Alert::error(_("chktex failure"),
1166 _("Could not run chktex successfully."));
1167 } else if (res > 0) {
1168 // Insert all errors as errors boxes
1169 bufferErrors(*this, terr);
1178 void Buffer::validate(LaTeXFeatures & features) const
1180 LyXTextClass const & tclass = params().getLyXTextClass();
1182 if (params().tracking_changes) {
1183 features.require("dvipost");
1184 features.require("color");
1187 // AMS Style is at document level
1188 if (params().use_amsmath == BufferParams::AMS_ON
1189 || tclass.provides(LyXTextClass::amsmath))
1190 features.require("amsmath");
1192 for_each(paragraphs().begin(), paragraphs().end(),
1193 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1195 // the bullet shapes are buffer level not paragraph level
1196 // so they are tested here
1197 for (int i = 0; i < 4; ++i) {
1198 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1199 int const font = params().user_defined_bullet(i).getFont();
1201 int const c = params()
1202 .user_defined_bullet(i)
1209 features.require("latexsym");
1211 } else if (font == 1) {
1212 features.require("amssymb");
1213 } else if ((font >= 2 && font <= 5)) {
1214 features.require("pifont");
1219 if (lyxerr.debugging(Debug::LATEX)) {
1220 features.showStruct();
1225 void Buffer::getLabelList(std::vector<string> & list) const
1227 /// if this is a child document and the parent is already loaded
1228 /// Use the parent's list instead [ale990407]
1229 Buffer const * tmp = getMasterBuffer();
1231 lyxerr << "getMasterBuffer() failed!" << endl;
1235 tmp->getLabelList(list);
1239 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1240 it.nextInset()->getLabelList(*this, list);
1244 // This is also a buffer property (ale)
1245 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys)
1248 /// if this is a child document and the parent is already loaded
1249 /// use the parent's list instead [ale990412]
1250 Buffer const * tmp = getMasterBuffer();
1253 tmp->fillWithBibKeys(keys);
1257 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1258 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1259 InsetBibtex const & inset =
1260 dynamic_cast<InsetBibtex const &>(*it);
1261 inset.fillWithBibKeys(*this, keys);
1262 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1263 InsetInclude const & inset =
1264 dynamic_cast<InsetInclude const &>(*it);
1265 inset.fillWithBibKeys(*this, keys);
1266 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1267 InsetBibitem const & inset =
1268 dynamic_cast<InsetBibitem const &>(*it);
1269 string const key = inset.getContents();
1270 string const opt = inset.getOptions();
1271 string const ref; // = pit->asString(this, false);
1272 string const info = opt + "TheBibliographyRef" + ref;
1273 keys.push_back(pair<string, string>(key, info));
1279 bool Buffer::isDepClean(string const & name) const
1281 DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1282 if (it == pimpl_->dep_clean.end())
1288 void Buffer::markDepClean(string const & name)
1290 pimpl_->dep_clean[name] = true;
1294 bool Buffer::dispatch(string const & command, bool * result)
1296 return dispatch(lyxaction.lookupFunc(command), result);
1300 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1302 bool dispatched = true;
1304 switch (func.action) {
1306 bool const tmp = Exporter::Export(this, func.argument, false);
1319 void Buffer::changeLanguage(Language const * from, Language const * to)
1321 lyxerr << "Changing Language!" << endl;
1323 // Take care of l10n/i18n
1326 for_each(par_iterator_begin(),
1328 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1332 void Buffer::updateDocLang(Language const * nlang)
1334 pimpl_->messages.reset(new Messages(nlang->code()));
1338 bool Buffer::isMultiLingual() const
1340 ParConstIterator end = par_iterator_end();
1341 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1342 if (it->isMultiLingual(params()))
1349 ParIterator Buffer::getParFromID(int id) const
1351 ParConstIterator it = par_iterator_begin();
1352 ParConstIterator end = par_iterator_end();
1355 // John says this is called with id == -1 from undo
1356 lyxerr << "getParFromID(), id: " << id << endl;
1360 for (; it != end; ++it)
1368 bool Buffer::hasParWithID(int id) const
1370 ParConstIterator it = getParFromID(id);
1371 return it != par_iterator_end();
1375 ParIterator Buffer::par_iterator_begin()
1377 return ::par_iterator_begin(inset());
1381 ParIterator Buffer::par_iterator_end()
1383 return ::par_iterator_end(inset());
1387 ParConstIterator Buffer::par_iterator_begin() const
1389 return ::par_const_iterator_begin(inset());
1393 ParConstIterator Buffer::par_iterator_end() const
1395 return ::par_const_iterator_end(inset());
1399 Language const * Buffer::getLanguage() const
1401 return params().language;
1405 string const Buffer::B_(string const & l10n) const
1407 if (pimpl_->messages.get()) {
1408 return pimpl_->messages->get(l10n);
1415 bool Buffer::isClean() const
1417 return pimpl_->lyx_clean;
1421 bool Buffer::isBakClean() const
1423 return pimpl_->bak_clean;
1427 void Buffer::markClean() const
1429 if (!pimpl_->lyx_clean) {
1430 pimpl_->lyx_clean = true;
1433 // if the .lyx file has been saved, we don't need an
1435 pimpl_->bak_clean = true;
1439 void Buffer::markBakClean()
1441 pimpl_->bak_clean = true;
1445 void Buffer::setUnnamed(bool flag)
1447 pimpl_->unnamed = flag;
1451 bool Buffer::isUnnamed() const
1453 return pimpl_->unnamed;
1457 void Buffer::markDirty()
1459 if (pimpl_->lyx_clean) {
1460 pimpl_->lyx_clean = false;
1463 pimpl_->bak_clean = false;
1465 DepClean::iterator it = pimpl_->dep_clean.begin();
1466 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1468 for (; it != end; ++it) {
1474 string const & Buffer::fileName() const
1476 return pimpl_->filename;
1480 string const & Buffer::filePath() const
1482 return pimpl_->filepath;
1486 bool Buffer::isReadonly() const
1488 return pimpl_->read_only;
1492 void Buffer::setParentName(string const & name)
1494 params().parentname = name;
1498 Buffer const * Buffer::getMasterBuffer() const
1500 if (!params().parentname.empty()
1501 && bufferlist.exists(params().parentname)) {
1502 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1504 return buf->getMasterBuffer();
1511 MacroData const & Buffer::getMacro(std::string const & name) const
1513 return pimpl_->macros.get(name);
1517 bool Buffer::hasMacro(string const & name) const
1519 return pimpl_->macros.has(name);
1523 void Buffer::insertMacro(string const & name, MacroData const & data)
1525 MacroTable::globalMacros().insert(name, data);
1526 pimpl_->macros.insert(name, data);
1530 void Buffer::buildMacros()
1532 // Start with global table.
1533 pimpl_->macros = MacroTable::globalMacros();
1536 ParagraphList & pars = text().paragraphs();
1537 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1538 //lyxerr << "searching main par " << i
1539 // << " for macro definitions" << std::endl;
1540 InsetList::iterator it = pars[i].insetlist.begin();
1541 InsetList::iterator end = pars[i].insetlist.end();
1542 for ( ; it != end; ++it) {
1543 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1544 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1545 MathMacroTemplate & mac
1546 = static_cast<MathMacroTemplate &>(*it->inset);
1547 insertMacro(mac.name(), mac.asMacroData());