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"
23 #include "errorlist.h"
26 #include "funcrequest.h"
28 #include "iterators.h"
31 #include "LaTeXFeatures.h"
32 #include "LyXAction.h"
39 #include "output_docbook.h"
40 #include "output_latex.h"
41 #include "output_linuxdoc.h"
42 #include "paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "PosIterator.h"
51 #include "insets/insetbibitem.h"
52 #include "insets/insetbibtex.h"
53 #include "insets/insetinclude.h"
54 #include "insets/insettext.h"
56 #include "frontends/Alert.h"
58 #include "graphics/Previews.h"
60 #include "support/FileInfo.h"
61 #include "support/filetools.h"
62 #include "support/gzstream.h"
63 #include "support/lyxlib.h"
64 #include "support/os.h"
65 #include "support/path.h"
66 #include "support/textutils.h"
67 #include "support/tostr.h"
69 #include <boost/bind.hpp>
71 #include "support/std_sstream.h"
83 using lyx::support::AddName;
84 using lyx::support::atoi;
85 using lyx::support::bformat;
86 using lyx::support::ChangeExtension;
87 using lyx::support::cmd_ret;
88 using lyx::support::CreateBufferTmpDir;
89 using lyx::support::destroyDir;
90 using lyx::support::FileInfo;
91 using lyx::support::FileInfo;
92 using lyx::support::getExtFromContents;
93 using lyx::support::IsDirWriteable;
94 using lyx::support::IsFileWriteable;
95 using lyx::support::LibFileSearch;
96 using lyx::support::ltrim;
97 using lyx::support::MakeAbsPath;
98 using lyx::support::MakeDisplayPath;
99 using lyx::support::MakeLatexName;
100 using lyx::support::OnlyFilename;
101 using lyx::support::OnlyPath;
102 using lyx::support::Path;
103 using lyx::support::QuoteName;
104 using lyx::support::removeAutosaveFile;
105 using lyx::support::rename;
106 using lyx::support::RunCommand;
107 using lyx::support::split;
108 using lyx::support::strToInt;
109 using lyx::support::subst;
110 using lyx::support::tempName;
111 using lyx::support::trim;
113 namespace os = lyx::support::os;
117 using std::make_pair;
122 using std::ostringstream;
130 // all these externs should eventually be removed.
131 extern BufferList bufferlist;
135 const int LYX_FORMAT = 225;
140 typedef std::map<string, bool> DepClean;
144 Impl(Buffer & parent, string const & file, bool readonly);
146 limited_stack<Undo> undostack;
147 limited_stack<Undo> redostack;
149 ParagraphList paragraphs;
155 /// need to regenerate .tex ?
159 mutable bool lyx_clean;
161 /// is autosave needed
162 mutable bool bak_clean;
164 /// is this a unnamed file (New...)
170 /// name of the file the buffer is associated with.
173 /// The path to the document file.
176 boost::scoped_ptr<Messages> messages;
178 /** set to true only when the file is fully loaded.
179 * Used to prevent the premature generation of previews
180 * and by the citation inset.
182 bool file_fully_loaded;
189 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
191 lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
192 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
193 text(0, 0, 0, paragraphs)
195 lyxvc.buffer(&parent);
196 if (readonly_ || lyxrc.use_tempdir)
197 temppath = CreateBufferTmpDir();
201 Buffer::Buffer(string const & file, bool ronly)
202 : pimpl_(new Impl(*this, file, ronly))
204 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
210 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
211 // here the buffer should take care that it is
212 // saved properly, before it goes into the void.
216 if (!temppath().empty() && destroyDir(temppath()) != 0) {
217 Alert::warning(_("Could not remove temporary directory"),
218 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
221 paragraphs().clear();
223 // Remove any previewed LaTeX snippets associated with this buffer.
224 lyx::graphics::Previews::get().removeLoader(*this);
228 LyXText & Buffer::text() const
230 return const_cast<LyXText &>(pimpl_->text);
234 limited_stack<Undo> & Buffer::undostack()
236 return pimpl_->undostack;
240 limited_stack<Undo> const & Buffer::undostack() const
242 return pimpl_->undostack;
246 limited_stack<Undo> & Buffer::redostack()
248 return pimpl_->redostack;
252 limited_stack<Undo> const & Buffer::redostack() const
254 return pimpl_->redostack;
258 BufferParams & Buffer::params()
260 return pimpl_->params;
264 BufferParams const & Buffer::params() const
266 return pimpl_->params;
270 ParagraphList & Buffer::paragraphs()
272 return pimpl_->paragraphs;
276 ParagraphList const & Buffer::paragraphs() const
278 return pimpl_->paragraphs;
282 LyXVC & Buffer::lyxvc()
284 return pimpl_->lyxvc;
288 LyXVC const & Buffer::lyxvc() const
290 return pimpl_->lyxvc;
294 string const & Buffer::temppath() const
296 return pimpl_->temppath;
300 bool & Buffer::niceFile()
302 return pimpl_->nicefile;
306 bool Buffer::niceFile() const
308 return pimpl_->nicefile;
312 TexRow & Buffer::texrow()
314 return pimpl_->texrow;
318 TexRow const & Buffer::texrow() const
320 return pimpl_->texrow;
324 string const Buffer::getLatexName(bool no_path) const
326 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
327 return no_path ? OnlyFilename(name) : name;
331 pair<Buffer::LogType, string> const Buffer::getLogName() const
333 string const filename = getLatexName(false);
335 if (filename.empty())
336 return make_pair(Buffer::latexlog, string());
338 string path = OnlyPath(filename);
340 if (lyxrc.use_tempdir || !IsDirWriteable(path))
343 string const fname = AddName(path,
344 OnlyFilename(ChangeExtension(filename,
347 AddName(path, OnlyFilename(
348 ChangeExtension(filename,
349 formats.extension("literate") + ".out")));
351 // If no Latex log or Build log is newer, show Build log
353 FileInfo const f_fi(fname);
354 FileInfo const b_fi(bname);
357 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
358 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
359 return make_pair(Buffer::buildlog, bname);
361 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
362 return make_pair(Buffer::latexlog, fname);
366 void Buffer::setReadonly(bool flag)
368 if (pimpl_->read_only != flag) {
369 pimpl_->read_only = flag;
375 void Buffer::setFileName(string const & newfile)
377 pimpl_->filename = MakeAbsPath(newfile);
378 pimpl_->filepath = OnlyPath(pimpl_->filename);
379 setReadonly(IsFileWriteable(pimpl_->filename) == 0);
384 // We'll remove this later. (Lgb)
387 void unknownClass(string const & unknown)
389 Alert::warning(_("Unknown document class"),
390 bformat(_("Using the default document class, because the "
391 "class %1$s is unknown."), unknown));
396 int Buffer::readHeader(LyXLex & lex)
398 int unknown_tokens = 0;
402 string const token = lex.getString();
407 if (token == "\\end_header")
410 lyxerr[Debug::PARSER] << "Handling header token: `"
411 << token << '\'' << endl;
414 string unknown = params().readToken(lex, token);
415 if (!unknown.empty()) {
416 if (unknown[0] != '\\') {
417 unknownClass(unknown);
420 string const s = bformat(_("Unknown token: "
424 error(ErrorItem(_("Header error"), s,
429 return unknown_tokens;
433 // candidate for move to BufferView
434 // (at least some parts in the beginning of the func)
437 // changed to be public and have one parameter
438 // if par = 0 normal behavior
439 // else insert behavior
440 // Returns false if "\end_document" is not read (Asger)
441 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
443 Paragraph::depth_type depth = 0;
444 bool the_end_read = false;
446 if (paragraphs().empty()) {
448 if (!params().getLyXTextClass().load()) {
449 string theclass = params().getLyXTextClass().name();
450 Alert::error(_("Can't load document class"), bformat(
451 "Using the default document class, because the "
452 " class %1$s could not be loaded.", theclass));
453 params().textclass = 0;
456 // We don't want to adopt the parameters from the
457 // document we insert, so read them into a temporary buffer
458 // and then discard it
460 Buffer tmpbuf("", false);
461 tmpbuf.readHeader(lex);
466 string const token = lex.getString();
471 lyxerr[Debug::PARSER] << "Handling token: `"
472 << token << '\'' << endl;
474 if (token == "\\end_document") {
479 readParagraph(lex, token, paragraphs(), pit, depth);
486 int Buffer::readParagraph(LyXLex & lex, string const & token,
487 ParagraphList & pars, ParagraphList::iterator & pit,
488 lyx::depth_type & depth)
490 static Change current_change;
493 if (token == "\\begin_layout") {
494 lex.pushToken(token);
497 par.params().depth(depth);
498 if (params().tracking_changes)
500 LyXFont f(LyXFont::ALL_INHERIT, params().language);
504 if (pit != pars.end())
507 pit = pars.insert(pit, par);
509 // FIXME: goddamn InsetTabular makes us pass a Buffer
511 ::readParagraph(*this, *pit, lex);
513 } else if (token == "\\begin_deeper") {
515 } else if (token == "\\end_deeper") {
517 lex.printError("\\end_deeper: " "depth is already null");
528 // needed to insert the selection
529 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
530 LyXFont const & fn,string const & str)
532 LyXLayout_ptr const & layout = par->layout();
536 par->checkInsertChar(font);
537 // insert the string, don't insert doublespace
538 bool space_inserted = true;
539 bool autobreakrows = !par->inInset() ||
540 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
541 for(string::const_iterator cit = str.begin();
542 cit != str.end(); ++cit) {
544 if (autobreakrows && (!par->empty() || par->allowEmpty())) {
545 breakParagraph(params(), paragraphs(), par, pos,
546 layout->isEnvironment());
549 space_inserted = true;
553 // do not insert consecutive spaces if !free_spacing
554 } else if ((*cit == ' ' || *cit == '\t') &&
555 space_inserted && !par->isFreeSpacing()) {
557 } else if (*cit == '\t') {
558 if (!par->isFreeSpacing()) {
559 // tabs are like spaces here
560 par->insertChar(pos, ' ', font);
562 space_inserted = true;
564 const pos_type nb = 8 - pos % 8;
565 for (pos_type a = 0; a < nb ; ++a) {
566 par->insertChar(pos, ' ', font);
569 space_inserted = true;
571 } else if (!IsPrintable(*cit)) {
572 // Ignore unprintables
575 // just insert the character
576 par->insertChar(pos, *cit, font);
578 space_inserted = (*cit == ' ');
585 bool Buffer::readFile(string const & filename)
587 // Check if the file is compressed.
588 string const format = getExtFromContents(filename);
589 if (format == "gzip" || format == "zip" || format == "compress") {
590 params().compressed = true;
593 bool ret = readFile(filename, paragraphs().begin());
595 // After we have read a file, we must ensure that the buffer
596 // language is set and used in the gui.
597 // If you know of a better place to put this, please tell me. (Lgb)
598 updateDocLang(params().language);
604 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
607 lex.setFile(filename);
609 return readFile(lex, filename, pit);
613 bool Buffer::fully_loaded() const
615 return pimpl_->file_fully_loaded;
619 void Buffer::fully_loaded(bool value)
621 pimpl_->file_fully_loaded = value;
625 bool Buffer::readFile(LyXLex & lex, string const & filename,
626 ParagraphList::iterator pit)
628 BOOST_ASSERT(!filename.empty());
631 Alert::error(_("Document could not be read"),
632 bformat(_("%1$s could not be read."), filename));
637 string const token(lex.getString());
640 Alert::error(_("Document could not be read"),
641 bformat(_("%1$s could not be read."), filename));
645 // the first token _must_ be...
646 if (token != "\\lyxformat") {
647 lyxerr << "Token: " << token << endl;
649 Alert::error(_("Document format failure"),
650 bformat(_("%1$s is not a LyX document."),
656 string tmp_format = lex.getString();
657 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
658 // if present remove ".," from string.
659 string::size_type dot = tmp_format.find_first_of(".,");
660 //lyxerr << " dot found at " << dot << endl;
661 if (dot != string::npos)
662 tmp_format.erase(dot, 1);
663 int file_format = strToInt(tmp_format);
664 //lyxerr << "format: " << file_format << endl;
666 if (file_format > LYX_FORMAT) {
667 Alert::warning(_("Document format failure"),
668 bformat(_("%1$s was created with a newer"
669 " version of LyX. This is likely to"
672 } else if (file_format < LYX_FORMAT) {
673 string const tmpfile = tempName();
674 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
675 if (command.empty()) {
676 Alert::error(_("Conversion script not found"),
677 bformat(_("%1$s is from an earlier"
678 " version of LyX, but the"
679 " conversion script lyx2lyx"
680 " could not be found."),
686 + " -o " + tmpfile + ' '
687 + QuoteName(filename);
688 lyxerr[Debug::INFO] << "Running '"
691 cmd_ret const ret = RunCommand(command);
692 if (ret.first != 0) {
693 Alert::error(_("Conversion script failed"),
694 bformat(_("%1$s is from an earlier version"
695 " of LyX, but the lyx2lyx script"
696 " failed to convert it."),
700 bool ret = readFile(tmpfile, pit);
701 // Do stuff with tmpfile name and buffer name here.
707 bool the_end = readBody(lex, pit);
708 params().setPaperStuff();
711 Alert::error(_("Document format failure"),
712 bformat(_("%1$s ended unexpectedly, which means"
713 " that it is probably corrupted."),
716 pimpl_->file_fully_loaded = true;
721 // Should probably be moved to somewhere else: BufferView? LyXView?
722 bool Buffer::save() const
724 // We don't need autosaves in the immediate future. (Asger)
725 resetAutosaveTimers();
729 if (lyxrc.make_backup) {
730 s = fileName() + '~';
731 if (!lyxrc.backupdir_path.empty())
732 s = AddName(lyxrc.backupdir_path,
733 subst(os::slashify_path(s),'/','!'));
735 // Rename is the wrong way of making a backup,
736 // this is the correct way.
737 /* truss cp fil fil2:
738 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
739 stat("LyXVC.lyx", 0xEFFFF688) = 0
740 open("LyXVC.lyx", O_RDONLY) = 3
741 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
742 fstat(4, 0xEFFFF508) = 0
743 fstat(3, 0xEFFFF508) = 0
744 read(3, " # T h i s f i l e w".., 8192) = 5579
745 write(4, " # T h i s f i l e w".., 5579) = 5579
746 read(3, 0xEFFFD4A0, 8192) = 0
749 chmod("LyXVC3.lyx", 0100644) = 0
750 lseek(0, 0, SEEK_CUR) = 46440
754 // Should probably have some more error checking here.
755 // Doing it this way, also makes the inodes stay the same.
756 // This is still not a very good solution, in particular we
757 // might loose the owner of the backup.
758 FileInfo finfo(fileName());
760 mode_t fmode = finfo.getMode();
761 struct utimbuf times = {
762 finfo.getAccessTime(),
763 finfo.getModificationTime() };
765 ifstream ifs(fileName().c_str());
766 ofstream ofs(s.c_str(), ios::out|ios::trunc);
771 ::chmod(s.c_str(), fmode);
773 if (::utime(s.c_str(), ×)) {
774 lyxerr << "utime error." << endl;
777 lyxerr << "LyX was not able to make "
778 "backup copy. Beware." << endl;
783 if (writeFile(fileName())) {
785 removeAutosaveFile(fileName());
787 // Saving failed, so backup is not backup
788 if (lyxrc.make_backup) {
789 rename(s, fileName());
797 bool Buffer::writeFile(string const & fname) const
799 if (pimpl_->read_only && (fname == fileName())) {
803 FileInfo finfo(fname);
804 if (finfo.exist() && !finfo.writable()) {
810 if (params().compressed) {
811 gz::ogzstream ofs(fname.c_str());
816 retval = do_writeFile(ofs);
819 ofstream ofs(fname.c_str());
823 retval = do_writeFile(ofs);
830 bool Buffer::do_writeFile(ostream & ofs) const
834 // Use the standard "C" locale for file output.
835 ofs.imbue(std::locale::classic());
838 // The top of the file should not be written by params().
840 // write out a comment in the top of the file
841 ofs << "#LyX " << lyx_version
842 << " created this file. For more info see http://www.lyx.org/\n"
843 << "\\lyxformat " << LYX_FORMAT << "\n";
845 // now write out the buffer paramters.
846 params().writeFile(ofs);
848 ofs << "\\end_header\n";
850 Paragraph::depth_type depth = 0;
852 // this will write out all the paragraphs
853 // using recursive descent.
854 ParagraphList::const_iterator pit = paragraphs().begin();
855 ParagraphList::const_iterator pend = paragraphs().end();
856 for (; pit != pend; ++pit)
857 pit->write(*this, ofs, params(), depth);
859 // Write marker that shows file is complete
860 ofs << "\n\\end_document" << endl;
862 // Shouldn't really be needed....
865 // how to check if close went ok?
866 // Following is an attempt... (BE 20001011)
868 // good() returns false if any error occured, including some
870 // bad() returns true if something bad happened in the buffer,
871 // which should include file system full errors.
878 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
880 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
890 void Buffer::makeLaTeXFile(string const & fname,
891 string const & original_path,
892 OutputParams const & runparams,
893 bool output_preamble, bool output_body)
895 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
898 if (!openFileWrite(ofs, fname))
901 makeLaTeXFile(ofs, original_path,
902 runparams, output_preamble, output_body);
906 lyxerr << "File was not closed properly." << endl;
911 void Buffer::makeLaTeXFile(ostream & os,
912 string const & original_path,
913 OutputParams const & runparams_in,
914 bool output_preamble, bool output_body)
916 OutputParams runparams = runparams_in;
917 niceFile() = runparams.nice; // this will be used by Insetincludes.
919 // validate the buffer.
920 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
921 LaTeXFeatures features(*this, params());
923 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
926 // The starting paragraph of the coming rows is the
927 // first paragraph of the document. (Asger)
928 texrow().start(paragraphs().begin()->id(), 0);
930 if (output_preamble && runparams.nice) {
931 os << "%% LyX " << lyx_version << " created this file. "
932 "For more info, see http://www.lyx.org/.\n"
933 "%% Do not edit unless you really know what "
938 lyxerr[Debug::INFO] << "lyx header finished" << endl;
939 // There are a few differences between nice LaTeX and usual files:
940 // usual is \batchmode and has a
941 // special input@path to allow the including of figures
942 // with either \input or \includegraphics (what figinsets do).
943 // input@path is set when the actual parameter
944 // original_path is set. This is done for usual tex-file, but not
945 // for nice-latex-file. (Matthias 250696)
946 if (output_preamble) {
947 if (!runparams.nice) {
948 // code for usual, NOT nice-latex-file
949 os << "\\batchmode\n"; // changed
953 if (!original_path.empty()) {
954 string inputpath = os::external_path(original_path);
955 subst(inputpath, "~", "\\string~");
956 os << "\\makeatletter\n"
957 << "\\def\\input@path{{"
958 << inputpath << "/}}\n"
959 << "\\makeatother\n";
965 // Write the preamble
966 runparams.use_babel = params().writeLaTeX(os, features, texrow());
972 os << "\\begin{document}\n";
975 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
977 if (!lyxrc.language_auto_begin) {
978 os << subst(lyxrc.language_command_begin, "$$lang",
979 params().language->babel())
984 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
986 // add this just in case after all the paragraphs
990 if (!lyxrc.language_auto_end) {
991 os << subst(lyxrc.language_command_end, "$$lang",
992 params().language->babel())
997 if (output_preamble) {
998 os << "\\end{document}\n";
1001 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1003 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1007 // Just to be sure. (Asger)
1010 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1011 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1014 // we want this to be true outside previews (for insetexternal)
1019 bool Buffer::isLatex() const
1021 return params().getLyXTextClass().outputType() == LATEX;
1025 bool Buffer::isLinuxDoc() const
1027 return params().getLyXTextClass().outputType() == LINUXDOC;
1031 bool Buffer::isLiterate() const
1033 return params().getLyXTextClass().outputType() == LITERATE;
1037 bool Buffer::isDocBook() const
1039 return params().getLyXTextClass().outputType() == DOCBOOK;
1043 bool Buffer::isSGML() const
1045 LyXTextClass const & tclass = params().getLyXTextClass();
1047 return tclass.outputType() == LINUXDOC ||
1048 tclass.outputType() == DOCBOOK;
1052 void Buffer::makeLinuxDocFile(string const & fname,
1053 OutputParams const & runparams,
1057 if (!openFileWrite(ofs, fname))
1060 niceFile() = runparams.nice; // this will be used by included files.
1062 LaTeXFeatures features(*this, params());
1068 LyXTextClass const & tclass = params().getLyXTextClass();
1070 string top_element = tclass.latexname();
1073 ofs << tclass.class_header();
1075 string preamble = params().preamble;
1076 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1078 preamble += features.getIncludedFiles(name);
1079 preamble += features.getLyXSGMLEntities();
1081 if (!preamble.empty()) {
1082 ofs << " [ " << preamble << " ]";
1086 if (params().options.empty())
1087 sgml::openTag(ofs, 0, false, top_element);
1089 string top = top_element;
1091 top += params().options;
1092 sgml::openTag(ofs, 0, false, top);
1096 ofs << "<!-- LyX " << lyx_version
1097 << " created this file. For more info see http://www.lyx.org/"
1100 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1104 sgml::closeTag(ofs, 0, false, top_element);
1108 // How to check for successful close
1110 // we want this to be true outside previews (for insetexternal)
1115 void Buffer::makeDocBookFile(string const & fname,
1116 OutputParams const & runparams,
1120 if (!openFileWrite(ofs, fname))
1123 niceFile() = runparams.nice; // this will be used by Insetincludes.
1125 LaTeXFeatures features(*this, params());
1130 LyXTextClass const & tclass = params().getLyXTextClass();
1131 string top_element = tclass.latexname();
1134 ofs << subst(tclass.class_header(), "#", top_element);
1136 string preamble = params().preamble;
1137 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1139 preamble += features.getIncludedFiles(name);
1140 preamble += features.getLyXSGMLEntities();
1142 if (!preamble.empty()) {
1143 ofs << "\n [ " << preamble << " ]";
1148 string top = top_element;
1150 top += params().language->code();
1153 if (!params().options.empty()) {
1155 top += params().options;
1157 sgml::openTag(ofs, 0, false, top);
1159 ofs << "<!-- SGML/XML file was created by LyX " << lyx_version
1160 << "\n See http://www.lyx.org/ for more information -->\n";
1162 params().getLyXTextClass().counters().reset();
1163 docbookParagraphs(*this, paragraphs(), ofs, runparams);
1166 sgml::closeTag(ofs, 0, false, top_element);
1169 // How to check for successful close
1171 // we want this to be true outside previews (for insetexternal)
1176 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1177 // Other flags: -wall -v0 -x
1178 int Buffer::runChktex()
1182 // get LaTeX-Filename
1183 string const name = getLatexName();
1184 string path = filePath();
1186 string const org_path = path;
1187 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1191 Path p(path); // path to LaTeX file
1192 message(_("Running chktex..."));
1194 // Generate the LaTeX file if neccessary
1195 OutputParams runparams;
1196 runparams.flavor = OutputParams::LATEX;
1197 runparams.nice = false;
1198 makeLaTeXFile(name, org_path, runparams);
1201 Chktex chktex(lyxrc.chktex_command, name, filePath());
1202 int res = chktex.run(terr); // run chktex
1205 Alert::error(_("chktex failure"),
1206 _("Could not run chktex successfully."));
1207 } else if (res > 0) {
1208 // Insert all errors as errors boxes
1209 bufferErrors(*this, terr);
1218 void Buffer::validate(LaTeXFeatures & features) const
1220 LyXTextClass const & tclass = params().getLyXTextClass();
1222 if (params().tracking_changes) {
1223 features.require("dvipost");
1224 features.require("color");
1227 // AMS Style is at document level
1228 if (params().use_amsmath == BufferParams::AMS_ON
1229 || tclass.provides(LyXTextClass::amsmath))
1230 features.require("amsmath");
1232 for_each(paragraphs().begin(), paragraphs().end(),
1233 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1235 // the bullet shapes are buffer level not paragraph level
1236 // so they are tested here
1237 for (int i = 0; i < 4; ++i) {
1238 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1239 int const font = params().user_defined_bullet(i).getFont();
1241 int const c = params()
1242 .user_defined_bullet(i)
1249 features.require("latexsym");
1251 } else if (font == 1) {
1252 features.require("amssymb");
1253 } else if ((font >= 2 && font <= 5)) {
1254 features.require("pifont");
1259 if (lyxerr.debugging(Debug::LATEX)) {
1260 features.showStruct();
1265 void Buffer::getLabelList(std::vector<string> & list) const
1267 /// if this is a child document and the parent is already loaded
1268 /// Use the parent's list instead [ale990407]
1269 if (!params().parentname.empty()
1270 && bufferlist.exists(params().parentname)) {
1271 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1273 tmp->getLabelList(list);
1278 for (inset_iterator it = inset_const_iterator_begin();
1279 it != inset_const_iterator_end(); ++it) {
1280 it->getLabelList(*this, list);
1285 // This is also a buffer property (ale)
1286 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys) const
1288 /// if this is a child document and the parent is already loaded
1289 /// use the parent's list instead [ale990412]
1290 if (!params().parentname.empty() &&
1291 bufferlist.exists(params().parentname)) {
1292 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1294 tmp->fillWithBibKeys(keys);
1299 for (inset_iterator it = inset_const_iterator_begin();
1300 it != inset_const_iterator_end(); ++it) {
1301 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1302 InsetBibtex const & inset =
1303 dynamic_cast<InsetBibtex const &>(*it);
1304 inset.fillWithBibKeys(*this, keys);
1305 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1306 InsetInclude const & inset =
1307 dynamic_cast<InsetInclude const &>(*it);
1308 inset.fillWithBibKeys(*this, keys);
1309 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1310 InsetBibitem const & inset =
1311 dynamic_cast<InsetBibitem const &>(*it);
1312 string const key = inset.getContents();
1313 string const opt = inset.getOptions();
1314 string const ref; // = pit->asString(this, false);
1315 string const info = opt + "TheBibliographyRef" + ref;
1316 keys.push_back(pair<string, string>(key, info));
1322 bool Buffer::isDepClean(string const & name) const
1324 DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1325 if (it == pimpl_->dep_clean.end())
1331 void Buffer::markDepClean(string const & name)
1333 pimpl_->dep_clean[name] = true;
1337 bool Buffer::dispatch(string const & command, bool * result)
1339 return dispatch(lyxaction.lookupFunc(command), result);
1343 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1345 bool dispatched = true;
1347 switch (func.action) {
1349 bool const tmp = Exporter::Export(this, func.argument, false);
1362 void Buffer::changeLanguage(Language const * from, Language const * to)
1364 lyxerr << "Changing Language!" << endl;
1366 // Take care of l10n/i18n
1369 ParIterator end = par_iterator_end();
1370 for (ParIterator it = par_iterator_begin(); it != end; ++it)
1371 it->changeLanguage(params(), from, to);
1375 void Buffer::updateDocLang(Language const * nlang)
1377 pimpl_->messages.reset(new Messages(nlang->code()));
1381 bool Buffer::isMultiLingual()
1383 ParIterator end = par_iterator_end();
1384 for (ParIterator it = par_iterator_begin(); it != end; ++it)
1385 if (it->isMultiLingual(params()))
1392 void Buffer::inset_iterator::setParagraph()
1394 while (pit != pend) {
1395 it = pit->insetlist.begin();
1396 if (it != pit->insetlist.end())
1403 ParIterator Buffer::getParFromID(int id) const
1405 #warning FIXME: const correctness! (Andre)
1406 ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1407 ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1409 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1411 // John says this is called with id == -1 from undo
1412 lyxerr << "getParFromID(), id: " << id << endl;
1416 for (; it != end; ++it)
1424 bool Buffer::hasParWithID(int id) const
1426 ParConstIterator it = par_iterator_begin();
1427 ParConstIterator end = par_iterator_end();
1430 // John says this is called with id == -1 from undo
1431 lyxerr << "hasParWithID(), id: " << id << endl;
1435 for (; it != end; ++it)
1443 PosIterator Buffer::pos_iterator_begin()
1445 return PosIterator(¶graphs(), paragraphs().begin(), 0);
1449 PosIterator Buffer::pos_iterator_end()
1451 return PosIterator(¶graphs(), paragraphs().end(), 0);
1455 ParIterator Buffer::par_iterator_begin()
1457 return ParIterator(paragraphs().begin(), paragraphs());
1461 ParIterator Buffer::par_iterator_end()
1463 return ParIterator(paragraphs().end(), paragraphs());
1467 ParConstIterator Buffer::par_iterator_begin() const
1469 ParagraphList const & pars = paragraphs();
1470 return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
1474 ParConstIterator Buffer::par_iterator_end() const
1476 ParagraphList const & pars = paragraphs();
1477 return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
1481 Language const * Buffer::getLanguage() const
1483 return params().language;
1487 string const Buffer::B_(string const & l10n) const
1489 if (pimpl_->messages.get()) {
1490 return pimpl_->messages->get(l10n);
1497 bool Buffer::isClean() const
1499 return pimpl_->lyx_clean;
1503 bool Buffer::isBakClean() const
1505 return pimpl_->bak_clean;
1509 void Buffer::markClean() const
1511 if (!pimpl_->lyx_clean) {
1512 pimpl_->lyx_clean = true;
1515 // if the .lyx file has been saved, we don't need an
1517 pimpl_->bak_clean = true;
1521 void Buffer::markBakClean()
1523 pimpl_->bak_clean = true;
1527 void Buffer::setUnnamed(bool flag)
1529 pimpl_->unnamed = flag;
1533 bool Buffer::isUnnamed()
1535 return pimpl_->unnamed;
1539 void Buffer::markDirty()
1541 if (pimpl_->lyx_clean) {
1542 pimpl_->lyx_clean = false;
1545 pimpl_->bak_clean = false;
1547 DepClean::iterator it = pimpl_->dep_clean.begin();
1548 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1550 for (; it != end; ++it) {
1556 string const & Buffer::fileName() const
1558 return pimpl_->filename;
1562 string const & Buffer::filePath() const
1564 return pimpl_->filepath;
1568 bool Buffer::isReadonly() const
1570 return pimpl_->read_only;
1574 void Buffer::setParentName(string const & name)
1576 params().parentname = name;
1580 Buffer::inset_iterator::inset_iterator()
1585 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
1592 Buffer::inset_iterator Buffer::inset_iterator_begin()
1594 return inset_iterator(paragraphs().begin(), paragraphs().end());
1598 Buffer::inset_iterator Buffer::inset_iterator_end()
1600 return inset_iterator(paragraphs().end(), paragraphs().end());
1604 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1606 ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1607 return inset_iterator(pars.begin(), pars.end());
1611 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1613 ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1614 return inset_iterator(pars.end(), pars.end());
1618 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1622 if (it == pit->insetlist.end()) {
1631 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1633 inset_iterator tmp = *this;
1639 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1645 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1651 ParagraphList::iterator Buffer::inset_iterator::getPar() const
1657 lyx::pos_type Buffer::inset_iterator::getPos() const
1663 bool operator==(Buffer::inset_iterator const & iter1,
1664 Buffer::inset_iterator const & iter2)
1666 return iter1.pit == iter2.pit
1667 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
1671 bool operator!=(Buffer::inset_iterator const & iter1,
1672 Buffer::inset_iterator const & iter2)
1674 return !(iter1 == iter2);