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"
37 #include "output_docbook.h"
38 #include "output_latex.h"
39 #include "output_linuxdoc.h"
40 #include "paragraph.h"
41 #include "paragraph_funcs.h"
42 #include "ParagraphParameters.h"
43 #include "PosIterator.h"
49 #include "insets/insetbibitem.h"
50 #include "insets/insetbibtex.h"
51 #include "insets/insetinclude.h"
52 #include "insets/insettext.h"
54 #include "frontends/Alert.h"
56 #include "graphics/Previews.h"
58 #include "support/FileInfo.h"
59 #include "support/filetools.h"
60 #include "support/gzstream.h"
61 #include "support/lyxlib.h"
62 #include "support/os.h"
63 #include "support/path.h"
64 #include "support/textutils.h"
65 #include "support/tostr.h"
67 #include <boost/bind.hpp>
69 #include "support/std_sstream.h"
81 using lyx::support::AddName;
82 using lyx::support::atoi;
83 using lyx::support::bformat;
84 using lyx::support::ChangeExtension;
85 using lyx::support::cmd_ret;
86 using lyx::support::CreateBufferTmpDir;
87 using lyx::support::destroyDir;
88 using lyx::support::FileInfo;
89 using lyx::support::FileInfo;
90 using lyx::support::getExtFromContents;
91 using lyx::support::IsDirWriteable;
92 using lyx::support::IsFileWriteable;
93 using lyx::support::LibFileSearch;
94 using lyx::support::ltrim;
95 using lyx::support::MakeAbsPath;
96 using lyx::support::MakeDisplayPath;
97 using lyx::support::MakeLatexName;
98 using lyx::support::OnlyFilename;
99 using lyx::support::OnlyPath;
100 using lyx::support::Path;
101 using lyx::support::QuoteName;
102 using lyx::support::removeAutosaveFile;
103 using lyx::support::rename;
104 using lyx::support::RunCommand;
105 using lyx::support::split;
106 using lyx::support::strToInt;
107 using lyx::support::subst;
108 using lyx::support::tempName;
109 using lyx::support::trim;
111 namespace os = lyx::support::os;
115 using std::make_pair;
120 using std::ostringstream;
128 // all these externs should eventually be removed.
129 extern BufferList bufferlist;
133 const int LYX_FORMAT = 225;
138 typedef std::map<string, bool> DepClean;
142 Impl(Buffer & parent, string const & file, bool readonly);
144 limited_stack<Undo> undostack;
145 limited_stack<Undo> redostack;
147 ParagraphList paragraphs;
153 /// need to regenerate .tex ?
157 mutable bool lyx_clean;
159 /// is autosave needed
160 mutable bool bak_clean;
162 /// is this a unnamed file (New...)
168 /// name of the file the buffer is associated with.
171 /// The path to the document file.
174 boost::scoped_ptr<Messages> messages;
176 /** set to true only when the file is fully loaded.
177 * Used to prevent the premature generation of previews
178 * and by the citation inset.
180 bool file_fully_loaded;
184 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
186 lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
187 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false)
189 lyxvc.buffer(&parent);
190 if (readonly_ || lyxrc.use_tempdir)
191 temppath = CreateBufferTmpDir();
195 Buffer::Buffer(string const & file, bool ronly)
196 : pimpl_(new Impl(*this, file, ronly))
198 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
204 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
205 // here the buffer should take care that it is
206 // saved properly, before it goes into the void.
210 if (!temppath().empty() && destroyDir(temppath()) != 0) {
211 Alert::warning(_("Could not remove temporary directory"),
212 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
215 paragraphs().clear();
217 // Remove any previewed LaTeX snippets associated with this buffer.
218 lyx::graphics::Previews::get().removeLoader(*this);
222 limited_stack<Undo> & Buffer::undostack()
224 return pimpl_->undostack;
228 limited_stack<Undo> const & Buffer::undostack() const
230 return pimpl_->undostack;
234 limited_stack<Undo> & Buffer::redostack()
236 return pimpl_->redostack;
240 limited_stack<Undo> const & Buffer::redostack() const
242 return pimpl_->redostack;
246 BufferParams & Buffer::params()
248 return pimpl_->params;
252 BufferParams const & Buffer::params() const
254 return pimpl_->params;
258 ParagraphList & Buffer::paragraphs()
260 return pimpl_->paragraphs;
264 ParagraphList const & Buffer::paragraphs() const
266 return pimpl_->paragraphs;
270 LyXVC & Buffer::lyxvc()
272 return pimpl_->lyxvc;
276 LyXVC const & Buffer::lyxvc() const
278 return pimpl_->lyxvc;
282 string const & Buffer::temppath() const
284 return pimpl_->temppath;
288 bool & Buffer::niceFile()
290 return pimpl_->nicefile;
294 bool Buffer::niceFile() const
296 return pimpl_->nicefile;
300 TexRow & Buffer::texrow()
302 return pimpl_->texrow;
306 TexRow const & Buffer::texrow() const
308 return pimpl_->texrow;
312 string const Buffer::getLatexName(bool no_path) const
314 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
315 return no_path ? OnlyFilename(name) : name;
319 pair<Buffer::LogType, string> const Buffer::getLogName() const
321 string const filename = getLatexName(false);
323 if (filename.empty())
324 return make_pair(Buffer::latexlog, string());
326 string path = OnlyPath(filename);
328 if (lyxrc.use_tempdir || !IsDirWriteable(path))
331 string const fname = AddName(path,
332 OnlyFilename(ChangeExtension(filename,
335 AddName(path, OnlyFilename(
336 ChangeExtension(filename,
337 formats.extension("literate") + ".out")));
339 // If no Latex log or Build log is newer, show Build log
341 FileInfo const f_fi(fname);
342 FileInfo const b_fi(bname);
345 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
346 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
347 return make_pair(Buffer::buildlog, bname);
349 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
350 return make_pair(Buffer::latexlog, fname);
354 void Buffer::setReadonly(bool flag)
356 if (pimpl_->read_only != flag) {
357 pimpl_->read_only = flag;
363 void Buffer::setFileName(string const & newfile)
365 pimpl_->filename = MakeAbsPath(newfile);
366 pimpl_->filepath = OnlyPath(pimpl_->filename);
367 setReadonly(IsFileWriteable(pimpl_->filename) == 0);
372 // We'll remove this later. (Lgb)
375 void unknownClass(string const & unknown)
377 Alert::warning(_("Unknown document class"),
378 bformat(_("Using the default document class, because the "
379 "class %1$s is unknown."), unknown));
384 int Buffer::readHeader(LyXLex & lex)
386 int unknown_tokens = 0;
390 string const token = lex.getString();
395 if (token == "\\end_header")
398 lyxerr[Debug::PARSER] << "Handling header token: `"
399 << token << '\'' << endl;
402 string unknown = params().readToken(lex, token);
403 if (!unknown.empty()) {
404 if (unknown[0] != '\\') {
405 unknownClass(unknown);
408 string const s = bformat(_("Unknown token: "
412 error(ErrorItem(_("Header error"), s,
417 return unknown_tokens;
421 // candidate for move to BufferView
422 // (at least some parts in the beginning of the func)
425 // changed to be public and have one parameter
426 // if par = 0 normal behavior
427 // else insert behavior
428 // Returns false if "\end_document" is not read (Asger)
429 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
431 Paragraph::depth_type depth = 0;
432 bool the_end_read = false;
434 if (paragraphs().empty()) {
436 if (!params().getLyXTextClass().load()) {
437 string theclass = params().getLyXTextClass().name();
438 Alert::error(_("Can't load document class"), bformat(
439 "Using the default document class, because the "
440 " class %1$s could not be loaded.", theclass));
441 params().textclass = 0;
444 // We don't want to adopt the parameters from the
445 // document we insert, so read them into a temporary buffer
446 // and then discard it
448 Buffer tmpbuf("", false);
449 tmpbuf.readHeader(lex);
454 string const token = lex.getString();
459 lyxerr[Debug::PARSER] << "Handling token: `"
460 << token << '\'' << endl;
462 if (token == "\\end_document") {
467 readParagraph(lex, token, paragraphs(), pit, depth);
474 int Buffer::readParagraph(LyXLex & lex, string const & token,
475 ParagraphList & pars, ParagraphList::iterator & pit,
476 lyx::depth_type & depth)
478 static Change current_change;
481 if (token == "\\begin_layout") {
482 lex.pushToken(token);
485 par.params().depth(depth);
486 if (params().tracking_changes)
488 LyXFont f(LyXFont::ALL_INHERIT, params().language);
492 if (pit != pars.end())
495 pit = pars.insert(pit, par);
497 // FIXME: goddamn InsetTabular makes us pass a Buffer
499 ::readParagraph(*this, *pit, lex);
501 } else if (token == "\\begin_deeper") {
503 } else if (token == "\\end_deeper") {
505 lex.printError("\\end_deeper: " "depth is already null");
516 // needed to insert the selection
517 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
518 LyXFont const & fn,string const & str)
520 LyXLayout_ptr const & layout = par->layout();
524 par->checkInsertChar(font);
525 // insert the string, don't insert doublespace
526 bool space_inserted = true;
527 bool autobreakrows = !par->inInset() ||
528 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
529 for(string::const_iterator cit = str.begin();
530 cit != str.end(); ++cit) {
532 if (autobreakrows && (!par->empty() || par->allowEmpty())) {
533 breakParagraph(params(), paragraphs(), par, pos,
534 layout->isEnvironment());
537 space_inserted = true;
541 // do not insert consecutive spaces if !free_spacing
542 } else if ((*cit == ' ' || *cit == '\t') &&
543 space_inserted && !par->isFreeSpacing()) {
545 } else if (*cit == '\t') {
546 if (!par->isFreeSpacing()) {
547 // tabs are like spaces here
548 par->insertChar(pos, ' ', font);
550 space_inserted = true;
552 const pos_type nb = 8 - pos % 8;
553 for (pos_type a = 0; a < nb ; ++a) {
554 par->insertChar(pos, ' ', font);
557 space_inserted = true;
559 } else if (!IsPrintable(*cit)) {
560 // Ignore unprintables
563 // just insert the character
564 par->insertChar(pos, *cit, font);
566 space_inserted = (*cit == ' ');
573 bool Buffer::readFile(string const & filename)
575 // Check if the file is compressed.
576 string const format = getExtFromContents(filename);
577 if (format == "gzip" || format == "zip" || format == "compress") {
578 params().compressed = true;
581 bool ret = readFile(filename, paragraphs().begin());
583 // After we have read a file, we must ensure that the buffer
584 // language is set and used in the gui.
585 // If you know of a better place to put this, please tell me. (Lgb)
586 updateDocLang(params().language);
592 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
595 lex.setFile(filename);
597 return readFile(lex, filename, pit);
601 bool Buffer::fully_loaded() const
603 return pimpl_->file_fully_loaded;
607 void Buffer::fully_loaded(bool value)
609 pimpl_->file_fully_loaded = value;
613 bool Buffer::readFile(LyXLex & lex, string const & filename,
614 ParagraphList::iterator pit)
616 BOOST_ASSERT(!filename.empty());
619 Alert::error(_("Document could not be read"),
620 bformat(_("%1$s could not be read."), filename));
625 string const token(lex.getString());
628 Alert::error(_("Document could not be read"),
629 bformat(_("%1$s could not be read."), filename));
633 // the first token _must_ be...
634 if (token != "\\lyxformat") {
635 lyxerr << "Token: " << token << endl;
637 Alert::error(_("Document format failure"),
638 bformat(_("%1$s is not a LyX document."),
644 string tmp_format = lex.getString();
645 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
646 // if present remove ".," from string.
647 string::size_type dot = tmp_format.find_first_of(".,");
648 //lyxerr << " dot found at " << dot << endl;
649 if (dot != string::npos)
650 tmp_format.erase(dot, 1);
651 int file_format = strToInt(tmp_format);
652 //lyxerr << "format: " << file_format << endl;
654 if (file_format > LYX_FORMAT) {
655 Alert::warning(_("Document format failure"),
656 bformat(_("%1$s was created with a newer"
657 " version of LyX. This is likely to"
660 } else if (file_format < LYX_FORMAT) {
661 string const tmpfile = tempName();
662 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
663 if (command.empty()) {
664 Alert::error(_("Conversion script not found"),
665 bformat(_("%1$s is from an earlier"
666 " version of LyX, but the"
667 " conversion script lyx2lyx"
668 " could not be found."),
674 + " -o " + tmpfile + ' '
675 + QuoteName(filename);
676 lyxerr[Debug::INFO] << "Running '"
679 cmd_ret const ret = RunCommand(command);
680 if (ret.first != 0) {
681 Alert::error(_("Conversion script failed"),
682 bformat(_("%1$s is from an earlier version"
683 " of LyX, but the lyx2lyx script"
684 " failed to convert it."),
688 bool ret = readFile(tmpfile, pit);
689 // Do stuff with tmpfile name and buffer name here.
695 bool the_end = readBody(lex, pit);
696 params().setPaperStuff();
699 Alert::error(_("Document format failure"),
700 bformat(_("%1$s ended unexpectedly, which means"
701 " that it is probably corrupted."),
704 pimpl_->file_fully_loaded = true;
709 // Should probably be moved to somewhere else: BufferView? LyXView?
710 bool Buffer::save() const
712 // We don't need autosaves in the immediate future. (Asger)
713 resetAutosaveTimers();
717 if (lyxrc.make_backup) {
718 s = fileName() + '~';
719 if (!lyxrc.backupdir_path.empty())
720 s = AddName(lyxrc.backupdir_path,
721 subst(os::slashify_path(s),'/','!'));
723 // Rename is the wrong way of making a backup,
724 // this is the correct way.
725 /* truss cp fil fil2:
726 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
727 stat("LyXVC.lyx", 0xEFFFF688) = 0
728 open("LyXVC.lyx", O_RDONLY) = 3
729 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
730 fstat(4, 0xEFFFF508) = 0
731 fstat(3, 0xEFFFF508) = 0
732 read(3, " # T h i s f i l e w".., 8192) = 5579
733 write(4, " # T h i s f i l e w".., 5579) = 5579
734 read(3, 0xEFFFD4A0, 8192) = 0
737 chmod("LyXVC3.lyx", 0100644) = 0
738 lseek(0, 0, SEEK_CUR) = 46440
742 // Should probably have some more error checking here.
743 // Doing it this way, also makes the inodes stay the same.
744 // This is still not a very good solution, in particular we
745 // might loose the owner of the backup.
746 FileInfo finfo(fileName());
748 mode_t fmode = finfo.getMode();
749 struct utimbuf times = {
750 finfo.getAccessTime(),
751 finfo.getModificationTime() };
753 ifstream ifs(fileName().c_str());
754 ofstream ofs(s.c_str(), ios::out|ios::trunc);
759 ::chmod(s.c_str(), fmode);
761 if (::utime(s.c_str(), ×)) {
762 lyxerr << "utime error." << endl;
765 lyxerr << "LyX was not able to make "
766 "backup copy. Beware." << endl;
771 if (writeFile(fileName())) {
773 removeAutosaveFile(fileName());
775 // Saving failed, so backup is not backup
776 if (lyxrc.make_backup) {
777 rename(s, fileName());
785 bool Buffer::writeFile(string const & fname) const
787 if (pimpl_->read_only && (fname == fileName())) {
791 FileInfo finfo(fname);
792 if (finfo.exist() && !finfo.writable()) {
798 if (params().compressed) {
799 gz::ogzstream ofs(fname.c_str());
804 retval = do_writeFile(ofs);
807 ofstream ofs(fname.c_str());
811 retval = do_writeFile(ofs);
818 bool Buffer::do_writeFile(ostream & ofs) const
822 // Use the standard "C" locale for file output.
823 ofs.imbue(std::locale::classic());
826 // The top of the file should not be written by params().
828 // write out a comment in the top of the file
829 ofs << "#LyX " << lyx_version
830 << " created this file. For more info see http://www.lyx.org/\n"
831 << "\\lyxformat " << LYX_FORMAT << "\n";
833 // now write out the buffer paramters.
834 params().writeFile(ofs);
836 ofs << "\\end_header\n";
838 Paragraph::depth_type depth = 0;
840 // this will write out all the paragraphs
841 // using recursive descent.
842 ParagraphList::const_iterator pit = paragraphs().begin();
843 ParagraphList::const_iterator pend = paragraphs().end();
844 for (; pit != pend; ++pit)
845 pit->write(*this, ofs, params(), depth);
847 // Write marker that shows file is complete
848 ofs << "\n\\end_document" << endl;
850 // Shouldn't really be needed....
853 // how to check if close went ok?
854 // Following is an attempt... (BE 20001011)
856 // good() returns false if any error occured, including some
858 // bad() returns true if something bad happened in the buffer,
859 // which should include file system full errors.
866 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
868 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
878 void Buffer::makeLaTeXFile(string const & fname,
879 string const & original_path,
880 OutputParams const & runparams,
881 bool output_preamble, bool output_body)
883 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
886 if (!openFileWrite(ofs, fname))
889 makeLaTeXFile(ofs, original_path,
890 runparams, output_preamble, output_body);
894 lyxerr << "File was not closed properly." << endl;
899 void Buffer::makeLaTeXFile(ostream & os,
900 string const & original_path,
901 OutputParams const & runparams_in,
902 bool output_preamble, bool output_body)
904 OutputParams runparams = runparams_in;
905 niceFile() = runparams.nice; // this will be used by Insetincludes.
907 // validate the buffer.
908 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
909 LaTeXFeatures features(*this, params());
911 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
914 // The starting paragraph of the coming rows is the
915 // first paragraph of the document. (Asger)
916 texrow().start(paragraphs().begin()->id(), 0);
918 if (output_preamble && runparams.nice) {
919 os << "%% LyX " << lyx_version << " created this file. "
920 "For more info, see http://www.lyx.org/.\n"
921 "%% Do not edit unless you really know what "
926 lyxerr[Debug::INFO] << "lyx header finished" << endl;
927 // There are a few differences between nice LaTeX and usual files:
928 // usual is \batchmode and has a
929 // special input@path to allow the including of figures
930 // with either \input or \includegraphics (what figinsets do).
931 // input@path is set when the actual parameter
932 // original_path is set. This is done for usual tex-file, but not
933 // for nice-latex-file. (Matthias 250696)
934 if (output_preamble) {
935 if (!runparams.nice) {
936 // code for usual, NOT nice-latex-file
937 os << "\\batchmode\n"; // changed
941 if (!original_path.empty()) {
942 string inputpath = os::external_path(original_path);
943 subst(inputpath, "~", "\\string~");
944 os << "\\makeatletter\n"
945 << "\\def\\input@path{{"
946 << inputpath << "/}}\n"
947 << "\\makeatother\n";
953 // Write the preamble
954 runparams.use_babel = params().writeLaTeX(os, features, texrow());
960 os << "\\begin{document}\n";
963 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
965 if (!lyxrc.language_auto_begin) {
966 os << subst(lyxrc.language_command_begin, "$$lang",
967 params().language->babel())
972 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
974 // add this just in case after all the paragraphs
978 if (!lyxrc.language_auto_end) {
979 os << subst(lyxrc.language_command_end, "$$lang",
980 params().language->babel())
985 if (output_preamble) {
986 os << "\\end{document}\n";
989 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
991 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
995 // Just to be sure. (Asger)
998 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
999 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1002 // we want this to be true outside previews (for insetexternal)
1007 bool Buffer::isLatex() const
1009 return params().getLyXTextClass().outputType() == LATEX;
1013 bool Buffer::isLinuxDoc() const
1015 return params().getLyXTextClass().outputType() == LINUXDOC;
1019 bool Buffer::isLiterate() const
1021 return params().getLyXTextClass().outputType() == LITERATE;
1025 bool Buffer::isDocBook() const
1027 return params().getLyXTextClass().outputType() == DOCBOOK;
1031 bool Buffer::isSGML() const
1033 LyXTextClass const & tclass = params().getLyXTextClass();
1035 return tclass.outputType() == LINUXDOC ||
1036 tclass.outputType() == DOCBOOK;
1040 void Buffer::makeLinuxDocFile(string const & fname,
1041 OutputParams const & runparams,
1045 if (!openFileWrite(ofs, fname))
1048 niceFile() = runparams.nice; // this will be used by included files.
1050 LaTeXFeatures features(*this, params());
1056 LyXTextClass const & tclass = params().getLyXTextClass();
1058 string top_element = tclass.latexname();
1061 ofs << "<!doctype linuxdoc system";
1063 string preamble = params().preamble;
1064 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1066 preamble += features.getIncludedFiles(name);
1067 preamble += features.getLyXSGMLEntities();
1069 if (!preamble.empty()) {
1070 ofs << " [ " << preamble << " ]";
1074 if (params().options.empty())
1075 sgml::openTag(ofs, 0, false, top_element);
1077 string top = top_element;
1079 top += params().options;
1080 sgml::openTag(ofs, 0, false, top);
1084 ofs << "<!-- LyX " << lyx_version
1085 << " created this file. For more info see http://www.lyx.org/"
1088 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1092 sgml::closeTag(ofs, 0, false, top_element);
1096 // How to check for successful close
1098 // we want this to be true outside previews (for insetexternal)
1103 void Buffer::makeDocBookFile(string const & fname,
1104 OutputParams const & runparams,
1108 if (!openFileWrite(ofs, fname))
1111 niceFile() = runparams.nice; // this will be used by Insetincludes.
1113 LaTeXFeatures features(*this, params());
1118 LyXTextClass const & tclass = params().getLyXTextClass();
1119 string top_element = tclass.latexname();
1122 ofs << "<!DOCTYPE " << top_element
1123 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1125 string preamble = params().preamble;
1126 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1128 preamble += features.getIncludedFiles(name);
1129 preamble += features.getLyXSGMLEntities();
1131 if (!preamble.empty()) {
1132 ofs << "\n [ " << preamble << " ]";
1137 string top = top_element;
1139 top += params().language->code();
1142 if (!params().options.empty()) {
1144 top += params().options;
1146 sgml::openTag(ofs, 0, false, top);
1148 ofs << "<!-- DocBook file was created by LyX " << lyx_version
1149 << "\n See http://www.lyx.org/ for more information -->\n";
1151 docbookParagraphs(*this, paragraphs(), ofs, runparams);
1154 sgml::closeTag(ofs, 0, false, top_element);
1157 // How to check for successful close
1159 // we want this to be true outside previews (for insetexternal)
1164 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1165 // Other flags: -wall -v0 -x
1166 int Buffer::runChktex()
1170 // get LaTeX-Filename
1171 string const name = getLatexName();
1172 string path = filePath();
1174 string const org_path = path;
1175 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1179 Path p(path); // path to LaTeX file
1180 message(_("Running chktex..."));
1182 // Generate the LaTeX file if neccessary
1183 OutputParams runparams;
1184 runparams.flavor = OutputParams::LATEX;
1185 runparams.nice = false;
1186 makeLaTeXFile(name, org_path, runparams);
1189 Chktex chktex(lyxrc.chktex_command, name, filePath());
1190 int res = chktex.run(terr); // run chktex
1193 Alert::error(_("chktex failure"),
1194 _("Could not run chktex successfully."));
1195 } else if (res > 0) {
1196 // Insert all errors as errors boxes
1197 bufferErrors(*this, terr);
1206 void Buffer::validate(LaTeXFeatures & features) const
1208 LyXTextClass const & tclass = params().getLyXTextClass();
1210 if (params().tracking_changes) {
1211 features.require("dvipost");
1212 features.require("color");
1215 // AMS Style is at document level
1216 if (params().use_amsmath == BufferParams::AMS_ON
1217 || tclass.provides(LyXTextClass::amsmath))
1218 features.require("amsmath");
1220 for_each(paragraphs().begin(), paragraphs().end(),
1221 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1223 // the bullet shapes are buffer level not paragraph level
1224 // so they are tested here
1225 for (int i = 0; i < 4; ++i) {
1226 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1227 int const font = params().user_defined_bullet(i).getFont();
1229 int const c = params()
1230 .user_defined_bullet(i)
1237 features.require("latexsym");
1239 } else if (font == 1) {
1240 features.require("amssymb");
1241 } else if ((font >= 2 && font <= 5)) {
1242 features.require("pifont");
1247 if (lyxerr.debugging(Debug::LATEX)) {
1248 features.showStruct();
1253 void Buffer::getLabelList(std::vector<string> & list) const
1255 /// if this is a child document and the parent is already loaded
1256 /// Use the parent's list instead [ale990407]
1257 if (!params().parentname.empty()
1258 && bufferlist.exists(params().parentname)) {
1259 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1261 tmp->getLabelList(list);
1266 for (inset_iterator it = inset_const_iterator_begin();
1267 it != inset_const_iterator_end(); ++it) {
1268 it->getLabelList(*this, list);
1273 // This is also a buffer property (ale)
1274 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys) const
1276 /// if this is a child document and the parent is already loaded
1277 /// use the parent's list instead [ale990412]
1278 if (!params().parentname.empty() &&
1279 bufferlist.exists(params().parentname)) {
1280 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1282 tmp->fillWithBibKeys(keys);
1287 for (inset_iterator it = inset_const_iterator_begin();
1288 it != inset_const_iterator_end(); ++it) {
1289 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1290 InsetBibtex const & inset =
1291 dynamic_cast<InsetBibtex const &>(*it);
1292 inset.fillWithBibKeys(*this, keys);
1293 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1294 InsetInclude const & inset =
1295 dynamic_cast<InsetInclude const &>(*it);
1296 inset.fillWithBibKeys(*this, keys);
1297 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1298 InsetBibitem const & inset =
1299 dynamic_cast<InsetBibitem const &>(*it);
1300 string const key = inset.getContents();
1301 string const opt = inset.getOptions();
1302 string const ref; // = pit->asString(this, false);
1303 string const info = opt + "TheBibliographyRef" + ref;
1304 keys.push_back(pair<string, string>(key, info));
1310 bool Buffer::isDepClean(string const & name) const
1312 DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1313 if (it == pimpl_->dep_clean.end())
1319 void Buffer::markDepClean(string const & name)
1321 pimpl_->dep_clean[name] = true;
1325 bool Buffer::dispatch(string const & command, bool * result)
1327 return dispatch(lyxaction.lookupFunc(command), result);
1331 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1333 bool dispatched = true;
1335 switch (func.action) {
1337 bool const tmp = Exporter::Export(this, func.argument, false);
1350 void Buffer::changeLanguage(Language const * from, Language const * to)
1352 lyxerr << "Changing Language!" << endl;
1354 // Take care of l10n/i18n
1357 ParIterator end = par_iterator_end();
1358 for (ParIterator it = par_iterator_begin(); it != end; ++it)
1359 it->changeLanguage(params(), from, to);
1363 void Buffer::updateDocLang(Language const * nlang)
1365 pimpl_->messages.reset(new Messages(nlang->code()));
1369 bool Buffer::isMultiLingual()
1371 ParIterator end = par_iterator_end();
1372 for (ParIterator it = par_iterator_begin(); it != end; ++it)
1373 if (it->isMultiLingual(params()))
1380 void Buffer::inset_iterator::setParagraph()
1382 while (pit != pend) {
1383 it = pit->insetlist.begin();
1384 if (it != pit->insetlist.end())
1391 ParIterator Buffer::getParFromID(int id) const
1393 #warning FIXME: const correctness! (Andre)
1394 ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1395 ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1397 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1399 // John says this is called with id == -1 from undo
1400 lyxerr << "getParFromID(), id: " << id << endl;
1404 for (; it != end; ++it)
1412 bool Buffer::hasParWithID(int id) const
1414 ParConstIterator it = par_iterator_begin();
1415 ParConstIterator end = par_iterator_end();
1418 // John says this is called with id == -1 from undo
1419 lyxerr << "hasParWithID(), id: " << id << endl;
1423 for (; it != end; ++it)
1431 PosIterator Buffer::pos_iterator_begin()
1433 return PosIterator(¶graphs(), paragraphs().begin(), 0);
1437 PosIterator Buffer::pos_iterator_end()
1439 return PosIterator(¶graphs(), paragraphs().end(), 0);
1443 ParIterator Buffer::par_iterator_begin()
1445 return ParIterator(paragraphs().begin(), paragraphs());
1449 ParIterator Buffer::par_iterator_end()
1451 return ParIterator(paragraphs().end(), paragraphs());
1455 ParConstIterator Buffer::par_iterator_begin() const
1457 ParagraphList const & pars = paragraphs();
1458 return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
1462 ParConstIterator Buffer::par_iterator_end() const
1464 ParagraphList const & pars = paragraphs();
1465 return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
1469 Language const * Buffer::getLanguage() const
1471 return params().language;
1475 string const Buffer::B_(string const & l10n) const
1477 if (pimpl_->messages.get()) {
1478 return pimpl_->messages->get(l10n);
1485 bool Buffer::isClean() const
1487 return pimpl_->lyx_clean;
1491 bool Buffer::isBakClean() const
1493 return pimpl_->bak_clean;
1497 void Buffer::markClean() const
1499 if (!pimpl_->lyx_clean) {
1500 pimpl_->lyx_clean = true;
1503 // if the .lyx file has been saved, we don't need an
1505 pimpl_->bak_clean = true;
1509 void Buffer::markBakClean()
1511 pimpl_->bak_clean = true;
1515 void Buffer::setUnnamed(bool flag)
1517 pimpl_->unnamed = flag;
1521 bool Buffer::isUnnamed()
1523 return pimpl_->unnamed;
1527 void Buffer::markDirty()
1529 if (pimpl_->lyx_clean) {
1530 pimpl_->lyx_clean = false;
1533 pimpl_->bak_clean = false;
1535 DepClean::iterator it = pimpl_->dep_clean.begin();
1536 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1538 for (; it != end; ++it) {
1544 string const & Buffer::fileName() const
1546 return pimpl_->filename;
1550 string const & Buffer::filePath() const
1552 return pimpl_->filepath;
1556 bool Buffer::isReadonly() const
1558 return pimpl_->read_only;
1562 void Buffer::setParentName(string const & name)
1564 params().parentname = name;
1568 Buffer::inset_iterator::inset_iterator()
1573 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
1580 Buffer::inset_iterator Buffer::inset_iterator_begin()
1582 return inset_iterator(paragraphs().begin(), paragraphs().end());
1586 Buffer::inset_iterator Buffer::inset_iterator_end()
1588 return inset_iterator(paragraphs().end(), paragraphs().end());
1592 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1594 ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1595 return inset_iterator(pars.begin(), pars.end());
1599 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1601 ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1602 return inset_iterator(pars.end(), pars.end());
1606 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1610 if (it == pit->insetlist.end()) {
1619 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1621 inset_iterator tmp = *this;
1627 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1633 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1639 ParagraphList::iterator Buffer::inset_iterator::getPar() const
1645 lyx::pos_type Buffer::inset_iterator::getPos() const
1651 bool operator==(Buffer::inset_iterator const & iter1,
1652 Buffer::inset_iterator const & iter2)
1654 return iter1.pit == iter2.pit
1655 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
1659 bool operator!=(Buffer::inset_iterator const & iter1,
1660 Buffer::inset_iterator const & iter2)
1662 return !(iter1 == iter2);