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 <boost/iostreams/filtering_stream.hpp>
73 # include <boost/iostreams/filter/gzip.hpp>
74 # include <boost/iostreams/device/file.hpp>
75 namespace io = boost::iostreams;
77 #include "support/lyxlib.h"
78 #include "support/os.h"
79 #include "support/path.h"
80 #include "support/textutils.h"
81 #include "support/convert.h"
83 #include <boost/bind.hpp>
84 #include <boost/filesystem/operations.hpp>
86 #if defined (HAVE_UTIME_H)
88 #elif defined (HAVE_SYS_UTIME_H)
89 # include <sys/utime.h>
101 using lyx::support::addName;
102 using lyx::support::bformat;
103 using lyx::support::changeExtension;
104 using lyx::support::cmd_ret;
105 using lyx::support::createBufferTmpDir;
106 using lyx::support::destroyDir;
107 using lyx::support::getFormatFromContents;
108 using lyx::support::isDirWriteable;
109 using lyx::support::libFileSearch;
110 using lyx::support::latex_path;
111 using lyx::support::ltrim;
112 using lyx::support::makeAbsPath;
113 using lyx::support::makeDisplayPath;
114 using lyx::support::makeLatexName;
115 using lyx::support::onlyFilename;
116 using lyx::support::onlyPath;
117 using lyx::support::Path;
118 using lyx::support::quoteName;
119 using lyx::support::removeAutosaveFile;
120 using lyx::support::rename;
121 using lyx::support::runCommand;
122 using lyx::support::split;
123 using lyx::support::subst;
124 using lyx::support::tempName;
125 using lyx::support::trim;
127 namespace os = lyx::support::os;
128 namespace fs = boost::filesystem;
132 using std::make_pair;
138 using std::ostringstream;
146 // all these externs should eventually be removed.
147 extern BufferList bufferlist;
151 int const LYX_FORMAT = 245;
156 typedef std::map<string, bool> DepClean;
161 Impl(Buffer & parent, string const & file, bool readonly);
163 limited_stack<Undo> undostack;
164 limited_stack<Undo> redostack;
170 /// need to regenerate .tex?
174 mutable bool lyx_clean;
176 /// is autosave needed?
177 mutable bool bak_clean;
179 /// is this a unnamed file (New...)?
185 /// name of the file the buffer is associated with.
188 boost::scoped_ptr<Messages> messages;
190 /** Set to true only when the file is fully loaded.
191 * Used to prevent the premature generation of previews
192 * and by the citation inset.
194 bool file_fully_loaded;
196 /// our LyXText that should be wrapped in an InsetText
204 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
205 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
206 filename(file), file_fully_loaded(false),
209 inset.setAutoBreakRows(true);
210 lyxvc.buffer(&parent);
211 temppath = createBufferTmpDir();
212 params.filepath = onlyPath(file);
213 // FIXME: And now do something if temppath == string(), because we
214 // assume from now on that temppath points to a valid temp dir.
215 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
219 Buffer::Buffer(string const & file, bool readonly)
220 : pimpl_(new Impl(*this, file, readonly))
222 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
228 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
229 // here the buffer should take care that it is
230 // saved properly, before it goes into the void.
234 if (!temppath().empty() && !destroyDir(temppath())) {
235 Alert::warning(_("Could not remove temporary directory"),
236 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
239 // Remove any previewed LaTeX snippets associated with this buffer.
240 lyx::graphics::Previews::get().removeLoader(*this);
244 LyXText & Buffer::text() const
246 return const_cast<LyXText &>(pimpl_->inset.text_);
250 InsetBase & Buffer::inset() const
252 return const_cast<InsetText &>(pimpl_->inset);
256 limited_stack<Undo> & Buffer::undostack()
258 return pimpl_->undostack;
262 limited_stack<Undo> const & Buffer::undostack() const
264 return pimpl_->undostack;
268 limited_stack<Undo> & Buffer::redostack()
270 return pimpl_->redostack;
274 limited_stack<Undo> const & Buffer::redostack() const
276 return pimpl_->redostack;
280 BufferParams & Buffer::params()
282 return pimpl_->params;
286 BufferParams const & Buffer::params() const
288 return pimpl_->params;
292 ParagraphList & Buffer::paragraphs()
294 return text().paragraphs();
298 ParagraphList const & Buffer::paragraphs() const
300 return text().paragraphs();
304 LyXVC & Buffer::lyxvc()
306 return pimpl_->lyxvc;
310 LyXVC const & Buffer::lyxvc() const
312 return pimpl_->lyxvc;
316 string const & Buffer::temppath() const
318 return pimpl_->temppath;
322 TexRow & Buffer::texrow()
324 return pimpl_->texrow;
328 TexRow const & Buffer::texrow() const
330 return pimpl_->texrow;
334 string const Buffer::getLatexName(bool const no_path) const
336 string const name = changeExtension(makeLatexName(fileName()), ".tex");
337 return no_path ? onlyFilename(name) : name;
341 pair<Buffer::LogType, string> const Buffer::getLogName() const
343 string const filename = getLatexName(false);
345 if (filename.empty())
346 return make_pair(Buffer::latexlog, string());
348 string const path = temppath();
350 string const fname = addName(path,
351 onlyFilename(changeExtension(filename,
354 addName(path, onlyFilename(
355 changeExtension(filename,
356 formats.extension("literate") + ".out")));
358 // If no Latex log or Build log is newer, show Build log
360 if (fs::exists(bname) &&
361 (!fs::exists(fname) || fs::last_write_time(fname) < fs::last_write_time(bname))) {
362 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
363 return make_pair(Buffer::buildlog, bname);
365 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
366 return make_pair(Buffer::latexlog, fname);
370 void Buffer::setReadonly(bool const flag)
372 if (pimpl_->read_only != flag) {
373 pimpl_->read_only = flag;
379 void Buffer::setFileName(string const & newfile)
381 pimpl_->filename = makeAbsPath(newfile);
382 params().filepath = onlyPath(pimpl_->filename);
383 setReadonly(fs::is_readonly(pimpl_->filename));
388 // We'll remove this later. (Lgb)
391 void unknownClass(string const & unknown)
393 Alert::warning(_("Unknown document class"),
394 bformat(_("Using the default document class, because the "
395 "class %1$s is unknown."), unknown));
401 int Buffer::readHeader(LyXLex & lex)
403 int unknown_tokens = 0;
405 int begin_header_line = -1;
407 // Initialize parameters that may be/go lacking in header:
408 params().branchlist().clear();
409 params().preamble.erase();
410 params().options.erase();
411 params().float_placement.erase();
412 params().paperwidth.erase();
413 params().paperheight.erase();
414 params().leftmargin.erase();
415 params().rightmargin.erase();
416 params().topmargin.erase();
417 params().bottommargin.erase();
418 params().headheight.erase();
419 params().headsep.erase();
420 params().footskip.erase();
424 string const token = lex.getString();
429 if (token == "\\end_header")
433 if (token == "\\begin_header") {
434 begin_header_line = line;
438 lyxerr[Debug::PARSER] << "Handling document header token: `"
439 << token << '\'' << endl;
441 string unknown = params().readToken(lex, token);
442 if (!unknown.empty()) {
443 if (unknown[0] != '\\' && token == "\\textclass") {
444 unknownClass(unknown);
447 string const s = bformat(_("Unknown token: "
451 error(ErrorItem(_("Document header error"), s,
456 if (begin_header_line) {
457 string const s = _("\\begin_header is missing");
458 error(ErrorItem(_("Document header error"), s, -1, 0, 0));
460 return unknown_tokens;
465 // changed to be public and have one parameter
466 // Returns false if "\end_document" is not read (Asger)
467 bool Buffer::readDocument(LyXLex & lex)
470 string const token = lex.getString();
471 if (token != "\\begin_document") {
472 string const s = _("\\begin_document is missing");
473 error(ErrorItem(_("Document header error"), s, -1, 0, 0));
476 // we are reading in a brand new document
477 BOOST_ASSERT(paragraphs().empty());
480 if (!params().getLyXTextClass().load(filePath())) {
481 string theclass = params().getLyXTextClass().name();
482 Alert::error(_("Can't load document class"), bformat(
483 "Using the default document class, because the "
484 " class %1$s could not be loaded.", theclass));
485 params().textclass = 0;
488 bool const res = text().read(*this, lex);
489 for_each(text().paragraphs().begin(),
490 text().paragraphs().end(),
491 bind(&Paragraph::setInsetOwner, _1, &inset()));
492 updateBibfilesCache();
497 // needed to insert the selection
498 void Buffer::insertStringAsLines(ParagraphList & pars,
499 pit_type & pit, pos_type & pos,
500 LyXFont const & fn, string const & str, bool autobreakrows)
504 // insert the string, don't insert doublespace
505 bool space_inserted = true;
506 for (string::const_iterator cit = str.begin();
507 cit != str.end(); ++cit) {
508 Paragraph & par = pars[pit];
510 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
511 breakParagraph(params(), pars, pit, pos,
512 par.layout()->isEnvironment());
515 space_inserted = true;
519 // do not insert consecutive spaces if !free_spacing
520 } else if ((*cit == ' ' || *cit == '\t') &&
521 space_inserted && !par.isFreeSpacing()) {
523 } else if (*cit == '\t') {
524 if (!par.isFreeSpacing()) {
525 // tabs are like spaces here
526 par.insertChar(pos, ' ', font);
528 space_inserted = true;
530 const pos_type n = 8 - pos % 8;
531 for (pos_type i = 0; i < n; ++i) {
532 par.insertChar(pos, ' ', font);
535 space_inserted = true;
537 } else if (!isPrintable(*cit)) {
538 // Ignore unprintables
541 // just insert the character
542 par.insertChar(pos, *cit, font);
544 space_inserted = (*cit == ' ');
551 bool Buffer::readFile(string const & filename)
553 // Check if the file is compressed.
554 string const format = getFormatFromContents(filename);
555 if (format == "gzip" || format == "zip" || format == "compress") {
556 params().compressed = true;
559 // remove dummy empty par
560 paragraphs().clear();
562 lex.setFile(filename);
563 bool ret = readFile(lex, filename);
565 // After we have read a file, we must ensure that the buffer
566 // language is set and used in the gui.
567 // If you know of a better place to put this, please tell me. (Lgb)
568 updateDocLang(params().language);
574 bool Buffer::fully_loaded() const
576 return pimpl_->file_fully_loaded;
580 void Buffer::fully_loaded(bool const value)
582 pimpl_->file_fully_loaded = value;
586 bool Buffer::readFile(LyXLex & lex, string const & filename)
588 BOOST_ASSERT(!filename.empty());
591 Alert::error(_("Document could not be read"),
592 bformat(_("%1$s could not be read."), filename));
597 string const token(lex.getString());
600 Alert::error(_("Document could not be read"),
601 bformat(_("%1$s could not be read."), filename));
605 // the first token _must_ be...
606 if (token != "\\lyxformat") {
607 lyxerr << "Token: " << token << endl;
609 Alert::error(_("Document format failure"),
610 bformat(_("%1$s is not a LyX document."),
616 string tmp_format = lex.getString();
617 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
618 // if present remove ".," from string.
619 string::size_type dot = tmp_format.find_first_of(".,");
620 //lyxerr << " dot found at " << dot << endl;
621 if (dot != string::npos)
622 tmp_format.erase(dot, 1);
623 int const file_format = convert<int>(tmp_format);
624 //lyxerr << "format: " << file_format << endl;
626 if (file_format != LYX_FORMAT) {
627 string const tmpfile = tempName();
628 if (tmpfile.empty()) {
629 Alert::error(_("Conversion failed"),
630 bformat(_("%1$s is from an earlier"
631 " version of LyX, but a temporary"
632 " file for converting it could"
637 string const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
638 if (lyx2lyx.empty()) {
639 Alert::error(_("Conversion script not found"),
640 bformat(_("%1$s is from an earlier"
641 " version of LyX, but the"
642 " conversion script lyx2lyx"
643 " could not be found."),
647 ostringstream command;
648 command << "python " << quoteName(lyx2lyx)
649 << " -t " << convert<string>(LYX_FORMAT)
650 << " -o " << quoteName(tmpfile) << ' '
651 << quoteName(filename);
652 string const command_str = command.str();
654 lyxerr[Debug::INFO] << "Running '"
655 << command_str << '\''
658 cmd_ret const ret = runCommand(command_str);
659 if (ret.first != 0) {
660 Alert::error(_("Conversion script failed"),
661 bformat(_("%1$s is from an earlier version"
662 " of LyX, but the lyx2lyx script"
663 " failed to convert it."),
667 bool const ret = readFile(tmpfile);
668 // Do stuff with tmpfile name and buffer name here.
674 if (readDocument(lex)) {
675 Alert::error(_("Document format failure"),
676 bformat(_("%1$s ended unexpectedly, which means"
677 " that it is probably corrupted."),
681 //lyxerr << "removing " << MacroTable::localMacros().size()
682 // << " temporary macro entries" << endl;
683 //MacroTable::localMacros().clear();
685 pimpl_->file_fully_loaded = true;
690 // Should probably be moved to somewhere else: BufferView? LyXView?
691 bool Buffer::save() const
693 // We don't need autosaves in the immediate future. (Asger)
694 resetAutosaveTimers();
698 if (lyxrc.make_backup) {
699 s = fileName() + '~';
700 if (!lyxrc.backupdir_path.empty())
701 s = addName(lyxrc.backupdir_path,
702 subst(os::internal_path(s),'/','!'));
704 // It might very well be that this variant is just
705 // good enough. (Lgb)
706 // But to use this we need fs::copy_file to actually do a copy,
707 // even when the target file exists. (Lgb)
708 if (fs::exists(fileName()) && fs::is_writable(fs::path(fileName()).branch_path())) {
710 fs::copy_file(fileName(), s, false);
712 //catch (fs::filesystem_error const & fe) {
713 //lyxerr << "LyX was not able to make backup copy. Beware.\n"
714 // << fe.what() << endl;
719 if (writeFile(fileName())) {
721 removeAutosaveFile(fileName());
723 // Saving failed, so backup is not backup
724 if (lyxrc.make_backup)
725 rename(s, fileName());
732 bool Buffer::writeFile(string const & fname) const
734 if (pimpl_->read_only && fname == fileName())
739 if (params().compressed) {
740 #ifdef USE_COMPRESSION
741 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname));
745 retval = do_writeFile(ofs);
750 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
754 retval = do_writeFile(ofs);
761 bool Buffer::do_writeFile(ostream & ofs) const
764 // Use the standard "C" locale for file output.
765 ofs.imbue(std::locale::classic());
768 // The top of the file should not be written by params().
770 // write out a comment in the top of the file
771 ofs << "#LyX " << lyx_version
772 << " created this file. For more info see http://www.lyx.org/\n"
773 << "\\lyxformat " << LYX_FORMAT << "\n"
774 << "\\begin_document\n";
776 // now write out the buffer parameters.
777 ofs << "\\begin_header\n";
778 params().writeFile(ofs);
779 ofs << "\\end_header\n";
782 ofs << "\n\\begin_body\n";
783 text().write(*this, ofs);
784 ofs << "\n\\end_body\n";
786 // Write marker that shows file is complete
787 ofs << "\\end_document" << endl;
789 // Shouldn't really be needed....
792 // how to check if close went ok?
793 // Following is an attempt... (BE 20001011)
795 // good() returns false if any error occured, including some
797 // bad() returns true if something bad happened in the buffer,
798 // which should include file system full errors.
803 lyxerr << "File was not closed properly." << endl;
810 void Buffer::makeLaTeXFile(string const & fname,
811 string const & original_path,
812 OutputParams const & runparams,
813 bool output_preamble, bool output_body)
815 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
818 if (!openFileWrite(ofs, fname))
821 makeLaTeXFile(ofs, original_path,
822 runparams, output_preamble, output_body);
826 lyxerr << "File '" << fname << "' was not closed properly." << endl;
830 void Buffer::makeLaTeXFile(ostream & os,
831 string const & original_path,
832 OutputParams const & runparams_in,
833 bool const output_preamble, bool const output_body)
835 OutputParams runparams = runparams_in;
837 // validate the buffer.
838 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
839 LaTeXFeatures features(*this, params(), runparams);
841 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
845 // The starting paragraph of the coming rows is the
846 // first paragraph of the document. (Asger)
847 texrow().start(paragraphs().begin()->id(), 0);
849 if (output_preamble && runparams.nice) {
850 os << "%% LyX " << lyx_version << " created this file. "
851 "For more info, see http://www.lyx.org/.\n"
852 "%% Do not edit unless you really know what "
857 lyxerr[Debug::INFO] << "lyx document header finished" << endl;
858 // There are a few differences between nice LaTeX and usual files:
859 // usual is \batchmode and has a
860 // special input@path to allow the including of figures
861 // with either \input or \includegraphics (what figinsets do).
862 // input@path is set when the actual parameter
863 // original_path is set. This is done for usual tex-file, but not
864 // for nice-latex-file. (Matthias 250696)
865 // Note that input@path is only needed for something the user does
866 // in the preamble, included .tex files or ERT, files included by
867 // LyX work without it.
868 if (output_preamble) {
869 if (!runparams.nice) {
870 // code for usual, NOT nice-latex-file
871 os << "\\batchmode\n"; // changed
875 if (!original_path.empty()) {
876 string const inputpath = latex_path(original_path);
877 os << "\\makeatletter\n"
878 << "\\def\\input@path{{"
879 << inputpath << "/}}\n"
880 << "\\makeatother\n";
886 // Write the preamble
887 runparams.use_babel = params().writeLaTeX(os, features, texrow());
893 os << "\\begin{document}\n";
896 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
898 if (!lyxrc.language_auto_begin) {
899 os << subst(lyxrc.language_command_begin, "$$lang",
900 params().language->babel())
905 // if we are doing a real file with body, even if this is the
906 // child of some other buffer, let's cut the link here.
907 // This happens for example if only a child document is printed.
908 string save_parentname;
909 if (output_preamble) {
910 save_parentname = params().parentname;
911 params().parentname.erase();
915 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
917 // Restore the parenthood if needed
919 params().parentname = save_parentname;
921 // add this just in case after all the paragraphs
925 if (!lyxrc.language_auto_end) {
926 os << subst(lyxrc.language_command_end, "$$lang",
927 params().language->babel())
932 if (output_preamble) {
933 os << "\\end{document}\n";
936 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
938 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
942 // Just to be sure. (Asger)
945 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
946 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
951 bool Buffer::isLatex() const
953 return params().getLyXTextClass().outputType() == LATEX;
957 bool Buffer::isLinuxDoc() const
959 return params().getLyXTextClass().outputType() == LINUXDOC;
963 bool Buffer::isLiterate() const
965 return params().getLyXTextClass().outputType() == LITERATE;
969 bool Buffer::isDocBook() const
971 return params().getLyXTextClass().outputType() == DOCBOOK;
975 bool Buffer::isSGML() const
977 LyXTextClass const & tclass = params().getLyXTextClass();
979 return tclass.outputType() == LINUXDOC ||
980 tclass.outputType() == DOCBOOK;
984 void Buffer::makeLinuxDocFile(string const & fname,
985 OutputParams const & runparams,
986 bool const body_only)
989 if (!openFileWrite(ofs, fname))
992 LaTeXFeatures features(*this, params(), runparams);
997 LyXTextClass const & tclass = params().getLyXTextClass();
999 string const & top_element = tclass.latexname();
1002 ofs << tclass.class_header();
1004 string preamble = params().preamble;
1005 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1007 preamble += features.getIncludedFiles(name);
1008 preamble += features.getLyXSGMLEntities();
1010 if (!preamble.empty()) {
1011 ofs << " [ " << preamble << " ]";
1015 if (params().options.empty())
1016 sgml::openTag(ofs, top_element);
1018 string top = top_element;
1020 top += params().options;
1021 sgml::openTag(ofs, top);
1025 ofs << "<!-- LyX " << lyx_version
1026 << " created this file. For more info see http://www.lyx.org/"
1029 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1033 sgml::closeTag(ofs, top_element);
1038 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1042 void Buffer::makeDocBookFile(string const & fname,
1043 OutputParams const & runparams,
1044 bool const only_body)
1047 if (!openFileWrite(ofs, fname))
1050 LaTeXFeatures features(*this, params(), runparams);
1055 LyXTextClass const & tclass = params().getLyXTextClass();
1056 string const & top_element = tclass.latexname();
1059 if (runparams.flavor == OutputParams::XML)
1060 ofs << "<?xml version=\"1.0\" encoding=\""
1061 << params().language->encoding()->name() << "\"?>\n";
1063 ofs << "<!DOCTYPE " << top_element << " ";
1065 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1066 else if (runparams.flavor == OutputParams::XML)
1067 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1068 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1070 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1072 string preamble = params().preamble;
1073 if (runparams.flavor != OutputParams::XML ) {
1074 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1075 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1076 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1077 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1080 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1082 preamble += features.getIncludedFiles(name);
1083 preamble += features.getLyXSGMLEntities();
1085 if (!preamble.empty()) {
1086 ofs << "\n [ " << preamble << " ]";
1091 string top = top_element;
1093 if (runparams.flavor == OutputParams::XML)
1094 top += params().language->code();
1096 top += params().language->code().substr(0,2);
1099 if (!params().options.empty()) {
1101 top += params().options;
1104 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1105 << " file was created by LyX " << lyx_version
1106 << "\n See http://www.lyx.org/ for more information -->\n";
1108 params().getLyXTextClass().counters().reset();
1110 sgml::openTag(ofs, top);
1112 docbookParagraphs(paragraphs(), *this, ofs, runparams);
1113 sgml::closeTag(ofs, top_element);
1117 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1121 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1122 // Other flags: -wall -v0 -x
1123 int Buffer::runChktex()
1127 // get LaTeX-Filename
1128 string const name = getLatexName();
1129 string const path = temppath();
1130 string const org_path = filePath();
1132 Path p(path); // path to LaTeX file
1133 message(_("Running chktex..."));
1135 // Generate the LaTeX file if neccessary
1136 OutputParams runparams;
1137 runparams.flavor = OutputParams::LATEX;
1138 runparams.nice = false;
1139 makeLaTeXFile(name, org_path, runparams);
1142 Chktex chktex(lyxrc.chktex_command, name, filePath());
1143 int const res = chktex.run(terr); // run chktex
1146 Alert::error(_("chktex failure"),
1147 _("Could not run chktex successfully."));
1148 } else if (res > 0) {
1149 // Insert all errors as errors boxes
1150 bufferErrors(*this, terr);
1159 void Buffer::validate(LaTeXFeatures & features) const
1161 LyXTextClass const & tclass = params().getLyXTextClass();
1163 if (features.isAvailable("dvipost") && params().tracking_changes
1164 && params().output_changes)
1165 features.require("dvipost");
1167 // AMS Style is at document level
1168 if (params().use_amsmath == BufferParams::AMS_ON
1169 || tclass.provides(LyXTextClass::amsmath))
1170 features.require("amsmath");
1172 for_each(paragraphs().begin(), paragraphs().end(),
1173 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1175 // the bullet shapes are buffer level not paragraph level
1176 // so they are tested here
1177 for (int i = 0; i < 4; ++i) {
1178 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1179 int const font = params().user_defined_bullet(i).getFont();
1181 int const c = params()
1182 .user_defined_bullet(i)
1189 features.require("latexsym");
1191 } else if (font == 1) {
1192 features.require("amssymb");
1193 } else if ((font >= 2 && font <= 5)) {
1194 features.require("pifont");
1199 if (lyxerr.debugging(Debug::LATEX)) {
1200 features.showStruct();
1205 void Buffer::getLabelList(vector<string> & list) const
1207 /// if this is a child document and the parent is already loaded
1208 /// Use the parent's list instead [ale990407]
1209 Buffer const * tmp = getMasterBuffer();
1211 lyxerr << "getMasterBuffer() failed!" << endl;
1215 tmp->getLabelList(list);
1219 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1220 it.nextInset()->getLabelList(*this, list);
1224 // This is also a buffer property (ale)
1225 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1228 /// if this is a child document and the parent is already loaded
1229 /// use the parent's list instead [ale990412]
1230 Buffer const * tmp = getMasterBuffer();
1233 tmp->fillWithBibKeys(keys);
1237 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1238 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1239 InsetBibtex const & inset =
1240 dynamic_cast<InsetBibtex const &>(*it);
1241 inset.fillWithBibKeys(*this, keys);
1242 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1243 InsetInclude const & inset =
1244 dynamic_cast<InsetInclude const &>(*it);
1245 inset.fillWithBibKeys(*this, keys);
1246 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1247 InsetBibitem const & inset =
1248 dynamic_cast<InsetBibitem const &>(*it);
1249 string const key = inset.getContents();
1250 string const opt = inset.getOptions();
1251 string const ref; // = pit->asString(this, false);
1252 string const info = opt + "TheBibliographyRef" + ref;
1253 keys.push_back(pair<string, string>(key, info));
1259 void Buffer::updateBibfilesCache()
1261 // if this is a child document and the parent is already loaded
1262 // update the parent's cache instead
1263 Buffer * tmp = getMasterBuffer();
1266 tmp->updateBibfilesCache();
1270 bibfilesCache_.clear();
1271 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1272 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1273 InsetBibtex const & inset =
1274 dynamic_cast<InsetBibtex const &>(*it);
1275 vector<string> const bibfiles = inset.getFiles(*this);
1276 bibfilesCache_.insert(bibfilesCache_.end(),
1279 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1280 InsetInclude & inset =
1281 dynamic_cast<InsetInclude &>(*it);
1282 inset.updateBibfilesCache(*this);
1283 vector<string> const & bibfiles =
1284 inset.getBibfilesCache(*this);
1285 bibfilesCache_.insert(bibfilesCache_.end(),
1293 vector<string> const & Buffer::getBibfilesCache() const
1295 // if this is a child document and the parent is already loaded
1296 // use the parent's cache instead
1297 Buffer const * tmp = getMasterBuffer();
1300 return tmp->getBibfilesCache();
1302 return bibfilesCache_;
1306 bool Buffer::isDepClean(string const & name) const
1308 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1309 if (it == pimpl_->dep_clean.end())
1315 void Buffer::markDepClean(string const & name)
1317 pimpl_->dep_clean[name] = true;
1321 bool Buffer::dispatch(string const & command, bool * result)
1323 return dispatch(lyxaction.lookupFunc(command), result);
1327 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1329 bool dispatched = true;
1331 switch (func.action) {
1333 bool const tmp = Exporter::Export(this, func.argument, false);
1346 void Buffer::changeLanguage(Language const * from, Language const * to)
1351 lyxerr << "Changing Language!" << endl;
1353 // Take care of l10n/i18n
1356 for_each(par_iterator_begin(),
1358 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1360 text().current_font.setLanguage(to);
1361 text().real_current_font.setLanguage(to);
1365 void Buffer::updateDocLang(Language const * nlang)
1367 BOOST_ASSERT(nlang);
1369 pimpl_->messages.reset(new Messages(nlang->code()));
1373 bool Buffer::isMultiLingual() const
1375 ParConstIterator end = par_iterator_end();
1376 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1377 if (it->isMultiLingual(params()))
1384 ParIterator Buffer::getParFromID(int const id) const
1386 ParConstIterator it = par_iterator_begin();
1387 ParConstIterator const end = par_iterator_end();
1390 // John says this is called with id == -1 from undo
1391 lyxerr << "getParFromID(), id: " << id << endl;
1395 for (; it != end; ++it)
1403 bool Buffer::hasParWithID(int const id) const
1405 ParConstIterator const it = getParFromID(id);
1406 return it != par_iterator_end();
1410 ParIterator Buffer::par_iterator_begin()
1412 return ::par_iterator_begin(inset());
1416 ParIterator Buffer::par_iterator_end()
1418 return ::par_iterator_end(inset());
1422 ParConstIterator Buffer::par_iterator_begin() const
1424 return ::par_const_iterator_begin(inset());
1428 ParConstIterator Buffer::par_iterator_end() const
1430 return ::par_const_iterator_end(inset());
1434 Language const * Buffer::getLanguage() const
1436 return params().language;
1440 string const Buffer::B_(string const & l10n) const
1442 if (pimpl_->messages.get()) {
1443 return pimpl_->messages->get(l10n);
1450 bool Buffer::isClean() const
1452 return pimpl_->lyx_clean;
1456 bool Buffer::isBakClean() const
1458 return pimpl_->bak_clean;
1462 void Buffer::markClean() const
1464 if (!pimpl_->lyx_clean) {
1465 pimpl_->lyx_clean = true;
1468 // if the .lyx file has been saved, we don't need an
1470 pimpl_->bak_clean = true;
1474 void Buffer::markBakClean()
1476 pimpl_->bak_clean = true;
1480 void Buffer::setUnnamed(bool flag)
1482 pimpl_->unnamed = flag;
1486 bool Buffer::isUnnamed() const
1488 return pimpl_->unnamed;
1492 #ifdef WITH_WARNINGS
1493 #warning this function should be moved to buffer_pimpl.C
1495 void Buffer::markDirty()
1497 if (pimpl_->lyx_clean) {
1498 pimpl_->lyx_clean = false;
1501 pimpl_->bak_clean = false;
1503 DepClean::iterator it = pimpl_->dep_clean.begin();
1504 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1506 for (; it != end; ++it) {
1512 string const & Buffer::fileName() const
1514 return pimpl_->filename;
1518 string const & Buffer::filePath() const
1520 return params().filepath;
1524 bool Buffer::isReadonly() const
1526 return pimpl_->read_only;
1530 void Buffer::setParentName(string const & name)
1532 params().parentname = name;
1536 Buffer const * Buffer::getMasterBuffer() const
1538 if (!params().parentname.empty()
1539 && bufferlist.exists(params().parentname)) {
1540 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1542 return buf->getMasterBuffer();
1549 Buffer * Buffer::getMasterBuffer()
1551 if (!params().parentname.empty()
1552 && bufferlist.exists(params().parentname)) {
1553 Buffer * buf = bufferlist.getBuffer(params().parentname);
1555 return buf->getMasterBuffer();
1562 MacroData const & Buffer::getMacro(std::string const & name) const
1564 return pimpl_->macros.get(name);
1568 bool Buffer::hasMacro(string const & name) const
1570 return pimpl_->macros.has(name);
1574 void Buffer::insertMacro(string const & name, MacroData const & data)
1576 MacroTable::globalMacros().insert(name, data);
1577 pimpl_->macros.insert(name, data);
1581 void Buffer::buildMacros()
1583 // Start with global table.
1584 pimpl_->macros = MacroTable::globalMacros();
1587 ParagraphList const & pars = text().paragraphs();
1588 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1589 //lyxerr << "searching main par " << i
1590 // << " for macro definitions" << std::endl;
1591 InsetList const & insets = pars[i].insetlist;
1592 InsetList::const_iterator it = insets.begin();
1593 InsetList::const_iterator end = insets.end();
1594 for ( ; it != end; ++it) {
1595 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1596 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1597 MathMacroTemplate const & mac
1598 = static_cast<MathMacroTemplate const &>(*it->inset);
1599 insertMacro(mac.name(), mac.asMacroData());
1606 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1613 void Buffer::changeRefsIfUnique(string const & from, string const & to)
1615 // Check if the label 'from' appears more than once
1616 vector<string> labels;
1617 getLabelList(labels);
1619 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1622 InsetBase::Code code = InsetBase::REF_CODE;
1624 ParIterator it = par_iterator_begin();
1625 ParIterator end = par_iterator_end();
1626 for ( ; it != end; ++it) {
1627 bool changed_inset = false;
1628 for (InsetList::iterator it2 = it->insetlist.begin();
1629 it2 != it->insetlist.end(); ++it2) {
1630 if (it2->inset->lyxCode() == code) {
1631 InsetCommand * inset = static_cast<InsetCommand *>(it2->inset);
1632 if (inset->getContents() == from) {
1633 inset->setContents(to);
1634 //inset->setButtonLabel();
1635 changed_inset = true;
1643 void Buffer::getSourceCode(ostream & os, lyx::pit_type par_begin, lyx::pit_type par_end)
1645 OutputParams runparams;
1646 runparams.nice = true;
1647 runparams.flavor = OutputParams::LATEX;
1648 runparams.linelen = lyxrc.ascii_linelen;
1649 runparams.par_begin = par_begin;
1650 runparams.par_end = par_end;
1651 // No side effect of file copying and image conversion
1652 runparams.dryrun = true;
1654 if (par_begin + 1 == par_end)
1655 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1657 os << "% Preview source code from paragraph " << par_begin << " to " << par_end - 1 << "\n\n";
1658 // output paragraphs
1661 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1662 } else if (isLinuxDoc())
1663 linuxdocParagraphs(*this, paragraphs(), os, runparams);
1665 docbookParagraphs(paragraphs(), *this, os, runparams);