3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
24 #include "errorlist.h"
27 #include "funcrequest.h"
29 #include "insetiterator.h"
32 #include "LaTeXFeatures.h"
33 #include "LyXAction.h"
41 #include "output_docbook.h"
42 #include "output_latex.h"
43 #include "output_linuxdoc.h"
44 #include "paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "pariterator.h"
53 #include "insets/insetbibitem.h"
54 #include "insets/insetbibtex.h"
55 #include "insets/insetinclude.h"
56 #include "insets/insettext.h"
58 #include "mathed/math_macrotemplate.h"
59 #include "mathed/math_macrotable.h"
60 #include "mathed/math_support.h"
62 #include "frontends/Alert.h"
64 #include "graphics/Previews.h"
66 #include "support/FileInfo.h"
67 #include "support/filetools.h"
68 #include "support/gzstream.h"
69 #include "support/lyxlib.h"
70 #include "support/os.h"
71 #include "support/path.h"
72 #include "support/textutils.h"
73 #include "support/tostr.h"
75 #include <boost/bind.hpp>
87 using lyx::support::AddName;
88 using lyx::support::bformat;
89 using lyx::support::ChangeExtension;
90 using lyx::support::cmd_ret;
91 using lyx::support::createBufferTmpDir;
92 using lyx::support::destroyDir;
93 using lyx::support::FileInfo;
94 using lyx::support::FileInfo;
95 using lyx::support::getFormatFromContents;
96 using lyx::support::IsDirWriteable;
97 using lyx::support::IsFileWriteable;
98 using lyx::support::LibFileSearch;
99 using lyx::support::ltrim;
100 using lyx::support::MakeAbsPath;
101 using lyx::support::MakeDisplayPath;
102 using lyx::support::MakeLatexName;
103 using lyx::support::OnlyFilename;
104 using lyx::support::OnlyPath;
105 using lyx::support::Path;
106 using lyx::support::QuoteName;
107 using lyx::support::removeAutosaveFile;
108 using lyx::support::rename;
109 using lyx::support::RunCommand;
110 using lyx::support::split;
111 using lyx::support::strToInt;
112 using lyx::support::subst;
113 using lyx::support::tempName;
114 using lyx::support::trim;
116 namespace os = lyx::support::os;
120 using std::make_pair;
126 using std::ostringstream;
134 // all these externs should eventually be removed.
135 extern BufferList bufferlist;
139 const int LYX_FORMAT = 237;
144 typedef std::map<string, bool> DepClean;
148 Impl(Buffer & parent, string const & file, bool readonly);
150 limited_stack<Undo> undostack;
151 limited_stack<Undo> redostack;
157 /// need to regenerate .tex?
161 mutable bool lyx_clean;
163 /// is autosave needed?
164 mutable bool bak_clean;
166 /// is this a unnamed file (New...)?
172 /// name of the file the buffer is associated with.
175 /// The path to the document file.
178 boost::scoped_ptr<Messages> messages;
180 /** Set to true only when the file is fully loaded.
181 * Used to prevent the premature generation of previews
182 * and by the citation inset.
184 bool file_fully_loaded;
186 /// our LyXText that should be wrapped in an InsetText
194 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
195 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
196 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
199 lyxvc.buffer(&parent);
200 temppath = createBufferTmpDir();
201 // FIXME: And now do something if temppath == string(), because we
202 // assume from now on that temppath points to a valid temp dir.
203 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
207 Buffer::Buffer(string const & file, bool ronly)
208 : pimpl_(new Impl(*this, file, ronly))
210 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
216 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
217 // here the buffer should take care that it is
218 // saved properly, before it goes into the void.
222 if (!temppath().empty() && destroyDir(temppath()) != 0) {
223 Alert::warning(_("Could not remove temporary directory"),
224 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
227 // Remove any previewed LaTeX snippets associated with this buffer.
228 lyx::graphics::Previews::get().removeLoader(*this);
232 LyXText & Buffer::text() const
234 return const_cast<LyXText &>(pimpl_->inset.text_);
238 InsetBase & Buffer::inset() const
240 return const_cast<InsetText &>(pimpl_->inset);
244 limited_stack<Undo> & Buffer::undostack()
246 return pimpl_->undostack;
250 limited_stack<Undo> const & Buffer::undostack() const
252 return pimpl_->undostack;
256 limited_stack<Undo> & Buffer::redostack()
258 return pimpl_->redostack;
262 limited_stack<Undo> const & Buffer::redostack() const
264 return pimpl_->redostack;
268 BufferParams & Buffer::params()
270 return pimpl_->params;
274 BufferParams const & Buffer::params() const
276 return pimpl_->params;
280 ParagraphList & Buffer::paragraphs()
282 return text().paragraphs();
286 ParagraphList const & Buffer::paragraphs() const
288 return text().paragraphs();
292 LyXVC & Buffer::lyxvc()
294 return pimpl_->lyxvc;
298 LyXVC const & Buffer::lyxvc() const
300 return pimpl_->lyxvc;
304 string const & Buffer::temppath() const
306 return pimpl_->temppath;
310 TexRow & Buffer::texrow()
312 return pimpl_->texrow;
316 TexRow const & Buffer::texrow() const
318 return pimpl_->texrow;
322 string const Buffer::getLatexName(bool no_path) const
324 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
325 return no_path ? OnlyFilename(name) : name;
329 pair<Buffer::LogType, string> const Buffer::getLogName() const
331 string const filename = getLatexName(false);
333 if (filename.empty())
334 return make_pair(Buffer::latexlog, string());
336 string const path = temppath();
338 string const fname = AddName(path,
339 OnlyFilename(ChangeExtension(filename,
342 AddName(path, OnlyFilename(
343 ChangeExtension(filename,
344 formats.extension("literate") + ".out")));
346 // If no Latex log or Build log is newer, show Build log
348 FileInfo const f_fi(fname);
349 FileInfo const b_fi(bname);
352 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
353 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
354 return make_pair(Buffer::buildlog, bname);
356 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
357 return make_pair(Buffer::latexlog, fname);
361 void Buffer::setReadonly(bool flag)
363 if (pimpl_->read_only != flag) {
364 pimpl_->read_only = flag;
370 void Buffer::setFileName(string const & newfile)
372 pimpl_->filename = MakeAbsPath(newfile);
373 pimpl_->filepath = OnlyPath(pimpl_->filename);
374 setReadonly(IsFileWriteable(pimpl_->filename) == 0);
379 // We'll remove this later. (Lgb)
382 void unknownClass(string const & unknown)
384 Alert::warning(_("Unknown document class"),
385 bformat(_("Using the default document class, because the "
386 "class %1$s is unknown."), unknown));
392 int Buffer::readHeader(LyXLex & lex)
394 int unknown_tokens = 0;
396 int begin_header_line = -1;
400 string const token = lex.getString();
405 if (token == "\\end_header")
409 if (token == "\\begin_header") {
410 begin_header_line = line;
414 lyxerr[Debug::PARSER] << "Handling header token: `"
415 << token << '\'' << endl;
417 string unknown = params().readToken(lex, token);
418 if (!unknown.empty()) {
419 if (unknown[0] != '\\' and token == "\\textclass") {
420 unknownClass(unknown);
423 string const s = bformat(_("Unknown token: "
427 error(ErrorItem(_("Header error"), s,
432 if (begin_header_line) {
433 string const s = _("\\begin_header is missing");
434 error(ErrorItem(_("Header error"), s, -1, 0, 0));
436 return unknown_tokens;
441 // changed to be public and have one parameter
442 // Returns false if "\end_document" is not read (Asger)
443 bool Buffer::readDocument(LyXLex & lex)
446 string const token = lex.getString();
447 if (token != "\\begin_document") {
448 string const s = _("\\begin_document is missing");
449 error(ErrorItem(_("Header error"), s, -1, 0, 0));
452 if (paragraphs().empty()) {
454 if (!params().getLyXTextClass().load()) {
455 string theclass = params().getLyXTextClass().name();
456 Alert::error(_("Can't load document class"), bformat(
457 "Using the default document class, because the "
458 " class %1$s could not be loaded.", theclass));
459 params().textclass = 0;
462 // We don't want to adopt the parameters from the
463 // document we insert, so read them into a temporary buffer
464 // and then discard it
466 Buffer tmpbuf("", false);
467 tmpbuf.readHeader(lex);
470 return text().read(*this, lex);
474 // needed to insert the selection
475 void Buffer::insertStringAsLines(ParagraphList & pars,
476 par_type & par, pos_type & pos,
477 LyXFont const & fn, string const & str)
479 LyXLayout_ptr const & layout = pars[par].layout();
483 pars[par].checkInsertChar(font);
484 // insert the string, don't insert doublespace
485 bool space_inserted = true;
486 bool autobreakrows = pars[par].autoBreakRows();
487 for (string::const_iterator cit = str.begin();
488 cit != str.end(); ++cit) {
490 if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
491 breakParagraph(params(), paragraphs(), par, pos,
492 layout->isEnvironment());
495 space_inserted = true;
499 // do not insert consecutive spaces if !free_spacing
500 } else if ((*cit == ' ' || *cit == '\t') &&
501 space_inserted && !pars[par].isFreeSpacing()) {
503 } else if (*cit == '\t') {
504 if (!pars[par].isFreeSpacing()) {
505 // tabs are like spaces here
506 pars[par].insertChar(pos, ' ', font);
508 space_inserted = true;
510 const pos_type n = 8 - pos % 8;
511 for (pos_type i = 0; i < n; ++i) {
512 pars[par].insertChar(pos, ' ', font);
515 space_inserted = true;
517 } else if (!IsPrintable(*cit)) {
518 // Ignore unprintables
521 // just insert the character
522 pars[par].insertChar(pos, *cit, font);
524 space_inserted = (*cit == ' ');
531 bool Buffer::readFile(string const & filename)
533 // Check if the file is compressed.
534 string const format = getFormatFromContents(filename);
535 if (format == "gzip" || format == "zip" || format == "compress") {
536 params().compressed = true;
539 // remove dummy empty par
540 paragraphs().clear();
541 bool ret = readFile(filename, paragraphs().size());
543 // After we have read a file, we must ensure that the buffer
544 // language is set and used in the gui.
545 // If you know of a better place to put this, please tell me. (Lgb)
546 updateDocLang(params().language);
552 bool Buffer::readFile(string const & filename, par_type pit)
555 lex.setFile(filename);
556 return readFile(lex, filename, pit);
560 bool Buffer::fully_loaded() const
562 return pimpl_->file_fully_loaded;
566 void Buffer::fully_loaded(bool value)
568 pimpl_->file_fully_loaded = value;
572 bool Buffer::readFile(LyXLex & lex, string const & filename, par_type pit)
574 BOOST_ASSERT(!filename.empty());
577 Alert::error(_("Document could not be read"),
578 bformat(_("%1$s could not be read."), filename));
583 string const token(lex.getString());
586 Alert::error(_("Document could not be read"),
587 bformat(_("%1$s could not be read."), filename));
591 // the first token _must_ be...
592 if (token != "\\lyxformat") {
593 lyxerr << "Token: " << token << endl;
595 Alert::error(_("Document format failure"),
596 bformat(_("%1$s is not a LyX document."),
602 string tmp_format = lex.getString();
603 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
604 // if present remove ".," from string.
605 string::size_type dot = tmp_format.find_first_of(".,");
606 //lyxerr << " dot found at " << dot << endl;
607 if (dot != string::npos)
608 tmp_format.erase(dot, 1);
609 int file_format = strToInt(tmp_format);
610 //lyxerr << "format: " << file_format << endl;
612 if (file_format != LYX_FORMAT) {
613 string const tmpfile = tempName();
614 if (tmpfile.empty()) {
615 Alert::error(_("Conversion failed"),
616 bformat(_("%1$s is from an earlier"
617 " version of LyX, but a temporary"
618 " file for converting it could"
623 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
624 if (command.empty()) {
625 Alert::error(_("Conversion script not found"),
626 bformat(_("%1$s is from an earlier"
627 " version of LyX, but the"
628 " conversion script lyx2lyx"
629 " could not be found."),
635 + " -o " + tmpfile + ' '
636 + QuoteName(filename);
637 lyxerr[Debug::INFO] << "Running '"
640 cmd_ret const ret = RunCommand(command);
641 if (ret.first != 0) {
642 Alert::error(_("Conversion script failed"),
643 bformat(_("%1$s is from an earlier version"
644 " of LyX, but the lyx2lyx script"
645 " failed to convert it."),
649 bool ret = readFile(tmpfile, pit);
650 // Do stuff with tmpfile name and buffer name here.
656 if (readDocument(lex)) {
657 Alert::error(_("Document format failure"),
658 bformat(_("%1$s ended unexpectedly, which means"
659 " that it is probably corrupted."),
663 //lyxerr << "removing " << MacroTable::localMacros().size()
664 // << " temporary macro entries" << endl;
665 //MacroTable::localMacros().clear();
666 params().setPaperStuff();
668 pimpl_->file_fully_loaded = true;
673 // Should probably be moved to somewhere else: BufferView? LyXView?
674 bool Buffer::save() const
676 // We don't need autosaves in the immediate future. (Asger)
677 resetAutosaveTimers();
681 if (lyxrc.make_backup) {
682 s = fileName() + '~';
683 if (!lyxrc.backupdir_path.empty())
684 s = AddName(lyxrc.backupdir_path,
685 subst(os::slashify_path(s),'/','!'));
687 // Rename is the wrong way of making a backup,
688 // this is the correct way.
689 /* truss cp fil fil2:
690 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
691 stat("LyXVC.lyx", 0xEFFFF688) = 0
692 open("LyXVC.lyx", O_RDONLY) = 3
693 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
694 fstat(4, 0xEFFFF508) = 0
695 fstat(3, 0xEFFFF508) = 0
696 read(3, " # T h i s f i l e w".., 8192) = 5579
697 write(4, " # T h i s f i l e w".., 5579) = 5579
698 read(3, 0xEFFFD4A0, 8192) = 0
701 chmod("LyXVC3.lyx", 0100644) = 0
702 lseek(0, 0, SEEK_CUR) = 46440
706 // Should probably have some more error checking here.
707 // Doing it this way, also makes the inodes stay the same.
708 // This is still not a very good solution, in particular we
709 // might loose the owner of the backup.
710 FileInfo finfo(fileName());
712 mode_t fmode = finfo.getMode();
713 struct utimbuf times = {
714 finfo.getAccessTime(),
715 finfo.getModificationTime() };
717 ifstream ifs(fileName().c_str());
718 ofstream ofs(s.c_str(), ios::out|ios::trunc);
723 ::chmod(s.c_str(), fmode);
725 if (::utime(s.c_str(), ×)) {
726 lyxerr << "utime error." << endl;
729 lyxerr << "LyX was not able to make "
730 "backup copy. Beware." << endl;
735 if (writeFile(fileName())) {
737 removeAutosaveFile(fileName());
739 // Saving failed, so backup is not backup
740 if (lyxrc.make_backup)
741 rename(s, fileName());
748 bool Buffer::writeFile(string const & fname) const
750 if (pimpl_->read_only && fname == fileName())
753 FileInfo finfo(fname);
754 if (finfo.exist() && !finfo.writable())
759 if (params().compressed) {
760 gz::ogzstream ofs(fname.c_str());
764 retval = do_writeFile(ofs);
767 ofstream ofs(fname.c_str());
771 retval = do_writeFile(ofs);
778 bool Buffer::do_writeFile(ostream & ofs) const
781 // Use the standard "C" locale for file output.
782 ofs.imbue(std::locale::classic());
785 // The top of the file should not be written by params().
787 // write out a comment in the top of the file
788 ofs << "#LyX " << lyx_version
789 << " created this file. For more info see http://www.lyx.org/\n"
790 << "\\lyxformat " << LYX_FORMAT << "\n"
791 << "\\begin_document\n";
793 // now write out the buffer parameters.
794 ofs << "\\begin_header\n";
795 params().writeFile(ofs);
796 ofs << "\\end_header\n";
799 ofs << "\n\\begin_body\n";
800 text().write(*this, ofs);
801 ofs << "\n\\end_body\n";
803 // Write marker that shows file is complete
804 ofs << "\\end_document" << endl;
806 // Shouldn't really be needed....
809 // how to check if close went ok?
810 // Following is an attempt... (BE 20001011)
812 // good() returns false if any error occured, including some
814 // bad() returns true if something bad happened in the buffer,
815 // which should include file system full errors.
820 lyxerr << "File was not closed properly." << endl;
827 void Buffer::makeLaTeXFile(string const & fname,
828 string const & original_path,
829 OutputParams const & runparams,
830 bool output_preamble, bool output_body)
832 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
835 if (!openFileWrite(ofs, fname))
838 makeLaTeXFile(ofs, original_path,
839 runparams, output_preamble, output_body);
843 lyxerr << "File '" << fname << "' was not closed properly." << endl;
847 void Buffer::makeLaTeXFile(ostream & os,
848 string const & original_path,
849 OutputParams const & runparams_in,
850 bool output_preamble, bool output_body)
852 OutputParams runparams = runparams_in;
854 // validate the buffer.
855 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
856 LaTeXFeatures features(*this, params(), runparams.nice);
858 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
862 // The starting paragraph of the coming rows is the
863 // first paragraph of the document. (Asger)
864 texrow().start(paragraphs().begin()->id(), 0);
866 if (output_preamble && runparams.nice) {
867 os << "%% LyX " << lyx_version << " created this file. "
868 "For more info, see http://www.lyx.org/.\n"
869 "%% Do not edit unless you really know what "
874 lyxerr[Debug::INFO] << "lyx header finished" << endl;
875 // There are a few differences between nice LaTeX and usual files:
876 // usual is \batchmode and has a
877 // special input@path to allow the including of figures
878 // with either \input or \includegraphics (what figinsets do).
879 // input@path is set when the actual parameter
880 // original_path is set. This is done for usual tex-file, but not
881 // for nice-latex-file. (Matthias 250696)
882 // Note that input@path is only needed for something the user does
883 // in the preamble, included .tex files or ERT, files included by
884 // LyX work without it.
885 if (output_preamble) {
886 if (!runparams.nice) {
887 // code for usual, NOT nice-latex-file
888 os << "\\batchmode\n"; // changed
892 if (!original_path.empty()) {
893 string inputpath = os::external_path(original_path);
894 subst(inputpath, "~", "\\string~");
895 os << "\\makeatletter\n"
896 << "\\def\\input@path{{"
897 << inputpath << "/}}\n"
898 << "\\makeatother\n";
904 // Write the preamble
905 runparams.use_babel = params().writeLaTeX(os, features, texrow());
911 os << "\\begin{document}\n";
914 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
916 if (!lyxrc.language_auto_begin) {
917 os << subst(lyxrc.language_command_begin, "$$lang",
918 params().language->babel())
923 // if we are doing a real file with body, even if this is the
924 // child of some other buffer, let's cut the link here.
925 // This happens for example if only a child document is printed.
926 string save_parentname;
927 if (output_preamble) {
928 save_parentname = params().parentname;
929 params().parentname.erase();
933 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
935 // Restore the parenthood if needed
937 params().parentname = save_parentname;
939 // add this just in case after all the paragraphs
943 if (!lyxrc.language_auto_end) {
944 os << subst(lyxrc.language_command_end, "$$lang",
945 params().language->babel())
950 if (output_preamble) {
951 os << "\\end{document}\n";
954 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
956 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
960 // Just to be sure. (Asger)
963 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
964 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
969 bool Buffer::isLatex() const
971 return params().getLyXTextClass().outputType() == LATEX;
975 bool Buffer::isLinuxDoc() const
977 return params().getLyXTextClass().outputType() == LINUXDOC;
981 bool Buffer::isLiterate() const
983 return params().getLyXTextClass().outputType() == LITERATE;
987 bool Buffer::isDocBook() const
989 return params().getLyXTextClass().outputType() == DOCBOOK;
993 bool Buffer::isSGML() const
995 LyXTextClass const & tclass = params().getLyXTextClass();
997 return tclass.outputType() == LINUXDOC ||
998 tclass.outputType() == DOCBOOK;
1002 void Buffer::makeLinuxDocFile(string const & fname,
1003 OutputParams const & runparams,
1007 if (!openFileWrite(ofs, fname))
1010 LaTeXFeatures features(*this, params(), runparams.nice);
1015 LyXTextClass const & tclass = params().getLyXTextClass();
1017 string top_element = tclass.latexname();
1020 ofs << tclass.class_header();
1022 string preamble = params().preamble;
1023 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1025 preamble += features.getIncludedFiles(name);
1026 preamble += features.getLyXSGMLEntities();
1028 if (!preamble.empty()) {
1029 ofs << " [ " << preamble << " ]";
1033 if (params().options.empty())
1034 sgml::openTag(ofs, top_element);
1036 string top = top_element;
1038 top += params().options;
1039 sgml::openTag(ofs, top);
1043 ofs << "<!-- LyX " << lyx_version
1044 << " created this file. For more info see http://www.lyx.org/"
1047 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1051 sgml::closeTag(ofs, top_element);
1056 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1060 void Buffer::makeDocBookFile(string const & fname,
1061 OutputParams const & runparams,
1065 if (!openFileWrite(ofs, fname))
1068 LaTeXFeatures features(*this, params(), runparams.nice);
1073 LyXTextClass const & tclass = params().getLyXTextClass();
1074 string top_element = tclass.latexname();
1077 if (runparams.flavor == OutputParams::XML)
1078 ofs << "<?xml version=\"1.0\" encoding=\""
1079 << params().language->encoding()->Name() << "\"?>\n";
1081 ofs << "<!DOCTYPE " << top_element << " ";
1083 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1084 else if (runparams.flavor == OutputParams::XML)
1085 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1086 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1088 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1090 string preamble = params().preamble;
1091 if (runparams.flavor != OutputParams::XML ) {
1092 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1093 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1094 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1095 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1098 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1100 preamble += features.getIncludedFiles(name);
1101 preamble += features.getLyXSGMLEntities();
1103 if (!preamble.empty()) {
1104 ofs << "\n [ " << preamble << " ]";
1109 string top = top_element;
1111 if (runparams.flavor == OutputParams::XML)
1112 top += params().language->code();
1114 top += params().language->code().substr(0,2);
1117 if (!params().options.empty()) {
1119 top += params().options;
1122 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1123 << " file was created by LyX " << lyx_version
1124 << "\n See http://www.lyx.org/ for more information -->\n";
1126 params().getLyXTextClass().counters().reset();
1128 sgml::openTag(ofs, top);
1130 docbookParagraphs(paragraphs(), *this, ofs, runparams);
1131 sgml::closeTag(ofs, top_element);
1135 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1139 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1140 // Other flags: -wall -v0 -x
1141 int Buffer::runChktex()
1145 // get LaTeX-Filename
1146 string const name = getLatexName();
1147 string const path = temppath();
1148 string const org_path = filePath();
1150 Path p(path); // path to LaTeX file
1151 message(_("Running chktex..."));
1153 // Generate the LaTeX file if neccessary
1154 OutputParams runparams;
1155 runparams.flavor = OutputParams::LATEX;
1156 runparams.nice = false;
1157 makeLaTeXFile(name, org_path, runparams);
1160 Chktex chktex(lyxrc.chktex_command, name, filePath());
1161 int res = chktex.run(terr); // run chktex
1164 Alert::error(_("chktex failure"),
1165 _("Could not run chktex successfully."));
1166 } else if (res > 0) {
1167 // Insert all errors as errors boxes
1168 bufferErrors(*this, terr);
1177 void Buffer::validate(LaTeXFeatures & features) const
1179 LyXTextClass const & tclass = params().getLyXTextClass();
1181 if (params().tracking_changes) {
1182 features.require("dvipost");
1183 features.require("color");
1186 // AMS Style is at document level
1187 if (params().use_amsmath == BufferParams::AMS_ON
1188 || tclass.provides(LyXTextClass::amsmath))
1189 features.require("amsmath");
1191 for_each(paragraphs().begin(), paragraphs().end(),
1192 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1194 // the bullet shapes are buffer level not paragraph level
1195 // so they are tested here
1196 for (int i = 0; i < 4; ++i) {
1197 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1198 int const font = params().user_defined_bullet(i).getFont();
1200 int const c = params()
1201 .user_defined_bullet(i)
1208 features.require("latexsym");
1210 } else if (font == 1) {
1211 features.require("amssymb");
1212 } else if ((font >= 2 && font <= 5)) {
1213 features.require("pifont");
1218 if (lyxerr.debugging(Debug::LATEX)) {
1219 features.showStruct();
1224 void Buffer::getLabelList(std::vector<string> & list) const
1226 /// if this is a child document and the parent is already loaded
1227 /// Use the parent's list instead [ale990407]
1228 Buffer const * tmp = getMasterBuffer();
1230 lyxerr << "getMasterBuffer() failed!" << endl;
1234 tmp->getLabelList(list);
1238 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1239 it.nextInset()->getLabelList(*this, list);
1243 // This is also a buffer property (ale)
1244 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys)
1247 /// if this is a child document and the parent is already loaded
1248 /// use the parent's list instead [ale990412]
1249 Buffer const * tmp = getMasterBuffer();
1252 tmp->fillWithBibKeys(keys);
1256 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1257 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1258 InsetBibtex const & inset =
1259 dynamic_cast<InsetBibtex const &>(*it);
1260 inset.fillWithBibKeys(*this, keys);
1261 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1262 InsetInclude const & inset =
1263 dynamic_cast<InsetInclude const &>(*it);
1264 inset.fillWithBibKeys(*this, keys);
1265 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1266 InsetBibitem const & inset =
1267 dynamic_cast<InsetBibitem const &>(*it);
1268 string const key = inset.getContents();
1269 string const opt = inset.getOptions();
1270 string const ref; // = pit->asString(this, false);
1271 string const info = opt + "TheBibliographyRef" + ref;
1272 keys.push_back(pair<string, string>(key, info));
1278 bool Buffer::isDepClean(string const & name) const
1280 DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1281 if (it == pimpl_->dep_clean.end())
1287 void Buffer::markDepClean(string const & name)
1289 pimpl_->dep_clean[name] = true;
1293 bool Buffer::dispatch(string const & command, bool * result)
1295 return dispatch(lyxaction.lookupFunc(command), result);
1299 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1301 bool dispatched = true;
1303 switch (func.action) {
1305 bool const tmp = Exporter::Export(this, func.argument, false);
1318 void Buffer::changeLanguage(Language const * from, Language const * to)
1320 lyxerr << "Changing Language!" << endl;
1322 // Take care of l10n/i18n
1325 for_each(par_iterator_begin(),
1327 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1331 void Buffer::updateDocLang(Language const * nlang)
1333 pimpl_->messages.reset(new Messages(nlang->code()));
1337 bool Buffer::isMultiLingual() const
1339 ParConstIterator end = par_iterator_end();
1340 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1341 if (it->isMultiLingual(params()))
1348 ParIterator Buffer::getParFromID(int id) const
1350 ParConstIterator it = par_iterator_begin();
1351 ParConstIterator end = par_iterator_end();
1354 // John says this is called with id == -1 from undo
1355 lyxerr << "getParFromID(), id: " << id << endl;
1359 for (; it != end; ++it)
1367 bool Buffer::hasParWithID(int id) const
1369 ParConstIterator it = getParFromID(id);
1370 return it != par_iterator_end();
1374 ParIterator Buffer::par_iterator_begin()
1376 return ::par_iterator_begin(inset());
1380 ParIterator Buffer::par_iterator_end()
1382 return ::par_iterator_end(inset());
1386 ParConstIterator Buffer::par_iterator_begin() const
1388 return ::par_const_iterator_begin(inset());
1392 ParConstIterator Buffer::par_iterator_end() const
1394 return ::par_const_iterator_end(inset());
1398 Language const * Buffer::getLanguage() const
1400 return params().language;
1404 string const Buffer::B_(string const & l10n) const
1406 if (pimpl_->messages.get()) {
1407 return pimpl_->messages->get(l10n);
1414 bool Buffer::isClean() const
1416 return pimpl_->lyx_clean;
1420 bool Buffer::isBakClean() const
1422 return pimpl_->bak_clean;
1426 void Buffer::markClean() const
1428 if (!pimpl_->lyx_clean) {
1429 pimpl_->lyx_clean = true;
1432 // if the .lyx file has been saved, we don't need an
1434 pimpl_->bak_clean = true;
1438 void Buffer::markBakClean()
1440 pimpl_->bak_clean = true;
1444 void Buffer::setUnnamed(bool flag)
1446 pimpl_->unnamed = flag;
1450 bool Buffer::isUnnamed() const
1452 return pimpl_->unnamed;
1456 void Buffer::markDirty()
1458 if (pimpl_->lyx_clean) {
1459 pimpl_->lyx_clean = false;
1462 pimpl_->bak_clean = false;
1464 DepClean::iterator it = pimpl_->dep_clean.begin();
1465 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1467 for (; it != end; ++it) {
1473 string const & Buffer::fileName() const
1475 return pimpl_->filename;
1479 string const & Buffer::filePath() const
1481 return pimpl_->filepath;
1485 bool Buffer::isReadonly() const
1487 return pimpl_->read_only;
1491 void Buffer::setParentName(string const & name)
1493 params().parentname = name;
1497 Buffer const * Buffer::getMasterBuffer() const
1499 if (!params().parentname.empty()
1500 && bufferlist.exists(params().parentname)) {
1501 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1503 return buf->getMasterBuffer();
1510 MacroData const & Buffer::getMacro(std::string const & name) const
1512 return pimpl_->macros.get(name);
1516 bool Buffer::hasMacro(string const & name) const
1518 return pimpl_->macros.has(name);
1522 void Buffer::insertMacro(string const & name, MacroData const & data)
1524 MacroTable::globalMacros().insert(name, data);
1525 pimpl_->macros.insert(name, data);
1529 void Buffer::buildMacros()
1531 // Start with global table.
1532 pimpl_->macros = MacroTable::globalMacros();
1535 ParagraphList & pars = text().paragraphs();
1536 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1537 //lyxerr << "searching main par " << i
1538 // << " for macro definitions" << std::endl;
1539 InsetList::iterator it = pars[i].insetlist.begin();
1540 InsetList::iterator end = pars[i].insetlist.end();
1541 for ( ; it != end; ++it) {
1542 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1543 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1544 MathMacroTemplate & mac
1545 = static_cast<MathMacroTemplate &>(*it->inset);
1546 insertMacro(mac.name(), mac.asMacroData());