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"
22 #include "errorlist.h"
25 #include "funcrequest.h"
27 #include "iterators.h"
30 #include "LaTeXFeatures.h"
31 #include "LyXAction.h"
36 #include "paragraph.h"
37 #include "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
44 #include "insets/insetbibitem.h"
45 #include "insets/insetbibtex.h"
46 #include "insets/insetinclude.h"
47 #include "insets/insettext.h"
49 #include "frontends/Alert.h"
51 #include "graphics/Previews.h"
53 #include "support/FileInfo.h"
54 #include "support/filetools.h"
55 #include "support/gzstream.h"
56 #include "support/lyxlib.h"
57 #include "support/os.h"
58 #include "support/path.h"
59 #include "support/textutils.h"
60 #include "support/tostr.h"
62 #include <boost/bind.hpp>
64 #include "support/std_sstream.h"
76 using lyx::support::AddName;
77 using lyx::support::atoi;
78 using lyx::support::bformat;
79 using lyx::support::ChangeExtension;
80 using lyx::support::cmd_ret;
81 using lyx::support::CreateBufferTmpDir;
82 using lyx::support::destroyDir;
83 using lyx::support::FileInfo;
84 using lyx::support::FileInfo;
85 using lyx::support::getExtFromContents;
86 using lyx::support::IsDirWriteable;
87 using lyx::support::IsFileWriteable;
88 using lyx::support::LibFileSearch;
89 using lyx::support::ltrim;
90 using lyx::support::MakeAbsPath;
91 using lyx::support::MakeDisplayPath;
92 using lyx::support::MakeLatexName;
93 using lyx::support::OnlyFilename;
94 using lyx::support::OnlyPath;
95 using lyx::support::Path;
96 using lyx::support::QuoteName;
97 using lyx::support::removeAutosaveFile;
98 using lyx::support::rename;
99 using lyx::support::RunCommand;
100 using lyx::support::split;
101 using lyx::support::strToInt;
102 using lyx::support::subst;
103 using lyx::support::tempName;
104 using lyx::support::trim;
106 namespace os = lyx::support::os;
110 using std::make_pair;
115 using std::ostringstream;
123 // all these externs should eventually be removed.
124 extern BufferList bufferlist;
128 const int LYX_FORMAT = 225;
130 bool openFileWrite(ofstream & ofs, string const & fname)
132 ofs.open(fname.c_str());
134 string const file = MakeDisplayPath(fname, 50);
135 string text = bformat(_("Could not open the specified "
136 "document\n%1$s."), file);
137 Alert::error(_("Could not open file"), text);
146 typedef std::map<string, bool> DepClean;
150 Impl(Buffer & parent, string const & file, bool readonly);
152 limited_stack<Undo> undostack;
153 limited_stack<Undo> redostack;
155 ParagraphList paragraphs;
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;
192 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
194 lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
195 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false)
197 lyxvc.buffer(&parent);
198 if (readonly_ || lyxrc.use_tempdir)
199 temppath = CreateBufferTmpDir();
203 Buffer::Buffer(string const & file, bool ronly)
204 : pimpl_(new Impl(*this, file, ronly))
206 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
212 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
213 // here the buffer should take care that it is
214 // saved properly, before it goes into the void.
218 if (!temppath().empty() && destroyDir(temppath()) != 0) {
219 Alert::warning(_("Could not remove temporary directory"),
220 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
223 paragraphs().clear();
225 // Remove any previewed LaTeX snippets associated with this buffer.
226 lyx::graphics::Previews::get().removeLoader(*this);
230 limited_stack<Undo> & Buffer::undostack()
232 return pimpl_->undostack;
236 limited_stack<Undo> const & Buffer::undostack() const
238 return pimpl_->undostack;
242 limited_stack<Undo> & Buffer::redostack()
244 return pimpl_->redostack;
248 limited_stack<Undo> const & Buffer::redostack() const
250 return pimpl_->redostack;
254 BufferParams & Buffer::params()
256 return pimpl_->params;
260 BufferParams const & Buffer::params() const
262 return pimpl_->params;
266 ParagraphList & Buffer::paragraphs()
268 return pimpl_->paragraphs;
272 ParagraphList const & Buffer::paragraphs() const
274 return pimpl_->paragraphs;
278 LyXVC & Buffer::lyxvc()
280 return pimpl_->lyxvc;
284 LyXVC const & Buffer::lyxvc() const
286 return pimpl_->lyxvc;
290 string const & Buffer::temppath() const
292 return pimpl_->temppath;
296 bool & Buffer::niceFile()
298 return pimpl_->nicefile;
302 bool Buffer::niceFile() const
304 return pimpl_->nicefile;
308 TexRow & Buffer::texrow()
310 return pimpl_->texrow;
314 TexRow const & Buffer::texrow() const
316 return pimpl_->texrow;
320 string const Buffer::getLatexName(bool no_path) const
322 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
323 return no_path ? OnlyFilename(name) : name;
327 pair<Buffer::LogType, string> const Buffer::getLogName() const
329 string const filename = getLatexName(false);
331 if (filename.empty())
332 return make_pair(Buffer::latexlog, string());
334 string path = OnlyPath(filename);
336 if (lyxrc.use_tempdir || !IsDirWriteable(path))
339 string const fname = AddName(path,
340 OnlyFilename(ChangeExtension(filename,
343 AddName(path, OnlyFilename(
344 ChangeExtension(filename,
345 formats.extension("literate") + ".out")));
347 // If no Latex log or Build log is newer, show Build log
349 FileInfo const f_fi(fname);
350 FileInfo const b_fi(bname);
353 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
354 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
355 return make_pair(Buffer::buildlog, bname);
357 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
358 return make_pair(Buffer::latexlog, fname);
362 void Buffer::setReadonly(bool flag)
364 if (pimpl_->read_only != flag) {
365 pimpl_->read_only = flag;
371 void Buffer::setFileName(string const & newfile)
373 pimpl_->filename = MakeAbsPath(newfile);
374 pimpl_->filepath = OnlyPath(pimpl_->filename);
375 setReadonly(IsFileWriteable(pimpl_->filename) == 0);
380 // We'll remove this later. (Lgb)
383 void unknownClass(string const & unknown)
385 Alert::warning(_("Unknown document class"),
386 bformat(_("Using the default document class, because the "
387 "class %1$s is unknown."), unknown));
392 int Buffer::readHeader(LyXLex & lex)
394 int unknown_tokens = 0;
398 string const token = lex.getString();
403 if (token == "\\end_header")
406 lyxerr[Debug::PARSER] << "Handling header token: `"
407 << token << '\'' << endl;
410 string unknown = params().readToken(lex, token);
411 if (!unknown.empty()) {
412 if (unknown[0] != '\\') {
413 unknownClass(unknown);
416 string const s = bformat(_("Unknown token: "
420 error(ErrorItem(_("Header error"), s,
425 return unknown_tokens;
429 // candidate for move to BufferView
430 // (at least some parts in the beginning of the func)
433 // changed to be public and have one parameter
434 // if par = 0 normal behavior
435 // else insert behavior
436 // Returns false if "\end_document" is not read (Asger)
437 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
439 Paragraph::depth_type depth = 0;
440 bool the_end_read = false;
442 if (paragraphs().empty()) {
444 if (!params().getLyXTextClass().load()) {
445 string theclass = params().getLyXTextClass().name();
446 Alert::error(_("Can't load document class"), bformat(
447 "Using the default document class, because the "
448 " class %1$s could not be loaded.", theclass));
449 params().textclass = 0;
452 // We don't want to adopt the parameters from the
453 // document we insert, so read them into a temporary buffer
454 // and then discard it
456 Buffer tmpbuf("", false);
457 tmpbuf.readHeader(lex);
462 string const token = lex.getString();
467 lyxerr[Debug::PARSER] << "Handling token: `"
468 << token << '\'' << endl;
470 if (token == "\\end_document") {
475 readParagraph(lex, token, paragraphs(), pit, depth);
482 int Buffer::readParagraph(LyXLex & lex, string const & token,
483 ParagraphList & pars, ParagraphList::iterator & pit,
484 lyx::depth_type & depth)
486 static Change current_change;
489 if (token == "\\begin_layout") {
490 lex.pushToken(token);
493 par.params().depth(depth);
494 if (params().tracking_changes)
496 LyXFont f(LyXFont::ALL_INHERIT, params().language);
500 if (pit != pars.end())
503 pit = pars.insert(pit, par);
505 // FIXME: goddamn InsetTabular makes us pass a Buffer
507 ::readParagraph(*this, *pit, lex);
509 } else if (token == "\\begin_deeper") {
511 } else if (token == "\\end_deeper") {
513 lex.printError("\\end_deeper: " "depth is already null");
524 // needed to insert the selection
525 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
526 LyXFont const & fn,string const & str)
528 LyXLayout_ptr const & layout = par->layout();
532 par->checkInsertChar(font);
533 // insert the string, don't insert doublespace
534 bool space_inserted = true;
535 bool autobreakrows = !par->inInset() ||
536 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
537 for(string::const_iterator cit = str.begin();
538 cit != str.end(); ++cit) {
540 if (autobreakrows && (!par->empty() || par->allowEmpty())) {
541 breakParagraph(params(), paragraphs(), par, pos,
542 layout->isEnvironment());
545 space_inserted = true;
549 // do not insert consecutive spaces if !free_spacing
550 } else if ((*cit == ' ' || *cit == '\t') &&
551 space_inserted && !par->isFreeSpacing()) {
553 } else if (*cit == '\t') {
554 if (!par->isFreeSpacing()) {
555 // tabs are like spaces here
556 par->insertChar(pos, ' ', font);
558 space_inserted = true;
560 const pos_type nb = 8 - pos % 8;
561 for (pos_type a = 0; a < nb ; ++a) {
562 par->insertChar(pos, ' ', font);
565 space_inserted = true;
567 } else if (!IsPrintable(*cit)) {
568 // Ignore unprintables
571 // just insert the character
572 par->insertChar(pos, *cit, font);
574 space_inserted = (*cit == ' ');
581 bool Buffer::readFile(string const & filename)
583 // Check if the file is compressed.
584 string const format = getExtFromContents(filename);
585 if (format == "gzip" || format == "zip" || format == "compress") {
586 params().compressed = true;
589 bool ret = readFile(filename, paragraphs().begin());
591 // After we have read a file, we must ensure that the buffer
592 // language is set and used in the gui.
593 // If you know of a better place to put this, please tell me. (Lgb)
594 updateDocLang(params().language);
600 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
603 lex.setFile(filename);
605 return readFile(lex, filename, pit);
609 bool Buffer::fully_loaded() const
611 return pimpl_->file_fully_loaded;
615 void Buffer::fully_loaded(bool value)
617 pimpl_->file_fully_loaded = value;
621 bool Buffer::readFile(LyXLex & lex, string const & filename,
622 ParagraphList::iterator pit)
624 BOOST_ASSERT(!filename.empty());
627 Alert::error(_("Document could not be read"),
628 bformat(_("%1$s could not be read."), filename));
633 string const token(lex.getString());
636 Alert::error(_("Document could not be read"),
637 bformat(_("%1$s could not be read."), filename));
641 // the first token _must_ be...
642 if (token != "\\lyxformat") {
643 lyxerr << "Token: " << token << endl;
645 Alert::error(_("Document format failure"),
646 bformat(_("%1$s is not a LyX document."),
652 string tmp_format = lex.getString();
653 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
654 // if present remove ".," from string.
655 string::size_type dot = tmp_format.find_first_of(".,");
656 //lyxerr << " dot found at " << dot << endl;
657 if (dot != string::npos)
658 tmp_format.erase(dot, 1);
659 int file_format = strToInt(tmp_format);
660 //lyxerr << "format: " << file_format << endl;
662 if (file_format > LYX_FORMAT) {
663 Alert::warning(_("Document format failure"),
664 bformat(_("%1$s was created with a newer"
665 " version of LyX. This is likely to"
668 } else if (file_format < LYX_FORMAT) {
669 string const tmpfile = tempName();
670 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
671 if (command.empty()) {
672 Alert::error(_("Conversion script not found"),
673 bformat(_("%1$s is from an earlier"
674 " version of LyX, but the"
675 " conversion script lyx2lyx"
676 " could not be found."),
682 + " -o " + tmpfile + ' '
683 + QuoteName(filename);
684 lyxerr[Debug::INFO] << "Running '"
687 cmd_ret const ret = RunCommand(command);
688 if (ret.first != 0) {
689 Alert::error(_("Conversion script failed"),
690 bformat(_("%1$s is from an earlier version"
691 " of LyX, but the lyx2lyx script"
692 " failed to convert it."),
696 bool ret = readFile(tmpfile, pit);
697 // Do stuff with tmpfile name and buffer name here.
703 bool the_end = readBody(lex, pit);
704 params().setPaperStuff();
707 Alert::error(_("Document format failure"),
708 bformat(_("%1$s ended unexpectedly, which means"
709 " that it is probably corrupted."),
712 pimpl_->file_fully_loaded = true;
717 // Should probably be moved to somewhere else: BufferView? LyXView?
718 bool Buffer::save() const
720 // We don't need autosaves in the immediate future. (Asger)
721 resetAutosaveTimers();
725 if (lyxrc.make_backup) {
726 s = fileName() + '~';
727 if (!lyxrc.backupdir_path.empty())
728 s = AddName(lyxrc.backupdir_path,
729 subst(os::slashify_path(s),'/','!'));
731 // Rename is the wrong way of making a backup,
732 // this is the correct way.
733 /* truss cp fil fil2:
734 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
735 stat("LyXVC.lyx", 0xEFFFF688) = 0
736 open("LyXVC.lyx", O_RDONLY) = 3
737 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
738 fstat(4, 0xEFFFF508) = 0
739 fstat(3, 0xEFFFF508) = 0
740 read(3, " # T h i s f i l e w".., 8192) = 5579
741 write(4, " # T h i s f i l e w".., 5579) = 5579
742 read(3, 0xEFFFD4A0, 8192) = 0
745 chmod("LyXVC3.lyx", 0100644) = 0
746 lseek(0, 0, SEEK_CUR) = 46440
750 // Should probably have some more error checking here.
751 // Doing it this way, also makes the inodes stay the same.
752 // This is still not a very good solution, in particular we
753 // might loose the owner of the backup.
754 FileInfo finfo(fileName());
756 mode_t fmode = finfo.getMode();
757 struct utimbuf times = {
758 finfo.getAccessTime(),
759 finfo.getModificationTime() };
761 ifstream ifs(fileName().c_str());
762 ofstream ofs(s.c_str(), ios::out|ios::trunc);
767 ::chmod(s.c_str(), fmode);
769 if (::utime(s.c_str(), ×)) {
770 lyxerr << "utime error." << endl;
773 lyxerr << "LyX was not able to make "
774 "backup copy. Beware." << endl;
779 if (writeFile(fileName())) {
781 removeAutosaveFile(fileName());
783 // Saving failed, so backup is not backup
784 if (lyxrc.make_backup) {
785 rename(s, fileName());
793 bool Buffer::writeFile(string const & fname) const
795 if (pimpl_->read_only && (fname == fileName())) {
799 FileInfo finfo(fname);
800 if (finfo.exist() && !finfo.writable()) {
806 if (params().compressed) {
807 gz::ogzstream ofs(fname.c_str());
812 retval = do_writeFile(ofs);
815 ofstream ofs(fname.c_str());
819 retval = do_writeFile(ofs);
826 bool Buffer::do_writeFile(ostream & ofs) const
830 // Use the standard "C" locale for file output.
831 ofs.imbue(std::locale::classic());
834 // The top of the file should not be written by params().
836 // write out a comment in the top of the file
837 ofs << "#LyX " << lyx_version
838 << " created this file. For more info see http://www.lyx.org/\n"
839 << "\\lyxformat " << LYX_FORMAT << "\n";
841 // now write out the buffer paramters.
842 params().writeFile(ofs);
844 ofs << "\\end_header\n";
846 Paragraph::depth_type depth = 0;
848 // this will write out all the paragraphs
849 // using recursive descent.
850 ParagraphList::const_iterator pit = paragraphs().begin();
851 ParagraphList::const_iterator pend = paragraphs().end();
852 for (; pit != pend; ++pit)
853 pit->write(*this, ofs, params(), depth);
855 // Write marker that shows file is complete
856 ofs << "\n\\end_document" << endl;
858 // Shouldn't really be needed....
861 // how to check if close went ok?
862 // Following is an attempt... (BE 20001011)
864 // good() returns false if any error occured, including some
866 // bad() returns true if something bad happened in the buffer,
867 // which should include file system full errors.
874 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
876 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
886 void Buffer::writeFileAscii(string const & fname, LatexRunParams const & runparams)
889 if (!::openFileWrite(ofs, fname))
891 writeFileAscii(ofs, runparams);
895 void Buffer::writeFileAscii(ostream & os, LatexRunParams const & runparams)
897 ParagraphList::iterator beg = paragraphs().begin();
898 ParagraphList::iterator end = paragraphs().end();
899 ParagraphList::iterator it = beg;
900 for (; it != end; ++it) {
901 asciiParagraph(*this, *it, os, runparams, it == beg);
907 void Buffer::makeLaTeXFile(string const & fname,
908 string const & original_path,
909 LatexRunParams const & runparams,
910 bool output_preamble, bool output_body)
912 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
915 if (!::openFileWrite(ofs, fname))
918 makeLaTeXFile(ofs, original_path,
919 runparams, output_preamble, output_body);
923 lyxerr << "File was not closed properly." << endl;
928 void Buffer::makeLaTeXFile(ostream & os,
929 string const & original_path,
930 LatexRunParams const & runparams_in,
931 bool output_preamble, bool output_body)
933 LatexRunParams runparams = runparams_in;
934 niceFile() = runparams.nice; // this will be used by Insetincludes.
936 // validate the buffer.
937 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
938 LaTeXFeatures features(*this, params());
940 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
943 // The starting paragraph of the coming rows is the
944 // first paragraph of the document. (Asger)
945 texrow().start(paragraphs().begin()->id(), 0);
947 if (output_preamble && runparams.nice) {
948 os << "%% LyX " << lyx_version << " created this file. "
949 "For more info, see http://www.lyx.org/.\n"
950 "%% Do not edit unless you really know what "
955 lyxerr[Debug::INFO] << "lyx header finished" << endl;
956 // There are a few differences between nice LaTeX and usual files:
957 // usual is \batchmode and has a
958 // special input@path to allow the including of figures
959 // with either \input or \includegraphics (what figinsets do).
960 // input@path is set when the actual parameter
961 // original_path is set. This is done for usual tex-file, but not
962 // for nice-latex-file. (Matthias 250696)
963 if (output_preamble) {
964 if (!runparams.nice) {
965 // code for usual, NOT nice-latex-file
966 os << "\\batchmode\n"; // changed
970 if (!original_path.empty()) {
971 string inputpath = os::external_path(original_path);
972 subst(inputpath, "~", "\\string~");
973 os << "\\makeatletter\n"
974 << "\\def\\input@path{{"
975 << inputpath << "/}}\n"
976 << "\\makeatother\n";
982 // Write the preamble
983 runparams.use_babel = params().writeLaTeX(os, features, texrow());
989 os << "\\begin{document}\n";
992 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
994 if (!lyxrc.language_auto_begin) {
995 os << subst(lyxrc.language_command_begin, "$$lang",
996 params().language->babel())
1001 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1003 // add this just in case after all the paragraphs
1007 if (!lyxrc.language_auto_end) {
1008 os << subst(lyxrc.language_command_end, "$$lang",
1009 params().language->babel())
1014 if (output_preamble) {
1015 os << "\\end{document}\n";
1018 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1020 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1024 // Just to be sure. (Asger)
1027 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1028 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1031 // we want this to be true outside previews (for insetexternal)
1036 bool Buffer::isLatex() const
1038 return params().getLyXTextClass().outputType() == LATEX;
1042 bool Buffer::isLinuxDoc() const
1044 return params().getLyXTextClass().outputType() == LINUXDOC;
1048 bool Buffer::isLiterate() const
1050 return params().getLyXTextClass().outputType() == LITERATE;
1054 bool Buffer::isDocBook() const
1056 return params().getLyXTextClass().outputType() == DOCBOOK;
1060 bool Buffer::isSGML() const
1062 LyXTextClass const & tclass = params().getLyXTextClass();
1064 return tclass.outputType() == LINUXDOC ||
1065 tclass.outputType() == DOCBOOK;
1069 void Buffer::makeLinuxDocFile(string const & fname,
1070 LatexRunParams const & runparams,
1074 if (!::openFileWrite(ofs, fname))
1077 niceFile() = runparams.nice; // this will be used by included files.
1079 LaTeXFeatures features(*this, params());
1085 LyXTextClass const & tclass = params().getLyXTextClass();
1087 string top_element = tclass.latexname();
1090 ofs << "<!doctype linuxdoc system";
1092 string preamble = params().preamble;
1093 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1095 preamble += features.getIncludedFiles(name);
1096 preamble += features.getLyXSGMLEntities();
1098 if (!preamble.empty()) {
1099 ofs << " [ " << preamble << " ]";
1103 if (params().options.empty())
1104 sgml::openTag(ofs, 0, false, top_element);
1106 string top = top_element;
1108 top += params().options;
1109 sgml::openTag(ofs, 0, false, top);
1113 ofs << "<!-- LyX " << lyx_version
1114 << " created this file. For more info see http://www.lyx.org/"
1117 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1121 sgml::closeTag(ofs, 0, false, top_element);
1125 // How to check for successful close
1127 // we want this to be true outside previews (for insetexternal)
1132 void Buffer::makeDocBookFile(string const & fname,
1133 LatexRunParams const & runparams,
1137 if (!::openFileWrite(ofs, fname))
1140 niceFile() = runparams.nice; // this will be used by Insetincludes.
1142 LaTeXFeatures features(*this, params());
1147 LyXTextClass const & tclass = params().getLyXTextClass();
1148 string top_element = tclass.latexname();
1151 ofs << "<!DOCTYPE " << top_element
1152 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1154 string preamble = params().preamble;
1155 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1157 preamble += features.getIncludedFiles(name);
1158 preamble += features.getLyXSGMLEntities();
1160 if (!preamble.empty()) {
1161 ofs << "\n [ " << preamble << " ]";
1166 string top = top_element;
1168 top += params().language->code();
1171 if (!params().options.empty()) {
1173 top += params().options;
1175 sgml::openTag(ofs, 0, false, top);
1177 ofs << "<!-- DocBook file was created by LyX " << lyx_version
1178 << "\n See http://www.lyx.org/ for more information -->\n";
1180 docbookParagraphs(*this, paragraphs(), ofs, runparams);
1183 sgml::closeTag(ofs, 0, false, top_element);
1186 // How to check for successful close
1188 // we want this to be true outside previews (for insetexternal)
1193 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1194 // Other flags: -wall -v0 -x
1195 int Buffer::runChktex()
1199 // get LaTeX-Filename
1200 string const name = getLatexName();
1201 string path = filePath();
1203 string const org_path = path;
1204 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1208 Path p(path); // path to LaTeX file
1209 message(_("Running chktex..."));
1211 // Generate the LaTeX file if neccessary
1212 LatexRunParams runparams;
1213 runparams.flavor = LatexRunParams::LATEX;
1214 runparams.nice = false;
1215 makeLaTeXFile(name, org_path, runparams);
1218 Chktex chktex(lyxrc.chktex_command, name, filePath());
1219 int res = chktex.run(terr); // run chktex
1222 Alert::error(_("chktex failure"),
1223 _("Could not run chktex successfully."));
1224 } else if (res > 0) {
1225 // Insert all errors as errors boxes
1226 bufferErrors(*this, terr);
1235 void Buffer::validate(LaTeXFeatures & features) const
1237 LyXTextClass const & tclass = params().getLyXTextClass();
1239 if (params().tracking_changes) {
1240 features.require("dvipost");
1241 features.require("color");
1244 // AMS Style is at document level
1245 if (params().use_amsmath == BufferParams::AMS_ON
1246 || tclass.provides(LyXTextClass::amsmath))
1247 features.require("amsmath");
1249 for_each(paragraphs().begin(), paragraphs().end(),
1250 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1252 // the bullet shapes are buffer level not paragraph level
1253 // so they are tested here
1254 for (int i = 0; i < 4; ++i) {
1255 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1256 int const font = params().user_defined_bullet(i).getFont();
1258 int const c = params()
1259 .user_defined_bullet(i)
1266 features.require("latexsym");
1268 } else if (font == 1) {
1269 features.require("amssymb");
1270 } else if ((font >= 2 && font <= 5)) {
1271 features.require("pifont");
1276 if (lyxerr.debugging(Debug::LATEX)) {
1277 features.showStruct();
1282 void Buffer::getLabelList(std::vector<string> & list) const
1284 /// if this is a child document and the parent is already loaded
1285 /// Use the parent's list instead [ale990407]
1286 if (!params().parentname.empty()
1287 && bufferlist.exists(params().parentname)) {
1288 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1290 tmp->getLabelList(list);
1295 for (inset_iterator it = inset_const_iterator_begin();
1296 it != inset_const_iterator_end(); ++it) {
1297 it->getLabelList(*this, list);
1302 // This is also a buffer property (ale)
1303 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys) const
1305 /// if this is a child document and the parent is already loaded
1306 /// use the parent's list instead [ale990412]
1307 if (!params().parentname.empty() &&
1308 bufferlist.exists(params().parentname)) {
1309 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1311 tmp->fillWithBibKeys(keys);
1316 for (inset_iterator it = inset_const_iterator_begin();
1317 it != inset_const_iterator_end(); ++it) {
1318 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1319 InsetBibtex const & inset =
1320 dynamic_cast<InsetBibtex const &>(*it);
1321 inset.fillWithBibKeys(*this, keys);
1322 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1323 InsetInclude const & inset =
1324 dynamic_cast<InsetInclude const &>(*it);
1325 inset.fillWithBibKeys(*this, keys);
1326 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1327 InsetBibitem const & inset =
1328 dynamic_cast<InsetBibitem const &>(*it);
1329 string const key = inset.getContents();
1330 string const opt = inset.getOptions();
1331 string const ref; // = pit->asString(this, false);
1332 string const info = opt + "TheBibliographyRef" + ref;
1333 keys.push_back(pair<string, string>(key, info));
1339 bool Buffer::isDepClean(string const & name) const
1341 DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1342 if (it == pimpl_->dep_clean.end())
1348 void Buffer::markDepClean(string const & name)
1350 pimpl_->dep_clean[name] = true;
1354 bool Buffer::dispatch(string const & command, bool * result)
1356 return dispatch(lyxaction.lookupFunc(command), result);
1360 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1362 bool dispatched = true;
1364 switch (func.action) {
1366 bool const tmp = Exporter::Export(this, func.argument, false);
1379 void Buffer::changeLanguage(Language const * from, Language const * to)
1381 lyxerr << "Changing Language!" << endl;
1383 // Take care of l10n/i18n
1386 ParIterator end = par_iterator_end();
1387 for (ParIterator it = par_iterator_begin(); it != end; ++it)
1388 it->changeLanguage(params(), from, to);
1392 void Buffer::updateDocLang(Language const * nlang)
1394 pimpl_->messages.reset(new Messages(nlang->code()));
1398 bool Buffer::isMultiLingual()
1400 ParIterator end = par_iterator_end();
1401 for (ParIterator it = par_iterator_begin(); it != end; ++it)
1402 if (it->isMultiLingual(params()))
1409 void Buffer::inset_iterator::setParagraph()
1411 while (pit != pend) {
1412 it = pit->insetlist.begin();
1413 if (it != pit->insetlist.end())
1420 InsetOld * Buffer::getInsetFromID(int id_arg) const
1422 for (inset_iterator it = inset_const_iterator_begin();
1423 it != inset_const_iterator_end(); ++it)
1425 if (it->id() == id_arg)
1427 InsetOld * in = it->getInsetFromID(id_arg);
1435 ParIterator Buffer::getParFromID(int id) const
1437 #warning FIXME: const correctness! (Andre)
1438 ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1439 ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1441 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1443 // John says this is called with id == -1 from undo
1444 lyxerr << "getParFromID(), id: " << id << endl;
1448 for (; it != end; ++it)
1456 bool Buffer::hasParWithID(int id) const
1458 ParConstIterator it = par_iterator_begin();
1459 ParConstIterator end = par_iterator_end();
1462 // John says this is called with id == -1 from undo
1463 lyxerr << "hasParWithID(), id: " << id << endl;
1467 for (; it != end; ++it)
1475 ParIterator Buffer::par_iterator_begin()
1477 return ParIterator(paragraphs().begin(), paragraphs());
1481 ParIterator Buffer::par_iterator_end()
1483 return ParIterator(paragraphs().end(), paragraphs());
1487 ParConstIterator Buffer::par_iterator_begin() const
1489 ParagraphList const & pars = paragraphs();
1490 return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
1494 ParConstIterator Buffer::par_iterator_end() const
1496 ParagraphList const & pars = paragraphs();
1497 return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
1501 Language const * Buffer::getLanguage() const
1503 return params().language;
1507 string const Buffer::B_(string const & l10n) const
1509 if (pimpl_->messages.get()) {
1510 return pimpl_->messages->get(l10n);
1517 bool Buffer::isClean() const
1519 return pimpl_->lyx_clean;
1523 bool Buffer::isBakClean() const
1525 return pimpl_->bak_clean;
1529 void Buffer::markClean() const
1531 if (!pimpl_->lyx_clean) {
1532 pimpl_->lyx_clean = true;
1535 // if the .lyx file has been saved, we don't need an
1537 pimpl_->bak_clean = true;
1541 void Buffer::markBakClean()
1543 pimpl_->bak_clean = true;
1547 void Buffer::setUnnamed(bool flag)
1549 pimpl_->unnamed = flag;
1553 bool Buffer::isUnnamed()
1555 return pimpl_->unnamed;
1559 void Buffer::markDirty()
1561 if (pimpl_->lyx_clean) {
1562 pimpl_->lyx_clean = false;
1565 pimpl_->bak_clean = false;
1567 DepClean::iterator it = pimpl_->dep_clean.begin();
1568 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1570 for (; it != end; ++it) {
1576 string const & Buffer::fileName() const
1578 return pimpl_->filename;
1582 string const & Buffer::filePath() const
1584 return pimpl_->filepath;
1588 bool Buffer::isReadonly() const
1590 return pimpl_->read_only;
1594 void Buffer::setParentName(string const & name)
1596 params().parentname = name;
1600 Buffer::inset_iterator::inset_iterator()
1605 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
1612 Buffer::inset_iterator Buffer::inset_iterator_begin()
1614 return inset_iterator(paragraphs().begin(), paragraphs().end());
1618 Buffer::inset_iterator Buffer::inset_iterator_end()
1620 return inset_iterator(paragraphs().end(), paragraphs().end());
1624 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1626 ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1627 return inset_iterator(pars.begin(), pars.end());
1631 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1633 ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1634 return inset_iterator(pars.end(), pars.end());
1638 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1642 if (it == pit->insetlist.end()) {
1651 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1653 inset_iterator tmp = *this;
1659 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1665 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1671 ParagraphList::iterator Buffer::inset_iterator::getPar() const
1677 lyx::pos_type Buffer::inset_iterator::getPos() const
1683 bool operator==(Buffer::inset_iterator const & iter1,
1684 Buffer::inset_iterator const & iter2)
1686 return iter1.pit == iter2.pit
1687 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
1691 bool operator!=(Buffer::inset_iterator const & iter1,
1692 Buffer::inset_iterator const & iter2)
1694 return !(iter1 == iter2);