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::latex_path;
102 using lyx::support::ltrim;
103 using lyx::support::MakeAbsPath;
104 using lyx::support::MakeDisplayPath;
105 using lyx::support::MakeLatexName;
106 using lyx::support::OnlyFilename;
107 using lyx::support::OnlyPath;
108 using lyx::support::Path;
109 using lyx::support::QuoteName;
110 using lyx::support::removeAutosaveFile;
111 using lyx::support::rename;
112 using lyx::support::RunCommand;
113 using lyx::support::split;
114 using lyx::support::subst;
115 using lyx::support::tempName;
116 using lyx::support::trim;
118 namespace os = lyx::support::os;
119 namespace fs = boost::filesystem;
123 using std::make_pair;
129 using std::ostringstream;
137 // all these externs should eventually be removed.
138 extern BufferList bufferlist;
142 int const LYX_FORMAT = 241;
147 typedef std::map<string, bool> DepClean;
152 Impl(Buffer & parent, string const & file, bool readonly);
154 limited_stack<Undo> undostack;
155 limited_stack<Undo> redostack;
161 /// need to regenerate .tex?
165 mutable bool lyx_clean;
167 /// is autosave needed?
168 mutable bool bak_clean;
170 /// is this a unnamed file (New...)?
176 /// name of the file the buffer is associated with.
179 /// The path to the document file.
182 boost::scoped_ptr<Messages> messages;
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
190 /// our LyXText that should be wrapped in an InsetText
198 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
199 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
200 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
203 inset.setAutoBreakRows(true);
204 lyxvc.buffer(&parent);
205 temppath = createBufferTmpDir();
206 // FIXME: And now do something if temppath == string(), because we
207 // assume from now on that temppath points to a valid temp dir.
208 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
212 Buffer::Buffer(string const & file, bool ronly)
213 : pimpl_(new Impl(*this, file, ronly))
215 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
221 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
222 // here the buffer should take care that it is
223 // saved properly, before it goes into the void.
227 if (!temppath().empty() && !destroyDir(temppath())) {
228 Alert::warning(_("Could not remove temporary directory"),
229 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
232 // Remove any previewed LaTeX snippets associated with this buffer.
233 lyx::graphics::Previews::get().removeLoader(*this);
237 LyXText & Buffer::text() const
239 return const_cast<LyXText &>(pimpl_->inset.text_);
243 InsetBase & Buffer::inset() const
245 return const_cast<InsetText &>(pimpl_->inset);
249 limited_stack<Undo> & Buffer::undostack()
251 return pimpl_->undostack;
255 limited_stack<Undo> const & Buffer::undostack() const
257 return pimpl_->undostack;
261 limited_stack<Undo> & Buffer::redostack()
263 return pimpl_->redostack;
267 limited_stack<Undo> const & Buffer::redostack() const
269 return pimpl_->redostack;
273 BufferParams & Buffer::params()
275 return pimpl_->params;
279 BufferParams const & Buffer::params() const
281 return pimpl_->params;
285 ParagraphList & Buffer::paragraphs()
287 return text().paragraphs();
291 ParagraphList const & Buffer::paragraphs() const
293 return text().paragraphs();
297 LyXVC & Buffer::lyxvc()
299 return pimpl_->lyxvc;
303 LyXVC const & Buffer::lyxvc() const
305 return pimpl_->lyxvc;
309 string const & Buffer::temppath() const
311 return pimpl_->temppath;
315 TexRow & Buffer::texrow()
317 return pimpl_->texrow;
321 TexRow const & Buffer::texrow() const
323 return pimpl_->texrow;
327 string const Buffer::getLatexName(bool const no_path) const
329 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
330 return no_path ? OnlyFilename(name) : name;
334 pair<Buffer::LogType, string> const Buffer::getLogName() const
336 string const filename = getLatexName(false);
338 if (filename.empty())
339 return make_pair(Buffer::latexlog, string());
341 string const path = temppath();
343 string const fname = AddName(path,
344 OnlyFilename(ChangeExtension(filename,
347 AddName(path, OnlyFilename(
348 ChangeExtension(filename,
349 formats.extension("literate") + ".out")));
351 // If no Latex log or Build log is newer, show Build log
353 if (fs::exists(bname) &&
354 (!fs::exists(fname) || fs::last_write_time(fname) < fs::last_write_time(bname))) {
355 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
356 return make_pair(Buffer::buildlog, bname);
358 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
359 return make_pair(Buffer::latexlog, fname);
363 void Buffer::setReadonly(bool const flag)
365 if (pimpl_->read_only != flag) {
366 pimpl_->read_only = flag;
372 void Buffer::setFileName(string const & newfile)
374 pimpl_->filename = MakeAbsPath(newfile);
375 pimpl_->filepath = OnlyPath(pimpl_->filename);
376 setReadonly(fs::is_readonly(pimpl_->filename));
381 // We'll remove this later. (Lgb)
384 void unknownClass(string const & unknown)
386 Alert::warning(_("Unknown document class"),
387 bformat(_("Using the default document class, because the "
388 "class %1$s is unknown."), unknown));
394 int Buffer::readHeader(LyXLex & lex)
396 int unknown_tokens = 0;
398 int begin_header_line = -1;
400 // Initialize parameters that may be/go lacking in header:
401 params().branchlist().clear();
402 params().options.erase();
403 params().float_placement.erase();
404 params().paperwidth.erase();
405 params().paperheight.erase();
406 params().leftmargin.erase();
407 params().rightmargin.erase();
408 params().topmargin.erase();
409 params().bottommargin.erase();
410 params().headheight.erase();
411 params().headsep.erase();
412 params().footskip.erase();
416 string const token = lex.getString();
421 if (token == "\\end_header")
425 if (token == "\\begin_header") {
426 begin_header_line = line;
430 lyxerr[Debug::PARSER] << "Handling header token: `"
431 << token << '\'' << endl;
433 string unknown = params().readToken(lex, token);
434 if (!unknown.empty()) {
435 if (unknown[0] != '\\' && token == "\\textclass") {
436 unknownClass(unknown);
439 string const s = bformat(_("Unknown token: "
443 error(ErrorItem(_("Header error"), s,
448 if (begin_header_line) {
449 string const s = _("\\begin_header is missing");
450 error(ErrorItem(_("Header error"), s, -1, 0, 0));
452 return unknown_tokens;
457 // changed to be public and have one parameter
458 // Returns false if "\end_document" is not read (Asger)
459 bool Buffer::readDocument(LyXLex & lex)
462 string const token = lex.getString();
463 if (token != "\\begin_document") {
464 string const s = _("\\begin_document is missing");
465 error(ErrorItem(_("Header error"), s, -1, 0, 0));
468 if (paragraphs().empty()) {
470 if (!params().getLyXTextClass().load()) {
471 string theclass = params().getLyXTextClass().name();
472 Alert::error(_("Can't load document class"), bformat(
473 "Using the default document class, because the "
474 " class %1$s could not be loaded.", theclass));
475 params().textclass = 0;
478 // We don't want to adopt the parameters from the
479 // document we insert, so read them into a temporary buffer
480 // and then discard it
482 Buffer tmpbuf("", false);
483 tmpbuf.readHeader(lex);
486 return text().read(*this, lex);
490 // needed to insert the selection
491 void Buffer::insertStringAsLines(ParagraphList & pars,
492 pit_type & pit, pos_type & pos,
493 LyXFont const & fn, string const & str, bool autobreakrows)
497 pars[pit].checkInsertChar(font);
498 // insert the string, don't insert doublespace
499 bool space_inserted = true;
500 for (string::const_iterator cit = str.begin();
501 cit != str.end(); ++cit) {
502 Paragraph & par = pars[pit];
504 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
505 breakParagraph(params(), pars, pit, pos,
506 par.layout()->isEnvironment());
509 space_inserted = true;
513 // do not insert consecutive spaces if !free_spacing
514 } else if ((*cit == ' ' || *cit == '\t') &&
515 space_inserted && !par.isFreeSpacing()) {
517 } else if (*cit == '\t') {
518 if (!par.isFreeSpacing()) {
519 // tabs are like spaces here
520 par.insertChar(pos, ' ', font);
522 space_inserted = true;
524 const pos_type n = 8 - pos % 8;
525 for (pos_type i = 0; i < n; ++i) {
526 par.insertChar(pos, ' ', font);
529 space_inserted = true;
531 } else if (!IsPrintable(*cit)) {
532 // Ignore unprintables
535 // just insert the character
536 par.insertChar(pos, *cit, font);
538 space_inserted = (*cit == ' ');
545 bool Buffer::readFile(string const & filename)
547 // Check if the file is compressed.
548 string const format = getFormatFromContents(filename);
549 if (format == "gzip" || format == "zip" || format == "compress") {
550 params().compressed = true;
553 // remove dummy empty par
554 paragraphs().clear();
555 bool ret = readFile(filename, paragraphs().size());
557 // After we have read a file, we must ensure that the buffer
558 // language is set and used in the gui.
559 // If you know of a better place to put this, please tell me. (Lgb)
560 updateDocLang(params().language);
566 bool Buffer::readFile(string const & filename, pit_type const pit)
569 lex.setFile(filename);
570 return readFile(lex, filename, pit);
574 bool Buffer::fully_loaded() const
576 return pimpl_->file_fully_loaded;
580 void Buffer::fully_loaded(bool const value)
582 pimpl_->file_fully_loaded = value;
586 bool Buffer::readFile(LyXLex & lex, string const & filename, pit_type const pit)
588 BOOST_ASSERT(!filename.empty());
591 Alert::error(_("Document could not be read"),
592 bformat(_("%1$s could not be read."), filename));
597 string const token(lex.getString());
600 Alert::error(_("Document could not be read"),
601 bformat(_("%1$s could not be read."), filename));
605 // the first token _must_ be...
606 if (token != "\\lyxformat") {
607 lyxerr << "Token: " << token << endl;
609 Alert::error(_("Document format failure"),
610 bformat(_("%1$s is not a LyX document."),
616 string tmp_format = lex.getString();
617 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
618 // if present remove ".," from string.
619 string::size_type dot = tmp_format.find_first_of(".,");
620 //lyxerr << " dot found at " << dot << endl;
621 if (dot != string::npos)
622 tmp_format.erase(dot, 1);
623 int const file_format = convert<int>(tmp_format);
624 //lyxerr << "format: " << file_format << endl;
626 if (file_format != LYX_FORMAT) {
627 string const tmpfile = tempName();
628 if (tmpfile.empty()) {
629 Alert::error(_("Conversion failed"),
630 bformat(_("%1$s is from an earlier"
631 " version of LyX, but a temporary"
632 " file for converting it could"
638 "python " + LibFileSearch("lyx2lyx", "lyx2lyx");
639 if (command.empty()) {
640 Alert::error(_("Conversion script not found"),
641 bformat(_("%1$s is from an earlier"
642 " version of LyX, but the"
643 " conversion script lyx2lyx"
644 " could not be found."),
649 + convert<string>(LYX_FORMAT)
650 + " -o " + tmpfile + ' '
651 + QuoteName(filename);
652 lyxerr[Debug::INFO] << "Running '"
655 cmd_ret const ret = RunCommand(command);
656 if (ret.first != 0) {
657 Alert::error(_("Conversion script failed"),
658 bformat(_("%1$s is from an earlier version"
659 " of LyX, but the lyx2lyx script"
660 " failed to convert it."),
664 bool const ret = readFile(tmpfile, pit);
665 // Do stuff with tmpfile name and buffer name here.
671 if (readDocument(lex)) {
672 Alert::error(_("Document format failure"),
673 bformat(_("%1$s ended unexpectedly, which means"
674 " that it is probably corrupted."),
678 //lyxerr << "removing " << MacroTable::localMacros().size()
679 // << " temporary macro entries" << endl;
680 //MacroTable::localMacros().clear();
681 params().setPaperStuff();
683 pimpl_->file_fully_loaded = true;
688 // Should probably be moved to somewhere else: BufferView? LyXView?
689 bool Buffer::save() const
691 // We don't need autosaves in the immediate future. (Asger)
692 resetAutosaveTimers();
696 if (lyxrc.make_backup) {
697 s = fileName() + '~';
698 if (!lyxrc.backupdir_path.empty())
699 s = AddName(lyxrc.backupdir_path,
700 subst(os::internal_path(s),'/','!'));
702 // It might very well be that this variant is just
703 // good enough. (Lgb)
704 // But to use this we need fs::copy_file to actually do a copy,
705 // even when the target file exists. (Lgb)
706 if (fs::exists(fileName())) {
708 fs::copy_file(fileName(), s, false);
710 //catch (fs::filesystem_error const & fe) {
711 //lyxerr << "LyX was not able to make backup copy. Beware.\n"
712 // << fe.what() << endl;
717 if (writeFile(fileName())) {
719 removeAutosaveFile(fileName());
721 // Saving failed, so backup is not backup
722 if (lyxrc.make_backup)
723 rename(s, fileName());
730 bool Buffer::writeFile(string const & fname) const
732 if (pimpl_->read_only && fname == fileName())
737 if (params().compressed) {
738 #ifdef USE_COMPRESSION
739 gz::ogzstream ofs(fname.c_str(), ios::out|ios::trunc);
743 retval = do_writeFile(ofs);
748 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
752 retval = do_writeFile(ofs);
759 bool Buffer::do_writeFile(ostream & ofs) const
762 // Use the standard "C" locale for file output.
763 ofs.imbue(std::locale::classic());
766 // The top of the file should not be written by params().
768 // write out a comment in the top of the file
769 ofs << "#LyX " << lyx_version
770 << " created this file. For more info see http://www.lyx.org/\n"
771 << "\\lyxformat " << LYX_FORMAT << "\n"
772 << "\\begin_document\n";
774 // now write out the buffer parameters.
775 ofs << "\\begin_header\n";
776 params().writeFile(ofs);
777 ofs << "\\end_header\n";
780 ofs << "\n\\begin_body\n";
781 text().write(*this, ofs);
782 ofs << "\n\\end_body\n";
784 // Write marker that shows file is complete
785 ofs << "\\end_document" << endl;
787 // Shouldn't really be needed....
790 // how to check if close went ok?
791 // Following is an attempt... (BE 20001011)
793 // good() returns false if any error occured, including some
795 // bad() returns true if something bad happened in the buffer,
796 // which should include file system full errors.
801 lyxerr << "File was not closed properly." << endl;
808 void Buffer::makeLaTeXFile(string const & fname,
809 string const & original_path,
810 OutputParams const & runparams,
811 bool output_preamble, bool output_body)
813 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
816 if (!openFileWrite(ofs, fname))
819 makeLaTeXFile(ofs, original_path,
820 runparams, output_preamble, output_body);
824 lyxerr << "File '" << fname << "' was not closed properly." << endl;
828 void Buffer::makeLaTeXFile(ostream & os,
829 string const & original_path,
830 OutputParams const & runparams_in,
831 bool const output_preamble, bool const output_body)
833 OutputParams runparams = runparams_in;
835 // validate the buffer.
836 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
837 LaTeXFeatures features(*this, params(), runparams.nice);
839 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
843 // The starting paragraph of the coming rows is the
844 // first paragraph of the document. (Asger)
845 texrow().start(paragraphs().begin()->id(), 0);
847 if (output_preamble && runparams.nice) {
848 os << "%% LyX " << lyx_version << " created this file. "
849 "For more info, see http://www.lyx.org/.\n"
850 "%% Do not edit unless you really know what "
855 lyxerr[Debug::INFO] << "lyx header finished" << endl;
856 // There are a few differences between nice LaTeX and usual files:
857 // usual is \batchmode and has a
858 // special input@path to allow the including of figures
859 // with either \input or \includegraphics (what figinsets do).
860 // input@path is set when the actual parameter
861 // original_path is set. This is done for usual tex-file, but not
862 // for nice-latex-file. (Matthias 250696)
863 // Note that input@path is only needed for something the user does
864 // in the preamble, included .tex files or ERT, files included by
865 // LyX work without it.
866 if (output_preamble) {
867 if (!runparams.nice) {
868 // code for usual, NOT nice-latex-file
869 os << "\\batchmode\n"; // changed
873 if (!original_path.empty()) {
874 string const inputpath = latex_path(original_path);
875 os << "\\makeatletter\n"
876 << "\\def\\input@path{{"
877 << inputpath << "/}}\n"
878 << "\\makeatother\n";
884 // Write the preamble
885 runparams.use_babel = params().writeLaTeX(os, features, texrow());
891 os << "\\begin{document}\n";
894 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
896 if (!lyxrc.language_auto_begin) {
897 os << subst(lyxrc.language_command_begin, "$$lang",
898 params().language->babel())
903 // if we are doing a real file with body, even if this is the
904 // child of some other buffer, let's cut the link here.
905 // This happens for example if only a child document is printed.
906 string save_parentname;
907 if (output_preamble) {
908 save_parentname = params().parentname;
909 params().parentname.erase();
913 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
915 // Restore the parenthood if needed
917 params().parentname = save_parentname;
919 // add this just in case after all the paragraphs
923 if (!lyxrc.language_auto_end) {
924 os << subst(lyxrc.language_command_end, "$$lang",
925 params().language->babel())
930 if (output_preamble) {
931 os << "\\end{document}\n";
934 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
936 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
940 // Just to be sure. (Asger)
943 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
944 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
949 bool Buffer::isLatex() const
951 return params().getLyXTextClass().outputType() == LATEX;
955 bool Buffer::isLinuxDoc() const
957 return params().getLyXTextClass().outputType() == LINUXDOC;
961 bool Buffer::isLiterate() const
963 return params().getLyXTextClass().outputType() == LITERATE;
967 bool Buffer::isDocBook() const
969 return params().getLyXTextClass().outputType() == DOCBOOK;
973 bool Buffer::isSGML() const
975 LyXTextClass const & tclass = params().getLyXTextClass();
977 return tclass.outputType() == LINUXDOC ||
978 tclass.outputType() == DOCBOOK;
982 void Buffer::makeLinuxDocFile(string const & fname,
983 OutputParams const & runparams,
984 bool const body_only)
987 if (!openFileWrite(ofs, fname))
990 LaTeXFeatures features(*this, params(), runparams.nice);
995 LyXTextClass const & tclass = params().getLyXTextClass();
997 string const & top_element = tclass.latexname();
1000 ofs << tclass.class_header();
1002 string preamble = params().preamble;
1003 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1005 preamble += features.getIncludedFiles(name);
1006 preamble += features.getLyXSGMLEntities();
1008 if (!preamble.empty()) {
1009 ofs << " [ " << preamble << " ]";
1013 if (params().options.empty())
1014 sgml::openTag(ofs, top_element);
1016 string top = top_element;
1018 top += params().options;
1019 sgml::openTag(ofs, top);
1023 ofs << "<!-- LyX " << lyx_version
1024 << " created this file. For more info see http://www.lyx.org/"
1027 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1031 sgml::closeTag(ofs, top_element);
1036 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1040 void Buffer::makeDocBookFile(string const & fname,
1041 OutputParams const & runparams,
1042 bool const only_body)
1045 if (!openFileWrite(ofs, fname))
1048 LaTeXFeatures features(*this, params(), runparams.nice);
1053 LyXTextClass const & tclass = params().getLyXTextClass();
1054 string const & top_element = tclass.latexname();
1057 if (runparams.flavor == OutputParams::XML)
1058 ofs << "<?xml version=\"1.0\" encoding=\""
1059 << params().language->encoding()->Name() << "\"?>\n";
1061 ofs << "<!DOCTYPE " << top_element << " ";
1063 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1064 else if (runparams.flavor == OutputParams::XML)
1065 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1066 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1068 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1070 string preamble = params().preamble;
1071 if (runparams.flavor != OutputParams::XML ) {
1072 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1073 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1074 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1075 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1078 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1080 preamble += features.getIncludedFiles(name);
1081 preamble += features.getLyXSGMLEntities();
1083 if (!preamble.empty()) {
1084 ofs << "\n [ " << preamble << " ]";
1089 string top = top_element;
1091 if (runparams.flavor == OutputParams::XML)
1092 top += params().language->code();
1094 top += params().language->code().substr(0,2);
1097 if (!params().options.empty()) {
1099 top += params().options;
1102 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1103 << " file was created by LyX " << lyx_version
1104 << "\n See http://www.lyx.org/ for more information -->\n";
1106 params().getLyXTextClass().counters().reset();
1108 sgml::openTag(ofs, top);
1110 docbookParagraphs(paragraphs(), *this, ofs, runparams);
1111 sgml::closeTag(ofs, top_element);
1115 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1119 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1120 // Other flags: -wall -v0 -x
1121 int Buffer::runChktex()
1125 // get LaTeX-Filename
1126 string const name = getLatexName();
1127 string const path = temppath();
1128 string const org_path = filePath();
1130 Path p(path); // path to LaTeX file
1131 message(_("Running chktex..."));
1133 // Generate the LaTeX file if neccessary
1134 OutputParams runparams;
1135 runparams.flavor = OutputParams::LATEX;
1136 runparams.nice = false;
1137 makeLaTeXFile(name, org_path, runparams);
1140 Chktex chktex(lyxrc.chktex_command, name, filePath());
1141 int const res = chktex.run(terr); // run chktex
1144 Alert::error(_("chktex failure"),
1145 _("Could not run chktex successfully."));
1146 } else if (res > 0) {
1147 // Insert all errors as errors boxes
1148 bufferErrors(*this, terr);
1157 void Buffer::validate(LaTeXFeatures & features) const
1159 LyXTextClass const & tclass = params().getLyXTextClass();
1161 if (features.isAvailable("dvipost") && params().tracking_changes
1162 && params().output_changes) {
1163 features.require("dvipost");
1164 features.require("color");
1167 // AMS Style is at document level
1168 if (params().use_amsmath == BufferParams::AMS_ON
1169 || tclass.provides(LyXTextClass::amsmath))
1170 features.require("amsmath");
1172 for_each(paragraphs().begin(), paragraphs().end(),
1173 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1175 // the bullet shapes are buffer level not paragraph level
1176 // so they are tested here
1177 for (int i = 0; i < 4; ++i) {
1178 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1179 int const font = params().user_defined_bullet(i).getFont();
1181 int const c = params()
1182 .user_defined_bullet(i)
1189 features.require("latexsym");
1191 } else if (font == 1) {
1192 features.require("amssymb");
1193 } else if ((font >= 2 && font <= 5)) {
1194 features.require("pifont");
1199 if (lyxerr.debugging(Debug::LATEX)) {
1200 features.showStruct();
1205 void Buffer::getLabelList(vector<string> & list) const
1207 /// if this is a child document and the parent is already loaded
1208 /// Use the parent's list instead [ale990407]
1209 Buffer const * tmp = getMasterBuffer();
1211 lyxerr << "getMasterBuffer() failed!" << endl;
1215 tmp->getLabelList(list);
1219 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1220 it.nextInset()->getLabelList(*this, list);
1224 // This is also a buffer property (ale)
1225 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1228 /// if this is a child document and the parent is already loaded
1229 /// use the parent's list instead [ale990412]
1230 Buffer const * tmp = getMasterBuffer();
1233 tmp->fillWithBibKeys(keys);
1237 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1238 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1239 InsetBibtex const & inset =
1240 dynamic_cast<InsetBibtex const &>(*it);
1241 inset.fillWithBibKeys(*this, keys);
1242 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1243 InsetInclude const & inset =
1244 dynamic_cast<InsetInclude const &>(*it);
1245 inset.fillWithBibKeys(*this, keys);
1246 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1247 InsetBibitem const & inset =
1248 dynamic_cast<InsetBibitem const &>(*it);
1249 string const key = inset.getContents();
1250 string const opt = inset.getOptions();
1251 string const ref; // = pit->asString(this, false);
1252 string const info = opt + "TheBibliographyRef" + ref;
1253 keys.push_back(pair<string, string>(key, info));
1259 bool Buffer::isDepClean(string const & name) const
1261 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1262 if (it == pimpl_->dep_clean.end())
1268 void Buffer::markDepClean(string const & name)
1270 pimpl_->dep_clean[name] = true;
1274 bool Buffer::dispatch(string const & command, bool * result)
1276 return dispatch(lyxaction.lookupFunc(command), result);
1280 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1282 bool dispatched = true;
1284 switch (func.action) {
1286 bool const tmp = Exporter::Export(this, func.argument, false);
1299 void Buffer::changeLanguage(Language const * from, Language const * to)
1304 lyxerr << "Changing Language!" << endl;
1306 // Take care of l10n/i18n
1309 for_each(par_iterator_begin(),
1311 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1315 void Buffer::updateDocLang(Language const * nlang)
1317 BOOST_ASSERT(nlang);
1319 pimpl_->messages.reset(new Messages(nlang->code()));
1323 bool Buffer::isMultiLingual() const
1325 ParConstIterator end = par_iterator_end();
1326 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1327 if (it->isMultiLingual(params()))
1334 ParIterator Buffer::getParFromID(int const id) const
1336 ParConstIterator it = par_iterator_begin();
1337 ParConstIterator const end = par_iterator_end();
1340 // John says this is called with id == -1 from undo
1341 lyxerr << "getParFromID(), id: " << id << endl;
1345 for (; it != end; ++it)
1353 bool Buffer::hasParWithID(int const id) const
1355 ParConstIterator const it = getParFromID(id);
1356 return it != par_iterator_end();
1360 ParIterator Buffer::par_iterator_begin()
1362 return ::par_iterator_begin(inset());
1366 ParIterator Buffer::par_iterator_end()
1368 return ::par_iterator_end(inset());
1372 ParConstIterator Buffer::par_iterator_begin() const
1374 return ::par_const_iterator_begin(inset());
1378 ParConstIterator Buffer::par_iterator_end() const
1380 return ::par_const_iterator_end(inset());
1384 Language const * Buffer::getLanguage() const
1386 return params().language;
1390 string const Buffer::B_(string const & l10n) const
1392 if (pimpl_->messages.get()) {
1393 return pimpl_->messages->get(l10n);
1400 bool Buffer::isClean() const
1402 return pimpl_->lyx_clean;
1406 bool Buffer::isBakClean() const
1408 return pimpl_->bak_clean;
1412 void Buffer::markClean() const
1414 if (!pimpl_->lyx_clean) {
1415 pimpl_->lyx_clean = true;
1418 // if the .lyx file has been saved, we don't need an
1420 pimpl_->bak_clean = true;
1424 void Buffer::markBakClean()
1426 pimpl_->bak_clean = true;
1430 void Buffer::setUnnamed(bool flag)
1432 pimpl_->unnamed = flag;
1436 bool Buffer::isUnnamed() const
1438 return pimpl_->unnamed;
1442 #ifdef WITH_WARNINGS
1443 #warning this function should be moved to buffer_pimpl.C
1445 void Buffer::markDirty()
1447 if (pimpl_->lyx_clean) {
1448 pimpl_->lyx_clean = false;
1451 pimpl_->bak_clean = false;
1453 DepClean::iterator it = pimpl_->dep_clean.begin();
1454 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1456 for (; it != end; ++it) {
1462 string const & Buffer::fileName() const
1464 return pimpl_->filename;
1468 string const & Buffer::filePath() const
1470 return pimpl_->filepath;
1474 bool Buffer::isReadonly() const
1476 return pimpl_->read_only;
1480 void Buffer::setParentName(string const & name)
1482 params().parentname = name;
1486 Buffer const * Buffer::getMasterBuffer() const
1488 if (!params().parentname.empty()
1489 && bufferlist.exists(params().parentname)) {
1490 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1492 return buf->getMasterBuffer();
1499 MacroData const & Buffer::getMacro(std::string const & name) const
1501 return pimpl_->macros.get(name);
1505 bool Buffer::hasMacro(string const & name) const
1507 return pimpl_->macros.has(name);
1511 void Buffer::insertMacro(string const & name, MacroData const & data)
1513 MacroTable::globalMacros().insert(name, data);
1514 pimpl_->macros.insert(name, data);
1518 void Buffer::buildMacros()
1520 // Start with global table.
1521 pimpl_->macros = MacroTable::globalMacros();
1524 ParagraphList & pars = text().paragraphs();
1525 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1526 //lyxerr << "searching main par " << i
1527 // << " for macro definitions" << std::endl;
1528 InsetList::iterator it = pars[i].insetlist.begin();
1529 InsetList::iterator end = pars[i].insetlist.end();
1530 for ( ; it != end; ++it) {
1531 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1532 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1533 MathMacroTemplate & mac
1534 = static_cast<MathMacroTemplate &>(*it->inset);
1535 insertMacro(mac.name(), mac.asMacroData());