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/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 "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 = 256;
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.
183 /** Set to true only when the file is fully loaded.
184 * Used to prevent the premature generation of previews
185 * and by the citation inset.
187 bool file_fully_loaded;
189 /// our LyXText that should be wrapped in an InsetText
196 TocBackend toc_backend;
200 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
201 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
202 filename(file), file_fully_loaded(false), inset(params),
203 toc_backend(&parent), messages(0)
205 inset.setAutoBreakRows(true);
206 lyxvc.buffer(&parent);
207 temppath = createBufferTmpDir();
208 params.filepath = onlyPath(file.absFilename());
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, FileName(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(FileName(temppath()))) {
231 Alert::warning(_("Could not remove temporary directory"),
232 bformat(_("Could not remove the temporary directory %1$s"),
233 from_utf8(temppath())));
236 // Remove any previewed LaTeX snippets associated with this buffer.
237 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 TocBackend & Buffer::tocBackend()
333 return pimpl_->toc_backend;
337 TocBackend const & Buffer::tocBackend() const
339 return pimpl_->toc_backend;
343 string const Buffer::getLatexName(bool const no_path) const
345 string const name = changeExtension(makeLatexName(fileName()), ".tex");
346 return no_path ? onlyFilename(name) : name;
350 pair<Buffer::LogType, string> const Buffer::getLogName() const
352 string const filename = getLatexName(false);
354 if (filename.empty())
355 return make_pair(Buffer::latexlog, string());
357 string const path = temppath();
359 FileName const fname(addName(temppath(),
360 onlyFilename(changeExtension(filename,
362 FileName const bname(
363 addName(path, onlyFilename(
364 changeExtension(filename,
365 formats.extension("literate") + ".out"))));
367 // If no Latex log or Build log is newer, show Build log
369 if (fs::exists(bname.toFilesystemEncoding()) &&
370 (!fs::exists(fname.toFilesystemEncoding()) ||
371 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
372 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
373 return make_pair(Buffer::buildlog, bname.absFilename());
375 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
376 return make_pair(Buffer::latexlog, fname.absFilename());
380 void Buffer::setReadonly(bool const flag)
382 if (pimpl_->read_only != flag) {
383 pimpl_->read_only = flag;
389 void Buffer::setFileName(string const & newfile)
391 pimpl_->filename = makeAbsPath(newfile);
392 params().filepath = onlyPath(pimpl_->filename.absFilename());
393 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
398 // We'll remove this later. (Lgb)
401 void unknownClass(string const & unknown)
403 Alert::warning(_("Unknown document class"),
404 bformat(_("Using the default document class, because the "
405 "class %1$s is unknown."), from_utf8(unknown)));
411 int Buffer::readHeader(LyXLex & lex)
413 int unknown_tokens = 0;
415 int begin_header_line = -1;
417 // Initialize parameters that may be/go lacking in header:
418 params().branchlist().clear();
419 params().preamble.erase();
420 params().options.erase();
421 params().float_placement.erase();
422 params().paperwidth.erase();
423 params().paperheight.erase();
424 params().leftmargin.erase();
425 params().rightmargin.erase();
426 params().topmargin.erase();
427 params().bottommargin.erase();
428 params().headheight.erase();
429 params().headsep.erase();
430 params().footskip.erase();
432 ErrorList & errorList = errorLists_["Parse"];
436 string const token = lex.getString();
441 if (token == "\\end_header")
445 if (token == "\\begin_header") {
446 begin_header_line = line;
450 lyxerr[Debug::PARSER] << "Handling document header token: `"
451 << token << '\'' << endl;
453 string unknown = params().readToken(lex, token);
454 if (!unknown.empty()) {
455 if (unknown[0] != '\\' && token == "\\textclass") {
456 unknownClass(unknown);
459 docstring const s = bformat(_("Unknown token: "
463 errorList.push_back(ErrorItem(_("Document header error"),
468 if (begin_header_line) {
469 docstring const s = _("\\begin_header is missing");
470 errorList.push_back(ErrorItem(_("Document header error"),
474 return unknown_tokens;
479 // changed to be public and have one parameter
480 // Returns false if "\end_document" is not read (Asger)
481 bool Buffer::readDocument(LyXLex & lex)
483 ErrorList & errorList = errorLists_["Parse"];
487 string const token = lex.getString();
488 if (token != "\\begin_document") {
489 docstring const s = _("\\begin_document is missing");
490 errorList.push_back(ErrorItem(_("Document header error"),
494 // we are reading in a brand new document
495 BOOST_ASSERT(paragraphs().empty());
498 if (!params().getLyXTextClass().load(filePath())) {
499 string theclass = params().getLyXTextClass().name();
500 Alert::error(_("Can't load document class"), bformat(
501 _("Using the default document class, because the "
502 "class %1$s could not be loaded."), from_utf8(theclass)));
503 params().textclass = 0;
506 bool const res = text().read(*this, lex, errorList);
507 for_each(text().paragraphs().begin(),
508 text().paragraphs().end(),
509 bind(&Paragraph::setInsetOwner, _1, &inset()));
515 // needed to insert the selection
516 void Buffer::insertStringAsLines(ParagraphList & pars,
517 pit_type & pit, pos_type & pos,
518 LyXFont const & fn, docstring const & str, bool autobreakrows)
522 // insert the string, don't insert doublespace
523 bool space_inserted = true;
524 for (docstring::const_iterator cit = str.begin();
525 cit != str.end(); ++cit) {
526 Paragraph & par = pars[pit];
528 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
529 breakParagraph(params(), pars, pit, pos,
530 par.layout()->isEnvironment());
533 space_inserted = true;
537 // do not insert consecutive spaces if !free_spacing
538 } else if ((*cit == ' ' || *cit == '\t') &&
539 space_inserted && !par.isFreeSpacing()) {
541 } else if (*cit == '\t') {
542 if (!par.isFreeSpacing()) {
543 // tabs are like spaces here
544 par.insertChar(pos, ' ', font, params().trackChanges);
546 space_inserted = true;
548 const pos_type n = 8 - pos % 8;
549 for (pos_type i = 0; i < n; ++i) {
550 par.insertChar(pos, ' ', font, params().trackChanges);
553 space_inserted = true;
555 } else if (!isPrintable(*cit)) {
556 // Ignore unprintables
559 // just insert the character
560 par.insertChar(pos, *cit, font, params().trackChanges);
562 space_inserted = (*cit == ' ');
569 bool Buffer::readString(std::string const & s)
571 params().compressed = false;
573 // remove dummy empty par
574 paragraphs().clear();
576 std::istringstream is(s);
578 FileName const name(tempName());
579 switch (readFile(lex, name)) {
583 // We need to call lyx2lyx, so write the input to a file
584 std::ofstream os(name.toFilesystemEncoding().c_str());
587 return readFile(name) == success;
593 // After we have read a file, we must ensure that the buffer
594 // language is set and used in the gui.
595 // If you know of a better place to put this, please tell me. (Lgb)
596 updateDocLang(params().language);
602 bool Buffer::readFile(FileName const & filename)
604 // Check if the file is compressed.
605 string const format = getFormatFromContents(filename);
606 if (format == "gzip" || format == "zip" || format == "compress") {
607 params().compressed = true;
610 // remove dummy empty par
611 paragraphs().clear();
613 lex.setFile(filename);
614 if (readFile(lex, filename) != success)
617 // After we have read a file, we must ensure that the buffer
618 // language is set and used in the gui.
619 // If you know of a better place to put this, please tell me. (Lgb)
620 updateDocLang(params().language);
626 bool Buffer::fully_loaded() const
628 return pimpl_->file_fully_loaded;
632 void Buffer::fully_loaded(bool const value)
634 pimpl_->file_fully_loaded = value;
638 Buffer::ReadStatus Buffer::readFile(LyXLex & lex, FileName const & filename,
641 BOOST_ASSERT(!filename.empty());
644 Alert::error(_("Document could not be read"),
645 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
650 string const token(lex.getString());
653 Alert::error(_("Document could not be read"),
654 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
658 // the first token _must_ be...
659 if (token != "\\lyxformat") {
660 lyxerr << "Token: " << token << endl;
662 Alert::error(_("Document format failure"),
663 bformat(_("%1$s is not a LyX document."),
664 from_utf8(filename.absFilename())));
669 string tmp_format = lex.getString();
670 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
671 // if present remove ".," from string.
672 string::size_type dot = tmp_format.find_first_of(".,");
673 //lyxerr << " dot found at " << dot << endl;
674 if (dot != string::npos)
675 tmp_format.erase(dot, 1);
676 int const file_format = convert<int>(tmp_format);
677 //lyxerr << "format: " << file_format << endl;
679 if (file_format != LYX_FORMAT) {
682 // lyx2lyx would fail
685 FileName const tmpfile(tempName());
686 if (tmpfile.empty()) {
687 Alert::error(_("Conversion failed"),
688 bformat(_("%1$s is from an earlier"
689 " version of LyX, but a temporary"
690 " file for converting it could"
692 from_utf8(filename.absFilename())));
695 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
696 if (lyx2lyx.empty()) {
697 Alert::error(_("Conversion script not found"),
698 bformat(_("%1$s is from an earlier"
699 " version of LyX, but the"
700 " conversion script lyx2lyx"
701 " could not be found."),
702 from_utf8(filename.absFilename())));
705 ostringstream command;
706 command << os::python()
707 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
708 << " -t " << convert<string>(LYX_FORMAT)
709 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
710 << ' ' << quoteName(filename.toFilesystemEncoding());
711 string const command_str = command.str();
713 lyxerr[Debug::INFO] << "Running '"
714 << command_str << '\''
717 cmd_ret const ret = runCommand(command_str);
718 if (ret.first != 0) {
719 Alert::error(_("Conversion script failed"),
720 bformat(_("%1$s is from an earlier version"
721 " of LyX, but the lyx2lyx script"
722 " failed to convert it."),
723 from_utf8(filename.absFilename())));
726 bool const ret = readFile(tmpfile);
727 // Do stuff with tmpfile name and buffer name here.
728 return ret ? success : failure;
733 if (readDocument(lex)) {
734 Alert::error(_("Document format failure"),
735 bformat(_("%1$s ended unexpectedly, which means"
736 " that it is probably corrupted."),
737 from_utf8(filename.absFilename())));
740 //lyxerr << "removing " << MacroTable::localMacros().size()
741 // << " temporary macro entries" << endl;
742 //MacroTable::localMacros().clear();
744 pimpl_->file_fully_loaded = true;
749 // Should probably be moved to somewhere else: BufferView? LyXView?
750 bool Buffer::save() const
752 // We don't need autosaves in the immediate future. (Asger)
753 resetAutosaveTimers();
755 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
758 bool madeBackup = false;
760 // make a backup if the file already exists
761 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
762 backupName = FileName(fileName() + '~');
763 if (!lyxrc.backupdir_path.empty())
764 backupName = FileName(addName(lyxrc.backupdir_path,
765 subst(os::internal_path(backupName.absFilename()), '/', '!')));
768 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
770 } catch (fs::filesystem_error const & fe) {
771 Alert::error(_("Backup failure"),
772 bformat(_("Cannot create backup file %1$s.\n"
773 "Please check whether the directory exists and is writeable."),
774 from_utf8(backupName.absFilename())));
775 lyxerr[Debug::DEBUG] << "Fs error: " << fe.what() << endl;
779 if (writeFile(pimpl_->filename)) {
781 removeAutosaveFile(fileName());
784 // Saving failed, so backup is not backup
786 rename(backupName, pimpl_->filename);
792 bool Buffer::writeFile(FileName const & fname) const
794 if (pimpl_->read_only && fname == pimpl_->filename)
799 if (params().compressed) {
800 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
806 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
817 bool Buffer::write(ostream & ofs) const
820 // Use the standard "C" locale for file output.
821 ofs.imbue(std::locale::classic());
824 // The top of the file should not be written by params().
826 // write out a comment in the top of the file
827 ofs << "#LyX " << lyx_version
828 << " created this file. For more info see http://www.lyx.org/\n"
829 << "\\lyxformat " << LYX_FORMAT << "\n"
830 << "\\begin_document\n";
832 // now write out the buffer parameters.
833 ofs << "\\begin_header\n";
834 params().writeFile(ofs);
835 ofs << "\\end_header\n";
838 ofs << "\n\\begin_body\n";
839 text().write(*this, ofs);
840 ofs << "\n\\end_body\n";
842 // Write marker that shows file is complete
843 ofs << "\\end_document" << endl;
845 // Shouldn't really be needed....
848 // how to check if close went ok?
849 // Following is an attempt... (BE 20001011)
851 // good() returns false if any error occured, including some
853 // bad() returns true if something bad happened in the buffer,
854 // which should include file system full errors.
859 lyxerr << "File was not closed properly." << endl;
866 bool Buffer::makeLaTeXFile(FileName const & fname,
867 string const & original_path,
868 OutputParams const & runparams,
869 bool output_preamble, bool output_body)
871 string const encoding = params().encoding().iconvName();
872 lyxerr[Debug::LATEX] << "makeLaTeXFile encoding: "
873 << encoding << "..." << endl;
875 odocfstream ofs(encoding);
876 if (!openFileWrite(ofs, fname))
880 writeLaTeXSource(ofs, original_path,
881 runparams, output_preamble, output_body);
883 catch (iconv_codecvt_facet_exception &) {
884 Alert::error(_("Encoding error"),
885 _("Some characters of your document are not "
886 "representable in the chosen encoding.\n"
887 "Changing the document encoding to utf8 could help."));
893 lyxerr << "File '" << fname << "' was not closed properly." << endl;
894 Alert::error(_("Error closing file"),
895 _("The output file could not be closed properly.\n"
896 " Probably some characters of your document are not "
897 "representable in the chosen encoding.\n"
898 "Changing the document encoding to utf8 could help."));
905 void Buffer::writeLaTeXSource(odocstream & os,
906 string const & original_path,
907 OutputParams const & runparams_in,
908 bool const output_preamble, bool const output_body)
910 OutputParams runparams = runparams_in;
912 // validate the buffer.
913 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
914 LaTeXFeatures features(*this, params(), runparams);
916 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
920 // The starting paragraph of the coming rows is the
921 // first paragraph of the document. (Asger)
922 texrow().start(paragraphs().begin()->id(), 0);
924 if (output_preamble && runparams.nice) {
925 os << "%% LyX " << lyx_version << " created this file. "
926 "For more info, see http://www.lyx.org/.\n"
927 "%% Do not edit unless you really know what "
932 lyxerr[Debug::INFO] << "lyx document header finished" << endl;
933 // There are a few differences between nice LaTeX and usual files:
934 // usual is \batchmode and has a
935 // special input@path to allow the including of figures
936 // with either \input or \includegraphics (what figinsets do).
937 // input@path is set when the actual parameter
938 // original_path is set. This is done for usual tex-file, but not
939 // for nice-latex-file. (Matthias 250696)
940 // Note that input@path is only needed for something the user does
941 // in the preamble, included .tex files or ERT, files included by
942 // LyX work without it.
943 if (output_preamble) {
944 if (!runparams.nice) {
945 // code for usual, NOT nice-latex-file
946 os << "\\batchmode\n"; // changed
950 if (!original_path.empty()) {
952 // We don't know the encoding of inputpath
953 docstring const inputpath = from_utf8(latex_path(original_path));
954 os << "\\makeatletter\n"
955 << "\\def\\input@path{{"
956 << inputpath << "/}}\n"
957 << "\\makeatother\n";
963 // Write the preamble
964 runparams.use_babel = params().writeLaTeX(os, features, texrow());
970 os << "\\begin{document}\n";
973 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
975 if (!lyxrc.language_auto_begin) {
977 os << from_utf8(subst(lyxrc.language_command_begin,
979 params().language->babel()))
984 // if we are doing a real file with body, even if this is the
985 // child of some other buffer, let's cut the link here.
986 // This happens for example if only a child document is printed.
987 string save_parentname;
988 if (output_preamble) {
989 save_parentname = params().parentname;
990 params().parentname.erase();
994 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
996 // Restore the parenthood if needed
998 params().parentname = save_parentname;
1000 // add this just in case after all the paragraphs
1004 if (!lyxrc.language_auto_end) {
1005 os << from_utf8(subst(lyxrc.language_command_end,
1007 params().language->babel()))
1012 if (output_preamble) {
1013 os << "\\end{document}\n";
1016 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1018 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1022 // Just to be sure. (Asger)
1025 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1026 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1031 bool Buffer::isLatex() const
1033 return params().getLyXTextClass().outputType() == LATEX;
1037 bool Buffer::isLiterate() const
1039 return params().getLyXTextClass().outputType() == LITERATE;
1043 bool Buffer::isDocBook() const
1045 return params().getLyXTextClass().outputType() == DOCBOOK;
1049 void Buffer::makeDocBookFile(FileName const & fname,
1050 OutputParams const & runparams,
1051 bool const body_only)
1053 lyxerr[Debug::LATEX] << "makeDocBookFile..." << endl;
1057 if (!openFileWrite(ofs, fname))
1060 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1064 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1068 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1069 OutputParams const & runparams,
1070 bool const only_body)
1072 LaTeXFeatures features(*this, params(), runparams);
1077 LyXTextClass const & tclass = params().getLyXTextClass();
1078 string const top_element = tclass.latexname();
1081 if (runparams.flavor == OutputParams::XML)
1082 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1085 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1088 if (! tclass.class_header().empty())
1089 os << from_ascii(tclass.class_header());
1090 else if (runparams.flavor == OutputParams::XML)
1091 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1092 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1094 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1096 docstring preamble = from_utf8(params().preamble);
1097 if (runparams.flavor != OutputParams::XML ) {
1098 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1099 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1100 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1101 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1104 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1106 preamble += features.getIncludedFiles(name);
1107 preamble += features.getLyXSGMLEntities();
1109 if (!preamble.empty()) {
1110 os << "\n [ " << preamble << " ]";
1115 string top = top_element;
1117 if (runparams.flavor == OutputParams::XML)
1118 top += params().language->code();
1120 top += params().language->code().substr(0,2);
1123 if (!params().options.empty()) {
1125 top += params().options;
1128 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1129 << " file was created by LyX " << lyx_version
1130 << "\n See http://www.lyx.org/ for more information -->\n";
1132 params().getLyXTextClass().counters().reset();
1134 sgml::openTag(os, top);
1136 docbookParagraphs(paragraphs(), *this, os, runparams);
1137 sgml::closeTag(os, top_element);
1141 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1142 // Other flags: -wall -v0 -x
1143 int Buffer::runChktex()
1147 // get LaTeX-Filename
1148 string const name = getLatexName(false);
1149 string const path = temppath();
1150 string const org_path = filePath();
1152 support::Path p(path); // path to LaTeX file
1153 message(_("Running chktex..."));
1155 // Generate the LaTeX file if neccessary
1156 OutputParams runparams;
1157 runparams.flavor = OutputParams::LATEX;
1158 runparams.nice = false;
1159 makeLaTeXFile(FileName(name), org_path, runparams);
1162 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1163 int const res = chktex.run(terr); // run chktex
1166 Alert::error(_("chktex failure"),
1167 _("Could not run chktex successfully."));
1168 } else if (res > 0) {
1169 // Fill-in the error list with the TeX errors
1170 bufferErrors(*this, terr, errorLists_["ChkTex"]);
1181 void Buffer::validate(LaTeXFeatures & features) const
1183 LyXTextClass const & tclass = params().getLyXTextClass();
1185 if (features.isAvailable("dvipost") && params().outputChanges)
1186 features.require("dvipost");
1188 // AMS Style is at document level
1189 if (params().use_amsmath == BufferParams::package_on
1190 || tclass.provides(LyXTextClass::amsmath))
1191 features.require("amsmath");
1192 if (params().use_esint == BufferParams::package_on)
1193 features.require("esint");
1195 for_each(paragraphs().begin(), paragraphs().end(),
1196 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1198 // the bullet shapes are buffer level not paragraph level
1199 // so they are tested here
1200 for (int i = 0; i < 4; ++i) {
1201 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1202 int const font = params().user_defined_bullet(i).getFont();
1204 int const c = params()
1205 .user_defined_bullet(i)
1212 features.require("latexsym");
1214 } else if (font == 1) {
1215 features.require("amssymb");
1216 } else if ((font >= 2 && font <= 5)) {
1217 features.require("pifont");
1222 if (lyxerr.debugging(Debug::LATEX)) {
1223 features.showStruct();
1228 void Buffer::getLabelList(vector<docstring> & list) const
1230 /// if this is a child document and the parent is already loaded
1231 /// Use the parent's list instead [ale990407]
1232 Buffer const * tmp = getMasterBuffer();
1234 lyxerr << "getMasterBuffer() failed!" << endl;
1238 tmp->getLabelList(list);
1242 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1243 it.nextInset()->getLabelList(*this, list);
1247 // This is also a buffer property (ale)
1248 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1251 /// if this is a child document and the parent is already loaded
1252 /// use the parent's list instead [ale990412]
1253 Buffer const * tmp = getMasterBuffer();
1256 tmp->fillWithBibKeys(keys);
1260 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1261 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1262 InsetBibtex const & inset =
1263 dynamic_cast<InsetBibtex const &>(*it);
1264 inset.fillWithBibKeys(*this, keys);
1265 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1266 InsetInclude const & inset =
1267 dynamic_cast<InsetInclude const &>(*it);
1268 inset.fillWithBibKeys(*this, keys);
1269 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1270 InsetBibitem const & inset =
1271 dynamic_cast<InsetBibitem const &>(*it);
1273 string const key = to_utf8(inset.getParam("key"));
1274 docstring const label = inset.getParam("label");
1275 docstring const ref; // = pit->asString(this, false);
1276 docstring const info = label + "TheBibliographyRef" + ref;
1277 keys.push_back(pair<string, docstring>(key, info));
1283 void Buffer::updateBibfilesCache()
1285 // if this is a child document and the parent is already loaded
1286 // update the parent's cache instead
1287 Buffer * tmp = getMasterBuffer();
1290 tmp->updateBibfilesCache();
1294 bibfilesCache_.clear();
1295 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1296 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1297 InsetBibtex const & inset =
1298 dynamic_cast<InsetBibtex const &>(*it);
1299 vector<FileName> const bibfiles = inset.getFiles(*this);
1300 bibfilesCache_.insert(bibfilesCache_.end(),
1303 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1304 InsetInclude & inset =
1305 dynamic_cast<InsetInclude &>(*it);
1306 inset.updateBibfilesCache(*this);
1307 vector<FileName> const & bibfiles =
1308 inset.getBibfilesCache(*this);
1309 bibfilesCache_.insert(bibfilesCache_.end(),
1317 vector<FileName> const & Buffer::getBibfilesCache() const
1319 // if this is a child document and the parent is already loaded
1320 // use the parent's cache instead
1321 Buffer const * tmp = getMasterBuffer();
1324 return tmp->getBibfilesCache();
1326 // We update the cache when first used instead of at loading time.
1327 if (bibfilesCache_.empty())
1328 const_cast<Buffer *>(this)->updateBibfilesCache();
1330 return bibfilesCache_;
1334 bool Buffer::isDepClean(string const & name) const
1336 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1337 if (it == pimpl_->dep_clean.end())
1343 void Buffer::markDepClean(string const & name)
1345 pimpl_->dep_clean[name] = true;
1349 bool Buffer::dispatch(string const & command, bool * result)
1351 return dispatch(lyxaction.lookupFunc(command), result);
1355 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1357 bool dispatched = true;
1359 switch (func.action) {
1360 case LFUN_BUFFER_EXPORT: {
1361 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1374 void Buffer::changeLanguage(Language const * from, Language const * to)
1379 // Take care of l10n/i18n
1382 for_each(par_iterator_begin(),
1384 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1386 text().current_font.setLanguage(to);
1387 text().real_current_font.setLanguage(to);
1391 void Buffer::updateDocLang(Language const * nlang)
1393 BOOST_ASSERT(nlang);
1395 pimpl_->messages = &getMessages(nlang->code());
1399 bool Buffer::isMultiLingual() const
1401 ParConstIterator end = par_iterator_end();
1402 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1403 if (it->isMultiLingual(params()))
1410 ParIterator Buffer::getParFromID(int const id) const
1412 ParConstIterator it = par_iterator_begin();
1413 ParConstIterator const end = par_iterator_end();
1416 // John says this is called with id == -1 from undo
1417 lyxerr << "getParFromID(), id: " << id << endl;
1421 for (; it != end; ++it)
1429 bool Buffer::hasParWithID(int const id) const
1431 ParConstIterator const it = getParFromID(id);
1432 return it != par_iterator_end();
1436 ParIterator Buffer::par_iterator_begin()
1438 return lyx::par_iterator_begin(inset());
1442 ParIterator Buffer::par_iterator_end()
1444 return lyx::par_iterator_end(inset());
1448 ParConstIterator Buffer::par_iterator_begin() const
1450 return lyx::par_const_iterator_begin(inset());
1454 ParConstIterator Buffer::par_iterator_end() const
1456 return lyx::par_const_iterator_end(inset());
1460 Language const * Buffer::getLanguage() const
1462 return params().language;
1466 docstring const Buffer::B_(string const & l10n) const
1468 if (pimpl_->messages)
1469 return pimpl_->messages->get(l10n);
1475 docstring const Buffer::translateLabel(docstring const & label) const
1477 if (support::isAscii(label))
1478 // Probably standard layout, try to translate
1479 return B_(to_ascii(label));
1481 // This must be a user defined layout. We cannot translate
1482 // this, since gettext accepts only ascii keys.
1487 bool Buffer::isClean() const
1489 return pimpl_->lyx_clean;
1493 bool Buffer::isBakClean() const
1495 return pimpl_->bak_clean;
1499 void Buffer::markClean() const
1501 if (!pimpl_->lyx_clean) {
1502 pimpl_->lyx_clean = true;
1505 // if the .lyx file has been saved, we don't need an
1507 pimpl_->bak_clean = true;
1511 void Buffer::markBakClean()
1513 pimpl_->bak_clean = true;
1517 void Buffer::setUnnamed(bool flag)
1519 pimpl_->unnamed = flag;
1523 bool Buffer::isUnnamed() const
1525 return pimpl_->unnamed;
1529 #ifdef WITH_WARNINGS
1530 #warning this function should be moved to buffer_pimpl.C
1532 void Buffer::markDirty()
1534 if (pimpl_->lyx_clean) {
1535 pimpl_->lyx_clean = false;
1538 pimpl_->bak_clean = false;
1540 DepClean::iterator it = pimpl_->dep_clean.begin();
1541 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1543 for (; it != end; ++it)
1548 string const Buffer::fileName() const
1550 return pimpl_->filename.absFilename();
1554 string const & Buffer::filePath() const
1556 return params().filepath;
1560 bool Buffer::isReadonly() const
1562 return pimpl_->read_only;
1566 void Buffer::setParentName(string const & name)
1568 params().parentname = name;
1572 Buffer const * Buffer::getMasterBuffer() const
1574 if (!params().parentname.empty()
1575 && theBufferList().exists(params().parentname)) {
1576 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1578 return buf->getMasterBuffer();
1585 Buffer * Buffer::getMasterBuffer()
1587 if (!params().parentname.empty()
1588 && theBufferList().exists(params().parentname)) {
1589 Buffer * buf = theBufferList().getBuffer(params().parentname);
1591 return buf->getMasterBuffer();
1598 MacroData const & Buffer::getMacro(docstring const & name) const
1600 return pimpl_->macros.get(name);
1604 bool Buffer::hasMacro(docstring const & name) const
1606 return pimpl_->macros.has(name);
1610 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1612 MacroTable::globalMacros().insert(name, data);
1613 pimpl_->macros.insert(name, data);
1617 void Buffer::buildMacros()
1619 // Start with global table.
1620 pimpl_->macros = MacroTable::globalMacros();
1623 ParagraphList const & pars = text().paragraphs();
1624 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1625 //lyxerr << "searching main par " << i
1626 // << " for macro definitions" << std::endl;
1627 InsetList const & insets = pars[i].insetlist;
1628 InsetList::const_iterator it = insets.begin();
1629 InsetList::const_iterator end = insets.end();
1630 for ( ; it != end; ++it) {
1631 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1632 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1633 MathMacroTemplate const & mac
1634 = static_cast<MathMacroTemplate const &>(*it->inset);
1635 insertMacro(mac.name(), mac.asMacroData());
1642 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1649 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1650 InsetBase::Code code)
1652 //FIXME: This does not work for child documents yet.
1653 BOOST_ASSERT(code == InsetBase::CITE_CODE || code == InsetBase::REF_CODE);
1654 // Check if the label 'from' appears more than once
1655 vector<docstring> labels;
1657 if (code == InsetBase::CITE_CODE) {
1658 vector<pair<string, docstring> > keys;
1659 fillWithBibKeys(keys);
1660 vector<pair<string, docstring> >::const_iterator bit = keys.begin();
1661 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1663 for (; bit != bend; ++bit)
1665 labels.push_back(from_utf8(bit->first));
1667 getLabelList(labels);
1669 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1672 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1673 if (it->lyxCode() == code) {
1674 InsetCommand & inset = dynamic_cast<InsetCommand &>(*it);
1675 inset.replaceContents(to_utf8(from), to_utf8(to));
1681 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1682 pit_type par_end, bool full_source)
1684 OutputParams runparams;
1685 runparams.nice = true;
1686 runparams.flavor = OutputParams::LATEX;
1687 runparams.linelen = lyxrc.ascii_linelen;
1688 // No side effect of file copying and image conversion
1689 runparams.dryrun = true;
1692 os << "% Preview source code\n\n";
1694 writeLaTeXSource(os, filePath(), runparams, true, true);
1696 writeDocBookSource(os, fileName(), runparams, false);
1699 runparams.par_begin = par_begin;
1700 runparams.par_end = par_end;
1701 if (par_begin + 1 == par_end)
1702 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1704 os << "% Preview source code from paragraph " << par_begin
1705 << " to " << par_end - 1 << "\n\n";
1706 // output paragraphs
1709 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1712 docbookParagraphs(paragraphs(), *this, os, runparams);
1718 ErrorList const & Buffer::errorList(string const & type) const
1720 static ErrorList const emptyErrorList;
1721 std::map<string, ErrorList>::const_iterator I = errorLists_.find(type);
1722 if (I == errorLists_.end())
1723 return emptyErrorList;
1729 ErrorList & Buffer::errorList(string const & type)
1731 return errorLists_[type];