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"
50 #include "TocBackend.h"
54 #include "insets/insetbibitem.h"
55 #include "insets/insetbibtex.h"
56 #include "insets/insetinclude.h"
57 #include "insets/insettext.h"
59 #include "mathed/MathMacroTemplate.h"
60 #include "mathed/MathMacroTable.h"
61 #include "mathed/MathSupport.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 #include "support/lyxlib.h"
72 #include "support/os.h"
73 #include "support/path.h"
74 #include "support/textutils.h"
75 #include "support/convert.h"
77 #include <boost/iostreams/filtering_stream.hpp>
78 #include <boost/iostreams/filter/gzip.hpp>
79 #include <boost/iostreams/device/file.hpp>
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>
98 using support::addName;
99 using support::bformat;
100 using support::changeExtension;
101 using support::cmd_ret;
102 using support::createBufferTmpDir;
103 using support::destroyDir;
104 using support::FileName;
105 using support::getFormatFromContents;
106 using support::isDirWriteable;
107 using support::libFileSearch;
108 using support::latex_path;
109 using support::ltrim;
110 using support::makeAbsPath;
111 using support::makeDisplayPath;
112 using support::makeLatexName;
113 using support::onlyFilename;
114 using support::onlyPath;
115 using support::quoteName;
116 using support::removeAutosaveFile;
117 using support::rename;
118 using support::runCommand;
119 using support::split;
120 using support::subst;
121 using support::tempName;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
126 namespace fs = boost::filesystem;
127 namespace io = boost::iostreams;
131 using std::make_pair;
136 using std::ostringstream;
146 int const LYX_FORMAT = 255;
151 typedef std::map<string, bool> DepClean;
156 Impl(Buffer & parent, FileName const & file, bool readonly);
158 limited_stack<Undo> undostack;
159 limited_stack<Undo> redostack;
165 /// need to regenerate .tex?
169 mutable bool lyx_clean;
171 /// is autosave needed?
172 mutable bool bak_clean;
174 /// is this a unnamed file (New...)?
180 /// name of the file the buffer is associated with.
183 boost::scoped_ptr<Messages> messages;
185 /** Set to true only when the file is fully loaded.
186 * Used to prevent the premature generation of previews
187 * and by the citation inset.
189 bool file_fully_loaded;
191 /// our LyXText that should be wrapped in an InsetText
198 TocBackend toc_backend;
202 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
203 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
204 filename(file), file_fully_loaded(false), inset(params),
207 inset.setAutoBreakRows(true);
208 lyxvc.buffer(&parent);
209 temppath = createBufferTmpDir();
210 params.filepath = onlyPath(file.absFilename());
211 // FIXME: And now do something if temppath == string(), because we
212 // assume from now on that temppath points to a valid temp dir.
213 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
217 Buffer::Buffer(string const & file, bool readonly)
218 : pimpl_(new Impl(*this, FileName(file), readonly))
220 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
226 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
227 // here the buffer should take care that it is
228 // saved properly, before it goes into the void.
232 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
233 Alert::warning(_("Could not remove temporary directory"),
234 bformat(_("Could not remove the temporary directory %1$s"),
235 from_utf8(temppath())));
238 // Remove any previewed LaTeX snippets associated with this buffer.
239 graphics::Previews::get().removeLoader(*this);
243 LyXText & Buffer::text() const
245 return const_cast<LyXText &>(pimpl_->inset.text_);
249 InsetBase & Buffer::inset() const
251 return const_cast<InsetText &>(pimpl_->inset);
255 limited_stack<Undo> & Buffer::undostack()
257 return pimpl_->undostack;
261 limited_stack<Undo> const & Buffer::undostack() const
263 return pimpl_->undostack;
267 limited_stack<Undo> & Buffer::redostack()
269 return pimpl_->redostack;
273 limited_stack<Undo> const & Buffer::redostack() const
275 return pimpl_->redostack;
279 BufferParams & Buffer::params()
281 return pimpl_->params;
285 BufferParams const & Buffer::params() const
287 return pimpl_->params;
291 ParagraphList & Buffer::paragraphs()
293 return text().paragraphs();
297 ParagraphList const & Buffer::paragraphs() const
299 return text().paragraphs();
303 LyXVC & Buffer::lyxvc()
305 return pimpl_->lyxvc;
309 LyXVC const & Buffer::lyxvc() const
311 return pimpl_->lyxvc;
315 string const & Buffer::temppath() const
317 return pimpl_->temppath;
321 TexRow & Buffer::texrow()
323 return pimpl_->texrow;
327 TexRow const & Buffer::texrow() const
329 return pimpl_->texrow;
333 TocBackend & Buffer::tocBackend()
335 return pimpl_->toc_backend;
339 TocBackend const & Buffer::tocBackend() const
341 return pimpl_->toc_backend;
345 string const Buffer::getLatexName(bool const no_path) const
347 string const name = changeExtension(makeLatexName(fileName()), ".tex");
348 return no_path ? onlyFilename(name) : name;
352 pair<Buffer::LogType, string> const Buffer::getLogName() const
354 string const filename = getLatexName(false);
356 if (filename.empty())
357 return make_pair(Buffer::latexlog, string());
359 string const path = temppath();
361 FileName const fname(addName(temppath(),
362 onlyFilename(changeExtension(filename,
364 FileName const bname(
365 addName(path, onlyFilename(
366 changeExtension(filename,
367 formats.extension("literate") + ".out"))));
369 // If no Latex log or Build log is newer, show Build log
371 if (fs::exists(bname.toFilesystemEncoding()) &&
372 (!fs::exists(fname.toFilesystemEncoding()) ||
373 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
374 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
375 return make_pair(Buffer::buildlog, bname.absFilename());
377 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
378 return make_pair(Buffer::latexlog, fname.absFilename());
382 void Buffer::setReadonly(bool const flag)
384 if (pimpl_->read_only != flag) {
385 pimpl_->read_only = flag;
391 void Buffer::setFileName(string const & newfile)
393 string const filename = makeAbsPath(newfile);
394 pimpl_->filename = FileName(filename);
395 params().filepath = onlyPath(filename);
396 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
401 // We'll remove this later. (Lgb)
404 void unknownClass(string const & unknown)
406 Alert::warning(_("Unknown document class"),
407 bformat(_("Using the default document class, because the "
408 "class %1$s is unknown."), from_utf8(unknown)));
414 int Buffer::readHeader(LyXLex & lex)
416 int unknown_tokens = 0;
418 int begin_header_line = -1;
420 // Initialize parameters that may be/go lacking in header:
421 params().branchlist().clear();
422 params().preamble.erase();
423 params().options.erase();
424 params().float_placement.erase();
425 params().paperwidth.erase();
426 params().paperheight.erase();
427 params().leftmargin.erase();
428 params().rightmargin.erase();
429 params().topmargin.erase();
430 params().bottommargin.erase();
431 params().headheight.erase();
432 params().headsep.erase();
433 params().footskip.erase();
435 ErrorList & errorList = errorLists_["Parse"];
439 string const token = lex.getString();
444 if (token == "\\end_header")
448 if (token == "\\begin_header") {
449 begin_header_line = line;
453 lyxerr[Debug::PARSER] << "Handling document header token: `"
454 << token << '\'' << endl;
456 string unknown = params().readToken(lex, token);
457 if (!unknown.empty()) {
458 if (unknown[0] != '\\' && token == "\\textclass") {
459 unknownClass(unknown);
462 docstring const s = bformat(_("Unknown token: "
466 errorList.push_back(ErrorItem(_("Document header error"),
471 if (begin_header_line) {
472 docstring const s = _("\\begin_header is missing");
473 errorList.push_back(ErrorItem(_("Document header error"),
477 return unknown_tokens;
482 // changed to be public and have one parameter
483 // Returns false if "\end_document" is not read (Asger)
484 bool Buffer::readDocument(LyXLex & lex)
486 ErrorList & errorList = errorLists_["Parse"];
490 string const token = lex.getString();
491 if (token != "\\begin_document") {
492 docstring const s = _("\\begin_document is missing");
493 errorList.push_back(ErrorItem(_("Document header error"),
497 // we are reading in a brand new document
498 BOOST_ASSERT(paragraphs().empty());
501 if (!params().getLyXTextClass().load(filePath())) {
502 string theclass = params().getLyXTextClass().name();
503 Alert::error(_("Can't load document class"), bformat(
504 _("Using the default document class, because the "
505 "class %1$s could not be loaded."), from_utf8(theclass)));
506 params().textclass = 0;
509 bool const res = text().read(*this, lex, errorList);
510 for_each(text().paragraphs().begin(),
511 text().paragraphs().end(),
512 bind(&Paragraph::setInsetOwner, _1, &inset()));
513 updateBibfilesCache();
519 // needed to insert the selection
520 void Buffer::insertStringAsLines(ParagraphList & pars,
521 pit_type & pit, pos_type & pos,
522 LyXFont const & fn, docstring const & str, bool autobreakrows)
526 // insert the string, don't insert doublespace
527 bool space_inserted = true;
528 for (docstring::const_iterator cit = str.begin();
529 cit != str.end(); ++cit) {
530 Paragraph & par = pars[pit];
532 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
533 breakParagraph(params(), pars, pit, pos,
534 par.layout()->isEnvironment());
537 space_inserted = true;
541 // do not insert consecutive spaces if !free_spacing
542 } else if ((*cit == ' ' || *cit == '\t') &&
543 space_inserted && !par.isFreeSpacing()) {
545 } else if (*cit == '\t') {
546 if (!par.isFreeSpacing()) {
547 // tabs are like spaces here
548 par.insertChar(pos, ' ', font, params().trackChanges);
550 space_inserted = true;
552 const pos_type n = 8 - pos % 8;
553 for (pos_type i = 0; i < n; ++i) {
554 par.insertChar(pos, ' ', font, params().trackChanges);
557 space_inserted = true;
559 } else if (!isPrintable(*cit)) {
560 // Ignore unprintables
563 // just insert the character
564 par.insertChar(pos, *cit, font, params().trackChanges);
566 space_inserted = (*cit == ' ');
573 bool Buffer::readFile(string const & filename)
575 // Check if the file is compressed.
576 FileName const name(makeAbsPath(filename));
577 string const format = getFormatFromContents(name);
578 if (format == "gzip" || format == "zip" || format == "compress") {
579 params().compressed = true;
582 // remove dummy empty par
583 paragraphs().clear();
586 if (!readFile(lex, filename))
589 // After we have read a file, we must ensure that the buffer
590 // language is set and used in the gui.
591 // If you know of a better place to put this, please tell me. (Lgb)
592 updateDocLang(params().language);
598 bool Buffer::fully_loaded() const
600 return pimpl_->file_fully_loaded;
604 void Buffer::fully_loaded(bool const value)
606 pimpl_->file_fully_loaded = value;
610 bool Buffer::readFile(LyXLex & lex, string const & filename)
612 BOOST_ASSERT(!filename.empty());
615 Alert::error(_("Document could not be read"),
616 bformat(_("%1$s could not be read."), from_utf8(filename)));
621 string const token(lex.getString());
624 Alert::error(_("Document could not be read"),
625 bformat(_("%1$s could not be read."), from_utf8(filename)));
629 // the first token _must_ be...
630 if (token != "\\lyxformat") {
631 lyxerr << "Token: " << token << endl;
633 Alert::error(_("Document format failure"),
634 bformat(_("%1$s is not a LyX document."),
635 from_utf8(filename)));
640 string tmp_format = lex.getString();
641 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
642 // if present remove ".," from string.
643 string::size_type dot = tmp_format.find_first_of(".,");
644 //lyxerr << " dot found at " << dot << endl;
645 if (dot != string::npos)
646 tmp_format.erase(dot, 1);
647 int const file_format = convert<int>(tmp_format);
648 //lyxerr << "format: " << file_format << endl;
650 if (file_format != LYX_FORMAT) {
651 string const tmpfile = tempName();
652 if (tmpfile.empty()) {
653 Alert::error(_("Conversion failed"),
654 bformat(_("%1$s is from an earlier"
655 " version of LyX, but a temporary"
656 " file for converting it could"
658 from_utf8(filename)));
661 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
662 if (lyx2lyx.empty()) {
663 Alert::error(_("Conversion script not found"),
664 bformat(_("%1$s is from an earlier"
665 " version of LyX, but the"
666 " conversion script lyx2lyx"
667 " could not be found."),
668 from_utf8(filename)));
671 ostringstream command;
672 command << os::python() << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
673 << " -t " << convert<string>(LYX_FORMAT)
674 << " -o " << quoteName(tmpfile) << ' '
675 << quoteName(filename);
676 string const command_str = command.str();
678 lyxerr[Debug::INFO] << "Running '"
679 << command_str << '\''
682 cmd_ret const ret = runCommand(command_str);
683 if (ret.first != 0) {
684 Alert::error(_("Conversion script failed"),
685 bformat(_("%1$s is from an earlier version"
686 " of LyX, but the lyx2lyx script"
687 " failed to convert it."),
688 from_utf8(filename)));
691 bool const ret = readFile(tmpfile);
692 // Do stuff with tmpfile name and buffer name here.
698 if (readDocument(lex)) {
699 Alert::error(_("Document format failure"),
700 bformat(_("%1$s ended unexpectedly, which means"
701 " that it is probably corrupted."),
702 from_utf8(filename)));
705 //lyxerr << "removing " << MacroTable::localMacros().size()
706 // << " temporary macro entries" << endl;
707 //MacroTable::localMacros().clear();
709 pimpl_->file_fully_loaded = true;
714 // Should probably be moved to somewhere else: BufferView? LyXView?
715 bool Buffer::save() const
717 // We don't need autosaves in the immediate future. (Asger)
718 resetAutosaveTimers();
720 // make a backup if the file already exists
722 if (lyxrc.make_backup && fs::exists(pimpl_->filename.toFilesystemEncoding())) {
723 s = fileName() + '~';
724 if (!lyxrc.backupdir_path.empty())
725 s = addName(lyxrc.backupdir_path,
726 subst(os::internal_path(s),'/','!'));
728 // It might very well be that this variant is just
729 // good enough. (Lgb)
730 // But to use this we need fs::copy_file to actually do a copy,
731 // even when the target file exists. (Lgb)
733 fs::copy_file(pimpl_->filename.toFilesystemEncoding(), s, false);
735 catch (fs::filesystem_error const & fe) {
736 Alert::error(_("Backup failure"),
737 bformat(_("LyX was not able to make a backup copy in %1$s.\n"
738 "Please check if the directory exists and is writeable."),
739 from_utf8(fs::path(s).branch_path().native_directory_string())));
740 lyxerr[Debug::DEBUG] << "Fs error: "
741 << fe.what() << endl;
745 if (writeFile(pimpl_->filename)) {
747 removeAutosaveFile(fileName());
749 // Saving failed, so backup is not backup
750 if (lyxrc.make_backup)
751 rename(FileName(s), pimpl_->filename);
758 bool Buffer::writeFile(FileName const & fname) const
760 if (pimpl_->read_only && fname == pimpl_->filename)
765 if (params().compressed) {
766 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
770 retval = do_writeFile(ofs);
772 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
776 retval = do_writeFile(ofs);
783 bool Buffer::do_writeFile(ostream & ofs) const
786 // Use the standard "C" locale for file output.
787 ofs.imbue(std::locale::classic());
790 // The top of the file should not be written by params().
792 // write out a comment in the top of the file
793 ofs << "#LyX " << lyx_version
794 << " created this file. For more info see http://www.lyx.org/\n"
795 << "\\lyxformat " << LYX_FORMAT << "\n"
796 << "\\begin_document\n";
798 // now write out the buffer parameters.
799 ofs << "\\begin_header\n";
800 params().writeFile(ofs);
801 ofs << "\\end_header\n";
804 ofs << "\n\\begin_body\n";
805 text().write(*this, ofs);
806 ofs << "\n\\end_body\n";
808 // Write marker that shows file is complete
809 ofs << "\\end_document" << endl;
811 // Shouldn't really be needed....
814 // how to check if close went ok?
815 // Following is an attempt... (BE 20001011)
817 // good() returns false if any error occured, including some
819 // bad() returns true if something bad happened in the buffer,
820 // which should include file system full errors.
825 lyxerr << "File was not closed properly." << endl;
832 bool Buffer::makeLaTeXFile(FileName const & fname,
833 string const & original_path,
834 OutputParams const & runparams,
835 bool output_preamble, bool output_body)
838 if (params().inputenc == "auto")
839 encoding = params().language->encoding()->iconvName();
841 Encoding const * enc = encodings.getFromLaTeXName(params().inputenc);
843 encoding = enc->iconvName();
845 lyxerr << "Unknown inputenc value `"
847 << "'. Using `auto' instead." << endl;
848 encoding = params().language->encoding()->iconvName();
851 lyxerr[Debug::LATEX] << "makeLaTeXFile encoding: "
852 << encoding << "..." << endl;
854 odocfstream ofs(encoding);
855 if (!openFileWrite(ofs, fname))
859 writeLaTeXSource(ofs, original_path,
860 runparams, output_preamble, output_body);
862 catch (iconv_codecvt_facet_exception &) {
863 Alert::error(_("Encoding error"),
864 _("Some characters of your document are not "
865 "representable in the chosen encoding.\n"
866 "Changing the document encoding to utf8 could help."));
872 lyxerr << "File '" << fname << "' was not closed properly." << endl;
873 Alert::error(_("Error closing file"),
874 _("The output file could not be closed properly.\n"
875 " Probably some characters of your document are not "
876 "representable in the chosen encoding.\n"
877 "Changing the document encoding to utf8 could help."));
884 void Buffer::writeLaTeXSource(odocstream & os,
885 string const & original_path,
886 OutputParams const & runparams_in,
887 bool const output_preamble, bool const output_body)
889 OutputParams runparams = runparams_in;
891 // validate the buffer.
892 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
893 LaTeXFeatures features(*this, params(), runparams);
895 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
899 // The starting paragraph of the coming rows is the
900 // first paragraph of the document. (Asger)
901 texrow().start(paragraphs().begin()->id(), 0);
903 if (output_preamble && runparams.nice) {
904 os << "%% LyX " << lyx_version << " created this file. "
905 "For more info, see http://www.lyx.org/.\n"
906 "%% Do not edit unless you really know what "
911 lyxerr[Debug::INFO] << "lyx document header finished" << endl;
912 // There are a few differences between nice LaTeX and usual files:
913 // usual is \batchmode and has a
914 // special input@path to allow the including of figures
915 // with either \input or \includegraphics (what figinsets do).
916 // input@path is set when the actual parameter
917 // original_path is set. This is done for usual tex-file, but not
918 // for nice-latex-file. (Matthias 250696)
919 // Note that input@path is only needed for something the user does
920 // in the preamble, included .tex files or ERT, files included by
921 // LyX work without it.
922 if (output_preamble) {
923 if (!runparams.nice) {
924 // code for usual, NOT nice-latex-file
925 os << "\\batchmode\n"; // changed
929 if (!original_path.empty()) {
931 // We don't know the encoding of inputpath
932 docstring const inputpath = from_utf8(latex_path(original_path));
933 os << "\\makeatletter\n"
934 << "\\def\\input@path{{"
935 << inputpath << "/}}\n"
936 << "\\makeatother\n";
942 // Write the preamble
943 runparams.use_babel = params().writeLaTeX(os, features, texrow());
949 os << "\\begin{document}\n";
952 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
954 if (!lyxrc.language_auto_begin) {
956 os << from_utf8(subst(lyxrc.language_command_begin,
958 params().language->babel()))
963 // if we are doing a real file with body, even if this is the
964 // child of some other buffer, let's cut the link here.
965 // This happens for example if only a child document is printed.
966 string save_parentname;
967 if (output_preamble) {
968 save_parentname = params().parentname;
969 params().parentname.erase();
973 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
975 // Restore the parenthood if needed
977 params().parentname = save_parentname;
979 // add this just in case after all the paragraphs
983 if (!lyxrc.language_auto_end) {
984 os << from_utf8(subst(lyxrc.language_command_end,
986 params().language->babel()))
991 if (output_preamble) {
992 os << "\\end{document}\n";
995 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
997 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1001 // Just to be sure. (Asger)
1004 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1005 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1010 bool Buffer::isLatex() const
1012 return params().getLyXTextClass().outputType() == LATEX;
1016 bool Buffer::isLiterate() const
1018 return params().getLyXTextClass().outputType() == LITERATE;
1022 bool Buffer::isDocBook() const
1024 return params().getLyXTextClass().outputType() == DOCBOOK;
1028 void Buffer::makeDocBookFile(FileName const & fname,
1029 OutputParams const & runparams,
1030 bool const body_only)
1032 lyxerr[Debug::LATEX] << "makeDocBookFile..." << endl;
1036 if (!openFileWrite(ofs, fname))
1039 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1043 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1047 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1048 OutputParams const & runparams,
1049 bool const only_body)
1051 LaTeXFeatures features(*this, params(), runparams);
1056 LyXTextClass const & tclass = params().getLyXTextClass();
1057 string const top_element = tclass.latexname();
1060 if (runparams.flavor == OutputParams::XML)
1061 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1064 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1067 if (! tclass.class_header().empty())
1068 os << from_ascii(tclass.class_header());
1069 else if (runparams.flavor == OutputParams::XML)
1070 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1071 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1073 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1075 docstring preamble = from_utf8(params().preamble);
1076 if (runparams.flavor != OutputParams::XML ) {
1077 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1078 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1079 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1080 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1083 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1085 preamble += features.getIncludedFiles(name);
1086 preamble += features.getLyXSGMLEntities();
1088 if (!preamble.empty()) {
1089 os << "\n [ " << preamble << " ]";
1094 string top = top_element;
1096 if (runparams.flavor == OutputParams::XML)
1097 top += params().language->code();
1099 top += params().language->code().substr(0,2);
1102 if (!params().options.empty()) {
1104 top += params().options;
1107 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1108 << " file was created by LyX " << lyx_version
1109 << "\n See http://www.lyx.org/ for more information -->\n";
1111 params().getLyXTextClass().counters().reset();
1113 sgml::openTag(os, top);
1115 docbookParagraphs(paragraphs(), *this, os, runparams);
1116 sgml::closeTag(os, top_element);
1120 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1121 // Other flags: -wall -v0 -x
1122 int Buffer::runChktex()
1126 // get LaTeX-Filename
1127 string const name = getLatexName(false);
1128 string const path = temppath();
1129 string const org_path = filePath();
1131 support::Path p(path); // path to LaTeX file
1132 message(_("Running chktex..."));
1134 // Generate the LaTeX file if neccessary
1135 OutputParams runparams;
1136 runparams.flavor = OutputParams::LATEX;
1137 runparams.nice = false;
1138 makeLaTeXFile(FileName(name), org_path, runparams);
1141 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1142 int const res = chktex.run(terr); // run chktex
1145 Alert::error(_("chktex failure"),
1146 _("Could not run chktex successfully."));
1147 } else if (res > 0) {
1148 // Fill-in the error list with the TeX errors
1149 bufferErrors(*this, terr, errorLists_["ChkTex"]);
1160 void Buffer::validate(LaTeXFeatures & features) const
1162 LyXTextClass const & tclass = params().getLyXTextClass();
1164 if (features.isAvailable("dvipost") && params().outputChanges)
1165 features.require("dvipost");
1167 // AMS Style is at document level
1168 if (params().use_amsmath == BufferParams::package_on
1169 || tclass.provides(LyXTextClass::amsmath))
1170 features.require("amsmath");
1171 if (params().use_esint == BufferParams::package_on)
1172 features.require("esint");
1174 for_each(paragraphs().begin(), paragraphs().end(),
1175 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1177 // the bullet shapes are buffer level not paragraph level
1178 // so they are tested here
1179 for (int i = 0; i < 4; ++i) {
1180 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1181 int const font = params().user_defined_bullet(i).getFont();
1183 int const c = params()
1184 .user_defined_bullet(i)
1191 features.require("latexsym");
1193 } else if (font == 1) {
1194 features.require("amssymb");
1195 } else if ((font >= 2 && font <= 5)) {
1196 features.require("pifont");
1201 if (lyxerr.debugging(Debug::LATEX)) {
1202 features.showStruct();
1207 void Buffer::getLabelList(vector<docstring> & list) const
1209 /// if this is a child document and the parent is already loaded
1210 /// Use the parent's list instead [ale990407]
1211 Buffer const * tmp = getMasterBuffer();
1213 lyxerr << "getMasterBuffer() failed!" << endl;
1217 tmp->getLabelList(list);
1221 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1222 it.nextInset()->getLabelList(*this, list);
1226 // This is also a buffer property (ale)
1227 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1230 /// if this is a child document and the parent is already loaded
1231 /// use the parent's list instead [ale990412]
1232 Buffer const * tmp = getMasterBuffer();
1235 tmp->fillWithBibKeys(keys);
1239 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1240 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1241 InsetBibtex const & inset =
1242 dynamic_cast<InsetBibtex const &>(*it);
1243 inset.fillWithBibKeys(*this, keys);
1244 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1245 InsetInclude const & inset =
1246 dynamic_cast<InsetInclude const &>(*it);
1247 inset.fillWithBibKeys(*this, keys);
1248 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1249 InsetBibitem const & inset =
1250 dynamic_cast<InsetBibitem const &>(*it);
1251 string const key = inset.getContents();
1252 string const opt = inset.getOptions();
1253 string const ref; // = pit->asString(this, false);
1254 string const info = opt + "TheBibliographyRef" + ref;
1255 keys.push_back(pair<string, string>(key, info));
1261 void Buffer::updateBibfilesCache()
1263 // if this is a child document and the parent is already loaded
1264 // update the parent's cache instead
1265 Buffer * tmp = getMasterBuffer();
1268 tmp->updateBibfilesCache();
1272 bibfilesCache_.clear();
1273 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1274 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1275 InsetBibtex const & inset =
1276 dynamic_cast<InsetBibtex const &>(*it);
1277 vector<FileName> const bibfiles = inset.getFiles(*this);
1278 bibfilesCache_.insert(bibfilesCache_.end(),
1281 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1282 InsetInclude & inset =
1283 dynamic_cast<InsetInclude &>(*it);
1284 inset.updateBibfilesCache(*this);
1285 vector<FileName> const & bibfiles =
1286 inset.getBibfilesCache(*this);
1287 bibfilesCache_.insert(bibfilesCache_.end(),
1295 vector<FileName> const & Buffer::getBibfilesCache() const
1297 // if this is a child document and the parent is already loaded
1298 // use the parent's cache instead
1299 Buffer const * tmp = getMasterBuffer();
1302 return tmp->getBibfilesCache();
1304 return bibfilesCache_;
1308 bool Buffer::isDepClean(string const & name) const
1310 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1311 if (it == pimpl_->dep_clean.end())
1317 void Buffer::markDepClean(string const & name)
1319 pimpl_->dep_clean[name] = true;
1323 bool Buffer::dispatch(string const & command, bool * result)
1325 return dispatch(lyxaction.lookupFunc(command), result);
1329 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1331 bool dispatched = true;
1333 switch (func.action) {
1334 case LFUN_BUFFER_EXPORT: {
1335 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1348 void Buffer::changeLanguage(Language const * from, Language const * to)
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()));
1371 updateLabels(*this);
1375 bool Buffer::isMultiLingual() const
1377 ParConstIterator end = par_iterator_end();
1378 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1379 if (it->isMultiLingual(params()))
1386 ParIterator Buffer::getParFromID(int const id) const
1388 ParConstIterator it = par_iterator_begin();
1389 ParConstIterator const end = par_iterator_end();
1392 // John says this is called with id == -1 from undo
1393 lyxerr << "getParFromID(), id: " << id << endl;
1397 for (; it != end; ++it)
1405 bool Buffer::hasParWithID(int const id) const
1407 ParConstIterator const it = getParFromID(id);
1408 return it != par_iterator_end();
1412 ParIterator Buffer::par_iterator_begin()
1414 return lyx::par_iterator_begin(inset());
1418 ParIterator Buffer::par_iterator_end()
1420 return lyx::par_iterator_end(inset());
1424 ParConstIterator Buffer::par_iterator_begin() const
1426 return lyx::par_const_iterator_begin(inset());
1430 ParConstIterator Buffer::par_iterator_end() const
1432 return lyx::par_const_iterator_end(inset());
1436 Language const * Buffer::getLanguage() const
1438 return params().language;
1442 docstring const Buffer::B_(string const & l10n) const
1444 if (pimpl_->messages.get())
1445 return pimpl_->messages->get(l10n);
1451 docstring const Buffer::translateLabel(docstring const & label) const
1453 if (support::isAscii(label))
1454 // Probably standard layout, try to translate
1455 return B_(to_ascii(label));
1457 // This must be a user defined layout. We cannot translate
1458 // this, since gettext accepts only ascii keys.
1463 bool Buffer::isClean() const
1465 return pimpl_->lyx_clean;
1469 bool Buffer::isBakClean() const
1471 return pimpl_->bak_clean;
1475 void Buffer::markClean() const
1477 if (!pimpl_->lyx_clean) {
1478 pimpl_->lyx_clean = true;
1481 // if the .lyx file has been saved, we don't need an
1483 pimpl_->bak_clean = true;
1487 void Buffer::markBakClean()
1489 pimpl_->bak_clean = true;
1493 void Buffer::setUnnamed(bool flag)
1495 pimpl_->unnamed = flag;
1499 bool Buffer::isUnnamed() const
1501 return pimpl_->unnamed;
1505 #ifdef WITH_WARNINGS
1506 #warning this function should be moved to buffer_pimpl.C
1508 void Buffer::markDirty()
1510 if (pimpl_->lyx_clean) {
1511 pimpl_->lyx_clean = false;
1514 pimpl_->bak_clean = false;
1516 DepClean::iterator it = pimpl_->dep_clean.begin();
1517 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1519 for (; it != end; ++it)
1524 string const Buffer::fileName() const
1526 return pimpl_->filename.absFilename();
1530 string const & Buffer::filePath() const
1532 return params().filepath;
1536 bool Buffer::isReadonly() const
1538 return pimpl_->read_only;
1542 void Buffer::setParentName(string const & name)
1544 params().parentname = name;
1548 Buffer const * Buffer::getMasterBuffer() const
1550 if (!params().parentname.empty()
1551 && theBufferList().exists(params().parentname)) {
1552 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1554 return buf->getMasterBuffer();
1561 Buffer * Buffer::getMasterBuffer()
1563 if (!params().parentname.empty()
1564 && theBufferList().exists(params().parentname)) {
1565 Buffer * buf = theBufferList().getBuffer(params().parentname);
1567 return buf->getMasterBuffer();
1574 MacroData const & Buffer::getMacro(docstring const & name) const
1576 return pimpl_->macros.get(name);
1580 bool Buffer::hasMacro(docstring const & name) const
1582 return pimpl_->macros.has(name);
1586 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1588 MacroTable::globalMacros().insert(name, data);
1589 pimpl_->macros.insert(name, data);
1593 void Buffer::buildMacros()
1595 // Start with global table.
1596 pimpl_->macros = MacroTable::globalMacros();
1599 ParagraphList const & pars = text().paragraphs();
1600 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1601 //lyxerr << "searching main par " << i
1602 // << " for macro definitions" << std::endl;
1603 InsetList const & insets = pars[i].insetlist;
1604 InsetList::const_iterator it = insets.begin();
1605 InsetList::const_iterator end = insets.end();
1606 for ( ; it != end; ++it) {
1607 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1608 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1609 MathMacroTemplate const & mac
1610 = static_cast<MathMacroTemplate const &>(*it->inset);
1611 insertMacro(mac.name(), mac.asMacroData());
1618 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1625 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1626 InsetBase::Code code)
1628 //FIXME: This does not work for child documents yet.
1629 BOOST_ASSERT(code == InsetBase::CITE_CODE || code == InsetBase::REF_CODE);
1630 // Check if the label 'from' appears more than once
1631 vector<docstring> labels;
1633 if (code == InsetBase::CITE_CODE) {
1634 vector<pair<string, string> > keys;
1635 fillWithBibKeys(keys);
1636 vector<pair<string, string> >::const_iterator bit = keys.begin();
1637 vector<pair<string, string> >::const_iterator bend = keys.end();
1639 for (; bit != bend; ++bit)
1641 labels.push_back(from_utf8(bit->first));
1643 getLabelList(labels);
1645 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1648 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1649 if (it->lyxCode() == code) {
1650 InsetCommand & inset = dynamic_cast<InsetCommand &>(*it);
1651 inset.replaceContents(to_utf8(from), to_utf8(to));
1657 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1658 pit_type par_end, bool full_source)
1660 OutputParams runparams;
1661 runparams.nice = true;
1662 runparams.flavor = OutputParams::LATEX;
1663 runparams.linelen = lyxrc.ascii_linelen;
1664 // No side effect of file copying and image conversion
1665 runparams.dryrun = true;
1667 /* Support for docbook temprarily commented out. */
1669 os << "% Preview source code\n\n";
1671 writeLaTeXSource(os, filePath(), runparams, true, true);
1673 writeDocBookSource(os, fileName(), runparams, false);
1676 runparams.par_begin = par_begin;
1677 runparams.par_end = par_end;
1678 if (par_begin + 1 == par_end)
1679 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1681 os << "% Preview source code from paragraph " << par_begin
1682 << " to " << par_end - 1 << "\n\n";
1683 // output paragraphs
1686 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1689 docbookParagraphs(paragraphs(), *this, os, runparams);
1695 ErrorList const & Buffer::errorList(string const & type) const
1697 static ErrorList const emptyErrorList;
1698 std::map<std::string, ErrorList>::const_iterator I = errorLists_.find(type);
1699 if (I == errorLists_.end())
1700 return emptyErrorList;
1706 ErrorList & Buffer::errorList(string const & type)
1708 return errorLists_[type];