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>
92 using lyx::support::AddName;
93 using lyx::support::bformat;
94 using lyx::support::ChangeExtension;
95 using lyx::support::cmd_ret;
96 using lyx::support::createBufferTmpDir;
97 using lyx::support::destroyDir;
98 using lyx::support::getFormatFromContents;
99 using lyx::support::IsDirWriteable;
100 using lyx::support::LibFileSearch;
101 using lyx::support::ltrim;
102 using lyx::support::MakeAbsPath;
103 using lyx::support::MakeDisplayPath;
104 using lyx::support::MakeLatexName;
105 using lyx::support::OnlyFilename;
106 using lyx::support::OnlyPath;
107 using lyx::support::Path;
108 using lyx::support::QuoteName;
109 using lyx::support::removeAutosaveFile;
110 using lyx::support::rename;
111 using lyx::support::RunCommand;
112 using lyx::support::split;
113 using lyx::support::subst;
114 using lyx::support::tempName;
115 using lyx::support::trim;
117 namespace os = lyx::support::os;
118 namespace fs = boost::filesystem;
122 using std::make_pair;
128 using std::ostringstream;
136 // all these externs should eventually be removed.
137 extern BufferList bufferlist;
141 int const LYX_FORMAT = 241;
146 typedef std::map<string, bool> DepClean;
151 Impl(Buffer & parent, string const & file, bool readonly);
153 limited_stack<Undo> undostack;
154 limited_stack<Undo> redostack;
160 /// need to regenerate .tex?
164 mutable bool lyx_clean;
166 /// is autosave needed?
167 mutable bool bak_clean;
169 /// is this a unnamed file (New...)?
175 /// name of the file the buffer is associated with.
178 /// The path to the document file.
181 boost::scoped_ptr<Messages> messages;
183 /** Set to true only when the file is fully loaded.
184 * Used to prevent the premature generation of previews
185 * and by the citation inset.
187 bool file_fully_loaded;
189 /// our LyXText that should be wrapped in an InsetText
197 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
198 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
199 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
202 inset.setAutoBreakRows(true);
203 lyxvc.buffer(&parent);
204 temppath = createBufferTmpDir();
205 // FIXME: And now do something if temppath == string(), because we
206 // assume from now on that temppath points to a valid temp dir.
207 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
211 Buffer::Buffer(string const & file, bool ronly)
212 : pimpl_(new Impl(*this, file, ronly))
214 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
220 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
221 // here the buffer should take care that it is
222 // saved properly, before it goes into the void.
226 if (!temppath().empty() && !destroyDir(temppath())) {
227 Alert::warning(_("Could not remove temporary directory"),
228 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
231 // Remove any previewed LaTeX snippets associated with this buffer.
232 lyx::graphics::Previews::get().removeLoader(*this);
236 LyXText & Buffer::text() const
238 return const_cast<LyXText &>(pimpl_->inset.text_);
242 InsetBase & Buffer::inset() const
244 return const_cast<InsetText &>(pimpl_->inset);
248 limited_stack<Undo> & Buffer::undostack()
250 return pimpl_->undostack;
254 limited_stack<Undo> const & Buffer::undostack() const
256 return pimpl_->undostack;
260 limited_stack<Undo> & Buffer::redostack()
262 return pimpl_->redostack;
266 limited_stack<Undo> const & Buffer::redostack() const
268 return pimpl_->redostack;
272 BufferParams & Buffer::params()
274 return pimpl_->params;
278 BufferParams const & Buffer::params() const
280 return pimpl_->params;
284 ParagraphList & Buffer::paragraphs()
286 return text().paragraphs();
290 ParagraphList const & Buffer::paragraphs() const
292 return text().paragraphs();
296 LyXVC & Buffer::lyxvc()
298 return pimpl_->lyxvc;
302 LyXVC const & Buffer::lyxvc() const
304 return pimpl_->lyxvc;
308 string const & Buffer::temppath() const
310 return pimpl_->temppath;
314 TexRow & Buffer::texrow()
316 return pimpl_->texrow;
320 TexRow const & Buffer::texrow() const
322 return pimpl_->texrow;
326 string const Buffer::getLatexName(bool const no_path) const
328 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
329 return no_path ? OnlyFilename(name) : name;
333 pair<Buffer::LogType, string> const Buffer::getLogName() const
335 string const filename = getLatexName(false);
337 if (filename.empty())
338 return make_pair(Buffer::latexlog, string());
340 string const path = temppath();
342 string const fname = AddName(path,
343 OnlyFilename(ChangeExtension(filename,
346 AddName(path, OnlyFilename(
347 ChangeExtension(filename,
348 formats.extension("literate") + ".out")));
350 // If no Latex log or Build log is newer, show Build log
352 if (fs::exists(bname) &&
353 (!fs::exists(fname) || fs::last_write_time(fname) < fs::last_write_time(bname))) {
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 const 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(fs::is_readonly(pimpl_->filename));
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;
399 // Initialize parameters that may be/go lacking in header:
400 params().branchlist().clear();
401 params().options.erase();
402 params().float_placement.erase();
403 params().paperwidth.erase();
404 params().paperheight.erase();
405 params().leftmargin.erase();
406 params().rightmargin.erase();
407 params().topmargin.erase();
408 params().bottommargin.erase();
409 params().headheight.erase();
410 params().headsep.erase();
411 params().footskip.erase();
415 string const token = lex.getString();
420 if (token == "\\end_header")
424 if (token == "\\begin_header") {
425 begin_header_line = line;
429 lyxerr[Debug::PARSER] << "Handling header token: `"
430 << token << '\'' << endl;
432 string unknown = params().readToken(lex, token);
433 if (!unknown.empty()) {
434 if (unknown[0] != '\\' && token == "\\textclass") {
435 unknownClass(unknown);
438 string const s = bformat(_("Unknown token: "
442 error(ErrorItem(_("Header error"), s,
447 if (begin_header_line) {
448 string const s = _("\\begin_header is missing");
449 error(ErrorItem(_("Header error"), s, -1, 0, 0));
451 return unknown_tokens;
456 // changed to be public and have one parameter
457 // Returns false if "\end_document" is not read (Asger)
458 bool Buffer::readDocument(LyXLex & lex)
461 string const token = lex.getString();
462 if (token != "\\begin_document") {
463 string const s = _("\\begin_document is missing");
464 error(ErrorItem(_("Header error"), s, -1, 0, 0));
467 if (paragraphs().empty()) {
469 if (!params().getLyXTextClass().load()) {
470 string theclass = params().getLyXTextClass().name();
471 Alert::error(_("Can't load document class"), bformat(
472 "Using the default document class, because the "
473 " class %1$s could not be loaded.", theclass));
474 params().textclass = 0;
477 // We don't want to adopt the parameters from the
478 // document we insert, so read them into a temporary buffer
479 // and then discard it
481 Buffer tmpbuf("", false);
482 tmpbuf.readHeader(lex);
485 return text().read(*this, lex);
489 // needed to insert the selection
490 void Buffer::insertStringAsLines(ParagraphList & pars,
491 pit_type & pit, pos_type & pos,
492 LyXFont const & fn, string const & str, bool autobreakrows)
496 pars[pit].checkInsertChar(font);
497 // insert the string, don't insert doublespace
498 bool space_inserted = true;
499 for (string::const_iterator cit = str.begin();
500 cit != str.end(); ++cit) {
501 Paragraph & par = pars[pit];
503 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
504 breakParagraph(params(), pars, pit, pos,
505 par.layout()->isEnvironment());
508 space_inserted = true;
512 // do not insert consecutive spaces if !free_spacing
513 } else if ((*cit == ' ' || *cit == '\t') &&
514 space_inserted && !par.isFreeSpacing()) {
516 } else if (*cit == '\t') {
517 if (!par.isFreeSpacing()) {
518 // tabs are like spaces here
519 par.insertChar(pos, ' ', font);
521 space_inserted = true;
523 const pos_type n = 8 - pos % 8;
524 for (pos_type i = 0; i < n; ++i) {
525 par.insertChar(pos, ' ', font);
528 space_inserted = true;
530 } else if (!IsPrintable(*cit)) {
531 // Ignore unprintables
534 // just insert the character
535 par.insertChar(pos, *cit, font);
537 space_inserted = (*cit == ' ');
544 bool Buffer::readFile(string const & filename)
546 // Check if the file is compressed.
547 string const format = getFormatFromContents(filename);
548 if (format == "gzip" || format == "zip" || format == "compress") {
549 params().compressed = true;
552 // remove dummy empty par
553 paragraphs().clear();
554 bool ret = readFile(filename, paragraphs().size());
556 // After we have read a file, we must ensure that the buffer
557 // language is set and used in the gui.
558 // If you know of a better place to put this, please tell me. (Lgb)
559 updateDocLang(params().language);
565 bool Buffer::readFile(string const & filename, pit_type const pit)
568 lex.setFile(filename);
569 return readFile(lex, filename, pit);
573 bool Buffer::fully_loaded() const
575 return pimpl_->file_fully_loaded;
579 void Buffer::fully_loaded(bool const value)
581 pimpl_->file_fully_loaded = value;
585 bool Buffer::readFile(LyXLex & lex, string const & filename, pit_type const pit)
587 BOOST_ASSERT(!filename.empty());
590 Alert::error(_("Document could not be read"),
591 bformat(_("%1$s could not be read."), filename));
596 string const token(lex.getString());
599 Alert::error(_("Document could not be read"),
600 bformat(_("%1$s could not be read."), filename));
604 // the first token _must_ be...
605 if (token != "\\lyxformat") {
606 lyxerr << "Token: " << token << endl;
608 Alert::error(_("Document format failure"),
609 bformat(_("%1$s is not a LyX document."),
615 string tmp_format = lex.getString();
616 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
617 // if present remove ".," from string.
618 string::size_type dot = tmp_format.find_first_of(".,");
619 //lyxerr << " dot found at " << dot << endl;
620 if (dot != string::npos)
621 tmp_format.erase(dot, 1);
622 int const file_format = convert<int>(tmp_format);
623 //lyxerr << "format: " << file_format << endl;
625 if (file_format != LYX_FORMAT) {
626 string const tmpfile = tempName();
627 if (tmpfile.empty()) {
628 Alert::error(_("Conversion failed"),
629 bformat(_("%1$s is from an earlier"
630 " version of LyX, but a temporary"
631 " file for converting it could"
637 "python " + LibFileSearch("lyx2lyx", "lyx2lyx");
638 if (command.empty()) {
639 Alert::error(_("Conversion script not found"),
640 bformat(_("%1$s is from an earlier"
641 " version of LyX, but the"
642 " conversion script lyx2lyx"
643 " could not be found."),
648 + convert<string>(LYX_FORMAT)
649 + " -o " + tmpfile + ' '
650 + QuoteName(filename);
651 lyxerr[Debug::INFO] << "Running '"
654 cmd_ret const ret = RunCommand(command);
655 if (ret.first != 0) {
656 Alert::error(_("Conversion script failed"),
657 bformat(_("%1$s is from an earlier version"
658 " of LyX, but the lyx2lyx script"
659 " failed to convert it."),
663 bool const ret = readFile(tmpfile, pit);
664 // Do stuff with tmpfile name and buffer name here.
670 if (readDocument(lex)) {
671 Alert::error(_("Document format failure"),
672 bformat(_("%1$s ended unexpectedly, which means"
673 " that it is probably corrupted."),
677 //lyxerr << "removing " << MacroTable::localMacros().size()
678 // << " temporary macro entries" << endl;
679 //MacroTable::localMacros().clear();
680 params().setPaperStuff();
682 pimpl_->file_fully_loaded = true;
687 // Should probably be moved to somewhere else: BufferView? LyXView?
688 bool Buffer::save() const
690 // We don't need autosaves in the immediate future. (Asger)
691 resetAutosaveTimers();
695 if (lyxrc.make_backup) {
696 s = fileName() + '~';
697 if (!lyxrc.backupdir_path.empty())
698 s = AddName(lyxrc.backupdir_path,
699 subst(os::internal_path(s),'/','!'));
701 // It might very well be that this variant is just
702 // good enough. (Lgb)
703 // But to use this we need fs::copy_file to actually do a copy,
704 // even when the target file exists. (Lgb)
705 if (fs::exists(fileName())) {
707 fs::copy_file(fileName(), s, false);
709 //catch (fs::filesystem_error const & fe) {
710 //lyxerr << "LyX was not able to make backup copy. Beware.\n"
711 // << fe.what() << endl;
716 if (writeFile(fileName())) {
718 removeAutosaveFile(fileName());
720 // Saving failed, so backup is not backup
721 if (lyxrc.make_backup)
722 rename(s, fileName());
729 bool Buffer::writeFile(string const & fname) const
731 if (pimpl_->read_only && fname == fileName())
736 if (params().compressed) {
737 #ifdef USE_COMPRESSION
738 gz::ogzstream ofs(fname.c_str(), ios::out|ios::trunc);
742 retval = do_writeFile(ofs);
747 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
751 retval = do_writeFile(ofs);
758 bool Buffer::do_writeFile(ostream & ofs) const
761 // Use the standard "C" locale for file output.
762 ofs.imbue(std::locale::classic());
765 // The top of the file should not be written by params().
767 // write out a comment in the top of the file
768 ofs << "#LyX " << lyx_version
769 << " created this file. For more info see http://www.lyx.org/\n"
770 << "\\lyxformat " << LYX_FORMAT << "\n"
771 << "\\begin_document\n";
773 // now write out the buffer parameters.
774 ofs << "\\begin_header\n";
775 params().writeFile(ofs);
776 ofs << "\\end_header\n";
779 ofs << "\n\\begin_body\n";
780 text().write(*this, ofs);
781 ofs << "\n\\end_body\n";
783 // Write marker that shows file is complete
784 ofs << "\\end_document" << endl;
786 // Shouldn't really be needed....
789 // how to check if close went ok?
790 // Following is an attempt... (BE 20001011)
792 // good() returns false if any error occured, including some
794 // bad() returns true if something bad happened in the buffer,
795 // which should include file system full errors.
800 lyxerr << "File was not closed properly." << endl;
807 void Buffer::makeLaTeXFile(string const & fname,
808 string const & original_path,
809 OutputParams const & runparams,
810 bool output_preamble, bool output_body)
812 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
815 if (!openFileWrite(ofs, fname))
818 makeLaTeXFile(ofs, original_path,
819 runparams, output_preamble, output_body);
823 lyxerr << "File '" << fname << "' was not closed properly." << endl;
827 void Buffer::makeLaTeXFile(ostream & os,
828 string const & original_path,
829 OutputParams const & runparams_in,
830 bool const output_preamble, bool const output_body)
832 OutputParams runparams = runparams_in;
834 // validate the buffer.
835 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
836 LaTeXFeatures features(*this, params(), runparams.nice);
838 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
842 // The starting paragraph of the coming rows is the
843 // first paragraph of the document. (Asger)
844 texrow().start(paragraphs().begin()->id(), 0);
846 if (output_preamble && runparams.nice) {
847 os << "%% LyX " << lyx_version << " created this file. "
848 "For more info, see http://www.lyx.org/.\n"
849 "%% Do not edit unless you really know what "
854 lyxerr[Debug::INFO] << "lyx header finished" << endl;
855 // There are a few differences between nice LaTeX and usual files:
856 // usual is \batchmode and has a
857 // special input@path to allow the including of figures
858 // with either \input or \includegraphics (what figinsets do).
859 // input@path is set when the actual parameter
860 // original_path is set. This is done for usual tex-file, but not
861 // for nice-latex-file. (Matthias 250696)
862 // Note that input@path is only needed for something the user does
863 // in the preamble, included .tex files or ERT, files included by
864 // LyX work without it.
865 if (output_preamble) {
866 if (!runparams.nice) {
867 // code for usual, NOT nice-latex-file
868 os << "\\batchmode\n"; // changed
872 if (!original_path.empty()) {
873 string inputpath = os::external_path(original_path);
874 subst(inputpath, "~", "\\string~");
875 if (inputpath.find(' ') != string::npos)
876 inputpath = '"' + inputpath + '"';
877 os << "\\makeatletter\n"
878 << "\\def\\input@path{{"
879 << inputpath << "/}}\n"
880 << "\\makeatother\n";
886 // Write the preamble
887 runparams.use_babel = params().writeLaTeX(os, features, texrow());
893 os << "\\begin{document}\n";
896 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
898 if (!lyxrc.language_auto_begin) {
899 os << subst(lyxrc.language_command_begin, "$$lang",
900 params().language->babel())
905 // if we are doing a real file with body, even if this is the
906 // child of some other buffer, let's cut the link here.
907 // This happens for example if only a child document is printed.
908 string save_parentname;
909 if (output_preamble) {
910 save_parentname = params().parentname;
911 params().parentname.erase();
915 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
917 // Restore the parenthood if needed
919 params().parentname = save_parentname;
921 // add this just in case after all the paragraphs
925 if (!lyxrc.language_auto_end) {
926 os << subst(lyxrc.language_command_end, "$$lang",
927 params().language->babel())
932 if (output_preamble) {
933 os << "\\end{document}\n";
936 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
938 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
942 // Just to be sure. (Asger)
945 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
946 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
951 bool Buffer::isLatex() const
953 return params().getLyXTextClass().outputType() == LATEX;
957 bool Buffer::isLinuxDoc() const
959 return params().getLyXTextClass().outputType() == LINUXDOC;
963 bool Buffer::isLiterate() const
965 return params().getLyXTextClass().outputType() == LITERATE;
969 bool Buffer::isDocBook() const
971 return params().getLyXTextClass().outputType() == DOCBOOK;
975 bool Buffer::isSGML() const
977 LyXTextClass const & tclass = params().getLyXTextClass();
979 return tclass.outputType() == LINUXDOC ||
980 tclass.outputType() == DOCBOOK;
984 void Buffer::makeLinuxDocFile(string const & fname,
985 OutputParams const & runparams,
986 bool const body_only)
989 if (!openFileWrite(ofs, fname))
992 LaTeXFeatures features(*this, params(), runparams.nice);
997 LyXTextClass const & tclass = params().getLyXTextClass();
999 string const & top_element = tclass.latexname();
1002 ofs << tclass.class_header();
1004 string preamble = params().preamble;
1005 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1007 preamble += features.getIncludedFiles(name);
1008 preamble += features.getLyXSGMLEntities();
1010 if (!preamble.empty()) {
1011 ofs << " [ " << preamble << " ]";
1015 if (params().options.empty())
1016 sgml::openTag(ofs, top_element);
1018 string top = top_element;
1020 top += params().options;
1021 sgml::openTag(ofs, top);
1025 ofs << "<!-- LyX " << lyx_version
1026 << " created this file. For more info see http://www.lyx.org/"
1029 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1033 sgml::closeTag(ofs, top_element);
1038 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1042 void Buffer::makeDocBookFile(string const & fname,
1043 OutputParams const & runparams,
1044 bool const only_body)
1047 if (!openFileWrite(ofs, fname))
1050 LaTeXFeatures features(*this, params(), runparams.nice);
1055 LyXTextClass const & tclass = params().getLyXTextClass();
1056 string const & top_element = tclass.latexname();
1059 if (runparams.flavor == OutputParams::XML)
1060 ofs << "<?xml version=\"1.0\" encoding=\""
1061 << params().language->encoding()->Name() << "\"?>\n";
1063 ofs << "<!DOCTYPE " << top_element << " ";
1065 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1066 else if (runparams.flavor == OutputParams::XML)
1067 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1068 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1070 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1072 string preamble = params().preamble;
1073 if (runparams.flavor != OutputParams::XML ) {
1074 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1075 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1076 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1077 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1080 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1082 preamble += features.getIncludedFiles(name);
1083 preamble += features.getLyXSGMLEntities();
1085 if (!preamble.empty()) {
1086 ofs << "\n [ " << preamble << " ]";
1091 string top = top_element;
1093 if (runparams.flavor == OutputParams::XML)
1094 top += params().language->code();
1096 top += params().language->code().substr(0,2);
1099 if (!params().options.empty()) {
1101 top += params().options;
1104 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1105 << " file was created by LyX " << lyx_version
1106 << "\n See http://www.lyx.org/ for more information -->\n";
1108 params().getLyXTextClass().counters().reset();
1110 sgml::openTag(ofs, top);
1112 docbookParagraphs(paragraphs(), *this, ofs, runparams);
1113 sgml::closeTag(ofs, top_element);
1117 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1121 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1122 // Other flags: -wall -v0 -x
1123 int Buffer::runChktex()
1127 // get LaTeX-Filename
1128 string const name = getLatexName();
1129 string const path = temppath();
1130 string const org_path = filePath();
1132 Path p(path); // path to LaTeX file
1133 message(_("Running chktex..."));
1135 // Generate the LaTeX file if neccessary
1136 OutputParams runparams;
1137 runparams.flavor = OutputParams::LATEX;
1138 runparams.nice = false;
1139 makeLaTeXFile(name, org_path, runparams);
1142 Chktex chktex(lyxrc.chktex_command, name, filePath());
1143 int const res = chktex.run(terr); // run chktex
1146 Alert::error(_("chktex failure"),
1147 _("Could not run chktex successfully."));
1148 } else if (res > 0) {
1149 // Insert all errors as errors boxes
1150 bufferErrors(*this, terr);
1159 void Buffer::validate(LaTeXFeatures & features) const
1161 LyXTextClass const & tclass = params().getLyXTextClass();
1163 if (features.isAvailable("dvipost") && params().tracking_changes
1164 && params().output_changes) {
1165 features.require("dvipost");
1166 features.require("color");
1169 // AMS Style is at document level
1170 if (params().use_amsmath == BufferParams::AMS_ON
1171 || tclass.provides(LyXTextClass::amsmath))
1172 features.require("amsmath");
1174 for_each(paragraphs().begin(), paragraphs().end(),
1175 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1177 // the bullet shapes are buffer level not paragraph level
1178 // so they are tested here
1179 for (int i = 0; i < 4; ++i) {
1180 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1181 int const font = params().user_defined_bullet(i).getFont();
1183 int const c = params()
1184 .user_defined_bullet(i)
1191 features.require("latexsym");
1193 } else if (font == 1) {
1194 features.require("amssymb");
1195 } else if ((font >= 2 && font <= 5)) {
1196 features.require("pifont");
1201 if (lyxerr.debugging(Debug::LATEX)) {
1202 features.showStruct();
1207 void Buffer::getLabelList(vector<string> & list) const
1209 /// if this is a child document and the parent is already loaded
1210 /// Use the parent's list instead [ale990407]
1211 Buffer const * tmp = getMasterBuffer();
1213 lyxerr << "getMasterBuffer() failed!" << endl;
1217 tmp->getLabelList(list);
1221 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1222 it.nextInset()->getLabelList(*this, list);
1226 // This is also a buffer property (ale)
1227 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1230 /// if this is a child document and the parent is already loaded
1231 /// use the parent's list instead [ale990412]
1232 Buffer const * tmp = getMasterBuffer();
1235 tmp->fillWithBibKeys(keys);
1239 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1240 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1241 InsetBibtex const & inset =
1242 dynamic_cast<InsetBibtex const &>(*it);
1243 inset.fillWithBibKeys(*this, keys);
1244 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1245 InsetInclude const & inset =
1246 dynamic_cast<InsetInclude const &>(*it);
1247 inset.fillWithBibKeys(*this, keys);
1248 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1249 InsetBibitem const & inset =
1250 dynamic_cast<InsetBibitem const &>(*it);
1251 string const key = inset.getContents();
1252 string const opt = inset.getOptions();
1253 string const ref; // = pit->asString(this, false);
1254 string const info = opt + "TheBibliographyRef" + ref;
1255 keys.push_back(pair<string, string>(key, info));
1261 bool Buffer::isDepClean(string const & name) const
1263 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1264 if (it == pimpl_->dep_clean.end())
1270 void Buffer::markDepClean(string const & name)
1272 pimpl_->dep_clean[name] = true;
1276 bool Buffer::dispatch(string const & command, bool * result)
1278 return dispatch(lyxaction.lookupFunc(command), result);
1282 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1284 bool dispatched = true;
1286 switch (func.action) {
1288 bool const tmp = Exporter::Export(this, func.argument, false);
1301 void Buffer::changeLanguage(Language const * from, Language const * to)
1306 lyxerr << "Changing Language!" << endl;
1308 // Take care of l10n/i18n
1311 for_each(par_iterator_begin(),
1313 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1317 void Buffer::updateDocLang(Language const * nlang)
1319 BOOST_ASSERT(nlang);
1321 pimpl_->messages.reset(new Messages(nlang->code()));
1325 bool Buffer::isMultiLingual() const
1327 ParConstIterator end = par_iterator_end();
1328 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1329 if (it->isMultiLingual(params()))
1336 ParIterator Buffer::getParFromID(int const id) const
1338 ParConstIterator it = par_iterator_begin();
1339 ParConstIterator const end = par_iterator_end();
1342 // John says this is called with id == -1 from undo
1343 lyxerr << "getParFromID(), id: " << id << endl;
1347 for (; it != end; ++it)
1355 bool Buffer::hasParWithID(int const id) const
1357 ParConstIterator const it = getParFromID(id);
1358 return it != par_iterator_end();
1362 ParIterator Buffer::par_iterator_begin()
1364 return ::par_iterator_begin(inset());
1368 ParIterator Buffer::par_iterator_end()
1370 return ::par_iterator_end(inset());
1374 ParConstIterator Buffer::par_iterator_begin() const
1376 return ::par_const_iterator_begin(inset());
1380 ParConstIterator Buffer::par_iterator_end() const
1382 return ::par_const_iterator_end(inset());
1386 Language const * Buffer::getLanguage() const
1388 return params().language;
1392 string const Buffer::B_(string const & l10n) const
1394 if (pimpl_->messages.get()) {
1395 return pimpl_->messages->get(l10n);
1402 bool Buffer::isClean() const
1404 return pimpl_->lyx_clean;
1408 bool Buffer::isBakClean() const
1410 return pimpl_->bak_clean;
1414 void Buffer::markClean() const
1416 if (!pimpl_->lyx_clean) {
1417 pimpl_->lyx_clean = true;
1420 // if the .lyx file has been saved, we don't need an
1422 pimpl_->bak_clean = true;
1426 void Buffer::markBakClean()
1428 pimpl_->bak_clean = true;
1432 void Buffer::setUnnamed(bool flag)
1434 pimpl_->unnamed = flag;
1438 bool Buffer::isUnnamed() const
1440 return pimpl_->unnamed;
1444 #ifdef WITH_WARNINGS
1445 #warning this function should be moved to buffer_pimpl.C
1447 void Buffer::markDirty()
1449 if (pimpl_->lyx_clean) {
1450 pimpl_->lyx_clean = false;
1453 pimpl_->bak_clean = false;
1455 DepClean::iterator it = pimpl_->dep_clean.begin();
1456 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1458 for (; it != end; ++it) {
1464 string const & Buffer::fileName() const
1466 return pimpl_->filename;
1470 string const & Buffer::filePath() const
1472 return pimpl_->filepath;
1476 bool Buffer::isReadonly() const
1478 return pimpl_->read_only;
1482 void Buffer::setParentName(string const & name)
1484 params().parentname = name;
1488 Buffer const * Buffer::getMasterBuffer() const
1490 if (!params().parentname.empty()
1491 && bufferlist.exists(params().parentname)) {
1492 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1494 return buf->getMasterBuffer();
1501 MacroData const & Buffer::getMacro(std::string const & name) const
1503 return pimpl_->macros.get(name);
1507 bool Buffer::hasMacro(string const & name) const
1509 return pimpl_->macros.has(name);
1513 void Buffer::insertMacro(string const & name, MacroData const & data)
1515 MacroTable::globalMacros().insert(name, data);
1516 pimpl_->macros.insert(name, data);
1520 void Buffer::buildMacros()
1522 // Start with global table.
1523 pimpl_->macros = MacroTable::globalMacros();
1526 ParagraphList & pars = text().paragraphs();
1527 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1528 //lyxerr << "searching main par " << i
1529 // << " for macro definitions" << std::endl;
1530 InsetList::iterator it = pars[i].insetlist.begin();
1531 InsetList::iterator end = pars[i].insetlist.end();
1532 for ( ; it != end; ++it) {
1533 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1534 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1535 MathMacroTemplate & mac
1536 = static_cast<MathMacroTemplate &>(*it->inset);
1537 insertMacro(mac.name(), mac.asMacroData());