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 "BranchList.h"
17 #include "buffer_funcs.h"
18 #include "bufferlist.h"
19 #include "bufferparams.h"
25 #include "errorlist.h"
28 #include "funcrequest.h"
30 #include "insetiterator.h"
33 #include "LaTeXFeatures.h"
34 #include "LyXAction.h"
42 #include "output_docbook.h"
43 #include "output_latex.h"
44 #include "output_linuxdoc.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "pariterator.h"
54 #include "insets/insetbibitem.h"
55 #include "insets/insetbibtex.h"
56 #include "insets/insetinclude.h"
57 #include "insets/insettext.h"
59 #include "mathed/math_macrotemplate.h"
60 #include "mathed/math_macrotable.h"
61 #include "mathed/math_support.h"
63 #include "frontends/Alert.h"
65 #include "graphics/Previews.h"
67 #include "support/filetools.h"
68 #include "support/fs_extras.h"
69 #ifdef USE_COMPRESSION
70 # include "support/gzstream.h"
72 #include "support/lyxlib.h"
73 #include "support/os.h"
74 #include "support/path.h"
75 #include "support/textutils.h"
76 #include "support/convert.h"
78 #include <boost/bind.hpp>
79 #include <boost/filesystem/operations.hpp>
81 #if defined (HAVE_UTIME_H)
83 #elif defined (HAVE_SYS_UTIME_H)
84 # include <sys/utime.h>
96 using lyx::support::AddName;
97 using lyx::support::bformat;
98 using lyx::support::ChangeExtension;
99 using lyx::support::cmd_ret;
100 using lyx::support::createBufferTmpDir;
101 using lyx::support::destroyDir;
102 using lyx::support::getFormatFromContents;
103 using lyx::support::IsDirWriteable;
104 using lyx::support::LibFileSearch;
105 using lyx::support::latex_path;
106 using lyx::support::ltrim;
107 using lyx::support::MakeAbsPath;
108 using lyx::support::MakeDisplayPath;
109 using lyx::support::MakeLatexName;
110 using lyx::support::OnlyFilename;
111 using lyx::support::OnlyPath;
112 using lyx::support::Path;
113 using lyx::support::QuoteName;
114 using lyx::support::removeAutosaveFile;
115 using lyx::support::rename;
116 using lyx::support::RunCommand;
117 using lyx::support::split;
118 using lyx::support::subst;
119 using lyx::support::tempName;
120 using lyx::support::trim;
122 namespace os = lyx::support::os;
123 namespace fs = boost::filesystem;
127 using std::make_pair;
133 using std::ostringstream;
141 // all these externs should eventually be removed.
142 extern BufferList bufferlist;
146 int const LYX_FORMAT = 242;
151 typedef std::map<string, bool> DepClean;
156 Impl(Buffer & parent, string const & file, bool readonly);
158 limited_stack<Undo> undostack;
159 limited_stack<Undo> redostack;
165 /// need to regenerate .tex?
169 mutable bool lyx_clean;
171 /// is autosave needed?
172 mutable bool bak_clean;
174 /// is this a unnamed file (New...)?
180 /// name of the file the buffer is associated with.
183 /// The path to the document file.
186 boost::scoped_ptr<Messages> messages;
188 /** Set to true only when the file is fully loaded.
189 * Used to prevent the premature generation of previews
190 * and by the citation inset.
192 bool file_fully_loaded;
194 /// our LyXText that should be wrapped in an InsetText
202 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
203 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
204 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
207 inset.setAutoBreakRows(true);
208 lyxvc.buffer(&parent);
209 temppath = createBufferTmpDir();
210 // FIXME: And now do something if temppath == string(), because we
211 // assume from now on that temppath points to a valid temp dir.
212 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
216 Buffer::Buffer(string const & file, bool readonly)
217 : pimpl_(new Impl(*this, file, readonly))
219 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
225 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
226 // here the buffer should take care that it is
227 // saved properly, before it goes into the void.
231 if (!temppath().empty() && !destroyDir(temppath())) {
232 Alert::warning(_("Could not remove temporary directory"),
233 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
236 // Remove any previewed LaTeX snippets associated with this buffer.
237 lyx::graphics::Previews::get().removeLoader(*this);
241 LyXText & Buffer::text() const
243 return const_cast<LyXText &>(pimpl_->inset.text_);
247 InsetBase & Buffer::inset() const
249 return const_cast<InsetText &>(pimpl_->inset);
253 limited_stack<Undo> & Buffer::undostack()
255 return pimpl_->undostack;
259 limited_stack<Undo> const & Buffer::undostack() const
261 return pimpl_->undostack;
265 limited_stack<Undo> & Buffer::redostack()
267 return pimpl_->redostack;
271 limited_stack<Undo> const & Buffer::redostack() const
273 return pimpl_->redostack;
277 BufferParams & Buffer::params()
279 return pimpl_->params;
283 BufferParams const & Buffer::params() const
285 return pimpl_->params;
289 ParagraphList & Buffer::paragraphs()
291 return text().paragraphs();
295 ParagraphList const & Buffer::paragraphs() const
297 return text().paragraphs();
301 LyXVC & Buffer::lyxvc()
303 return pimpl_->lyxvc;
307 LyXVC const & Buffer::lyxvc() const
309 return pimpl_->lyxvc;
313 string const & Buffer::temppath() const
315 return pimpl_->temppath;
319 TexRow & Buffer::texrow()
321 return pimpl_->texrow;
325 TexRow const & Buffer::texrow() const
327 return pimpl_->texrow;
331 string const Buffer::getLatexName(bool const no_path) const
333 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
334 return no_path ? OnlyFilename(name) : name;
338 pair<Buffer::LogType, string> const Buffer::getLogName() const
340 string const filename = getLatexName(false);
342 if (filename.empty())
343 return make_pair(Buffer::latexlog, string());
345 string const path = temppath();
347 string const fname = AddName(path,
348 OnlyFilename(ChangeExtension(filename,
351 AddName(path, OnlyFilename(
352 ChangeExtension(filename,
353 formats.extension("literate") + ".out")));
355 // If no Latex log or Build log is newer, show Build log
357 if (fs::exists(bname) &&
358 (!fs::exists(fname) || fs::last_write_time(fname) < fs::last_write_time(bname))) {
359 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
360 return make_pair(Buffer::buildlog, bname);
362 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
363 return make_pair(Buffer::latexlog, fname);
367 void Buffer::setReadonly(bool const flag)
369 if (pimpl_->read_only != flag) {
370 pimpl_->read_only = flag;
376 void Buffer::setFileName(string const & newfile)
378 pimpl_->filename = MakeAbsPath(newfile);
379 pimpl_->filepath = OnlyPath(pimpl_->filename);
380 setReadonly(fs::is_readonly(pimpl_->filename));
385 // We'll remove this later. (Lgb)
388 void unknownClass(string const & unknown)
390 Alert::warning(_("Unknown document class"),
391 bformat(_("Using the default document class, because the "
392 "class %1$s is unknown."), unknown));
398 int Buffer::readHeader(LyXLex & lex)
400 int unknown_tokens = 0;
402 int begin_header_line = -1;
404 // Initialize parameters that may be/go lacking in header:
405 params().branchlist().clear();
406 params().options.erase();
407 params().float_placement.erase();
408 params().paperwidth.erase();
409 params().paperheight.erase();
410 params().leftmargin.erase();
411 params().rightmargin.erase();
412 params().topmargin.erase();
413 params().bottommargin.erase();
414 params().headheight.erase();
415 params().headsep.erase();
416 params().footskip.erase();
420 string const token = lex.getString();
425 if (token == "\\end_header")
429 if (token == "\\begin_header") {
430 begin_header_line = line;
434 lyxerr[Debug::PARSER] << "Handling header token: `"
435 << token << '\'' << endl;
437 string unknown = params().readToken(lex, token);
438 if (!unknown.empty()) {
439 if (unknown[0] != '\\' && token == "\\textclass") {
440 unknownClass(unknown);
443 string const s = bformat(_("Unknown token: "
447 error(ErrorItem(_("Header error"), s,
452 if (begin_header_line) {
453 string const s = _("\\begin_header is missing");
454 error(ErrorItem(_("Header error"), s, -1, 0, 0));
456 return unknown_tokens;
461 // changed to be public and have one parameter
462 // Returns false if "\end_document" is not read (Asger)
463 bool Buffer::readDocument(LyXLex & lex)
466 string const token = lex.getString();
467 if (token != "\\begin_document") {
468 string const s = _("\\begin_document is missing");
469 error(ErrorItem(_("Header error"), s, -1, 0, 0));
472 if (paragraphs().empty()) {
474 if (!params().getLyXTextClass().load()) {
475 string theclass = params().getLyXTextClass().name();
476 Alert::error(_("Can't load document class"), bformat(
477 "Using the default document class, because the "
478 " class %1$s could not be loaded.", theclass));
479 params().textclass = 0;
482 // We don't want to adopt the parameters from the
483 // document we insert, so read them into a temporary buffer
484 // and then discard it
486 Buffer tmpbuf("", false);
487 tmpbuf.readHeader(lex);
490 return text().read(*this, lex);
494 // needed to insert the selection
495 void Buffer::insertStringAsLines(ParagraphList & pars,
496 pit_type & pit, pos_type & pos,
497 LyXFont const & fn, string const & str, bool autobreakrows)
501 // insert the string, don't insert doublespace
502 bool space_inserted = true;
503 for (string::const_iterator cit = str.begin();
504 cit != str.end(); ++cit) {
505 Paragraph & par = pars[pit];
507 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
508 breakParagraph(params(), pars, pit, pos,
509 par.layout()->isEnvironment());
512 space_inserted = true;
516 // do not insert consecutive spaces if !free_spacing
517 } else if ((*cit == ' ' || *cit == '\t') &&
518 space_inserted && !par.isFreeSpacing()) {
520 } else if (*cit == '\t') {
521 if (!par.isFreeSpacing()) {
522 // tabs are like spaces here
523 par.insertChar(pos, ' ', font);
525 space_inserted = true;
527 const pos_type n = 8 - pos % 8;
528 for (pos_type i = 0; i < n; ++i) {
529 par.insertChar(pos, ' ', font);
532 space_inserted = true;
534 } else if (!IsPrintable(*cit)) {
535 // Ignore unprintables
538 // just insert the character
539 par.insertChar(pos, *cit, font);
541 space_inserted = (*cit == ' ');
548 bool Buffer::readFile(string const & filename)
550 // Check if the file is compressed.
551 string const format = getFormatFromContents(filename);
552 if (format == "gzip" || format == "zip" || format == "compress") {
553 params().compressed = true;
556 // remove dummy empty par
557 paragraphs().clear();
558 bool ret = readFile(filename, paragraphs().size());
560 // After we have read a file, we must ensure that the buffer
561 // language is set and used in the gui.
562 // If you know of a better place to put this, please tell me. (Lgb)
563 updateDocLang(params().language);
569 bool Buffer::readFile(string const & filename, pit_type const pit)
572 lex.setFile(filename);
573 return readFile(lex, filename, pit);
577 bool Buffer::fully_loaded() const
579 return pimpl_->file_fully_loaded;
583 void Buffer::fully_loaded(bool const value)
585 pimpl_->file_fully_loaded = value;
589 bool Buffer::readFile(LyXLex & lex, string const & filename, pit_type const pit)
591 BOOST_ASSERT(!filename.empty());
594 Alert::error(_("Document could not be read"),
595 bformat(_("%1$s could not be read."), filename));
600 string const token(lex.getString());
603 Alert::error(_("Document could not be read"),
604 bformat(_("%1$s could not be read."), filename));
608 // the first token _must_ be...
609 if (token != "\\lyxformat") {
610 lyxerr << "Token: " << token << endl;
612 Alert::error(_("Document format failure"),
613 bformat(_("%1$s is not a LyX document."),
619 string tmp_format = lex.getString();
620 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
621 // if present remove ".," from string.
622 string::size_type dot = tmp_format.find_first_of(".,");
623 //lyxerr << " dot found at " << dot << endl;
624 if (dot != string::npos)
625 tmp_format.erase(dot, 1);
626 int const file_format = convert<int>(tmp_format);
627 //lyxerr << "format: " << file_format << endl;
629 if (file_format != LYX_FORMAT) {
630 string const tmpfile = tempName();
631 if (tmpfile.empty()) {
632 Alert::error(_("Conversion failed"),
633 bformat(_("%1$s is from an earlier"
634 " version of LyX, but a temporary"
635 " file for converting it could"
640 string const lyx2lyx = LibFileSearch("lyx2lyx", "lyx2lyx");
641 if (lyx2lyx.empty()) {
642 Alert::error(_("Conversion script not found"),
643 bformat(_("%1$s is from an earlier"
644 " version of LyX, but the"
645 " conversion script lyx2lyx"
646 " could not be found."),
650 ostringstream command;
651 command << "python " << QuoteName(lyx2lyx)
652 << " -t " << convert<string>(LYX_FORMAT)
653 << " -o " << QuoteName(tmpfile) << ' '
654 << QuoteName(filename);
655 string const command_str = command.str();
657 lyxerr[Debug::INFO] << "Running '"
658 << command_str << '\''
661 cmd_ret const ret = RunCommand(command_str);
662 if (ret.first != 0) {
663 Alert::error(_("Conversion script failed"),
664 bformat(_("%1$s is from an earlier version"
665 " of LyX, but the lyx2lyx script"
666 " failed to convert it."),
670 bool const ret = readFile(tmpfile, pit);
671 // Do stuff with tmpfile name and buffer name here.
677 if (readDocument(lex)) {
678 Alert::error(_("Document format failure"),
679 bformat(_("%1$s ended unexpectedly, which means"
680 " that it is probably corrupted."),
684 //lyxerr << "removing " << MacroTable::localMacros().size()
685 // << " temporary macro entries" << endl;
686 //MacroTable::localMacros().clear();
688 pimpl_->file_fully_loaded = true;
693 // Should probably be moved to somewhere else: BufferView? LyXView?
694 bool Buffer::save() const
696 // We don't need autosaves in the immediate future. (Asger)
697 resetAutosaveTimers();
701 if (lyxrc.make_backup) {
702 s = fileName() + '~';
703 if (!lyxrc.backupdir_path.empty())
704 s = AddName(lyxrc.backupdir_path,
705 subst(os::internal_path(s),'/','!'));
707 // It might very well be that this variant is just
708 // good enough. (Lgb)
709 // But to use this we need fs::copy_file to actually do a copy,
710 // even when the target file exists. (Lgb)
711 if (fs::exists(fileName()) && fs::is_writable(fs::path(fileName()).branch_path())) {
713 fs::copy_file(fileName(), s, false);
715 //catch (fs::filesystem_error const & fe) {
716 //lyxerr << "LyX was not able to make backup copy. Beware.\n"
717 // << fe.what() << endl;
722 if (writeFile(fileName())) {
724 removeAutosaveFile(fileName());
726 // Saving failed, so backup is not backup
727 if (lyxrc.make_backup)
728 rename(s, fileName());
735 bool Buffer::writeFile(string const & fname) const
737 if (pimpl_->read_only && fname == fileName())
742 if (params().compressed) {
743 #ifdef USE_COMPRESSION
744 gz::ogzstream ofs(fname.c_str(), ios::out|ios::trunc);
748 retval = do_writeFile(ofs);
753 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
757 retval = do_writeFile(ofs);
764 bool Buffer::do_writeFile(ostream & ofs) const
767 // Use the standard "C" locale for file output.
768 ofs.imbue(std::locale::classic());
771 // The top of the file should not be written by params().
773 // write out a comment in the top of the file
774 ofs << "#LyX " << lyx_version
775 << " created this file. For more info see http://www.lyx.org/\n"
776 << "\\lyxformat " << LYX_FORMAT << "\n"
777 << "\\begin_document\n";
779 // now write out the buffer parameters.
780 ofs << "\\begin_header\n";
781 params().writeFile(ofs);
782 ofs << "\\end_header\n";
785 ofs << "\n\\begin_body\n";
786 text().write(*this, ofs);
787 ofs << "\n\\end_body\n";
789 // Write marker that shows file is complete
790 ofs << "\\end_document" << endl;
792 // Shouldn't really be needed....
795 // how to check if close went ok?
796 // Following is an attempt... (BE 20001011)
798 // good() returns false if any error occured, including some
800 // bad() returns true if something bad happened in the buffer,
801 // which should include file system full errors.
806 lyxerr << "File was not closed properly." << endl;
813 void Buffer::makeLaTeXFile(string const & fname,
814 string const & original_path,
815 OutputParams const & runparams,
816 bool output_preamble, bool output_body)
818 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
821 if (!openFileWrite(ofs, fname))
824 makeLaTeXFile(ofs, original_path,
825 runparams, output_preamble, output_body);
829 lyxerr << "File '" << fname << "' was not closed properly." << endl;
833 void Buffer::makeLaTeXFile(ostream & os,
834 string const & original_path,
835 OutputParams const & runparams_in,
836 bool const output_preamble, bool const output_body)
838 OutputParams runparams = runparams_in;
840 // validate the buffer.
841 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
842 LaTeXFeatures features(*this, params(), runparams.nice);
844 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
848 // The starting paragraph of the coming rows is the
849 // first paragraph of the document. (Asger)
850 texrow().start(paragraphs().begin()->id(), 0);
852 if (output_preamble && runparams.nice) {
853 os << "%% LyX " << lyx_version << " created this file. "
854 "For more info, see http://www.lyx.org/.\n"
855 "%% Do not edit unless you really know what "
860 lyxerr[Debug::INFO] << "lyx header finished" << endl;
861 // There are a few differences between nice LaTeX and usual files:
862 // usual is \batchmode and has a
863 // special input@path to allow the including of figures
864 // with either \input or \includegraphics (what figinsets do).
865 // input@path is set when the actual parameter
866 // original_path is set. This is done for usual tex-file, but not
867 // for nice-latex-file. (Matthias 250696)
868 // Note that input@path is only needed for something the user does
869 // in the preamble, included .tex files or ERT, files included by
870 // LyX work without it.
871 if (output_preamble) {
872 if (!runparams.nice) {
873 // code for usual, NOT nice-latex-file
874 os << "\\batchmode\n"; // changed
878 if (!original_path.empty()) {
879 string const inputpath = latex_path(original_path);
880 os << "\\makeatletter\n"
881 << "\\def\\input@path{{"
882 << inputpath << "/}}\n"
883 << "\\makeatother\n";
889 // Write the preamble
890 runparams.use_babel = params().writeLaTeX(os, features, texrow());
896 os << "\\begin{document}\n";
899 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
901 if (!lyxrc.language_auto_begin) {
902 os << subst(lyxrc.language_command_begin, "$$lang",
903 params().language->babel())
908 // if we are doing a real file with body, even if this is the
909 // child of some other buffer, let's cut the link here.
910 // This happens for example if only a child document is printed.
911 string save_parentname;
912 if (output_preamble) {
913 save_parentname = params().parentname;
914 params().parentname.erase();
918 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
920 // Restore the parenthood if needed
922 params().parentname = save_parentname;
924 // add this just in case after all the paragraphs
928 if (!lyxrc.language_auto_end) {
929 os << subst(lyxrc.language_command_end, "$$lang",
930 params().language->babel())
935 if (output_preamble) {
936 os << "\\end{document}\n";
939 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
941 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
945 // Just to be sure. (Asger)
948 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
949 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
954 bool Buffer::isLatex() const
956 return params().getLyXTextClass().outputType() == LATEX;
960 bool Buffer::isLinuxDoc() const
962 return params().getLyXTextClass().outputType() == LINUXDOC;
966 bool Buffer::isLiterate() const
968 return params().getLyXTextClass().outputType() == LITERATE;
972 bool Buffer::isDocBook() const
974 return params().getLyXTextClass().outputType() == DOCBOOK;
978 bool Buffer::isSGML() const
980 LyXTextClass const & tclass = params().getLyXTextClass();
982 return tclass.outputType() == LINUXDOC ||
983 tclass.outputType() == DOCBOOK;
987 void Buffer::makeLinuxDocFile(string const & fname,
988 OutputParams const & runparams,
989 bool const body_only)
992 if (!openFileWrite(ofs, fname))
995 LaTeXFeatures features(*this, params(), runparams.nice);
1000 LyXTextClass const & tclass = params().getLyXTextClass();
1002 string const & top_element = tclass.latexname();
1005 ofs << tclass.class_header();
1007 string preamble = params().preamble;
1008 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1010 preamble += features.getIncludedFiles(name);
1011 preamble += features.getLyXSGMLEntities();
1013 if (!preamble.empty()) {
1014 ofs << " [ " << preamble << " ]";
1018 if (params().options.empty())
1019 sgml::openTag(ofs, top_element);
1021 string top = top_element;
1023 top += params().options;
1024 sgml::openTag(ofs, top);
1028 ofs << "<!-- LyX " << lyx_version
1029 << " created this file. For more info see http://www.lyx.org/"
1032 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1036 sgml::closeTag(ofs, top_element);
1041 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1045 void Buffer::makeDocBookFile(string const & fname,
1046 OutputParams const & runparams,
1047 bool const only_body)
1050 if (!openFileWrite(ofs, fname))
1053 LaTeXFeatures features(*this, params(), runparams.nice);
1058 LyXTextClass const & tclass = params().getLyXTextClass();
1059 string const & top_element = tclass.latexname();
1062 if (runparams.flavor == OutputParams::XML)
1063 ofs << "<?xml version=\"1.0\" encoding=\""
1064 << params().language->encoding()->Name() << "\"?>\n";
1066 ofs << "<!DOCTYPE " << top_element << " ";
1068 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1069 else if (runparams.flavor == OutputParams::XML)
1070 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1071 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1073 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1075 string preamble = params().preamble;
1076 if (runparams.flavor != OutputParams::XML ) {
1077 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1078 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1079 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1080 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1083 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1085 preamble += features.getIncludedFiles(name);
1086 preamble += features.getLyXSGMLEntities();
1088 if (!preamble.empty()) {
1089 ofs << "\n [ " << preamble << " ]";
1094 string top = top_element;
1096 if (runparams.flavor == OutputParams::XML)
1097 top += params().language->code();
1099 top += params().language->code().substr(0,2);
1102 if (!params().options.empty()) {
1104 top += params().options;
1107 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1108 << " file was created by LyX " << lyx_version
1109 << "\n See http://www.lyx.org/ for more information -->\n";
1111 params().getLyXTextClass().counters().reset();
1113 sgml::openTag(ofs, top);
1115 docbookParagraphs(paragraphs(), *this, ofs, runparams);
1116 sgml::closeTag(ofs, top_element);
1120 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1124 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1125 // Other flags: -wall -v0 -x
1126 int Buffer::runChktex()
1130 // get LaTeX-Filename
1131 string const name = getLatexName();
1132 string const path = temppath();
1133 string const org_path = filePath();
1135 Path p(path); // path to LaTeX file
1136 message(_("Running chktex..."));
1138 // Generate the LaTeX file if neccessary
1139 OutputParams runparams;
1140 runparams.flavor = OutputParams::LATEX;
1141 runparams.nice = false;
1142 makeLaTeXFile(name, org_path, runparams);
1145 Chktex chktex(lyxrc.chktex_command, name, filePath());
1146 int const res = chktex.run(terr); // run chktex
1149 Alert::error(_("chktex failure"),
1150 _("Could not run chktex successfully."));
1151 } else if (res > 0) {
1152 // Insert all errors as errors boxes
1153 bufferErrors(*this, terr);
1162 void Buffer::validate(LaTeXFeatures & features) const
1164 LyXTextClass const & tclass = params().getLyXTextClass();
1166 if (features.isAvailable("dvipost") && params().tracking_changes
1167 && params().output_changes) {
1168 features.require("dvipost");
1169 features.require("color");
1172 // AMS Style is at document level
1173 if (params().use_amsmath == BufferParams::AMS_ON
1174 || tclass.provides(LyXTextClass::amsmath))
1175 features.require("amsmath");
1177 for_each(paragraphs().begin(), paragraphs().end(),
1178 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1180 // the bullet shapes are buffer level not paragraph level
1181 // so they are tested here
1182 for (int i = 0; i < 4; ++i) {
1183 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1184 int const font = params().user_defined_bullet(i).getFont();
1186 int const c = params()
1187 .user_defined_bullet(i)
1194 features.require("latexsym");
1196 } else if (font == 1) {
1197 features.require("amssymb");
1198 } else if ((font >= 2 && font <= 5)) {
1199 features.require("pifont");
1204 if (lyxerr.debugging(Debug::LATEX)) {
1205 features.showStruct();
1210 void Buffer::getLabelList(vector<string> & list) const
1212 /// if this is a child document and the parent is already loaded
1213 /// Use the parent's list instead [ale990407]
1214 Buffer const * tmp = getMasterBuffer();
1216 lyxerr << "getMasterBuffer() failed!" << endl;
1220 tmp->getLabelList(list);
1224 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1225 it.nextInset()->getLabelList(*this, list);
1229 // This is also a buffer property (ale)
1230 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1233 /// if this is a child document and the parent is already loaded
1234 /// use the parent's list instead [ale990412]
1235 Buffer const * tmp = getMasterBuffer();
1238 tmp->fillWithBibKeys(keys);
1242 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1243 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1244 InsetBibtex const & inset =
1245 dynamic_cast<InsetBibtex const &>(*it);
1246 inset.fillWithBibKeys(*this, keys);
1247 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1248 InsetInclude const & inset =
1249 dynamic_cast<InsetInclude const &>(*it);
1250 inset.fillWithBibKeys(*this, keys);
1251 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1252 InsetBibitem const & inset =
1253 dynamic_cast<InsetBibitem const &>(*it);
1254 string const key = inset.getContents();
1255 string const opt = inset.getOptions();
1256 string const ref; // = pit->asString(this, false);
1257 string const info = opt + "TheBibliographyRef" + ref;
1258 keys.push_back(pair<string, string>(key, info));
1264 bool Buffer::isDepClean(string const & name) const
1266 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1267 if (it == pimpl_->dep_clean.end())
1273 void Buffer::markDepClean(string const & name)
1275 pimpl_->dep_clean[name] = true;
1279 bool Buffer::dispatch(string const & command, bool * result)
1281 return dispatch(lyxaction.lookupFunc(command), result);
1285 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1287 bool dispatched = true;
1289 switch (func.action) {
1291 bool const tmp = Exporter::Export(this, func.argument, false);
1304 void Buffer::changeLanguage(Language const * from, Language const * to)
1309 lyxerr << "Changing Language!" << endl;
1311 // Take care of l10n/i18n
1314 for_each(par_iterator_begin(),
1316 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1320 void Buffer::updateDocLang(Language const * nlang)
1322 BOOST_ASSERT(nlang);
1324 pimpl_->messages.reset(new Messages(nlang->code()));
1328 bool Buffer::isMultiLingual() const
1330 ParConstIterator end = par_iterator_end();
1331 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1332 if (it->isMultiLingual(params()))
1339 ParIterator Buffer::getParFromID(int const id) const
1341 ParConstIterator it = par_iterator_begin();
1342 ParConstIterator const end = par_iterator_end();
1345 // John says this is called with id == -1 from undo
1346 lyxerr << "getParFromID(), id: " << id << endl;
1350 for (; it != end; ++it)
1358 bool Buffer::hasParWithID(int const id) const
1360 ParConstIterator const it = getParFromID(id);
1361 return it != par_iterator_end();
1365 ParIterator Buffer::par_iterator_begin()
1367 return ::par_iterator_begin(inset());
1371 ParIterator Buffer::par_iterator_end()
1373 return ::par_iterator_end(inset());
1377 ParConstIterator Buffer::par_iterator_begin() const
1379 return ::par_const_iterator_begin(inset());
1383 ParConstIterator Buffer::par_iterator_end() const
1385 return ::par_const_iterator_end(inset());
1389 Language const * Buffer::getLanguage() const
1391 return params().language;
1395 string const Buffer::B_(string const & l10n) const
1397 if (pimpl_->messages.get()) {
1398 return pimpl_->messages->get(l10n);
1405 bool Buffer::isClean() const
1407 return pimpl_->lyx_clean;
1411 bool Buffer::isBakClean() const
1413 return pimpl_->bak_clean;
1417 void Buffer::markClean() const
1419 if (!pimpl_->lyx_clean) {
1420 pimpl_->lyx_clean = true;
1423 // if the .lyx file has been saved, we don't need an
1425 pimpl_->bak_clean = true;
1429 void Buffer::markBakClean()
1431 pimpl_->bak_clean = true;
1435 void Buffer::setUnnamed(bool flag)
1437 pimpl_->unnamed = flag;
1441 bool Buffer::isUnnamed() const
1443 return pimpl_->unnamed;
1447 #ifdef WITH_WARNINGS
1448 #warning this function should be moved to buffer_pimpl.C
1450 void Buffer::markDirty()
1452 if (pimpl_->lyx_clean) {
1453 pimpl_->lyx_clean = false;
1456 pimpl_->bak_clean = false;
1458 DepClean::iterator it = pimpl_->dep_clean.begin();
1459 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1461 for (; it != end; ++it) {
1467 string const & Buffer::fileName() const
1469 return pimpl_->filename;
1473 string const & Buffer::filePath() const
1475 return pimpl_->filepath;
1479 bool Buffer::isReadonly() const
1481 return pimpl_->read_only;
1485 void Buffer::setParentName(string const & name)
1487 params().parentname = name;
1491 Buffer const * Buffer::getMasterBuffer() const
1493 if (!params().parentname.empty()
1494 && bufferlist.exists(params().parentname)) {
1495 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1497 return buf->getMasterBuffer();
1504 MacroData const & Buffer::getMacro(std::string const & name) const
1506 return pimpl_->macros.get(name);
1510 bool Buffer::hasMacro(string const & name) const
1512 return pimpl_->macros.has(name);
1516 void Buffer::insertMacro(string const & name, MacroData const & data)
1518 MacroTable::globalMacros().insert(name, data);
1519 pimpl_->macros.insert(name, data);
1523 void Buffer::buildMacros()
1525 // Start with global table.
1526 pimpl_->macros = MacroTable::globalMacros();
1529 ParagraphList & pars = text().paragraphs();
1530 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1531 //lyxerr << "searching main par " << i
1532 // << " for macro definitions" << std::endl;
1533 InsetList::iterator it = pars[i].insetlist.begin();
1534 InsetList::iterator end = pars[i].insetlist.end();
1535 for ( ; it != end; ++it) {
1536 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1537 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1538 MathMacroTemplate & mac
1539 = static_cast<MathMacroTemplate &>(*it->inset);
1540 insertMacro(mac.name(), mac.asMacroData());