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 "BranchList.h"
17 #include "buffer_funcs.h"
18 #include "bufferlist.h"
19 #include "bufferparams.h"
25 #include "errorlist.h"
28 #include "funcrequest.h"
30 #include "insetiterator.h"
33 #include "LaTeXFeatures.h"
34 #include "LyXAction.h"
42 #include "output_docbook.h"
43 #include "output_latex.h"
44 #include "output_linuxdoc.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "pariterator.h"
54 #include "insets/insetbibitem.h"
55 #include "insets/insetbibtex.h"
56 #include "insets/insetinclude.h"
57 #include "insets/insettext.h"
59 #include "mathed/math_macrotemplate.h"
60 #include "mathed/math_macrotable.h"
61 #include "mathed/math_support.h"
63 #include "frontends/Alert.h"
65 #include "graphics/Previews.h"
67 #include "support/types.h"
68 #include "support/lyxalgo.h"
69 #include "support/filetools.h"
70 #include "support/fs_extras.h"
71 #ifdef USE_COMPRESSION
72 # include "support/gzstream.h"
74 #include "support/lyxlib.h"
75 #include "support/os.h"
76 #include "support/path.h"
77 #include "support/textutils.h"
78 #include "support/convert.h"
80 #include <boost/bind.hpp>
81 #include <boost/filesystem/operations.hpp>
83 #if defined (HAVE_UTIME_H)
85 #elif defined (HAVE_SYS_UTIME_H)
86 # include <sys/utime.h>
98 using lyx::support::addName;
99 using lyx::support::bformat;
100 using lyx::support::changeExtension;
101 using lyx::support::cmd_ret;
102 using lyx::support::createBufferTmpDir;
103 using lyx::support::destroyDir;
104 using lyx::support::getFormatFromContents;
105 using lyx::support::isDirWriteable;
106 using lyx::support::libFileSearch;
107 using lyx::support::latex_path;
108 using lyx::support::ltrim;
109 using lyx::support::makeAbsPath;
110 using lyx::support::makeDisplayPath;
111 using lyx::support::makeLatexName;
112 using lyx::support::onlyFilename;
113 using lyx::support::onlyPath;
114 using lyx::support::Path;
115 using lyx::support::quoteName;
116 using lyx::support::removeAutosaveFile;
117 using lyx::support::rename;
118 using lyx::support::runCommand;
119 using lyx::support::split;
120 using lyx::support::subst;
121 using lyx::support::tempName;
122 using lyx::support::trim;
124 namespace os = lyx::support::os;
125 namespace fs = boost::filesystem;
129 using std::make_pair;
135 using std::ostringstream;
143 // all these externs should eventually be removed.
144 extern BufferList bufferlist;
148 int const LYX_FORMAT = 245;
153 typedef std::map<string, bool> DepClean;
158 Impl(Buffer & parent, string const & file, bool readonly);
160 limited_stack<Undo> undostack;
161 limited_stack<Undo> redostack;
167 /// need to regenerate .tex?
171 mutable bool lyx_clean;
173 /// is autosave needed?
174 mutable bool bak_clean;
176 /// is this a unnamed file (New...)?
182 /// name of the file the buffer is associated with.
185 boost::scoped_ptr<Messages> messages;
187 /** Set to true only when the file is fully loaded.
188 * Used to prevent the premature generation of previews
189 * and by the citation inset.
191 bool file_fully_loaded;
193 /// our LyXText that should be wrapped in an InsetText
201 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
202 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
203 filename(file), file_fully_loaded(false),
206 inset.setAutoBreakRows(true);
207 lyxvc.buffer(&parent);
208 temppath = createBufferTmpDir();
209 params.filepath = onlyPath(file);
210 // FIXME: And now do something if temppath == string(), because we
211 // assume from now on that temppath points to a valid temp dir.
212 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
216 Buffer::Buffer(string const & file, bool readonly)
217 : pimpl_(new Impl(*this, file, readonly))
219 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
225 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
226 // here the buffer should take care that it is
227 // saved properly, before it goes into the void.
231 if (!temppath().empty() && !destroyDir(temppath())) {
232 Alert::warning(_("Could not remove temporary directory"),
233 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
236 // Remove any previewed LaTeX snippets associated with this buffer.
237 lyx::graphics::Previews::get().removeLoader(*this);
241 LyXText & Buffer::text() const
243 return const_cast<LyXText &>(pimpl_->inset.text_);
247 InsetBase & Buffer::inset() const
249 return const_cast<InsetText &>(pimpl_->inset);
253 limited_stack<Undo> & Buffer::undostack()
255 return pimpl_->undostack;
259 limited_stack<Undo> const & Buffer::undostack() const
261 return pimpl_->undostack;
265 limited_stack<Undo> & Buffer::redostack()
267 return pimpl_->redostack;
271 limited_stack<Undo> const & Buffer::redostack() const
273 return pimpl_->redostack;
277 BufferParams & Buffer::params()
279 return pimpl_->params;
283 BufferParams const & Buffer::params() const
285 return pimpl_->params;
289 ParagraphList & Buffer::paragraphs()
291 return text().paragraphs();
295 ParagraphList const & Buffer::paragraphs() const
297 return text().paragraphs();
301 LyXVC & Buffer::lyxvc()
303 return pimpl_->lyxvc;
307 LyXVC const & Buffer::lyxvc() const
309 return pimpl_->lyxvc;
313 string const & Buffer::temppath() const
315 return pimpl_->temppath;
319 TexRow & Buffer::texrow()
321 return pimpl_->texrow;
325 TexRow const & Buffer::texrow() const
327 return pimpl_->texrow;
331 string const Buffer::getLatexName(bool const no_path) const
333 string const name = changeExtension(makeLatexName(fileName()), ".tex");
334 return no_path ? onlyFilename(name) : name;
338 pair<Buffer::LogType, string> const Buffer::getLogName() const
340 string const filename = getLatexName(false);
342 if (filename.empty())
343 return make_pair(Buffer::latexlog, string());
345 string const path = temppath();
347 string const fname = addName(path,
348 onlyFilename(changeExtension(filename,
351 addName(path, onlyFilename(
352 changeExtension(filename,
353 formats.extension("literate") + ".out")));
355 // If no Latex log or Build log is newer, show Build log
357 if (fs::exists(bname) &&
358 (!fs::exists(fname) || fs::last_write_time(fname) < fs::last_write_time(bname))) {
359 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
360 return make_pair(Buffer::buildlog, bname);
362 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
363 return make_pair(Buffer::latexlog, fname);
367 void Buffer::setReadonly(bool const flag)
369 if (pimpl_->read_only != flag) {
370 pimpl_->read_only = flag;
376 void Buffer::setFileName(string const & newfile)
378 pimpl_->filename = makeAbsPath(newfile);
379 params().filepath = onlyPath(pimpl_->filename);
380 setReadonly(fs::is_readonly(pimpl_->filename));
385 // We'll remove this later. (Lgb)
388 void unknownClass(string const & unknown)
390 Alert::warning(_("Unknown document class"),
391 bformat(_("Using the default document class, because the "
392 "class %1$s is unknown."), unknown));
398 int Buffer::readHeader(LyXLex & lex)
400 int unknown_tokens = 0;
402 int begin_header_line = -1;
404 // Initialize parameters that may be/go lacking in header:
405 params().branchlist().clear();
406 params().preamble.erase();
407 params().options.erase();
408 params().float_placement.erase();
409 params().paperwidth.erase();
410 params().paperheight.erase();
411 params().leftmargin.erase();
412 params().rightmargin.erase();
413 params().topmargin.erase();
414 params().bottommargin.erase();
415 params().headheight.erase();
416 params().headsep.erase();
417 params().footskip.erase();
421 string const token = lex.getString();
426 if (token == "\\end_header")
430 if (token == "\\begin_header") {
431 begin_header_line = line;
435 lyxerr[Debug::PARSER] << "Handling document header token: `"
436 << token << '\'' << endl;
438 string unknown = params().readToken(lex, token);
439 if (!unknown.empty()) {
440 if (unknown[0] != '\\' && token == "\\textclass") {
441 unknownClass(unknown);
444 string const s = bformat(_("Unknown token: "
448 error(ErrorItem(_("Document header error"), s,
453 if (begin_header_line) {
454 string const s = _("\\begin_header is missing");
455 error(ErrorItem(_("Document header error"), s, -1, 0, 0));
457 return unknown_tokens;
462 // changed to be public and have one parameter
463 // Returns false if "\end_document" is not read (Asger)
464 bool Buffer::readDocument(LyXLex & lex)
467 string const token = lex.getString();
468 if (token != "\\begin_document") {
469 string const s = _("\\begin_document is missing");
470 error(ErrorItem(_("Document header error"), s, -1, 0, 0));
473 // we are reading in a brand new document
474 BOOST_ASSERT(paragraphs().empty());
477 if (!params().getLyXTextClass().load(filePath())) {
478 string theclass = params().getLyXTextClass().name();
479 Alert::error(_("Can't load document class"), bformat(
480 "Using the default document class, because the "
481 " class %1$s could not be loaded.", theclass));
482 params().textclass = 0;
485 bool const res = text().read(*this, lex);
486 for_each(text().paragraphs().begin(),
487 text().paragraphs().end(),
488 bind(&Paragraph::setInsetOwner, _1, &inset()));
489 updateBibfilesCache();
494 // needed to insert the selection
495 void Buffer::insertStringAsLines(ParagraphList & pars,
496 pit_type & pit, pos_type & pos,
497 LyXFont const & fn, string const & str, bool autobreakrows)
501 // insert the string, don't insert doublespace
502 bool space_inserted = true;
503 for (string::const_iterator cit = str.begin();
504 cit != str.end(); ++cit) {
505 Paragraph & par = pars[pit];
507 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
508 breakParagraph(params(), pars, pit, pos,
509 par.layout()->isEnvironment());
512 space_inserted = true;
516 // do not insert consecutive spaces if !free_spacing
517 } else if ((*cit == ' ' || *cit == '\t') &&
518 space_inserted && !par.isFreeSpacing()) {
520 } else if (*cit == '\t') {
521 if (!par.isFreeSpacing()) {
522 // tabs are like spaces here
523 par.insertChar(pos, ' ', font);
525 space_inserted = true;
527 const pos_type n = 8 - pos % 8;
528 for (pos_type i = 0; i < n; ++i) {
529 par.insertChar(pos, ' ', font);
532 space_inserted = true;
534 } else if (!isPrintable(*cit)) {
535 // Ignore unprintables
538 // just insert the character
539 par.insertChar(pos, *cit, font);
541 space_inserted = (*cit == ' ');
548 bool Buffer::readFile(string const & filename)
550 // Check if the file is compressed.
551 string const format = getFormatFromContents(filename);
552 if (format == "gzip" || format == "zip" || format == "compress") {
553 params().compressed = true;
556 // remove dummy empty par
557 paragraphs().clear();
559 lex.setFile(filename);
560 bool ret = readFile(lex, filename);
562 // After we have read a file, we must ensure that the buffer
563 // language is set and used in the gui.
564 // If you know of a better place to put this, please tell me. (Lgb)
565 updateDocLang(params().language);
571 bool Buffer::fully_loaded() const
573 return pimpl_->file_fully_loaded;
577 void Buffer::fully_loaded(bool const value)
579 pimpl_->file_fully_loaded = value;
583 bool Buffer::readFile(LyXLex & lex, string const & filename)
585 BOOST_ASSERT(!filename.empty());
588 Alert::error(_("Document could not be read"),
589 bformat(_("%1$s could not be read."), filename));
594 string const token(lex.getString());
597 Alert::error(_("Document could not be read"),
598 bformat(_("%1$s could not be read."), filename));
602 // the first token _must_ be...
603 if (token != "\\lyxformat") {
604 lyxerr << "Token: " << token << endl;
606 Alert::error(_("Document format failure"),
607 bformat(_("%1$s is not a LyX document."),
613 string tmp_format = lex.getString();
614 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
615 // if present remove ".," from string.
616 string::size_type dot = tmp_format.find_first_of(".,");
617 //lyxerr << " dot found at " << dot << endl;
618 if (dot != string::npos)
619 tmp_format.erase(dot, 1);
620 int const file_format = convert<int>(tmp_format);
621 //lyxerr << "format: " << file_format << endl;
623 if (file_format != LYX_FORMAT) {
624 string const tmpfile = tempName();
625 if (tmpfile.empty()) {
626 Alert::error(_("Conversion failed"),
627 bformat(_("%1$s is from an earlier"
628 " version of LyX, but a temporary"
629 " file for converting it could"
634 string const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
635 if (lyx2lyx.empty()) {
636 Alert::error(_("Conversion script not found"),
637 bformat(_("%1$s is from an earlier"
638 " version of LyX, but the"
639 " conversion script lyx2lyx"
640 " could not be found."),
644 ostringstream command;
645 command << "python " << quoteName(lyx2lyx)
646 << " -t " << convert<string>(LYX_FORMAT)
647 << " -o " << quoteName(tmpfile) << ' '
648 << quoteName(filename);
649 string const command_str = command.str();
651 lyxerr[Debug::INFO] << "Running '"
652 << command_str << '\''
655 cmd_ret const ret = runCommand(command_str);
656 if (ret.first != 0) {
657 Alert::error(_("Conversion script failed"),
658 bformat(_("%1$s is from an earlier version"
659 " of LyX, but the lyx2lyx script"
660 " failed to convert it."),
664 bool const ret = readFile(tmpfile);
665 // Do stuff with tmpfile name and buffer name here.
671 if (readDocument(lex)) {
672 Alert::error(_("Document format failure"),
673 bformat(_("%1$s ended unexpectedly, which means"
674 " that it is probably corrupted."),
678 //lyxerr << "removing " << MacroTable::localMacros().size()
679 // << " temporary macro entries" << endl;
680 //MacroTable::localMacros().clear();
682 pimpl_->file_fully_loaded = true;
687 // Should probably be moved to somewhere else: BufferView? LyXView?
688 bool Buffer::save() const
690 // We don't need autosaves in the immediate future. (Asger)
691 resetAutosaveTimers();
695 if (lyxrc.make_backup) {
696 s = fileName() + '~';
697 if (!lyxrc.backupdir_path.empty())
698 s = addName(lyxrc.backupdir_path,
699 subst(os::internal_path(s),'/','!'));
701 // It might very well be that this variant is just
702 // good enough. (Lgb)
703 // But to use this we need fs::copy_file to actually do a copy,
704 // even when the target file exists. (Lgb)
705 if (fs::exists(fileName()) && fs::is_writable(fs::path(fileName()).branch_path())) {
707 fs::copy_file(fileName(), s, false);
709 //catch (fs::filesystem_error const & fe) {
710 //lyxerr << "LyX was not able to make backup copy. Beware.\n"
711 // << fe.what() << endl;
716 if (writeFile(fileName())) {
718 removeAutosaveFile(fileName());
720 // Saving failed, so backup is not backup
721 if (lyxrc.make_backup)
722 rename(s, fileName());
729 bool Buffer::writeFile(string const & fname) const
731 if (pimpl_->read_only && fname == fileName())
736 if (params().compressed) {
737 #ifdef USE_COMPRESSION
738 gz::ogzstream ofs(fname.c_str(), ios::out|ios::trunc);
742 retval = do_writeFile(ofs);
747 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
751 retval = do_writeFile(ofs);
758 bool Buffer::do_writeFile(ostream & ofs) const
761 // Use the standard "C" locale for file output.
762 ofs.imbue(std::locale::classic());
765 // The top of the file should not be written by params().
767 // write out a comment in the top of the file
768 ofs << "#LyX " << lyx_version
769 << " created this file. For more info see http://www.lyx.org/\n"
770 << "\\lyxformat " << LYX_FORMAT << "\n"
771 << "\\begin_document\n";
773 // now write out the buffer parameters.
774 ofs << "\\begin_header\n";
775 params().writeFile(ofs);
776 ofs << "\\end_header\n";
779 ofs << "\n\\begin_body\n";
780 text().write(*this, ofs);
781 ofs << "\n\\end_body\n";
783 // Write marker that shows file is complete
784 ofs << "\\end_document" << endl;
786 // Shouldn't really be needed....
789 // how to check if close went ok?
790 // Following is an attempt... (BE 20001011)
792 // good() returns false if any error occured, including some
794 // bad() returns true if something bad happened in the buffer,
795 // which should include file system full errors.
800 lyxerr << "File was not closed properly." << endl;
807 void Buffer::makeLaTeXFile(string const & fname,
808 string const & original_path,
809 OutputParams const & runparams,
810 bool output_preamble, bool output_body)
812 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
815 if (!openFileWrite(ofs, fname))
818 makeLaTeXFile(ofs, original_path,
819 runparams, output_preamble, output_body);
823 lyxerr << "File '" << fname << "' was not closed properly." << endl;
827 void Buffer::makeLaTeXFile(ostream & os,
828 string const & original_path,
829 OutputParams const & runparams_in,
830 bool const output_preamble, bool const output_body)
832 OutputParams runparams = runparams_in;
834 // validate the buffer.
835 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
836 LaTeXFeatures features(*this, params(), runparams);
838 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
842 // The starting paragraph of the coming rows is the
843 // first paragraph of the document. (Asger)
844 texrow().start(paragraphs().begin()->id(), 0);
846 if (output_preamble && runparams.nice) {
847 os << "%% LyX " << lyx_version << " created this file. "
848 "For more info, see http://www.lyx.org/.\n"
849 "%% Do not edit unless you really know what "
854 lyxerr[Debug::INFO] << "lyx document header finished" << endl;
855 // There are a few differences between nice LaTeX and usual files:
856 // usual is \batchmode and has a
857 // special input@path to allow the including of figures
858 // with either \input or \includegraphics (what figinsets do).
859 // input@path is set when the actual parameter
860 // original_path is set. This is done for usual tex-file, but not
861 // for nice-latex-file. (Matthias 250696)
862 // Note that input@path is only needed for something the user does
863 // in the preamble, included .tex files or ERT, files included by
864 // LyX work without it.
865 if (output_preamble) {
866 if (!runparams.nice) {
867 // code for usual, NOT nice-latex-file
868 os << "\\batchmode\n"; // changed
872 if (!original_path.empty()) {
873 string const inputpath = latex_path(original_path);
874 os << "\\makeatletter\n"
875 << "\\def\\input@path{{"
876 << inputpath << "/}}\n"
877 << "\\makeatother\n";
883 // Write the preamble
884 runparams.use_babel = params().writeLaTeX(os, features, texrow());
890 os << "\\begin{document}\n";
893 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
895 if (!lyxrc.language_auto_begin) {
896 os << subst(lyxrc.language_command_begin, "$$lang",
897 params().language->babel())
902 // if we are doing a real file with body, even if this is the
903 // child of some other buffer, let's cut the link here.
904 // This happens for example if only a child document is printed.
905 string save_parentname;
906 if (output_preamble) {
907 save_parentname = params().parentname;
908 params().parentname.erase();
912 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
914 // Restore the parenthood if needed
916 params().parentname = save_parentname;
918 // add this just in case after all the paragraphs
922 if (!lyxrc.language_auto_end) {
923 os << subst(lyxrc.language_command_end, "$$lang",
924 params().language->babel())
929 if (output_preamble) {
930 os << "\\end{document}\n";
933 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
935 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
939 // Just to be sure. (Asger)
942 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
943 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
948 bool Buffer::isLatex() const
950 return params().getLyXTextClass().outputType() == LATEX;
954 bool Buffer::isLinuxDoc() const
956 return params().getLyXTextClass().outputType() == LINUXDOC;
960 bool Buffer::isLiterate() const
962 return params().getLyXTextClass().outputType() == LITERATE;
966 bool Buffer::isDocBook() const
968 return params().getLyXTextClass().outputType() == DOCBOOK;
972 bool Buffer::isSGML() const
974 LyXTextClass const & tclass = params().getLyXTextClass();
976 return tclass.outputType() == LINUXDOC ||
977 tclass.outputType() == DOCBOOK;
981 void Buffer::makeLinuxDocFile(string const & fname,
982 OutputParams const & runparams,
983 bool const body_only)
986 if (!openFileWrite(ofs, fname))
989 LaTeXFeatures features(*this, params(), runparams);
994 LyXTextClass const & tclass = params().getLyXTextClass();
996 string const & top_element = tclass.latexname();
999 ofs << tclass.class_header();
1001 string preamble = params().preamble;
1002 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1004 preamble += features.getIncludedFiles(name);
1005 preamble += features.getLyXSGMLEntities();
1007 if (!preamble.empty()) {
1008 ofs << " [ " << preamble << " ]";
1012 if (params().options.empty())
1013 sgml::openTag(ofs, top_element);
1015 string top = top_element;
1017 top += params().options;
1018 sgml::openTag(ofs, top);
1022 ofs << "<!-- LyX " << lyx_version
1023 << " created this file. For more info see http://www.lyx.org/"
1026 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1030 sgml::closeTag(ofs, top_element);
1035 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1039 void Buffer::makeDocBookFile(string const & fname,
1040 OutputParams const & runparams,
1041 bool const only_body)
1044 if (!openFileWrite(ofs, fname))
1047 LaTeXFeatures features(*this, params(), runparams);
1052 LyXTextClass const & tclass = params().getLyXTextClass();
1053 string const & top_element = tclass.latexname();
1056 if (runparams.flavor == OutputParams::XML)
1057 ofs << "<?xml version=\"1.0\" encoding=\""
1058 << params().language->encoding()->name() << "\"?>\n";
1060 ofs << "<!DOCTYPE " << top_element << " ";
1062 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1063 else if (runparams.flavor == OutputParams::XML)
1064 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1065 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1067 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1069 string preamble = params().preamble;
1070 if (runparams.flavor != OutputParams::XML ) {
1071 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1072 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1073 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1074 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1077 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1079 preamble += features.getIncludedFiles(name);
1080 preamble += features.getLyXSGMLEntities();
1082 if (!preamble.empty()) {
1083 ofs << "\n [ " << preamble << " ]";
1088 string top = top_element;
1090 if (runparams.flavor == OutputParams::XML)
1091 top += params().language->code();
1093 top += params().language->code().substr(0,2);
1096 if (!params().options.empty()) {
1098 top += params().options;
1101 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1102 << " file was created by LyX " << lyx_version
1103 << "\n See http://www.lyx.org/ for more information -->\n";
1105 params().getLyXTextClass().counters().reset();
1107 sgml::openTag(ofs, top);
1109 docbookParagraphs(paragraphs(), *this, ofs, runparams);
1110 sgml::closeTag(ofs, top_element);
1114 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1118 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1119 // Other flags: -wall -v0 -x
1120 int Buffer::runChktex()
1124 // get LaTeX-Filename
1125 string const name = getLatexName();
1126 string const path = temppath();
1127 string const org_path = filePath();
1129 Path p(path); // path to LaTeX file
1130 message(_("Running chktex..."));
1132 // Generate the LaTeX file if neccessary
1133 OutputParams runparams;
1134 runparams.flavor = OutputParams::LATEX;
1135 runparams.nice = false;
1136 makeLaTeXFile(name, org_path, runparams);
1139 Chktex chktex(lyxrc.chktex_command, name, filePath());
1140 int const res = chktex.run(terr); // run chktex
1143 Alert::error(_("chktex failure"),
1144 _("Could not run chktex successfully."));
1145 } else if (res > 0) {
1146 // Insert all errors as errors boxes
1147 bufferErrors(*this, terr);
1156 void Buffer::validate(LaTeXFeatures & features) const
1158 LyXTextClass const & tclass = params().getLyXTextClass();
1160 if (features.isAvailable("dvipost") && params().tracking_changes
1161 && params().output_changes)
1162 features.require("dvipost");
1164 // AMS Style is at document level
1165 if (params().use_amsmath == BufferParams::AMS_ON
1166 || tclass.provides(LyXTextClass::amsmath))
1167 features.require("amsmath");
1169 for_each(paragraphs().begin(), paragraphs().end(),
1170 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1172 // the bullet shapes are buffer level not paragraph level
1173 // so they are tested here
1174 for (int i = 0; i < 4; ++i) {
1175 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1176 int const font = params().user_defined_bullet(i).getFont();
1178 int const c = params()
1179 .user_defined_bullet(i)
1186 features.require("latexsym");
1188 } else if (font == 1) {
1189 features.require("amssymb");
1190 } else if ((font >= 2 && font <= 5)) {
1191 features.require("pifont");
1196 if (lyxerr.debugging(Debug::LATEX)) {
1197 features.showStruct();
1202 void Buffer::getLabelList(vector<string> & list) const
1204 /// if this is a child document and the parent is already loaded
1205 /// Use the parent's list instead [ale990407]
1206 Buffer const * tmp = getMasterBuffer();
1208 lyxerr << "getMasterBuffer() failed!" << endl;
1212 tmp->getLabelList(list);
1216 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1217 it.nextInset()->getLabelList(*this, list);
1221 // This is also a buffer property (ale)
1222 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1225 /// if this is a child document and the parent is already loaded
1226 /// use the parent's list instead [ale990412]
1227 Buffer const * tmp = getMasterBuffer();
1230 tmp->fillWithBibKeys(keys);
1234 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1235 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1236 InsetBibtex const & inset =
1237 dynamic_cast<InsetBibtex const &>(*it);
1238 inset.fillWithBibKeys(*this, keys);
1239 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1240 InsetInclude const & inset =
1241 dynamic_cast<InsetInclude const &>(*it);
1242 inset.fillWithBibKeys(*this, keys);
1243 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1244 InsetBibitem const & inset =
1245 dynamic_cast<InsetBibitem const &>(*it);
1246 string const key = inset.getContents();
1247 string const opt = inset.getOptions();
1248 string const ref; // = pit->asString(this, false);
1249 string const info = opt + "TheBibliographyRef" + ref;
1250 keys.push_back(pair<string, string>(key, info));
1256 void Buffer::updateBibfilesCache()
1258 // if this is a child document and the parent is already loaded
1259 // update the parent's cache instead
1260 Buffer * tmp = getMasterBuffer();
1263 tmp->updateBibfilesCache();
1267 bibfilesCache_.clear();
1268 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1269 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1270 InsetBibtex const & inset =
1271 dynamic_cast<InsetBibtex const &>(*it);
1272 vector<string> const bibfiles = inset.getFiles(*this);
1273 bibfilesCache_.insert(bibfilesCache_.end(),
1276 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1277 InsetInclude & inset =
1278 dynamic_cast<InsetInclude &>(*it);
1279 inset.updateBibfilesCache(*this);
1280 vector<string> const & bibfiles =
1281 inset.getBibfilesCache(*this);
1282 bibfilesCache_.insert(bibfilesCache_.end(),
1290 vector<string> const & Buffer::getBibfilesCache() const
1292 // if this is a child document and the parent is already loaded
1293 // use the parent's cache instead
1294 Buffer const * tmp = getMasterBuffer();
1297 return tmp->getBibfilesCache();
1299 return bibfilesCache_;
1303 bool Buffer::isDepClean(string const & name) const
1305 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1306 if (it == pimpl_->dep_clean.end())
1312 void Buffer::markDepClean(string const & name)
1314 pimpl_->dep_clean[name] = true;
1318 bool Buffer::dispatch(string const & command, bool * result)
1320 return dispatch(lyxaction.lookupFunc(command), result);
1324 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1326 bool dispatched = true;
1328 switch (func.action) {
1330 bool const tmp = Exporter::Export(this, func.argument, false);
1343 void Buffer::changeLanguage(Language const * from, Language const * to)
1348 lyxerr << "Changing Language!" << endl;
1350 // Take care of l10n/i18n
1353 for_each(par_iterator_begin(),
1355 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1357 text().current_font.setLanguage(to);
1358 text().real_current_font.setLanguage(to);
1362 void Buffer::updateDocLang(Language const * nlang)
1364 BOOST_ASSERT(nlang);
1366 pimpl_->messages.reset(new Messages(nlang->code()));
1370 bool Buffer::isMultiLingual() const
1372 ParConstIterator end = par_iterator_end();
1373 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1374 if (it->isMultiLingual(params()))
1381 ParIterator Buffer::getParFromID(int const id) const
1383 ParConstIterator it = par_iterator_begin();
1384 ParConstIterator const end = par_iterator_end();
1387 // John says this is called with id == -1 from undo
1388 lyxerr << "getParFromID(), id: " << id << endl;
1392 for (; it != end; ++it)
1400 bool Buffer::hasParWithID(int const id) const
1402 ParConstIterator const it = getParFromID(id);
1403 return it != par_iterator_end();
1407 ParIterator Buffer::par_iterator_begin()
1409 return ::par_iterator_begin(inset());
1413 ParIterator Buffer::par_iterator_end()
1415 return ::par_iterator_end(inset());
1419 ParConstIterator Buffer::par_iterator_begin() const
1421 return ::par_const_iterator_begin(inset());
1425 ParConstIterator Buffer::par_iterator_end() const
1427 return ::par_const_iterator_end(inset());
1431 Language const * Buffer::getLanguage() const
1433 return params().language;
1437 string const Buffer::B_(string const & l10n) const
1439 if (pimpl_->messages.get()) {
1440 return pimpl_->messages->get(l10n);
1447 bool Buffer::isClean() const
1449 return pimpl_->lyx_clean;
1453 bool Buffer::isBakClean() const
1455 return pimpl_->bak_clean;
1459 void Buffer::markClean() const
1461 if (!pimpl_->lyx_clean) {
1462 pimpl_->lyx_clean = true;
1465 // if the .lyx file has been saved, we don't need an
1467 pimpl_->bak_clean = true;
1471 void Buffer::markBakClean()
1473 pimpl_->bak_clean = true;
1477 void Buffer::setUnnamed(bool flag)
1479 pimpl_->unnamed = flag;
1483 bool Buffer::isUnnamed() const
1485 return pimpl_->unnamed;
1489 #ifdef WITH_WARNINGS
1490 #warning this function should be moved to buffer_pimpl.C
1492 void Buffer::markDirty()
1494 if (pimpl_->lyx_clean) {
1495 pimpl_->lyx_clean = false;
1498 pimpl_->bak_clean = false;
1500 DepClean::iterator it = pimpl_->dep_clean.begin();
1501 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1503 for (; it != end; ++it) {
1509 string const & Buffer::fileName() const
1511 return pimpl_->filename;
1515 string const & Buffer::filePath() const
1517 return params().filepath;
1521 bool Buffer::isReadonly() const
1523 return pimpl_->read_only;
1527 void Buffer::setParentName(string const & name)
1529 params().parentname = name;
1533 Buffer const * Buffer::getMasterBuffer() const
1535 if (!params().parentname.empty()
1536 && bufferlist.exists(params().parentname)) {
1537 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1539 return buf->getMasterBuffer();
1546 Buffer * Buffer::getMasterBuffer()
1548 if (!params().parentname.empty()
1549 && bufferlist.exists(params().parentname)) {
1550 Buffer * buf = bufferlist.getBuffer(params().parentname);
1552 return buf->getMasterBuffer();
1559 MacroData const & Buffer::getMacro(std::string const & name) const
1561 return pimpl_->macros.get(name);
1565 bool Buffer::hasMacro(string const & name) const
1567 return pimpl_->macros.has(name);
1571 void Buffer::insertMacro(string const & name, MacroData const & data)
1573 MacroTable::globalMacros().insert(name, data);
1574 pimpl_->macros.insert(name, data);
1578 void Buffer::buildMacros()
1580 // Start with global table.
1581 pimpl_->macros = MacroTable::globalMacros();
1584 ParagraphList const & pars = text().paragraphs();
1585 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1586 //lyxerr << "searching main par " << i
1587 // << " for macro definitions" << std::endl;
1588 InsetList const & insets = pars[i].insetlist;
1589 InsetList::const_iterator it = insets.begin();
1590 InsetList::const_iterator end = insets.end();
1591 for ( ; it != end; ++it) {
1592 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1593 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1594 MathMacroTemplate const & mac
1595 = static_cast<MathMacroTemplate const &>(*it->inset);
1596 insertMacro(mac.name(), mac.asMacroData());
1603 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1610 void Buffer::changeRefsIfUnique(string const & from, string const & to)
1612 // Check if the label 'from' appears more than once
1613 vector<string> labels;
1614 getLabelList(labels);
1616 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1619 InsetBase::Code code = InsetBase::REF_CODE;
1621 ParIterator it = par_iterator_begin();
1622 ParIterator end = par_iterator_end();
1623 for ( ; it != end; ++it) {
1624 bool changed_inset = false;
1625 for (InsetList::iterator it2 = it->insetlist.begin();
1626 it2 != it->insetlist.end(); ++it2) {
1627 if (it2->inset->lyxCode() == code) {
1628 InsetCommand * inset = static_cast<InsetCommand *>(it2->inset);
1629 if (inset->getContents() == from) {
1630 inset->setContents(to);
1631 //inset->setButtonLabel();
1632 changed_inset = true;
1640 void Buffer::getSourceCode(ostream & os, lyx::pit_type par_begin, lyx::pit_type par_end)
1642 OutputParams runparams;
1643 runparams.nice = true;
1644 runparams.flavor = OutputParams::LATEX;
1645 runparams.linelen = lyxrc.ascii_linelen;
1646 runparams.par_begin = par_begin;
1647 runparams.par_end = par_end;
1648 // No side effect of file copying and image conversion
1649 runparams.dryrun = true;
1651 if (par_begin + 1 == par_end)
1652 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1654 os << "% Preview source code from paragraph " << par_begin << " to " << par_end - 1 << "\n\n";
1655 // output paragraphs
1658 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1659 } else if (isLinuxDoc())
1660 linuxdocParagraphs(*this, paragraphs(), os, runparams);
1662 docbookParagraphs(paragraphs(), *this, os, runparams);