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"
41 #include "output_docbook.h"
42 #include "output_latex.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "TocBackend.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/MacroTable.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 "support/lyxlib.h"
71 #include "support/os.h"
72 #include "support/Path.h"
73 #include "support/textutils.h"
74 #include "support/convert.h"
76 #include <boost/iostreams/filtering_stream.hpp>
77 #include <boost/iostreams/filter/gzip.hpp>
78 #include <boost/iostreams/device/file.hpp>
79 #include <boost/bind.hpp>
80 #include <boost/filesystem/exception.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>
97 using support::addName;
98 using support::bformat;
99 using support::changeExtension;
100 using support::cmd_ret;
101 using support::createBufferTmpDir;
102 using support::destroyDir;
103 using support::FileName;
104 using support::getFormatFromContents;
105 using support::libFileSearch;
106 using support::latex_path;
107 using support::ltrim;
108 using support::makeAbsPath;
109 using support::makeDisplayPath;
110 using support::makeLatexName;
111 using support::onlyFilename;
112 using support::onlyPath;
113 using support::quoteName;
114 using support::removeAutosaveFile;
115 using support::rename;
116 using support::runCommand;
117 using support::split;
118 using support::subst;
119 using support::tempName;
122 namespace Alert = frontend::Alert;
123 namespace os = support::os;
124 namespace fs = boost::filesystem;
125 namespace io = boost::iostreams;
129 using std::make_pair;
134 using std::ostringstream;
144 int const LYX_FORMAT = 266;
149 typedef std::map<string, bool> DepClean;
154 Impl(Buffer & parent, FileName const & file, bool readonly);
156 limited_stack<Undo> undostack;
157 limited_stack<Undo> redostack;
163 /// need to regenerate .tex?
167 mutable bool lyx_clean;
169 /// is autosave needed?
170 mutable bool bak_clean;
172 /// is this a unnamed file (New...)?
178 /// name of the file the buffer is associated with.
181 /** Set to true only when the file is fully loaded.
182 * Used to prevent the premature generation of previews
183 * and by the citation inset.
185 bool file_fully_loaded;
187 /// our Text that should be wrapped in an InsetText
194 TocBackend toc_backend;
198 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
199 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
200 filename(file), file_fully_loaded(false), inset(params),
203 inset.setAutoBreakRows(true);
204 lyxvc.buffer(&parent);
205 temppath = createBufferTmpDir();
206 params.filepath = onlyPath(file.absFilename());
207 // FIXME: And now do something if temppath == string(), because we
208 // assume from now on that temppath points to a valid temp dir.
209 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
213 Buffer::Buffer(string const & file, bool readonly)
214 : pimpl_(new Impl(*this, FileName(file), readonly))
216 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
222 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
223 // here the buffer should take care that it is
224 // saved properly, before it goes into the void.
228 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
229 Alert::warning(_("Could not remove temporary directory"),
230 bformat(_("Could not remove the temporary directory %1$s"),
231 from_utf8(temppath())));
234 // Remove any previewed LaTeX snippets associated with this buffer.
235 graphics::Previews::get().removeLoader(*this);
239 Text & Buffer::text() const
241 return const_cast<Text &>(pimpl_->inset.text_);
245 Inset & Buffer::inset() const
247 return const_cast<InsetText &>(pimpl_->inset);
251 limited_stack<Undo> & Buffer::undostack()
253 return pimpl_->undostack;
257 limited_stack<Undo> const & Buffer::undostack() const
259 return pimpl_->undostack;
263 limited_stack<Undo> & Buffer::redostack()
265 return pimpl_->redostack;
269 limited_stack<Undo> const & Buffer::redostack() const
271 return pimpl_->redostack;
275 BufferParams & Buffer::params()
277 return pimpl_->params;
281 BufferParams const & Buffer::params() const
283 return pimpl_->params;
287 ParagraphList & Buffer::paragraphs()
289 return text().paragraphs();
293 ParagraphList const & Buffer::paragraphs() const
295 return text().paragraphs();
299 LyXVC & Buffer::lyxvc()
301 return pimpl_->lyxvc;
305 LyXVC const & Buffer::lyxvc() const
307 return pimpl_->lyxvc;
311 string const & Buffer::temppath() const
313 return pimpl_->temppath;
317 TexRow & Buffer::texrow()
319 return pimpl_->texrow;
323 TexRow const & Buffer::texrow() const
325 return pimpl_->texrow;
329 TocBackend & Buffer::tocBackend()
331 return pimpl_->toc_backend;
335 TocBackend const & Buffer::tocBackend() const
337 return pimpl_->toc_backend;
341 string const Buffer::getLatexName(bool const no_path) const
343 string const name = changeExtension(makeLatexName(fileName()), ".tex");
344 return no_path ? onlyFilename(name) : name;
348 pair<Buffer::LogType, string> const Buffer::getLogName() const
350 string const filename = getLatexName(false);
352 if (filename.empty())
353 return make_pair(Buffer::latexlog, string());
355 string const path = temppath();
357 FileName const fname(addName(temppath(),
358 onlyFilename(changeExtension(filename,
360 FileName const bname(
361 addName(path, onlyFilename(
362 changeExtension(filename,
363 formats.extension("literate") + ".out"))));
365 // If no Latex log or Build log is newer, show Build log
367 if (fs::exists(bname.toFilesystemEncoding()) &&
368 (!fs::exists(fname.toFilesystemEncoding()) ||
369 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
370 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
371 return make_pair(Buffer::buildlog, bname.absFilename());
373 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
374 return make_pair(Buffer::latexlog, fname.absFilename());
378 void Buffer::setReadonly(bool const flag)
380 if (pimpl_->read_only != flag) {
381 pimpl_->read_only = flag;
387 void Buffer::setFileName(string const & newfile)
389 pimpl_->filename = makeAbsPath(newfile);
390 params().filepath = onlyPath(pimpl_->filename.absFilename());
391 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
396 // We'll remove this later. (Lgb)
399 void unknownClass(string const & unknown)
401 Alert::warning(_("Unknown document class"),
402 bformat(_("Using the default document class, because the "
403 "class %1$s is unknown."), from_utf8(unknown)));
409 int Buffer::readHeader(Lexer & lex)
411 int unknown_tokens = 0;
413 int begin_header_line = -1;
415 // Initialize parameters that may be/go lacking in header:
416 params().branchlist().clear();
417 params().preamble.erase();
418 params().options.erase();
419 params().float_placement.erase();
420 params().paperwidth.erase();
421 params().paperheight.erase();
422 params().leftmargin.erase();
423 params().rightmargin.erase();
424 params().topmargin.erase();
425 params().bottommargin.erase();
426 params().headheight.erase();
427 params().headsep.erase();
428 params().footskip.erase();
429 for (int i = 0; i < 4; ++i) {
430 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
431 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
434 ErrorList & errorList = errorLists_["Parse"];
438 string const token = lex.getString();
443 if (token == "\\end_header")
447 if (token == "\\begin_header") {
448 begin_header_line = line;
452 LYXERR(Debug::PARSER) << "Handling document header token: `"
453 << token << '\'' << endl;
455 string unknown = params().readToken(lex, token);
456 if (!unknown.empty()) {
457 if (unknown[0] != '\\' && token == "\\textclass") {
458 unknownClass(unknown);
461 docstring const s = bformat(_("Unknown token: "
465 errorList.push_back(ErrorItem(_("Document header error"),
470 if (begin_header_line) {
471 docstring const s = _("\\begin_header is missing");
472 errorList.push_back(ErrorItem(_("Document header error"),
476 return unknown_tokens;
481 // changed to be public and have one parameter
482 // Returns false if "\end_document" is not read (Asger)
483 bool Buffer::readDocument(Lexer & lex)
485 ErrorList & errorList = errorLists_["Parse"];
489 string const token = lex.getString();
490 if (token != "\\begin_document") {
491 docstring const s = _("\\begin_document is missing");
492 errorList.push_back(ErrorItem(_("Document header error"),
496 // we are reading in a brand new document
497 BOOST_ASSERT(paragraphs().empty());
500 if (!params().getTextClass().load(filePath())) {
501 string theclass = params().getTextClass().name();
502 Alert::error(_("Can't load document class"), bformat(
503 _("Using the default document class, because the "
504 "class %1$s could not be loaded."), from_utf8(theclass)));
505 params().textclass = 0;
508 bool const res = text().read(*this, lex, errorList);
509 for_each(text().paragraphs().begin(),
510 text().paragraphs().end(),
511 bind(&Paragraph::setInsetOwner, _1, &inset()));
517 // needed to insert the selection
518 void Buffer::insertStringAsLines(ParagraphList & pars,
519 pit_type & pit, pos_type & pos,
520 Font const & fn, docstring const & str, bool autobreakrows)
524 // insert the string, don't insert doublespace
525 bool space_inserted = true;
526 for (docstring::const_iterator cit = str.begin();
527 cit != str.end(); ++cit) {
528 Paragraph & par = pars[pit];
530 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
531 breakParagraph(params(), pars, pit, pos,
532 par.layout()->isEnvironment());
535 space_inserted = true;
539 // do not insert consecutive spaces if !free_spacing
540 } else if ((*cit == ' ' || *cit == '\t') &&
541 space_inserted && !par.isFreeSpacing()) {
543 } else if (*cit == '\t') {
544 if (!par.isFreeSpacing()) {
545 // tabs are like spaces here
546 par.insertChar(pos, ' ', font, params().trackChanges);
548 space_inserted = true;
550 const pos_type n = 8 - pos % 8;
551 for (pos_type i = 0; i < n; ++i) {
552 par.insertChar(pos, ' ', font, params().trackChanges);
555 space_inserted = true;
557 } else if (!isPrintable(*cit)) {
558 // Ignore unprintables
561 // just insert the character
562 par.insertChar(pos, *cit, font, params().trackChanges);
564 space_inserted = (*cit == ' ');
571 bool Buffer::readString(std::string const & s)
573 params().compressed = false;
575 // remove dummy empty par
576 paragraphs().clear();
578 std::istringstream is(s);
580 FileName const name(tempName());
581 switch (readFile(lex, name, true)) {
585 // We need to call lyx2lyx, so write the input to a file
586 std::ofstream os(name.toFilesystemEncoding().c_str());
589 return readFile(name);
599 bool Buffer::readFile(FileName const & filename)
601 // Check if the file is compressed.
602 string const format = getFormatFromContents(filename);
603 if (format == "gzip" || format == "zip" || format == "compress") {
604 params().compressed = true;
607 // remove dummy empty par
608 paragraphs().clear();
610 lex.setFile(filename);
611 if (readFile(lex, filename) != success)
618 bool Buffer::fully_loaded() const
620 return pimpl_->file_fully_loaded;
624 void Buffer::fully_loaded(bool const value)
626 pimpl_->file_fully_loaded = value;
630 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
633 BOOST_ASSERT(!filename.empty());
636 Alert::error(_("Document could not be read"),
637 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
642 string const token(lex.getString());
645 Alert::error(_("Document could not be read"),
646 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
650 // the first token _must_ be...
651 if (token != "\\lyxformat") {
652 lyxerr << "Token: " << token << endl;
654 Alert::error(_("Document format failure"),
655 bformat(_("%1$s is not a LyX document."),
656 from_utf8(filename.absFilename())));
661 string tmp_format = lex.getString();
662 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
663 // if present remove ".," from string.
664 string::size_type dot = tmp_format.find_first_of(".,");
665 //lyxerr << " dot found at " << dot << endl;
666 if (dot != string::npos)
667 tmp_format.erase(dot, 1);
668 int const file_format = convert<int>(tmp_format);
669 //lyxerr << "format: " << file_format << endl;
671 if (file_format != LYX_FORMAT) {
674 // lyx2lyx would fail
677 FileName const tmpfile(tempName());
678 if (tmpfile.empty()) {
679 Alert::error(_("Conversion failed"),
680 bformat(_("%1$s is from a different"
681 " version of LyX, but a temporary"
682 " file for converting it could"
684 from_utf8(filename.absFilename())));
687 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
688 if (lyx2lyx.empty()) {
689 Alert::error(_("Conversion script not found"),
690 bformat(_("%1$s is from a different"
691 " version of LyX, but the"
692 " conversion script lyx2lyx"
693 " could not be found."),
694 from_utf8(filename.absFilename())));
697 ostringstream command;
698 command << os::python()
699 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
700 << " -t " << convert<string>(LYX_FORMAT)
701 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
702 << ' ' << quoteName(filename.toFilesystemEncoding());
703 string const command_str = command.str();
705 LYXERR(Debug::INFO) << "Running '"
706 << command_str << '\''
709 cmd_ret const ret = runCommand(command_str);
710 if (ret.first != 0) {
711 Alert::error(_("Conversion script failed"),
712 bformat(_("%1$s is from a different version"
713 " of LyX, but the lyx2lyx script"
714 " failed to convert it."),
715 from_utf8(filename.absFilename())));
718 bool const ret = readFile(tmpfile);
719 // Do stuff with tmpfile name and buffer name here.
720 return ret ? success : failure;
725 if (readDocument(lex)) {
726 Alert::error(_("Document format failure"),
727 bformat(_("%1$s ended unexpectedly, which means"
728 " that it is probably corrupted."),
729 from_utf8(filename.absFilename())));
732 //lyxerr << "removing " << MacroTable::localMacros().size()
733 // << " temporary macro entries" << endl;
734 //MacroTable::localMacros().clear();
736 pimpl_->file_fully_loaded = true;
741 // Should probably be moved to somewhere else: BufferView? LyXView?
742 bool Buffer::save() const
744 // We don't need autosaves in the immediate future. (Asger)
745 resetAutosaveTimers();
747 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
750 bool madeBackup = false;
752 // make a backup if the file already exists
753 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
754 backupName = FileName(fileName() + '~');
755 if (!lyxrc.backupdir_path.empty())
756 backupName = FileName(addName(lyxrc.backupdir_path,
757 subst(os::internal_path(backupName.absFilename()), '/', '!')));
760 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
762 } catch (fs::filesystem_error const & fe) {
763 Alert::error(_("Backup failure"),
764 bformat(_("Cannot create backup file %1$s.\n"
765 "Please check whether the directory exists and is writeable."),
766 from_utf8(backupName.absFilename())));
767 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
771 if (writeFile(pimpl_->filename)) {
773 removeAutosaveFile(fileName());
776 // Saving failed, so backup is not backup
778 rename(backupName, pimpl_->filename);
784 bool Buffer::writeFile(FileName const & fname) const
786 if (pimpl_->read_only && fname == pimpl_->filename)
791 if (params().compressed) {
792 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
798 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
809 bool Buffer::write(ostream & ofs) const
812 // Use the standard "C" locale for file output.
813 ofs.imbue(std::locale::classic());
816 // The top of the file should not be written by params().
818 // write out a comment in the top of the file
819 ofs << "#LyX " << lyx_version
820 << " created this file. For more info see http://www.lyx.org/\n"
821 << "\\lyxformat " << LYX_FORMAT << "\n"
822 << "\\begin_document\n";
824 // now write out the buffer parameters.
825 ofs << "\\begin_header\n";
826 params().writeFile(ofs);
827 ofs << "\\end_header\n";
830 ofs << "\n\\begin_body\n";
831 text().write(*this, ofs);
832 ofs << "\n\\end_body\n";
834 // Write marker that shows file is complete
835 ofs << "\\end_document" << endl;
837 // Shouldn't really be needed....
840 // how to check if close went ok?
841 // Following is an attempt... (BE 20001011)
843 // good() returns false if any error occured, including some
845 // bad() returns true if something bad happened in the buffer,
846 // which should include file system full errors.
851 lyxerr << "File was not closed properly." << endl;
858 bool Buffer::makeLaTeXFile(FileName const & fname,
859 string const & original_path,
860 OutputParams const & runparams,
861 bool output_preamble, bool output_body)
863 string const encoding = runparams.encoding->iconvName();
864 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
865 << encoding << "..." << endl;
867 odocfstream ofs(encoding);
868 if (!openFileWrite(ofs, fname))
872 writeLaTeXSource(ofs, original_path,
873 runparams, output_preamble, output_body);
875 catch (iconv_codecvt_facet_exception &) {
876 Alert::error(_("Encoding error"),
877 _("Some characters of your document are not "
878 "representable in the chosen encoding.\n"
879 "Changing the document encoding to utf8 could help."));
885 lyxerr << "File '" << fname << "' was not closed properly." << endl;
886 Alert::error(_("Error closing file"),
887 _("The output file could not be closed properly.\n"
888 " Probably some characters of your document are not "
889 "representable in the chosen encoding.\n"
890 "Changing the document encoding to utf8 could help."));
897 void Buffer::writeLaTeXSource(odocstream & os,
898 string const & original_path,
899 OutputParams const & runparams_in,
900 bool const output_preamble, bool const output_body)
902 OutputParams runparams = runparams_in;
904 // validate the buffer.
905 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
906 LaTeXFeatures features(*this, params(), runparams);
908 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
912 // The starting paragraph of the coming rows is the
913 // first paragraph of the document. (Asger)
914 texrow().start(paragraphs().begin()->id(), 0);
916 if (output_preamble && runparams.nice) {
917 os << "%% LyX " << lyx_version << " created this file. "
918 "For more info, see http://www.lyx.org/.\n"
919 "%% Do not edit unless you really know what "
924 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
925 // There are a few differences between nice LaTeX and usual files:
926 // usual is \batchmode and has a
927 // special input@path to allow the including of figures
928 // with either \input or \includegraphics (what figinsets do).
929 // input@path is set when the actual parameter
930 // original_path is set. This is done for usual tex-file, but not
931 // for nice-latex-file. (Matthias 250696)
932 // Note that input@path is only needed for something the user does
933 // in the preamble, included .tex files or ERT, files included by
934 // LyX work without it.
935 if (output_preamble) {
936 if (!runparams.nice) {
937 // code for usual, NOT nice-latex-file
938 os << "\\batchmode\n"; // changed
942 if (!original_path.empty()) {
944 // We don't know the encoding of inputpath
945 docstring const inputpath = from_utf8(latex_path(original_path));
946 os << "\\makeatletter\n"
947 << "\\def\\input@path{{"
948 << inputpath << "/}}\n"
949 << "\\makeatother\n";
955 // Write the preamble
956 runparams.use_babel = params().writeLaTeX(os, features, texrow());
962 os << "\\begin{document}\n";
965 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
967 if (!lyxrc.language_auto_begin) {
969 os << from_utf8(subst(lyxrc.language_command_begin,
971 params().language->babel()))
976 // if we are doing a real file with body, even if this is the
977 // child of some other buffer, let's cut the link here.
978 // This happens for example if only a child document is printed.
979 string save_parentname;
980 if (output_preamble) {
981 save_parentname = params().parentname;
982 params().parentname.erase();
986 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
988 // Restore the parenthood if needed
990 params().parentname = save_parentname;
992 // add this just in case after all the paragraphs
996 if (!lyxrc.language_auto_end) {
997 os << from_utf8(subst(lyxrc.language_command_end,
999 params().language->babel()))
1004 if (output_preamble) {
1005 os << "\\end{document}\n";
1008 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1010 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1013 runparams_in.encoding = runparams.encoding;
1015 // Just to be sure. (Asger)
1018 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1019 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1024 bool Buffer::isLatex() const
1026 return params().getTextClass().outputType() == LATEX;
1030 bool Buffer::isLiterate() const
1032 return params().getTextClass().outputType() == LITERATE;
1036 bool Buffer::isDocBook() const
1038 return params().getTextClass().outputType() == DOCBOOK;
1042 void Buffer::makeDocBookFile(FileName const & fname,
1043 OutputParams const & runparams,
1044 bool const body_only)
1046 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1050 if (!openFileWrite(ofs, fname))
1053 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1057 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1061 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1062 OutputParams const & runparams,
1063 bool const only_body)
1065 LaTeXFeatures features(*this, params(), runparams);
1070 TextClass const & tclass = params().getTextClass();
1071 string const top_element = tclass.latexname();
1074 if (runparams.flavor == OutputParams::XML)
1075 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1078 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1081 if (! tclass.class_header().empty())
1082 os << from_ascii(tclass.class_header());
1083 else if (runparams.flavor == OutputParams::XML)
1084 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1085 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1087 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1089 docstring preamble = from_utf8(params().preamble);
1090 if (runparams.flavor != OutputParams::XML ) {
1091 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1092 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1093 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1094 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1097 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1099 preamble += features.getIncludedFiles(name);
1100 preamble += features.getLyXSGMLEntities();
1102 if (!preamble.empty()) {
1103 os << "\n [ " << preamble << " ]";
1108 string top = top_element;
1110 if (runparams.flavor == OutputParams::XML)
1111 top += params().language->code();
1113 top += params().language->code().substr(0,2);
1116 if (!params().options.empty()) {
1118 top += params().options;
1121 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1122 << " file was created by LyX " << lyx_version
1123 << "\n See http://www.lyx.org/ for more information -->\n";
1125 params().getTextClass().counters().reset();
1127 sgml::openTag(os, top);
1129 docbookParagraphs(paragraphs(), *this, os, runparams);
1130 sgml::closeTag(os, top_element);
1134 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1135 // Other flags: -wall -v0 -x
1136 int Buffer::runChktex()
1140 // get LaTeX-Filename
1141 FileName const path(temppath());
1142 string const name = addName(path.absFilename(), getLatexName());
1143 string const org_path = filePath();
1145 support::Path p(path); // path to LaTeX file
1146 message(_("Running chktex..."));
1148 // Generate the LaTeX file if neccessary
1149 OutputParams runparams(¶ms().encoding());
1150 runparams.flavor = OutputParams::LATEX;
1151 runparams.nice = false;
1152 makeLaTeXFile(FileName(name), org_path, runparams);
1155 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1156 int const res = chktex.run(terr); // run chktex
1159 Alert::error(_("chktex failure"),
1160 _("Could not run chktex successfully."));
1161 } else if (res > 0) {
1162 ErrorList & errorList = errorLists_["ChkTeX"];
1163 // Clear out old errors
1165 // Fill-in the error list with the TeX errors
1166 bufferErrors(*this, terr, errorList);
1177 void Buffer::validate(LaTeXFeatures & features) const
1179 TextClass const & tclass = params().getTextClass();
1181 if (features.isAvailable("dvipost") && params().outputChanges)
1182 features.require("dvipost");
1184 // AMS Style is at document level
1185 if (params().use_amsmath == BufferParams::package_on
1186 || tclass.provides("amsmath"))
1187 features.require("amsmath");
1188 if (params().use_esint == BufferParams::package_on)
1189 features.require("esint");
1191 for_each(paragraphs().begin(), paragraphs().end(),
1192 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1194 // the bullet shapes are buffer level not paragraph level
1195 // so they are tested here
1196 for (int i = 0; i < 4; ++i) {
1197 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1198 int const font = params().user_defined_bullet(i).getFont();
1200 int const c = params()
1201 .user_defined_bullet(i)
1208 features.require("latexsym");
1210 } else if (font == 1) {
1211 features.require("amssymb");
1212 } else if ((font >= 2 && font <= 5)) {
1213 features.require("pifont");
1218 if (lyxerr.debugging(Debug::LATEX)) {
1219 features.showStruct();
1224 void Buffer::getLabelList(vector<docstring> & list) const
1226 /// if this is a child document and the parent is already loaded
1227 /// Use the parent's list instead [ale990407]
1228 Buffer const * tmp = getMasterBuffer();
1230 lyxerr << "getMasterBuffer() failed!" << endl;
1234 tmp->getLabelList(list);
1238 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1239 it.nextInset()->getLabelList(*this, list);
1243 // This is also a buffer property (ale)
1244 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1247 /// if this is a child document and the parent is already loaded
1248 /// use the parent's list instead [ale990412]
1249 Buffer const * tmp = getMasterBuffer();
1252 tmp->fillWithBibKeys(keys);
1256 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1257 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1258 InsetBibtex const & inset =
1259 static_cast<InsetBibtex const &>(*it);
1260 inset.fillWithBibKeys(*this, keys);
1261 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1262 InsetInclude const & inset =
1263 static_cast<InsetInclude const &>(*it);
1264 inset.fillWithBibKeys(*this, keys);
1265 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1266 InsetBibitem const & inset =
1267 static_cast<InsetBibitem const &>(*it);
1269 string const key = to_utf8(inset.getParam("key"));
1270 docstring const label = inset.getParam("label");
1271 DocIterator doc_it(it); doc_it.forwardPos();
1272 docstring const ref = doc_it.paragraph().asString(*this, false);
1273 docstring const info = label + "TheBibliographyRef" + ref;
1274 keys.push_back(pair<string, docstring>(key, info));
1280 void Buffer::updateBibfilesCache()
1282 // if this is a child document and the parent is already loaded
1283 // update the parent's cache instead
1284 Buffer * tmp = getMasterBuffer();
1287 tmp->updateBibfilesCache();
1291 bibfilesCache_.clear();
1292 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1293 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1294 InsetBibtex const & inset =
1295 static_cast<InsetBibtex const &>(*it);
1296 vector<FileName> const bibfiles = inset.getFiles(*this);
1297 bibfilesCache_.insert(bibfilesCache_.end(),
1300 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1301 InsetInclude & inset =
1302 static_cast<InsetInclude &>(*it);
1303 inset.updateBibfilesCache(*this);
1304 vector<FileName> const & bibfiles =
1305 inset.getBibfilesCache(*this);
1306 bibfilesCache_.insert(bibfilesCache_.end(),
1314 vector<FileName> const & Buffer::getBibfilesCache() const
1316 // if this is a child document and the parent is already loaded
1317 // use the parent's cache instead
1318 Buffer const * tmp = getMasterBuffer();
1321 return tmp->getBibfilesCache();
1323 // We update the cache when first used instead of at loading time.
1324 if (bibfilesCache_.empty())
1325 const_cast<Buffer *>(this)->updateBibfilesCache();
1327 return bibfilesCache_;
1331 bool Buffer::isDepClean(string const & name) const
1333 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1334 if (it == pimpl_->dep_clean.end())
1340 void Buffer::markDepClean(string const & name)
1342 pimpl_->dep_clean[name] = true;
1346 bool Buffer::dispatch(string const & command, bool * result)
1348 return dispatch(lyxaction.lookupFunc(command), result);
1352 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1354 bool dispatched = true;
1356 switch (func.action) {
1357 case LFUN_BUFFER_EXPORT: {
1358 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1371 void Buffer::changeLanguage(Language const * from, Language const * to)
1376 for_each(par_iterator_begin(),
1378 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1380 text().current_font.setLanguage(to);
1381 text().real_current_font.setLanguage(to);
1385 bool Buffer::isMultiLingual() const
1387 ParConstIterator end = par_iterator_end();
1388 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1389 if (it->isMultiLingual(params()))
1396 ParIterator Buffer::getParFromID(int const id) const
1398 ParConstIterator it = par_iterator_begin();
1399 ParConstIterator const end = par_iterator_end();
1402 // John says this is called with id == -1 from undo
1403 lyxerr << "getParFromID(), id: " << id << endl;
1407 for (; it != end; ++it)
1415 bool Buffer::hasParWithID(int const id) const
1417 ParConstIterator const it = getParFromID(id);
1418 return it != par_iterator_end();
1422 ParIterator Buffer::par_iterator_begin()
1424 return lyx::par_iterator_begin(inset());
1428 ParIterator Buffer::par_iterator_end()
1430 return lyx::par_iterator_end(inset());
1434 ParConstIterator Buffer::par_iterator_begin() const
1436 return lyx::par_const_iterator_begin(inset());
1440 ParConstIterator Buffer::par_iterator_end() const
1442 return lyx::par_const_iterator_end(inset());
1446 Language const * Buffer::getLanguage() const
1448 return params().language;
1452 docstring const Buffer::B_(string const & l10n) const
1454 return params().B_(l10n);
1458 bool Buffer::isClean() const
1460 return pimpl_->lyx_clean;
1464 bool Buffer::isBakClean() const
1466 return pimpl_->bak_clean;
1470 void Buffer::markClean() const
1472 if (!pimpl_->lyx_clean) {
1473 pimpl_->lyx_clean = true;
1476 // if the .lyx file has been saved, we don't need an
1478 pimpl_->bak_clean = true;
1482 void Buffer::markBakClean()
1484 pimpl_->bak_clean = true;
1488 void Buffer::setUnnamed(bool flag)
1490 pimpl_->unnamed = flag;
1494 bool Buffer::isUnnamed() const
1496 return pimpl_->unnamed;
1500 #ifdef WITH_WARNINGS
1501 #warning this function should be moved to buffer_pimpl.C
1503 void Buffer::markDirty()
1505 if (pimpl_->lyx_clean) {
1506 pimpl_->lyx_clean = false;
1509 pimpl_->bak_clean = false;
1511 DepClean::iterator it = pimpl_->dep_clean.begin();
1512 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1514 for (; it != end; ++it)
1519 string const Buffer::fileName() const
1521 return pimpl_->filename.absFilename();
1525 string const & Buffer::filePath() const
1527 return params().filepath;
1531 bool Buffer::isReadonly() const
1533 return pimpl_->read_only;
1537 void Buffer::setParentName(string const & name)
1539 params().parentname = name;
1543 Buffer const * Buffer::getMasterBuffer() const
1545 if (!params().parentname.empty()
1546 && theBufferList().exists(params().parentname)) {
1547 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1549 return buf->getMasterBuffer();
1556 Buffer * Buffer::getMasterBuffer()
1558 if (!params().parentname.empty()
1559 && theBufferList().exists(params().parentname)) {
1560 Buffer * buf = theBufferList().getBuffer(params().parentname);
1562 return buf->getMasterBuffer();
1569 MacroData const & Buffer::getMacro(docstring const & name) const
1571 return pimpl_->macros.get(name);
1575 bool Buffer::hasMacro(docstring const & name) const
1577 return pimpl_->macros.has(name);
1581 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1583 MacroTable::globalMacros().insert(name, data);
1584 pimpl_->macros.insert(name, data);
1588 void Buffer::buildMacros()
1590 // Start with global table.
1591 pimpl_->macros = MacroTable::globalMacros();
1594 ParagraphList const & pars = text().paragraphs();
1595 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1596 //lyxerr << "searching main par " << i
1597 // << " for macro definitions" << std::endl;
1598 InsetList const & insets = pars[i].insetlist;
1599 InsetList::const_iterator it = insets.begin();
1600 InsetList::const_iterator end = insets.end();
1601 for ( ; it != end; ++it) {
1602 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1603 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1604 MathMacroTemplate const & mac
1605 = static_cast<MathMacroTemplate const &>(*it->inset);
1606 insertMacro(mac.name(), mac.asMacroData());
1613 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1620 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1623 //FIXME: This does not work for child documents yet.
1624 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1625 // Check if the label 'from' appears more than once
1626 vector<docstring> labels;
1628 if (code == Inset::CITE_CODE) {
1629 vector<pair<string, docstring> > keys;
1630 fillWithBibKeys(keys);
1631 vector<pair<string, docstring> >::const_iterator bit = keys.begin();
1632 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1634 for (; bit != bend; ++bit)
1636 labels.push_back(from_utf8(bit->first));
1638 getLabelList(labels);
1640 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1643 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1644 if (it->lyxCode() == code) {
1645 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1646 inset.replaceContents(to_utf8(from), to_utf8(to));
1652 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1653 pit_type par_end, bool full_source)
1655 OutputParams runparams(¶ms().encoding());
1656 runparams.nice = true;
1657 runparams.flavor = OutputParams::LATEX;
1658 runparams.linelen = lyxrc.plaintext_linelen;
1659 // No side effect of file copying and image conversion
1660 runparams.dryrun = true;
1663 os << "% Preview source code\n\n";
1665 writeLaTeXSource(os, filePath(), runparams, true, true);
1667 writeDocBookSource(os, fileName(), runparams, false);
1670 runparams.par_begin = par_begin;
1671 runparams.par_end = par_end;
1672 if (par_begin + 1 == par_end)
1673 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1675 os << "% Preview source code from paragraph " << par_begin
1676 << " to " << par_end - 1 << "\n\n";
1677 // output paragraphs
1680 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1683 docbookParagraphs(paragraphs(), *this, os, runparams);
1689 ErrorList const & Buffer::errorList(string const & type) const
1691 static ErrorList const emptyErrorList;
1692 std::map<string, ErrorList>::const_iterator I = errorLists_.find(type);
1693 if (I == errorLists_.end())
1694 return emptyErrorList;
1700 ErrorList & Buffer::errorList(string const & type)
1702 return errorLists_[type];