3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
24 #include "errorlist.h"
27 #include "funcrequest.h"
29 #include "insetiterator.h"
32 #include "LaTeXFeatures.h"
33 #include "LyXAction.h"
41 #include "output_docbook.h"
42 #include "output_latex.h"
43 #include "output_linuxdoc.h"
44 #include "paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "pariterator.h"
53 #include "insets/insetbibitem.h"
54 #include "insets/insetbibtex.h"
55 #include "insets/insetinclude.h"
56 #include "insets/insettext.h"
58 #include "mathed/math_macrotemplate.h"
59 #include "mathed/math_macrotable.h"
60 #include "mathed/math_support.h"
62 #include "frontends/Alert.h"
64 #include "graphics/Previews.h"
66 #include "support/FileInfo.h"
67 #include "support/filetools.h"
68 #include "support/gzstream.h"
69 #include "support/lyxlib.h"
70 #include "support/os.h"
71 #include "support/path.h"
72 #include "support/textutils.h"
73 #include "support/tostr.h"
75 #include <boost/bind.hpp>
87 using lyx::support::AddName;
88 using lyx::support::atoi;
89 using lyx::support::bformat;
90 using lyx::support::ChangeExtension;
91 using lyx::support::cmd_ret;
92 using lyx::support::createBufferTmpDir;
93 using lyx::support::destroyDir;
94 using lyx::support::FileInfo;
95 using lyx::support::FileInfo;
96 using lyx::support::getExtFromContents;
97 using lyx::support::IsDirWriteable;
98 using lyx::support::IsFileWriteable;
99 using lyx::support::LibFileSearch;
100 using lyx::support::ltrim;
101 using lyx::support::MakeAbsPath;
102 using lyx::support::MakeDisplayPath;
103 using lyx::support::MakeLatexName;
104 using lyx::support::OnlyFilename;
105 using lyx::support::OnlyPath;
106 using lyx::support::Path;
107 using lyx::support::QuoteName;
108 using lyx::support::removeAutosaveFile;
109 using lyx::support::rename;
110 using lyx::support::RunCommand;
111 using lyx::support::split;
112 using lyx::support::strToInt;
113 using lyx::support::subst;
114 using lyx::support::tempName;
115 using lyx::support::trim;
117 namespace os = lyx::support::os;
121 using std::make_pair;
127 using std::ostringstream;
135 // all these externs should eventually be removed.
136 extern BufferList bufferlist;
140 const int LYX_FORMAT = 235;
145 typedef std::map<string, bool> DepClean;
149 Impl(Buffer & parent, string const & file, bool readonly);
151 limited_stack<Undo> undostack;
152 limited_stack<Undo> redostack;
158 /// need to regenerate .tex?
162 mutable bool lyx_clean;
164 /// is autosave needed?
165 mutable bool bak_clean;
167 /// is this a unnamed file (New...)?
173 /// name of the file the buffer is associated with.
176 /// The path to the document file.
179 boost::scoped_ptr<Messages> messages;
181 /** Set to true only when the file is fully loaded.
182 * Used to prevent the premature generation of previews
183 * and by the citation inset.
185 bool file_fully_loaded;
187 /// our LyXText that should be wrapped in an InsetText
195 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
196 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
197 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
200 lyxvc.buffer(&parent);
201 temppath = createBufferTmpDir();
202 // FIXME: And now do something if temppath == string(), because we
203 // assume from now on that temppath points to a valid temp dir.
204 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
208 Buffer::Buffer(string const & file, bool ronly)
209 : pimpl_(new Impl(*this, file, ronly))
211 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
217 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
218 // here the buffer should take care that it is
219 // saved properly, before it goes into the void.
223 if (!temppath().empty() && destroyDir(temppath()) != 0) {
224 Alert::warning(_("Could not remove temporary directory"),
225 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
228 // Remove any previewed LaTeX snippets associated with this buffer.
229 lyx::graphics::Previews::get().removeLoader(*this);
233 LyXText & Buffer::text() const
235 return const_cast<LyXText &>(pimpl_->inset.text_);
239 InsetBase & Buffer::inset() const
241 return const_cast<InsetText &>(pimpl_->inset);
245 limited_stack<Undo> & Buffer::undostack()
247 return pimpl_->undostack;
251 limited_stack<Undo> const & Buffer::undostack() const
253 return pimpl_->undostack;
257 limited_stack<Undo> & Buffer::redostack()
259 return pimpl_->redostack;
263 limited_stack<Undo> const & Buffer::redostack() const
265 return pimpl_->redostack;
269 BufferParams & Buffer::params()
271 return pimpl_->params;
275 BufferParams const & Buffer::params() const
277 return pimpl_->params;
281 ParagraphList & Buffer::paragraphs()
283 return text().paragraphs();
287 ParagraphList const & Buffer::paragraphs() const
289 return text().paragraphs();
293 LyXVC & Buffer::lyxvc()
295 return pimpl_->lyxvc;
299 LyXVC const & Buffer::lyxvc() const
301 return pimpl_->lyxvc;
305 string const & Buffer::temppath() const
307 return pimpl_->temppath;
311 TexRow & Buffer::texrow()
313 return pimpl_->texrow;
317 TexRow const & Buffer::texrow() const
319 return pimpl_->texrow;
323 string const Buffer::getLatexName(bool no_path) const
325 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
326 return no_path ? OnlyFilename(name) : name;
330 pair<Buffer::LogType, string> const Buffer::getLogName() const
332 string const filename = getLatexName(false);
334 if (filename.empty())
335 return make_pair(Buffer::latexlog, string());
337 string const path = temppath();
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));
393 int Buffer::readHeader(LyXLex & lex)
395 int unknown_tokens = 0;
399 string const token = lex.getString();
404 if (token == "\\end_header")
407 lyxerr[Debug::PARSER] << "Handling header token: `"
408 << token << '\'' << endl;
411 string unknown = params().readToken(lex, token);
412 if (!unknown.empty()) {
413 if (unknown[0] != '\\') {
414 unknownClass(unknown);
417 string const s = bformat(_("Unknown token: "
421 error(ErrorItem(_("Header error"), s,
426 return unknown_tokens;
431 // changed to be public and have one parameter
432 // Returns false if "\end_document" is not read (Asger)
433 bool Buffer::readBody(LyXLex & lex)
435 if (paragraphs().empty()) {
437 if (!params().getLyXTextClass().load()) {
438 string theclass = params().getLyXTextClass().name();
439 Alert::error(_("Can't load document class"), bformat(
440 "Using the default document class, because the "
441 " class %1$s could not be loaded.", theclass));
442 params().textclass = 0;
445 // We don't want to adopt the parameters from the
446 // document we insert, so read them into a temporary buffer
447 // and then discard it
449 Buffer tmpbuf("", false);
450 tmpbuf.readHeader(lex);
453 return text().read(*this, lex);
457 // needed to insert the selection
458 void Buffer::insertStringAsLines(ParagraphList & pars,
459 par_type & par, pos_type & pos,
460 LyXFont const & fn, string const & str)
462 LyXLayout_ptr const & layout = pars[par].layout();
466 pars[par].checkInsertChar(font);
467 // insert the string, don't insert doublespace
468 bool space_inserted = true;
469 bool autobreakrows = pars[par].autoBreakRows();
470 for (string::const_iterator cit = str.begin();
471 cit != str.end(); ++cit) {
473 if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
474 breakParagraph(params(), paragraphs(), par, pos,
475 layout->isEnvironment());
478 space_inserted = true;
482 // do not insert consecutive spaces if !free_spacing
483 } else if ((*cit == ' ' || *cit == '\t') &&
484 space_inserted && !pars[par].isFreeSpacing()) {
486 } else if (*cit == '\t') {
487 if (!pars[par].isFreeSpacing()) {
488 // tabs are like spaces here
489 pars[par].insertChar(pos, ' ', font);
491 space_inserted = true;
493 const pos_type n = 8 - pos % 8;
494 for (pos_type i = 0; i < n; ++i) {
495 pars[par].insertChar(pos, ' ', font);
498 space_inserted = true;
500 } else if (!IsPrintable(*cit)) {
501 // Ignore unprintables
504 // just insert the character
505 pars[par].insertChar(pos, *cit, font);
507 space_inserted = (*cit == ' ');
514 bool Buffer::readFile(string const & filename)
516 // Check if the file is compressed.
517 string const format = getExtFromContents(filename);
518 if (format == "gzip" || format == "zip" || format == "compress") {
519 params().compressed = true;
522 // remove dummy empty par
523 paragraphs().clear();
524 bool ret = readFile(filename, paragraphs().size());
526 // After we have read a file, we must ensure that the buffer
527 // language is set and used in the gui.
528 // If you know of a better place to put this, please tell me. (Lgb)
529 updateDocLang(params().language);
535 bool Buffer::readFile(string const & filename, par_type pit)
538 lex.setFile(filename);
539 return readFile(lex, filename, pit);
543 bool Buffer::fully_loaded() const
545 return pimpl_->file_fully_loaded;
549 void Buffer::fully_loaded(bool value)
551 pimpl_->file_fully_loaded = value;
555 bool Buffer::readFile(LyXLex & lex, string const & filename, par_type pit)
557 BOOST_ASSERT(!filename.empty());
560 Alert::error(_("Document could not be read"),
561 bformat(_("%1$s could not be read."), filename));
566 string const token(lex.getString());
569 Alert::error(_("Document could not be read"),
570 bformat(_("%1$s could not be read."), filename));
574 // the first token _must_ be...
575 if (token != "\\lyxformat") {
576 lyxerr << "Token: " << token << endl;
578 Alert::error(_("Document format failure"),
579 bformat(_("%1$s is not a LyX document."),
585 string tmp_format = lex.getString();
586 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
587 // if present remove ".," from string.
588 string::size_type dot = tmp_format.find_first_of(".,");
589 //lyxerr << " dot found at " << dot << endl;
590 if (dot != string::npos)
591 tmp_format.erase(dot, 1);
592 int file_format = strToInt(tmp_format);
593 //lyxerr << "format: " << file_format << endl;
595 if (file_format > LYX_FORMAT) {
596 Alert::warning(_("Document format failure"),
597 bformat(_("%1$s was created with a newer"
598 " version of LyX. This is likely to"
601 } else if (file_format < LYX_FORMAT) {
602 string const tmpfile = tempName();
603 if (tmpfile.empty()) {
604 Alert::error(_("Conversion failed"),
605 bformat(_("%1$s is from an earlier"
606 " version of LyX, but a temporary"
607 " file for converting it could"
612 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
613 if (command.empty()) {
614 Alert::error(_("Conversion script not found"),
615 bformat(_("%1$s is from an earlier"
616 " version of LyX, but the"
617 " conversion script lyx2lyx"
618 " could not be found."),
624 + " -o " + tmpfile + ' '
625 + QuoteName(filename);
626 lyxerr[Debug::INFO] << "Running '"
629 cmd_ret const ret = RunCommand(command);
630 if (ret.first != 0) {
631 Alert::error(_("Conversion script failed"),
632 bformat(_("%1$s is from an earlier version"
633 " of LyX, but the lyx2lyx script"
634 " failed to convert it."),
638 bool ret = readFile(tmpfile, pit);
639 // Do stuff with tmpfile name and buffer name here.
645 bool the_end = readBody(lex);
646 //lyxerr << "removing " << MacroTable::localMacros().size()
647 // << " temporary macro entries" << endl;
648 //MacroTable::localMacros().clear();
649 params().setPaperStuff();
655 if (token == "\\end_document")
659 Alert::error(_("Document format failure"),
660 bformat(_("%1$s ended unexpectedly, which means"
661 " that it is probably corrupted."),
665 pimpl_->file_fully_loaded = true;
670 // Should probably be moved to somewhere else: BufferView? LyXView?
671 bool Buffer::save() const
673 // We don't need autosaves in the immediate future. (Asger)
674 resetAutosaveTimers();
678 if (lyxrc.make_backup) {
679 s = fileName() + '~';
680 if (!lyxrc.backupdir_path.empty())
681 s = AddName(lyxrc.backupdir_path,
682 subst(os::slashify_path(s),'/','!'));
684 // Rename is the wrong way of making a backup,
685 // this is the correct way.
686 /* truss cp fil fil2:
687 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
688 stat("LyXVC.lyx", 0xEFFFF688) = 0
689 open("LyXVC.lyx", O_RDONLY) = 3
690 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
691 fstat(4, 0xEFFFF508) = 0
692 fstat(3, 0xEFFFF508) = 0
693 read(3, " # T h i s f i l e w".., 8192) = 5579
694 write(4, " # T h i s f i l e w".., 5579) = 5579
695 read(3, 0xEFFFD4A0, 8192) = 0
698 chmod("LyXVC3.lyx", 0100644) = 0
699 lseek(0, 0, SEEK_CUR) = 46440
703 // Should probably have some more error checking here.
704 // Doing it this way, also makes the inodes stay the same.
705 // This is still not a very good solution, in particular we
706 // might loose the owner of the backup.
707 FileInfo finfo(fileName());
709 mode_t fmode = finfo.getMode();
710 struct utimbuf times = {
711 finfo.getAccessTime(),
712 finfo.getModificationTime() };
714 ifstream ifs(fileName().c_str());
715 ofstream ofs(s.c_str(), ios::out|ios::trunc);
720 ::chmod(s.c_str(), fmode);
722 if (::utime(s.c_str(), ×)) {
723 lyxerr << "utime error." << endl;
726 lyxerr << "LyX was not able to make "
727 "backup copy. Beware." << endl;
732 if (writeFile(fileName())) {
734 removeAutosaveFile(fileName());
736 // Saving failed, so backup is not backup
737 if (lyxrc.make_backup)
738 rename(s, fileName());
745 bool Buffer::writeFile(string const & fname) const
747 if (pimpl_->read_only && fname == fileName())
750 FileInfo finfo(fname);
751 if (finfo.exist() && !finfo.writable())
756 if (params().compressed) {
757 gz::ogzstream ofs(fname.c_str());
761 retval = do_writeFile(ofs);
764 ofstream ofs(fname.c_str());
768 retval = do_writeFile(ofs);
775 bool Buffer::do_writeFile(ostream & ofs) const
778 // Use the standard "C" locale for file output.
779 ofs.imbue(std::locale::classic());
782 // The top of the file should not be written by params().
784 // write out a comment in the top of the file
785 ofs << "#LyX " << lyx_version
786 << " created this file. For more info see http://www.lyx.org/\n"
787 << "\\lyxformat " << LYX_FORMAT << "\n";
789 // now write out the buffer parameters.
790 params().writeFile(ofs);
792 ofs << "\\end_header\n";
795 text().write(*this, ofs);
797 // Write marker that shows file is complete
798 ofs << "\n\\end_document" << endl;
800 // Shouldn't really be needed....
803 // how to check if close went ok?
804 // Following is an attempt... (BE 20001011)
806 // good() returns false if any error occured, including some
808 // bad() returns true if something bad happened in the buffer,
809 // which should include file system full errors.
814 lyxerr << "File was not closed properly." << endl;
821 void Buffer::makeLaTeXFile(string const & fname,
822 string const & original_path,
823 OutputParams const & runparams,
824 bool output_preamble, bool output_body)
826 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
829 if (!openFileWrite(ofs, fname))
832 makeLaTeXFile(ofs, original_path,
833 runparams, output_preamble, output_body);
837 lyxerr << "File '" << fname << "' was not closed properly." << endl;
841 void Buffer::makeLaTeXFile(ostream & os,
842 string const & original_path,
843 OutputParams const & runparams_in,
844 bool output_preamble, bool output_body)
846 OutputParams runparams = runparams_in;
848 // validate the buffer.
849 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
850 LaTeXFeatures features(*this, params(), runparams.nice);
852 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
856 // The starting paragraph of the coming rows is the
857 // first paragraph of the document. (Asger)
858 texrow().start(paragraphs().begin()->id(), 0);
860 if (output_preamble && runparams.nice) {
861 os << "%% LyX " << lyx_version << " created this file. "
862 "For more info, see http://www.lyx.org/.\n"
863 "%% Do not edit unless you really know what "
868 lyxerr[Debug::INFO] << "lyx header finished" << endl;
869 // There are a few differences between nice LaTeX and usual files:
870 // usual is \batchmode and has a
871 // special input@path to allow the including of figures
872 // with either \input or \includegraphics (what figinsets do).
873 // input@path is set when the actual parameter
874 // original_path is set. This is done for usual tex-file, but not
875 // for nice-latex-file. (Matthias 250696)
876 // Note that input@path is only needed for something the user does
877 // in the preamble, included .tex files or ERT, files included by
878 // LyX work without it.
879 if (output_preamble) {
880 if (!runparams.nice) {
881 // code for usual, NOT nice-latex-file
882 os << "\\batchmode\n"; // changed
886 if (!original_path.empty()) {
887 string inputpath = os::external_path(original_path);
888 subst(inputpath, "~", "\\string~");
889 os << "\\makeatletter\n"
890 << "\\def\\input@path{{"
891 << inputpath << "/}}\n"
892 << "\\makeatother\n";
898 // Write the preamble
899 runparams.use_babel = params().writeLaTeX(os, features, texrow());
905 os << "\\begin{document}\n";
908 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
910 if (!lyxrc.language_auto_begin) {
911 os << subst(lyxrc.language_command_begin, "$$lang",
912 params().language->babel())
917 // if we are doing a real file with body, even if this is the
918 // child of some other buffer, let's cut the link here.
919 // This happens for example if only a child document is printed.
920 string save_parentname;
921 if (output_preamble) {
922 save_parentname = params().parentname;
923 params().parentname.erase();
927 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
929 // Restore the parenthood if needed
931 params().parentname = save_parentname;
933 // add this just in case after all the paragraphs
937 if (!lyxrc.language_auto_end) {
938 os << subst(lyxrc.language_command_end, "$$lang",
939 params().language->babel())
944 if (output_preamble) {
945 os << "\\end{document}\n";
948 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
950 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
954 // Just to be sure. (Asger)
957 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
958 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
963 bool Buffer::isLatex() const
965 return params().getLyXTextClass().outputType() == LATEX;
969 bool Buffer::isLinuxDoc() const
971 return params().getLyXTextClass().outputType() == LINUXDOC;
975 bool Buffer::isLiterate() const
977 return params().getLyXTextClass().outputType() == LITERATE;
981 bool Buffer::isDocBook() const
983 return params().getLyXTextClass().outputType() == DOCBOOK;
987 bool Buffer::isSGML() const
989 LyXTextClass const & tclass = params().getLyXTextClass();
991 return tclass.outputType() == LINUXDOC ||
992 tclass.outputType() == DOCBOOK;
996 void Buffer::makeLinuxDocFile(string const & fname,
997 OutputParams const & runparams,
1001 if (!openFileWrite(ofs, fname))
1004 LaTeXFeatures features(*this, params(), runparams.nice);
1009 LyXTextClass const & tclass = params().getLyXTextClass();
1011 string top_element = tclass.latexname();
1014 ofs << tclass.class_header();
1016 string preamble = params().preamble;
1017 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1019 preamble += features.getIncludedFiles(name);
1020 preamble += features.getLyXSGMLEntities();
1022 if (!preamble.empty()) {
1023 ofs << " [ " << preamble << " ]";
1027 if (params().options.empty())
1028 sgml::openTag(ofs, 0, false, top_element);
1030 string top = top_element;
1032 top += params().options;
1033 sgml::openTag(ofs, 0, false, top);
1037 ofs << "<!-- LyX " << lyx_version
1038 << " created this file. For more info see http://www.lyx.org/"
1041 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1045 sgml::closeTag(ofs, 0, false, top_element);
1050 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1054 void Buffer::makeDocBookFile(string const & fname,
1055 OutputParams const & runparams,
1059 if (!openFileWrite(ofs, fname))
1062 LaTeXFeatures features(*this, params(), runparams.nice);
1067 LyXTextClass const & tclass = params().getLyXTextClass();
1068 string top_element = tclass.latexname();
1071 if (runparams.flavor == OutputParams::XML)
1072 ofs << "<?xml version=\"1.0\" encoding=\""
1073 << params().language->encoding()->Name() << "\"?>\n";
1075 ofs << "<!DOCTYPE " << top_element << " ";
1077 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1078 else if (runparams.flavor == OutputParams::XML)
1079 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1080 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1082 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1084 string preamble = params().preamble;
1085 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1087 preamble += features.getIncludedFiles(name);
1088 preamble += features.getLyXSGMLEntities();
1090 if (!preamble.empty()) {
1091 ofs << "\n [ " << preamble << " ]";
1096 string top = top_element;
1098 if (runparams.flavor == OutputParams::XML)
1099 top += params().language->code();
1101 top += params().language->code().substr(0,2);
1104 if (!params().options.empty()) {
1106 top += params().options;
1108 sgml::openTag(ofs, 0, false, top);
1110 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1111 << " file was created by LyX " << lyx_version
1112 << "\n See http://www.lyx.org/ for more information -->\n";
1114 params().getLyXTextClass().counters().reset();
1115 docbookParagraphs(*this, paragraphs(), ofs, runparams);
1118 sgml::closeTag(ofs, 0, false, top_element);
1122 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1126 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1127 // Other flags: -wall -v0 -x
1128 int Buffer::runChktex()
1132 // get LaTeX-Filename
1133 string const name = getLatexName();
1134 string const path = temppath();
1135 string const org_path = filePath();
1137 Path p(path); // path to LaTeX file
1138 message(_("Running chktex..."));
1140 // Generate the LaTeX file if neccessary
1141 OutputParams runparams;
1142 runparams.flavor = OutputParams::LATEX;
1143 runparams.nice = false;
1144 makeLaTeXFile(name, org_path, runparams);
1147 Chktex chktex(lyxrc.chktex_command, name, filePath());
1148 int res = chktex.run(terr); // run chktex
1151 Alert::error(_("chktex failure"),
1152 _("Could not run chktex successfully."));
1153 } else if (res > 0) {
1154 // Insert all errors as errors boxes
1155 bufferErrors(*this, terr);
1164 void Buffer::validate(LaTeXFeatures & features) const
1166 LyXTextClass const & tclass = params().getLyXTextClass();
1168 if (params().tracking_changes) {
1169 features.require("dvipost");
1170 features.require("color");
1173 // AMS Style is at document level
1174 if (params().use_amsmath == BufferParams::AMS_ON
1175 || tclass.provides(LyXTextClass::amsmath))
1176 features.require("amsmath");
1178 for_each(paragraphs().begin(), paragraphs().end(),
1179 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1181 // the bullet shapes are buffer level not paragraph level
1182 // so they are tested here
1183 for (int i = 0; i < 4; ++i) {
1184 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1185 int const font = params().user_defined_bullet(i).getFont();
1187 int const c = params()
1188 .user_defined_bullet(i)
1195 features.require("latexsym");
1197 } else if (font == 1) {
1198 features.require("amssymb");
1199 } else if ((font >= 2 && font <= 5)) {
1200 features.require("pifont");
1205 if (lyxerr.debugging(Debug::LATEX)) {
1206 features.showStruct();
1211 void Buffer::getLabelList(std::vector<string> & list) const
1213 /// if this is a child document and the parent is already loaded
1214 /// Use the parent's list instead [ale990407]
1215 Buffer const * tmp = getMasterBuffer();
1217 lyxerr << "getMasterBuffer() failed!" << endl;
1221 tmp->getLabelList(list);
1225 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1226 it.nextInset()->getLabelList(*this, list);
1230 // This is also a buffer property (ale)
1231 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys)
1234 /// if this is a child document and the parent is already loaded
1235 /// use the parent's list instead [ale990412]
1236 Buffer const * tmp = getMasterBuffer();
1239 tmp->fillWithBibKeys(keys);
1243 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1244 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1245 InsetBibtex const & inset =
1246 dynamic_cast<InsetBibtex const &>(*it);
1247 inset.fillWithBibKeys(*this, keys);
1248 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1249 InsetInclude const & inset =
1250 dynamic_cast<InsetInclude const &>(*it);
1251 inset.fillWithBibKeys(*this, keys);
1252 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1253 InsetBibitem const & inset =
1254 dynamic_cast<InsetBibitem const &>(*it);
1255 string const key = inset.getContents();
1256 string const opt = inset.getOptions();
1257 string const ref; // = pit->asString(this, false);
1258 string const info = opt + "TheBibliographyRef" + ref;
1259 keys.push_back(pair<string, string>(key, info));
1265 bool Buffer::isDepClean(string const & name) const
1267 DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1268 if (it == pimpl_->dep_clean.end())
1274 void Buffer::markDepClean(string const & name)
1276 pimpl_->dep_clean[name] = true;
1280 bool Buffer::dispatch(string const & command, bool * result)
1282 return dispatch(lyxaction.lookupFunc(command), result);
1286 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1288 bool dispatched = true;
1290 switch (func.action) {
1292 bool const tmp = Exporter::Export(this, func.argument, false);
1305 void Buffer::changeLanguage(Language const * from, Language const * to)
1307 lyxerr << "Changing Language!" << endl;
1309 // Take care of l10n/i18n
1312 ParIterator end = par_iterator_end();
1313 for (ParIterator it = par_iterator_begin(); it != end; ++it)
1314 it->changeLanguage(params(), from, to);
1318 void Buffer::updateDocLang(Language const * nlang)
1320 pimpl_->messages.reset(new Messages(nlang->code()));
1324 bool Buffer::isMultiLingual() const
1326 ParConstIterator end = par_iterator_end();
1327 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1328 if (it->isMultiLingual(params()))
1335 ParIterator Buffer::getParFromID(int id) const
1337 ParConstIterator it = par_iterator_begin();
1338 ParConstIterator end = par_iterator_end();
1341 // John says this is called with id == -1 from undo
1342 lyxerr << "getParFromID(), id: " << id << endl;
1346 for (; it != end; ++it)
1354 bool Buffer::hasParWithID(int id) const
1356 ParConstIterator it = par_iterator_begin();
1357 ParConstIterator end = par_iterator_end();
1360 // John says this is called with id == -1 from undo
1361 lyxerr << "hasParWithID(), id: " << id << endl;
1365 for (; it != end; ++it)
1373 ParIterator Buffer::par_iterator_begin()
1375 return ::par_iterator_begin(inset());
1379 ParIterator Buffer::par_iterator_end()
1381 return ::par_iterator_end(inset());
1385 ParConstIterator Buffer::par_iterator_begin() const
1387 return ::par_const_iterator_begin(inset());
1391 ParConstIterator Buffer::par_iterator_end() const
1393 return ::par_const_iterator_end(inset());
1397 Language const * Buffer::getLanguage() const
1399 return params().language;
1403 string const Buffer::B_(string const & l10n) const
1405 if (pimpl_->messages.get()) {
1406 return pimpl_->messages->get(l10n);
1413 bool Buffer::isClean() const
1415 return pimpl_->lyx_clean;
1419 bool Buffer::isBakClean() const
1421 return pimpl_->bak_clean;
1425 void Buffer::markClean() const
1427 if (!pimpl_->lyx_clean) {
1428 pimpl_->lyx_clean = true;
1431 // if the .lyx file has been saved, we don't need an
1433 pimpl_->bak_clean = true;
1437 void Buffer::markBakClean()
1439 pimpl_->bak_clean = true;
1443 void Buffer::setUnnamed(bool flag)
1445 pimpl_->unnamed = flag;
1449 bool Buffer::isUnnamed() const
1451 return pimpl_->unnamed;
1455 void Buffer::markDirty()
1457 if (pimpl_->lyx_clean) {
1458 pimpl_->lyx_clean = false;
1461 pimpl_->bak_clean = false;
1463 DepClean::iterator it = pimpl_->dep_clean.begin();
1464 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1466 for (; it != end; ++it) {
1472 string const & Buffer::fileName() const
1474 return pimpl_->filename;
1478 string const & Buffer::filePath() const
1480 return pimpl_->filepath;
1484 bool Buffer::isReadonly() const
1486 return pimpl_->read_only;
1490 void Buffer::setParentName(string const & name)
1492 params().parentname = name;
1496 Buffer const * Buffer::getMasterBuffer() const
1498 if (!params().parentname.empty()
1499 && bufferlist.exists(params().parentname)) {
1500 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1502 return buf->getMasterBuffer();
1509 MacroData const & Buffer::getMacro(std::string const & name) const
1511 return pimpl_->macros.get(name);
1515 bool Buffer::hasMacro(string const & name) const
1517 return pimpl_->macros.has(name);
1521 void Buffer::insertMacro(string const & name, MacroData const & data)
1523 MacroTable::globalMacros().insert(name, data);
1524 pimpl_->macros.insert(name, data);
1528 void Buffer::buildMacros()
1530 // Start with global table.
1531 pimpl_->macros = MacroTable::globalMacros();
1534 ParagraphList & pars = text().paragraphs();
1535 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1536 //lyxerr << "searching main par " << i
1537 // << " for macro definitions" << std::endl;
1538 InsetList::iterator it = pars[i].insetlist.begin();
1539 InsetList::iterator end = pars[i].insetlist.end();
1540 for ( ; it != end; ++it) {
1541 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1542 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1543 MathMacroTemplate & mac
1544 = static_cast<MathMacroTemplate &>(*it->inset);
1545 insertMacro(mac.name(), mac.asMacroData());