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 "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/MathMacroTemplate.h"
59 #include "mathed/MathMacroTable.h"
60 #include "mathed/MathSupport.h"
62 #include "frontends/Alert.h"
64 #include "graphics/Previews.h"
66 #include "support/types.h"
67 #include "support/lyxalgo.h"
68 #include "support/filetools.h"
69 #include "support/fs_extras.h"
70 #include <boost/iostreams/filtering_stream.hpp>
71 #include <boost/iostreams/filter/gzip.hpp>
72 #include <boost/iostreams/device/file.hpp>
73 namespace io = boost::iostreams;
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/exception.hpp>
82 #include <boost/filesystem/operations.hpp>
84 #if defined (HAVE_UTIME_H)
86 #elif defined (HAVE_SYS_UTIME_H)
87 #include <sys/utime.h>
100 using lyx::support::addName;
101 using lyx::support::bformat;
102 using lyx::support::changeExtension;
103 using lyx::support::cmd_ret;
104 using lyx::support::createBufferTmpDir;
105 using lyx::support::destroyDir;
106 using lyx::support::getFormatFromContents;
107 using lyx::support::isDirWriteable;
108 using lyx::support::libFileSearch;
109 using lyx::support::latex_path;
110 using lyx::support::ltrim;
111 using lyx::support::makeAbsPath;
112 using lyx::support::makeDisplayPath;
113 using lyx::support::makeLatexName;
114 using lyx::support::onlyFilename;
115 using lyx::support::onlyPath;
116 using lyx::support::quoteName;
117 using lyx::support::removeAutosaveFile;
118 using lyx::support::rename;
119 using lyx::support::runCommand;
120 using lyx::support::split;
121 using lyx::support::subst;
122 using lyx::support::tempName;
123 using lyx::support::trim;
125 namespace Alert = lyx::frontend::Alert;
126 namespace os = lyx::support::os;
127 namespace fs = boost::filesystem;
131 using std::make_pair;
137 using std::ostringstream;
147 int const LYX_FORMAT = 249;
152 typedef std::map<string, bool> DepClean;
157 Impl(Buffer & parent, string const & file, bool readonly);
159 limited_stack<Undo> undostack;
160 limited_stack<Undo> redostack;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 boost::scoped_ptr<Messages> messages;
186 /** Set to true only when the file is fully loaded.
187 * Used to prevent the premature generation of previews
188 * and by the citation inset.
190 bool file_fully_loaded;
192 /// our LyXText that should be wrapped in an InsetText
200 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
201 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
202 filename(file), file_fully_loaded(false),
205 inset.setAutoBreakRows(true);
206 lyxvc.buffer(&parent);
207 temppath = createBufferTmpDir();
208 params.filepath = onlyPath(file);
209 // FIXME: And now do something if temppath == string(), because we
210 // assume from now on that temppath points to a valid temp dir.
211 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
215 Buffer::Buffer(string const & file, bool readonly)
216 : pimpl_(new Impl(*this, file, readonly))
218 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
224 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
225 // here the buffer should take care that it is
226 // saved properly, before it goes into the void.
230 if (!temppath().empty() && !destroyDir(temppath())) {
231 Alert::warning(_("Could not remove temporary directory"),
232 bformat(_("Could not remove the temporary directory %1$s"),
233 lyx::from_utf8(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."), lyx::from_utf8(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();
419 ErrorList & errorList = errorLists_["Parse"];
423 string const token = lex.getString();
428 if (token == "\\end_header")
432 if (token == "\\begin_header") {
433 begin_header_line = line;
437 lyxerr[Debug::PARSER] << "Handling document header token: `"
438 << token << '\'' << endl;
440 string unknown = params().readToken(lex, token);
441 if (!unknown.empty()) {
442 if (unknown[0] != '\\' && token == "\\textclass") {
443 unknownClass(unknown);
446 docstring const s = bformat(_("Unknown token: "
448 lyx::from_utf8(token),
449 lyx::from_utf8(lex.getString()));
450 errorList.push_back(ErrorItem(_("Document header error"),
455 if (begin_header_line) {
456 docstring const s = _("\\begin_header is missing");
457 errorList.push_back(ErrorItem(_("Document header error"),
461 return unknown_tokens;
466 // changed to be public and have one parameter
467 // Returns false if "\end_document" is not read (Asger)
468 bool Buffer::readDocument(LyXLex & lex)
470 ErrorList & errorList = errorLists_["Parse"];
474 string const token = lex.getString();
475 if (token != "\\begin_document") {
476 docstring const s = _("\\begin_document is missing");
477 errorList.push_back(ErrorItem(_("Document header error"),
481 // we are reading in a brand new document
482 BOOST_ASSERT(paragraphs().empty());
485 if (!params().getLyXTextClass().load(filePath())) {
486 string theclass = params().getLyXTextClass().name();
487 Alert::error(_("Can't load document class"), bformat(
488 _("Using the default document class, because the "
489 " class %1$s could not be loaded."), lyx::from_utf8(theclass)));
490 params().textclass = 0;
493 bool const res = text().read(*this, lex, errorList);
494 for_each(text().paragraphs().begin(),
495 text().paragraphs().end(),
496 bind(&Paragraph::setInsetOwner, _1, &inset()));
497 updateBibfilesCache();
503 // needed to insert the selection
504 void Buffer::insertStringAsLines(ParagraphList & pars,
505 pit_type & pit, pos_type & pos,
506 LyXFont const & fn, docstring const & str, bool autobreakrows)
510 // insert the string, don't insert doublespace
511 bool space_inserted = true;
512 for (docstring::const_iterator cit = str.begin();
513 cit != str.end(); ++cit) {
514 Paragraph & par = pars[pit];
516 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
517 breakParagraph(params(), pars, pit, pos,
518 par.layout()->isEnvironment());
521 space_inserted = true;
525 // do not insert consecutive spaces if !free_spacing
526 } else if ((*cit == ' ' || *cit == '\t') &&
527 space_inserted && !par.isFreeSpacing()) {
529 } else if (*cit == '\t') {
530 if (!par.isFreeSpacing()) {
531 // tabs are like spaces here
532 par.insertChar(pos, ' ', font);
534 space_inserted = true;
536 const pos_type n = 8 - pos % 8;
537 for (pos_type i = 0; i < n; ++i) {
538 par.insertChar(pos, ' ', font);
541 space_inserted = true;
543 /* FIXME: not needed anymore?
544 } else if (!isPrintable(*cit)) {
545 // Ignore unprintables
549 // just insert the character
550 par.insertChar(pos, *cit, font);
552 space_inserted = (*cit == ' ');
559 bool Buffer::readFile(string const & filename)
561 // Check if the file is compressed.
562 string const format = getFormatFromContents(filename);
563 if (format == "gzip" || format == "zip" || format == "compress") {
564 params().compressed = true;
567 // remove dummy empty par
568 paragraphs().clear();
570 lex.setFile(filename);
571 if (!readFile(lex, filename))
574 // After we have read a file, we must ensure that the buffer
575 // language is set and used in the gui.
576 // If you know of a better place to put this, please tell me. (Lgb)
577 updateDocLang(params().language);
583 bool Buffer::fully_loaded() const
585 return pimpl_->file_fully_loaded;
589 void Buffer::fully_loaded(bool const value)
591 pimpl_->file_fully_loaded = value;
595 bool Buffer::readFile(LyXLex & lex, string const & filename)
597 BOOST_ASSERT(!filename.empty());
600 Alert::error(_("Document could not be read"),
601 bformat(_("%1$s could not be read."), lyx::from_utf8(filename)));
606 string const token(lex.getString());
609 Alert::error(_("Document could not be read"),
610 bformat(_("%1$s could not be read."), lyx::from_utf8(filename)));
614 // the first token _must_ be...
615 if (token != "\\lyxformat") {
616 lyxerr << "Token: " << token << endl;
618 Alert::error(_("Document format failure"),
619 bformat(_("%1$s is not a LyX document."),
620 lyx::from_utf8(filename)));
625 string tmp_format = lex.getString();
626 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
627 // if present remove ".," from string.
628 string::size_type dot = tmp_format.find_first_of(".,");
629 //lyxerr << " dot found at " << dot << endl;
630 if (dot != string::npos)
631 tmp_format.erase(dot, 1);
632 int const file_format = convert<int>(tmp_format);
633 //lyxerr << "format: " << file_format << endl;
635 if (file_format != LYX_FORMAT) {
636 string const tmpfile = tempName();
637 if (tmpfile.empty()) {
638 Alert::error(_("Conversion failed"),
639 bformat(_("%1$s is from an earlier"
640 " version of LyX, but a temporary"
641 " file for converting it could"
643 lyx::from_utf8(filename)));
646 string const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
647 if (lyx2lyx.empty()) {
648 Alert::error(_("Conversion script not found"),
649 bformat(_("%1$s is from an earlier"
650 " version of LyX, but the"
651 " conversion script lyx2lyx"
652 " could not be found."),
653 lyx::from_utf8(filename)));
656 ostringstream command;
657 command << os::python() << ' ' << quoteName(lyx2lyx)
658 << " -t " << convert<string>(LYX_FORMAT)
659 << " -o " << quoteName(tmpfile) << ' '
660 << quoteName(filename);
661 string const command_str = command.str();
663 lyxerr[Debug::INFO] << "Running '"
664 << command_str << '\''
667 cmd_ret const ret = runCommand(command_str);
668 if (ret.first != 0) {
669 Alert::error(_("Conversion script failed"),
670 bformat(_("%1$s is from an earlier version"
671 " of LyX, but the lyx2lyx script"
672 " failed to convert it."),
673 lyx::from_utf8(filename)));
676 bool const ret = readFile(tmpfile);
677 // Do stuff with tmpfile name and buffer name here.
683 if (readDocument(lex)) {
684 Alert::error(_("Document format failure"),
685 bformat(_("%1$s ended unexpectedly, which means"
686 " that it is probably corrupted."),
687 lyx::from_utf8(filename)));
690 //lyxerr << "removing " << MacroTable::localMacros().size()
691 // << " temporary macro entries" << endl;
692 //MacroTable::localMacros().clear();
694 pimpl_->file_fully_loaded = true;
699 // Should probably be moved to somewhere else: BufferView? LyXView?
700 bool Buffer::save() const
702 // We don't need autosaves in the immediate future. (Asger)
703 resetAutosaveTimers();
707 if (lyxrc.make_backup) {
708 s = fileName() + '~';
709 if (!lyxrc.backupdir_path.empty())
710 s = addName(lyxrc.backupdir_path,
711 subst(os::internal_path(s),'/','!'));
713 // It might very well be that this variant is just
714 // good enough. (Lgb)
715 // But to use this we need fs::copy_file to actually do a copy,
716 // even when the target file exists. (Lgb)
718 fs::copy_file(fileName(), s, false);
720 catch (fs::filesystem_error const & fe) {
721 Alert::error(_("Backup failure"),
722 bformat(_("LyX was not able to make a backup copy in %1$s.\n"
723 "Please check if the directory exists and is writeable."),
724 lyx::from_utf8(fs::path(s).branch_path().native_directory_string())));
725 lyxerr[Debug::DEBUG] << "Fs error: "
726 << fe.what() << endl;
730 if (writeFile(fileName())) {
732 removeAutosaveFile(fileName());
734 // Saving failed, so backup is not backup
735 if (lyxrc.make_backup)
736 rename(s, fileName());
743 bool Buffer::writeFile(string const & fname) const
745 if (pimpl_->read_only && fname == fileName())
750 if (params().compressed) {
751 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname));
755 retval = do_writeFile(ofs);
757 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
761 retval = do_writeFile(ofs);
768 bool Buffer::do_writeFile(ostream & ofs) const
771 // Use the standard "C" locale for file output.
772 ofs.imbue(std::locale::classic());
775 // The top of the file should not be written by params().
777 // write out a comment in the top of the file
778 ofs << "#LyX " << lyx_version
779 << " created this file. For more info see http://www.lyx.org/\n"
780 << "\\lyxformat " << LYX_FORMAT << "\n"
781 << "\\begin_document\n";
783 // now write out the buffer parameters.
784 ofs << "\\begin_header\n";
785 params().writeFile(ofs);
786 ofs << "\\end_header\n";
789 ofs << "\n\\begin_body\n";
790 text().write(*this, ofs);
791 ofs << "\n\\end_body\n";
793 // Write marker that shows file is complete
794 ofs << "\\end_document" << endl;
796 // Shouldn't really be needed....
799 // how to check if close went ok?
800 // Following is an attempt... (BE 20001011)
802 // good() returns false if any error occured, including some
804 // bad() returns true if something bad happened in the buffer,
805 // which should include file system full errors.
810 lyxerr << "File was not closed properly." << endl;
817 void Buffer::makeLaTeXFile(string const & fname,
818 string const & original_path,
819 OutputParams const & runparams,
820 bool output_preamble, bool output_body)
822 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
825 if (!openFileWrite(ofs, fname))
828 writeLaTeXSource(ofs, original_path,
829 runparams, output_preamble, output_body);
833 lyxerr << "File '" << fname << "' was not closed properly." << endl;
837 void Buffer::writeLaTeXSource(ostream & os,
838 string const & original_path,
839 OutputParams const & runparams_in,
840 bool const output_preamble, bool const output_body)
842 OutputParams runparams = runparams_in;
844 // validate the buffer.
845 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
846 LaTeXFeatures features(*this, params(), runparams);
848 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
852 // The starting paragraph of the coming rows is the
853 // first paragraph of the document. (Asger)
854 texrow().start(paragraphs().begin()->id(), 0);
856 if (output_preamble && runparams.nice) {
857 os << "%% LyX " << lyx_version << " created this file. "
858 "For more info, see http://www.lyx.org/.\n"
859 "%% Do not edit unless you really know what "
864 lyxerr[Debug::INFO] << "lyx document header finished" << endl;
865 // There are a few differences between nice LaTeX and usual files:
866 // usual is \batchmode and has a
867 // special input@path to allow the including of figures
868 // with either \input or \includegraphics (what figinsets do).
869 // input@path is set when the actual parameter
870 // original_path is set. This is done for usual tex-file, but not
871 // for nice-latex-file. (Matthias 250696)
872 // Note that input@path is only needed for something the user does
873 // in the preamble, included .tex files or ERT, files included by
874 // LyX work without it.
875 if (output_preamble) {
876 if (!runparams.nice) {
877 // code for usual, NOT nice-latex-file
878 os << "\\batchmode\n"; // changed
882 if (!original_path.empty()) {
883 string const inputpath = latex_path(original_path);
884 os << "\\makeatletter\n"
885 << "\\def\\input@path{{"
886 << inputpath << "/}}\n"
887 << "\\makeatother\n";
893 // Write the preamble
894 runparams.use_babel = params().writeLaTeX(os, features, texrow());
900 os << "\\begin{document}\n";
903 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
905 if (!lyxrc.language_auto_begin) {
906 os << subst(lyxrc.language_command_begin, "$$lang",
907 params().language->babel())
912 // if we are doing a real file with body, even if this is the
913 // child of some other buffer, let's cut the link here.
914 // This happens for example if only a child document is printed.
915 string save_parentname;
916 if (output_preamble) {
917 save_parentname = params().parentname;
918 params().parentname.erase();
922 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
924 // Restore the parenthood if needed
926 params().parentname = save_parentname;
928 // add this just in case after all the paragraphs
932 if (!lyxrc.language_auto_end) {
933 os << subst(lyxrc.language_command_end, "$$lang",
934 params().language->babel())
939 if (output_preamble) {
940 os << "\\end{document}\n";
943 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
945 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
949 // Just to be sure. (Asger)
952 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
953 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
958 bool Buffer::isLatex() const
960 return params().getLyXTextClass().outputType() == LATEX;
964 bool Buffer::isLiterate() const
966 return params().getLyXTextClass().outputType() == LITERATE;
970 bool Buffer::isDocBook() const
972 return params().getLyXTextClass().outputType() == DOCBOOK;
976 void Buffer::makeDocBookFile(string const & fname,
977 OutputParams const & runparams,
978 bool const body_only)
980 lyxerr[Debug::LATEX] << "makeDocBookFile..." << endl;
983 if (!openFileWrite(ofs, fname))
986 writeDocBookSource(ofs, fname, runparams, body_only);
990 lyxerr << "File '" << fname << "' was not closed properly." << endl;
994 void Buffer::writeDocBookSource(ostream & os, string const & fname,
995 OutputParams const & runparams,
996 bool const only_body)
998 LaTeXFeatures features(*this, params(), runparams);
1003 LyXTextClass const & tclass = params().getLyXTextClass();
1004 string const & top_element = tclass.latexname();
1007 if (runparams.flavor == OutputParams::XML)
1008 os << "<?xml version=\"1.0\" encoding=\""
1009 << params().language->encoding()->name() << "\"?>\n";
1011 os << "<!DOCTYPE " << top_element << " ";
1013 if (! tclass.class_header().empty()) os << tclass.class_header();
1014 else if (runparams.flavor == OutputParams::XML)
1015 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1016 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1018 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1020 string preamble = params().preamble;
1021 if (runparams.flavor != OutputParams::XML ) {
1022 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1023 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1024 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1025 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1028 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1030 preamble += features.getIncludedFiles(name);
1031 preamble += features.getLyXSGMLEntities();
1033 if (!preamble.empty()) {
1034 os << "\n [ " << preamble << " ]";
1039 string top = top_element;
1041 if (runparams.flavor == OutputParams::XML)
1042 top += params().language->code();
1044 top += params().language->code().substr(0,2);
1047 if (!params().options.empty()) {
1049 top += params().options;
1052 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1053 << " file was created by LyX " << lyx_version
1054 << "\n See http://www.lyx.org/ for more information -->\n";
1056 params().getLyXTextClass().counters().reset();
1058 sgml::openTag(os, top);
1060 docbookParagraphs(paragraphs(), *this, os, runparams);
1061 sgml::closeTag(os, top_element);
1065 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1066 // Other flags: -wall -v0 -x
1067 int Buffer::runChktex()
1071 // get LaTeX-Filename
1072 string const name = getLatexName();
1073 string const path = temppath();
1074 string const org_path = filePath();
1076 lyx::support::Path p(path); // path to LaTeX file
1077 message(_("Running chktex..."));
1079 // Generate the LaTeX file if neccessary
1080 OutputParams runparams;
1081 runparams.flavor = OutputParams::LATEX;
1082 runparams.nice = false;
1083 makeLaTeXFile(name, org_path, runparams);
1086 Chktex chktex(lyxrc.chktex_command, name, filePath());
1087 int const res = chktex.run(terr); // run chktex
1090 Alert::error(_("chktex failure"),
1091 _("Could not run chktex successfully."));
1092 } else if (res > 0) {
1093 // Fill-in the error list with the TeX errors
1094 bufferErrors(*this, terr, errorLists_["ChkTex"]);
1105 void Buffer::validate(LaTeXFeatures & features) const
1107 LyXTextClass const & tclass = params().getLyXTextClass();
1109 if (features.isAvailable("dvipost") && params().outputChanges)
1110 features.require("dvipost");
1112 // AMS Style is at document level
1113 if (params().use_amsmath == BufferParams::AMS_ON
1114 || tclass.provides(LyXTextClass::amsmath))
1115 features.require("amsmath");
1117 for_each(paragraphs().begin(), paragraphs().end(),
1118 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1120 // the bullet shapes are buffer level not paragraph level
1121 // so they are tested here
1122 for (int i = 0; i < 4; ++i) {
1123 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1124 int const font = params().user_defined_bullet(i).getFont();
1126 int const c = params()
1127 .user_defined_bullet(i)
1134 features.require("latexsym");
1136 } else if (font == 1) {
1137 features.require("amssymb");
1138 } else if ((font >= 2 && font <= 5)) {
1139 features.require("pifont");
1144 if (lyxerr.debugging(Debug::LATEX)) {
1145 features.showStruct();
1150 void Buffer::getLabelList(vector<string> & list) const
1152 /// if this is a child document and the parent is already loaded
1153 /// Use the parent's list instead [ale990407]
1154 Buffer const * tmp = getMasterBuffer();
1156 lyxerr << "getMasterBuffer() failed!" << endl;
1160 tmp->getLabelList(list);
1164 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1165 it.nextInset()->getLabelList(*this, list);
1169 // This is also a buffer property (ale)
1170 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1173 /// if this is a child document and the parent is already loaded
1174 /// use the parent's list instead [ale990412]
1175 Buffer const * tmp = getMasterBuffer();
1178 tmp->fillWithBibKeys(keys);
1182 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1183 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1184 InsetBibtex const & inset =
1185 dynamic_cast<InsetBibtex const &>(*it);
1186 inset.fillWithBibKeys(*this, keys);
1187 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1188 InsetInclude const & inset =
1189 dynamic_cast<InsetInclude const &>(*it);
1190 inset.fillWithBibKeys(*this, keys);
1191 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1192 InsetBibitem const & inset =
1193 dynamic_cast<InsetBibitem const &>(*it);
1194 string const key = inset.getContents();
1195 string const opt = inset.getOptions();
1196 string const ref; // = pit->asString(this, false);
1197 string const info = opt + "TheBibliographyRef" + ref;
1198 keys.push_back(pair<string, string>(key, info));
1204 void Buffer::updateBibfilesCache()
1206 // if this is a child document and the parent is already loaded
1207 // update the parent's cache instead
1208 Buffer * tmp = getMasterBuffer();
1211 tmp->updateBibfilesCache();
1215 bibfilesCache_.clear();
1216 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1217 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1218 InsetBibtex const & inset =
1219 dynamic_cast<InsetBibtex const &>(*it);
1220 vector<string> const bibfiles = inset.getFiles(*this);
1221 bibfilesCache_.insert(bibfilesCache_.end(),
1224 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1225 InsetInclude & inset =
1226 dynamic_cast<InsetInclude &>(*it);
1227 inset.updateBibfilesCache(*this);
1228 vector<string> const & bibfiles =
1229 inset.getBibfilesCache(*this);
1230 bibfilesCache_.insert(bibfilesCache_.end(),
1238 vector<string> const & Buffer::getBibfilesCache() const
1240 // if this is a child document and the parent is already loaded
1241 // use the parent's cache instead
1242 Buffer const * tmp = getMasterBuffer();
1245 return tmp->getBibfilesCache();
1247 return bibfilesCache_;
1251 bool Buffer::isDepClean(string const & name) const
1253 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1254 if (it == pimpl_->dep_clean.end())
1260 void Buffer::markDepClean(string const & name)
1262 pimpl_->dep_clean[name] = true;
1266 bool Buffer::dispatch(string const & command, bool * result)
1268 return dispatch(lyxaction.lookupFunc(command), result);
1272 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1274 bool dispatched = true;
1276 switch (func.action) {
1277 case LFUN_BUFFER_EXPORT: {
1278 bool const tmp = Exporter::Export(this, lyx::to_utf8(func.argument()), false);
1291 void Buffer::changeLanguage(Language const * from, Language const * to)
1296 // Take care of l10n/i18n
1299 for_each(par_iterator_begin(),
1301 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1303 text().current_font.setLanguage(to);
1304 text().real_current_font.setLanguage(to);
1308 void Buffer::updateDocLang(Language const * nlang)
1310 BOOST_ASSERT(nlang);
1312 pimpl_->messages.reset(new Messages(nlang->code()));
1314 updateLabels(*this);
1318 bool Buffer::isMultiLingual() const
1320 ParConstIterator end = par_iterator_end();
1321 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1322 if (it->isMultiLingual(params()))
1329 ParIterator Buffer::getParFromID(int const id) const
1331 ParConstIterator it = par_iterator_begin();
1332 ParConstIterator const end = par_iterator_end();
1335 // John says this is called with id == -1 from undo
1336 lyxerr << "getParFromID(), id: " << id << endl;
1340 for (; it != end; ++it)
1348 bool Buffer::hasParWithID(int const id) const
1350 ParConstIterator const it = getParFromID(id);
1351 return it != par_iterator_end();
1355 ParIterator Buffer::par_iterator_begin()
1357 return ::par_iterator_begin(inset());
1361 ParIterator Buffer::par_iterator_end()
1363 return ::par_iterator_end(inset());
1367 ParConstIterator Buffer::par_iterator_begin() const
1369 return ::par_const_iterator_begin(inset());
1373 ParConstIterator Buffer::par_iterator_end() const
1375 return ::par_const_iterator_end(inset());
1379 Language const * Buffer::getLanguage() const
1381 return params().language;
1385 docstring const Buffer::B_(string const & l10n) const
1387 if (pimpl_->messages.get()) {
1388 return pimpl_->messages->get(l10n);
1395 bool Buffer::isClean() const
1397 return pimpl_->lyx_clean;
1401 bool Buffer::isBakClean() const
1403 return pimpl_->bak_clean;
1407 void Buffer::markClean() const
1409 if (!pimpl_->lyx_clean) {
1410 pimpl_->lyx_clean = true;
1413 // if the .lyx file has been saved, we don't need an
1415 pimpl_->bak_clean = true;
1419 void Buffer::markBakClean()
1421 pimpl_->bak_clean = true;
1425 void Buffer::setUnnamed(bool flag)
1427 pimpl_->unnamed = flag;
1431 bool Buffer::isUnnamed() const
1433 return pimpl_->unnamed;
1437 #ifdef WITH_WARNINGS
1438 #warning this function should be moved to buffer_pimpl.C
1440 void Buffer::markDirty()
1442 if (pimpl_->lyx_clean) {
1443 pimpl_->lyx_clean = false;
1446 pimpl_->bak_clean = false;
1448 DepClean::iterator it = pimpl_->dep_clean.begin();
1449 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1451 for (; it != end; ++it) {
1457 string const & Buffer::fileName() const
1459 return pimpl_->filename;
1463 string const & Buffer::filePath() const
1465 return params().filepath;
1469 bool Buffer::isReadonly() const
1471 return pimpl_->read_only;
1475 void Buffer::setParentName(string const & name)
1477 params().parentname = name;
1481 Buffer const * Buffer::getMasterBuffer() const
1483 if (!params().parentname.empty()
1484 && theBufferList().exists(params().parentname)) {
1485 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1487 return buf->getMasterBuffer();
1494 Buffer * Buffer::getMasterBuffer()
1496 if (!params().parentname.empty()
1497 && theBufferList().exists(params().parentname)) {
1498 Buffer * buf = theBufferList().getBuffer(params().parentname);
1500 return buf->getMasterBuffer();
1507 MacroData const & Buffer::getMacro(std::string const & name) const
1509 return pimpl_->macros.get(name);
1513 bool Buffer::hasMacro(string const & name) const
1515 return pimpl_->macros.has(name);
1519 void Buffer::insertMacro(string const & name, MacroData const & data)
1521 MacroTable::globalMacros().insert(name, data);
1522 pimpl_->macros.insert(name, data);
1526 void Buffer::buildMacros()
1528 // Start with global table.
1529 pimpl_->macros = MacroTable::globalMacros();
1532 ParagraphList const & pars = text().paragraphs();
1533 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1534 //lyxerr << "searching main par " << i
1535 // << " for macro definitions" << std::endl;
1536 InsetList const & insets = pars[i].insetlist;
1537 InsetList::const_iterator it = insets.begin();
1538 InsetList::const_iterator end = insets.end();
1539 for ( ; it != end; ++it) {
1540 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1541 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1542 MathMacroTemplate const & mac
1543 = static_cast<MathMacroTemplate const &>(*it->inset);
1544 insertMacro(mac.name(), mac.asMacroData());
1551 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1558 void Buffer::changeRefsIfUnique(string const & from, string const & to, InsetBase::Code code)
1560 //FIXME: This does not work for child documents yet.
1561 BOOST_ASSERT(code == InsetBase::CITE_CODE || code == InsetBase::REF_CODE);
1562 // Check if the label 'from' appears more than once
1563 vector<string> labels;
1565 if (code == InsetBase::CITE_CODE) {
1566 vector<pair<string, string> > keys;
1567 fillWithBibKeys(keys);
1568 vector<pair<string, string> >::const_iterator bit = keys.begin();
1569 vector<pair<string, string> >::const_iterator bend = keys.end();
1571 for (; bit != bend; ++bit)
1572 labels.push_back(bit->first);
1574 getLabelList(labels);
1576 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1579 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1580 if (it->lyxCode() == code) {
1581 InsetCommand & inset = dynamic_cast<InsetCommand &>(*it);
1582 inset.replaceContents(from, to);
1588 void Buffer::getSourceCode(ostream & os, lyx::pit_type par_begin, lyx::pit_type par_end, bool full_source)
1590 OutputParams runparams;
1591 runparams.nice = true;
1592 runparams.flavor = OutputParams::LATEX;
1593 runparams.linelen = lyxrc.ascii_linelen;
1594 // No side effect of file copying and image conversion
1595 runparams.dryrun = true;
1598 os << "% Preview source code\n\n";
1600 writeLaTeXSource(os, filePath(), runparams, true, true);
1602 writeDocBookSource(os, fileName(), runparams, false);
1604 runparams.par_begin = par_begin;
1605 runparams.par_end = par_end;
1606 if (par_begin + 1 == par_end)
1607 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1609 os << "% Preview source code from paragraph " << par_begin << " to " << par_end - 1 << "\n\n";
1610 // output paragraphs
1613 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1615 docbookParagraphs(paragraphs(), *this, os, runparams);
1620 ErrorList const & Buffer::errorList(string const & type) const
1622 static ErrorList const emptyErrorList;
1623 std::map<std::string, ErrorList>::const_iterator I = errorLists_.find(type);
1624 if (I == errorLists_.end())
1625 return emptyErrorList;
1631 ErrorList & Buffer::errorList(string const & type)
1633 return errorLists_[type];