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, string 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, string 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);
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, 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(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 string const fname = addName(path,
362 onlyFilename(changeExtension(filename,
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) &&
372 (!fs::exists(fname) || fs::last_write_time(fname) < fs::last_write_time(bname))) {
373 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
374 return make_pair(Buffer::buildlog, bname);
376 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
377 return make_pair(Buffer::latexlog, fname);
381 void Buffer::setReadonly(bool const flag)
383 if (pimpl_->read_only != flag) {
384 pimpl_->read_only = flag;
390 void Buffer::setFileName(string const & newfile)
392 pimpl_->filename = makeAbsPath(newfile);
393 params().filepath = onlyPath(pimpl_->filename);
394 setReadonly(fs::is_readonly(pimpl_->filename));
399 // We'll remove this later. (Lgb)
402 void unknownClass(string const & unknown)
404 Alert::warning(_("Unknown document class"),
405 bformat(_("Using the default document class, because the "
406 "class %1$s is unknown."), from_utf8(unknown)));
412 int Buffer::readHeader(LyXLex & lex)
414 int unknown_tokens = 0;
416 int begin_header_line = -1;
418 // Initialize parameters that may be/go lacking in header:
419 params().branchlist().clear();
420 params().preamble.erase();
421 params().options.erase();
422 params().float_placement.erase();
423 params().paperwidth.erase();
424 params().paperheight.erase();
425 params().leftmargin.erase();
426 params().rightmargin.erase();
427 params().topmargin.erase();
428 params().bottommargin.erase();
429 params().headheight.erase();
430 params().headsep.erase();
431 params().footskip.erase();
433 ErrorList & errorList = errorLists_["Parse"];
437 string const token = lex.getString();
442 if (token == "\\end_header")
446 if (token == "\\begin_header") {
447 begin_header_line = line;
451 lyxerr[Debug::PARSER] << "Handling document header token: `"
452 << token << '\'' << endl;
454 string unknown = params().readToken(lex, token);
455 if (!unknown.empty()) {
456 if (unknown[0] != '\\' && token == "\\textclass") {
457 unknownClass(unknown);
460 docstring const s = bformat(_("Unknown token: "
464 errorList.push_back(ErrorItem(_("Document header error"),
469 if (begin_header_line) {
470 docstring const s = _("\\begin_header is missing");
471 errorList.push_back(ErrorItem(_("Document header error"),
475 return unknown_tokens;
480 // changed to be public and have one parameter
481 // Returns false if "\end_document" is not read (Asger)
482 bool Buffer::readDocument(LyXLex & lex)
484 ErrorList & errorList = errorLists_["Parse"];
488 string const token = lex.getString();
489 if (token != "\\begin_document") {
490 docstring const s = _("\\begin_document is missing");
491 errorList.push_back(ErrorItem(_("Document header error"),
495 // we are reading in a brand new document
496 BOOST_ASSERT(paragraphs().empty());
499 if (!params().getLyXTextClass().load(filePath())) {
500 string theclass = params().getLyXTextClass().name();
501 Alert::error(_("Can't load document class"), bformat(
502 _("Using the default document class, because the "
503 " class %1$s could not be loaded."), from_utf8(theclass)));
504 params().textclass = 0;
507 bool const res = text().read(*this, lex, errorList);
508 for_each(text().paragraphs().begin(),
509 text().paragraphs().end(),
510 bind(&Paragraph::setInsetOwner, _1, &inset()));
511 updateBibfilesCache();
517 // needed to insert the selection
518 void Buffer::insertStringAsLines(ParagraphList & pars,
519 pit_type & pit, pos_type & pos,
520 LyXFont 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::readFile(string const & filename)
573 // Check if the file is compressed.
574 FileName const name(makeAbsPath(filename));
575 string const format = getFormatFromContents(name);
576 if (format == "gzip" || format == "zip" || format == "compress") {
577 params().compressed = true;
580 // remove dummy empty par
581 paragraphs().clear();
584 if (!readFile(lex, filename))
587 // After we have read a file, we must ensure that the buffer
588 // language is set and used in the gui.
589 // If you know of a better place to put this, please tell me. (Lgb)
590 updateDocLang(params().language);
596 bool Buffer::fully_loaded() const
598 return pimpl_->file_fully_loaded;
602 void Buffer::fully_loaded(bool const value)
604 pimpl_->file_fully_loaded = value;
608 bool Buffer::readFile(LyXLex & lex, string const & filename)
610 BOOST_ASSERT(!filename.empty());
613 Alert::error(_("Document could not be read"),
614 bformat(_("%1$s could not be read."), from_utf8(filename)));
619 string const token(lex.getString());
622 Alert::error(_("Document could not be read"),
623 bformat(_("%1$s could not be read."), from_utf8(filename)));
627 // the first token _must_ be...
628 if (token != "\\lyxformat") {
629 lyxerr << "Token: " << token << endl;
631 Alert::error(_("Document format failure"),
632 bformat(_("%1$s is not a LyX document."),
633 from_utf8(filename)));
638 string tmp_format = lex.getString();
639 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
640 // if present remove ".," from string.
641 string::size_type dot = tmp_format.find_first_of(".,");
642 //lyxerr << " dot found at " << dot << endl;
643 if (dot != string::npos)
644 tmp_format.erase(dot, 1);
645 int const file_format = convert<int>(tmp_format);
646 //lyxerr << "format: " << file_format << endl;
648 if (file_format != LYX_FORMAT) {
649 string const tmpfile = tempName();
650 if (tmpfile.empty()) {
651 Alert::error(_("Conversion failed"),
652 bformat(_("%1$s is from an earlier"
653 " version of LyX, but a temporary"
654 " file for converting it could"
656 from_utf8(filename)));
659 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
660 if (lyx2lyx.empty()) {
661 Alert::error(_("Conversion script not found"),
662 bformat(_("%1$s is from an earlier"
663 " version of LyX, but the"
664 " conversion script lyx2lyx"
665 " could not be found."),
666 from_utf8(filename)));
669 ostringstream command;
670 command << os::python() << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
671 << " -t " << convert<string>(LYX_FORMAT)
672 << " -o " << quoteName(tmpfile) << ' '
673 << quoteName(filename);
674 string const command_str = command.str();
676 lyxerr[Debug::INFO] << "Running '"
677 << command_str << '\''
680 cmd_ret const ret = runCommand(command_str);
681 if (ret.first != 0) {
682 Alert::error(_("Conversion script failed"),
683 bformat(_("%1$s is from an earlier version"
684 " of LyX, but the lyx2lyx script"
685 " failed to convert it."),
686 from_utf8(filename)));
689 bool const ret = readFile(tmpfile);
690 // Do stuff with tmpfile name and buffer name here.
696 if (readDocument(lex)) {
697 Alert::error(_("Document format failure"),
698 bformat(_("%1$s ended unexpectedly, which means"
699 " that it is probably corrupted."),
700 from_utf8(filename)));
703 //lyxerr << "removing " << MacroTable::localMacros().size()
704 // << " temporary macro entries" << endl;
705 //MacroTable::localMacros().clear();
707 pimpl_->file_fully_loaded = true;
712 // Should probably be moved to somewhere else: BufferView? LyXView?
713 bool Buffer::save() const
715 // We don't need autosaves in the immediate future. (Asger)
716 resetAutosaveTimers();
720 if (lyxrc.make_backup) {
721 s = fileName() + '~';
722 if (!lyxrc.backupdir_path.empty())
723 s = addName(lyxrc.backupdir_path,
724 subst(os::internal_path(s),'/','!'));
726 // It might very well be that this variant is just
727 // good enough. (Lgb)
728 // But to use this we need fs::copy_file to actually do a copy,
729 // even when the target file exists. (Lgb)
731 fs::copy_file(fileName(), s, false);
733 catch (fs::filesystem_error const & fe) {
734 Alert::error(_("Backup failure"),
735 bformat(_("LyX was not able to make a backup copy in %1$s.\n"
736 "Please check if the directory exists and is writeable."),
737 from_utf8(fs::path(s).branch_path().native_directory_string())));
738 lyxerr[Debug::DEBUG] << "Fs error: "
739 << fe.what() << endl;
743 if (writeFile(fileName())) {
745 removeAutosaveFile(fileName());
747 // Saving failed, so backup is not backup
748 if (lyxrc.make_backup)
749 rename(FileName(s), FileName(fileName()));
756 bool Buffer::writeFile(string const & fname) const
758 if (pimpl_->read_only && fname == fileName())
763 if (params().compressed) {
764 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname));
768 retval = do_writeFile(ofs);
770 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
774 retval = do_writeFile(ofs);
781 bool Buffer::do_writeFile(ostream & ofs) const
784 // Use the standard "C" locale for file output.
785 ofs.imbue(std::locale::classic());
788 // The top of the file should not be written by params().
790 // write out a comment in the top of the file
791 ofs << "#LyX " << lyx_version
792 << " created this file. For more info see http://www.lyx.org/\n"
793 << "\\lyxformat " << LYX_FORMAT << "\n"
794 << "\\begin_document\n";
796 // now write out the buffer parameters.
797 ofs << "\\begin_header\n";
798 params().writeFile(ofs);
799 ofs << "\\end_header\n";
802 ofs << "\n\\begin_body\n";
803 text().write(*this, ofs);
804 ofs << "\n\\end_body\n";
806 // Write marker that shows file is complete
807 ofs << "\\end_document" << endl;
809 // Shouldn't really be needed....
812 // how to check if close went ok?
813 // Following is an attempt... (BE 20001011)
815 // good() returns false if any error occured, including some
817 // bad() returns true if something bad happened in the buffer,
818 // which should include file system full errors.
823 lyxerr << "File was not closed properly." << endl;
830 bool Buffer::makeLaTeXFile(string const & fname,
831 string const & original_path,
832 OutputParams const & runparams,
833 bool output_preamble, bool output_body)
836 if (params().inputenc == "auto")
837 encoding = params().language->encoding()->iconvName();
839 Encoding const * enc = encodings.getFromLaTeXName(params().inputenc);
841 encoding = enc->iconvName();
843 lyxerr << "Unknown inputenc value `"
845 << "'. Using `auto' instead." << endl;
846 encoding = params().language->encoding()->iconvName();
849 lyxerr[Debug::LATEX] << "makeLaTeXFile encoding: "
850 << encoding << "..." << endl;
852 odocfstream ofs(encoding);
853 if (!openFileWrite(ofs, fname))
857 writeLaTeXSource(ofs, original_path,
858 runparams, output_preamble, output_body);
860 catch (iconv_codecvt_facet_exception &) {
861 Alert::error(_("Encoding error"),
862 _("Some characters of your document are not "
863 "representable in the chosen encoding.\n"
864 "Changing the document encoding to utf8 could help."));
870 lyxerr << "File '" << fname << "' was not closed properly." << endl;
871 Alert::error(_("Error closing file"),
872 _("The output file could not be closed properly.\n"
873 " Probably some characters of your document are not "
874 "representable in the chosen encoding.\n"
875 "Changing the document encoding to utf8 could help."));
882 void Buffer::writeLaTeXSource(odocstream & os,
883 string const & original_path,
884 OutputParams const & runparams_in,
885 bool const output_preamble, bool const output_body)
887 OutputParams runparams = runparams_in;
889 // validate the buffer.
890 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
891 LaTeXFeatures features(*this, params(), runparams);
893 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
897 // The starting paragraph of the coming rows is the
898 // first paragraph of the document. (Asger)
899 texrow().start(paragraphs().begin()->id(), 0);
901 if (output_preamble && runparams.nice) {
902 os << "%% LyX " << lyx_version << " created this file. "
903 "For more info, see http://www.lyx.org/.\n"
904 "%% Do not edit unless you really know what "
909 lyxerr[Debug::INFO] << "lyx document header finished" << endl;
910 // There are a few differences between nice LaTeX and usual files:
911 // usual is \batchmode and has a
912 // special input@path to allow the including of figures
913 // with either \input or \includegraphics (what figinsets do).
914 // input@path is set when the actual parameter
915 // original_path is set. This is done for usual tex-file, but not
916 // for nice-latex-file. (Matthias 250696)
917 // Note that input@path is only needed for something the user does
918 // in the preamble, included .tex files or ERT, files included by
919 // LyX work without it.
920 if (output_preamble) {
921 if (!runparams.nice) {
922 // code for usual, NOT nice-latex-file
923 os << "\\batchmode\n"; // changed
927 if (!original_path.empty()) {
929 // We don't know the encoding of inputpath
930 docstring const inputpath = from_utf8(latex_path(original_path));
931 os << "\\makeatletter\n"
932 << "\\def\\input@path{{"
933 << inputpath << "/}}\n"
934 << "\\makeatother\n";
940 // Write the preamble
941 runparams.use_babel = params().writeLaTeX(os, features, texrow());
947 os << "\\begin{document}\n";
950 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
952 if (!lyxrc.language_auto_begin) {
954 os << from_utf8(subst(lyxrc.language_command_begin,
956 params().language->babel()))
961 // if we are doing a real file with body, even if this is the
962 // child of some other buffer, let's cut the link here.
963 // This happens for example if only a child document is printed.
964 string save_parentname;
965 if (output_preamble) {
966 save_parentname = params().parentname;
967 params().parentname.erase();
971 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
973 // Restore the parenthood if needed
975 params().parentname = save_parentname;
977 // add this just in case after all the paragraphs
981 if (!lyxrc.language_auto_end) {
982 os << from_utf8(subst(lyxrc.language_command_end,
984 params().language->babel()))
989 if (output_preamble) {
990 os << "\\end{document}\n";
993 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
995 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
999 // Just to be sure. (Asger)
1002 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1003 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1008 bool Buffer::isLatex() const
1010 return params().getLyXTextClass().outputType() == LATEX;
1014 bool Buffer::isLiterate() const
1016 return params().getLyXTextClass().outputType() == LITERATE;
1020 bool Buffer::isDocBook() const
1022 return params().getLyXTextClass().outputType() == DOCBOOK;
1026 void Buffer::makeDocBookFile(string const & fname,
1027 OutputParams const & runparams,
1028 bool const body_only)
1030 lyxerr[Debug::LATEX] << "makeDocBookFile..." << endl;
1034 if (!openFileWrite(ofs, fname))
1037 writeDocBookSource(ofs, fname, runparams, body_only);
1041 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1045 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1046 OutputParams const & runparams,
1047 bool const only_body)
1049 LaTeXFeatures features(*this, params(), runparams);
1054 LyXTextClass const & tclass = params().getLyXTextClass();
1055 string const top_element = tclass.latexname();
1058 if (runparams.flavor == OutputParams::XML)
1059 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1062 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1065 if (! tclass.class_header().empty())
1066 os << from_ascii(tclass.class_header());
1067 else if (runparams.flavor == OutputParams::XML)
1068 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1069 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1071 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1073 docstring preamble = from_utf8(params().preamble);
1074 if (runparams.flavor != OutputParams::XML ) {
1075 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1076 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1077 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1078 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1081 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1083 preamble += features.getIncludedFiles(name);
1084 preamble += features.getLyXSGMLEntities();
1086 if (!preamble.empty()) {
1087 os << "\n [ " << preamble << " ]";
1092 string top = top_element;
1094 if (runparams.flavor == OutputParams::XML)
1095 top += params().language->code();
1097 top += params().language->code().substr(0,2);
1100 if (!params().options.empty()) {
1102 top += params().options;
1105 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1106 << " file was created by LyX " << lyx_version
1107 << "\n See http://www.lyx.org/ for more information -->\n";
1109 params().getLyXTextClass().counters().reset();
1111 sgml::openTag(os, top);
1113 docbookParagraphs(paragraphs(), *this, os, runparams);
1114 sgml::closeTag(os, top_element);
1118 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1119 // Other flags: -wall -v0 -x
1120 int Buffer::runChktex()
1124 // get LaTeX-Filename
1125 string const name = getLatexName();
1126 string const path = temppath();
1127 string const org_path = filePath();
1129 support::Path p(path); // path to LaTeX file
1130 message(_("Running chktex..."));
1132 // Generate the LaTeX file if neccessary
1133 OutputParams runparams;
1134 runparams.flavor = OutputParams::LATEX;
1135 runparams.nice = false;
1136 makeLaTeXFile(name, org_path, runparams);
1139 Chktex chktex(lyxrc.chktex_command, name, filePath());
1140 int const res = chktex.run(terr); // run chktex
1143 Alert::error(_("chktex failure"),
1144 _("Could not run chktex successfully."));
1145 } else if (res > 0) {
1146 // Fill-in the error list with the TeX errors
1147 bufferErrors(*this, terr, errorLists_["ChkTex"]);
1158 void Buffer::validate(LaTeXFeatures & features) const
1160 LyXTextClass const & tclass = params().getLyXTextClass();
1162 if (features.isAvailable("dvipost") && params().outputChanges)
1163 features.require("dvipost");
1165 // AMS Style is at document level
1166 if (params().use_amsmath == BufferParams::package_on
1167 || tclass.provides(LyXTextClass::amsmath))
1168 features.require("amsmath");
1169 if (params().use_esint == BufferParams::package_on)
1170 features.require("esint");
1172 for_each(paragraphs().begin(), paragraphs().end(),
1173 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1175 // the bullet shapes are buffer level not paragraph level
1176 // so they are tested here
1177 for (int i = 0; i < 4; ++i) {
1178 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1179 int const font = params().user_defined_bullet(i).getFont();
1181 int const c = params()
1182 .user_defined_bullet(i)
1189 features.require("latexsym");
1191 } else if (font == 1) {
1192 features.require("amssymb");
1193 } else if ((font >= 2 && font <= 5)) {
1194 features.require("pifont");
1199 if (lyxerr.debugging(Debug::LATEX)) {
1200 features.showStruct();
1205 void Buffer::getLabelList(vector<docstring> & list) const
1207 /// if this is a child document and the parent is already loaded
1208 /// Use the parent's list instead [ale990407]
1209 Buffer const * tmp = getMasterBuffer();
1211 lyxerr << "getMasterBuffer() failed!" << endl;
1215 tmp->getLabelList(list);
1219 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1220 it.nextInset()->getLabelList(*this, list);
1224 // This is also a buffer property (ale)
1225 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1228 /// if this is a child document and the parent is already loaded
1229 /// use the parent's list instead [ale990412]
1230 Buffer const * tmp = getMasterBuffer();
1233 tmp->fillWithBibKeys(keys);
1237 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1238 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1239 InsetBibtex const & inset =
1240 dynamic_cast<InsetBibtex const &>(*it);
1241 inset.fillWithBibKeys(*this, keys);
1242 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1243 InsetInclude const & inset =
1244 dynamic_cast<InsetInclude const &>(*it);
1245 inset.fillWithBibKeys(*this, keys);
1246 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1247 InsetBibitem const & inset =
1248 dynamic_cast<InsetBibitem const &>(*it);
1249 string const key = inset.getContents();
1250 string const opt = inset.getOptions();
1251 string const ref; // = pit->asString(this, false);
1252 string const info = opt + "TheBibliographyRef" + ref;
1253 keys.push_back(pair<string, string>(key, info));
1259 void Buffer::updateBibfilesCache()
1261 // if this is a child document and the parent is already loaded
1262 // update the parent's cache instead
1263 Buffer * tmp = getMasterBuffer();
1266 tmp->updateBibfilesCache();
1270 bibfilesCache_.clear();
1271 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1272 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1273 InsetBibtex const & inset =
1274 dynamic_cast<InsetBibtex const &>(*it);
1275 vector<string> const bibfiles = inset.getFiles(*this);
1276 bibfilesCache_.insert(bibfilesCache_.end(),
1279 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1280 InsetInclude & inset =
1281 dynamic_cast<InsetInclude &>(*it);
1282 inset.updateBibfilesCache(*this);
1283 vector<string> const & bibfiles =
1284 inset.getBibfilesCache(*this);
1285 bibfilesCache_.insert(bibfilesCache_.end(),
1293 vector<string> const & Buffer::getBibfilesCache() const
1295 // if this is a child document and the parent is already loaded
1296 // use the parent's cache instead
1297 Buffer const * tmp = getMasterBuffer();
1300 return tmp->getBibfilesCache();
1302 return bibfilesCache_;
1306 bool Buffer::isDepClean(string const & name) const
1308 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1309 if (it == pimpl_->dep_clean.end())
1315 void Buffer::markDepClean(string const & name)
1317 pimpl_->dep_clean[name] = true;
1321 bool Buffer::dispatch(string const & command, bool * result)
1323 return dispatch(lyxaction.lookupFunc(command), result);
1327 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1329 bool dispatched = true;
1331 switch (func.action) {
1332 case LFUN_BUFFER_EXPORT: {
1333 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1346 void Buffer::changeLanguage(Language const * from, Language const * to)
1351 // Take care of l10n/i18n
1354 for_each(par_iterator_begin(),
1356 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1358 text().current_font.setLanguage(to);
1359 text().real_current_font.setLanguage(to);
1363 void Buffer::updateDocLang(Language const * nlang)
1365 BOOST_ASSERT(nlang);
1367 pimpl_->messages.reset(new Messages(nlang->code()));
1369 updateLabels(*this);
1373 bool Buffer::isMultiLingual() const
1375 ParConstIterator end = par_iterator_end();
1376 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1377 if (it->isMultiLingual(params()))
1384 ParIterator Buffer::getParFromID(int const id) const
1386 ParConstIterator it = par_iterator_begin();
1387 ParConstIterator const end = par_iterator_end();
1390 // John says this is called with id == -1 from undo
1391 lyxerr << "getParFromID(), id: " << id << endl;
1395 for (; it != end; ++it)
1403 bool Buffer::hasParWithID(int const id) const
1405 ParConstIterator const it = getParFromID(id);
1406 return it != par_iterator_end();
1410 ParIterator Buffer::par_iterator_begin()
1412 return lyx::par_iterator_begin(inset());
1416 ParIterator Buffer::par_iterator_end()
1418 return lyx::par_iterator_end(inset());
1422 ParConstIterator Buffer::par_iterator_begin() const
1424 return lyx::par_const_iterator_begin(inset());
1428 ParConstIterator Buffer::par_iterator_end() const
1430 return lyx::par_const_iterator_end(inset());
1434 Language const * Buffer::getLanguage() const
1436 return params().language;
1440 docstring const Buffer::B_(string const & l10n) const
1442 if (pimpl_->messages.get())
1443 return pimpl_->messages->get(l10n);
1449 docstring const Buffer::translateLabel(docstring const & label) const
1451 if (support::isAscii(label))
1452 // Probably standard layout, try to translate
1453 return B_(to_ascii(label));
1455 // This must be a user defined layout. We cannot translate
1456 // this, since gettext accepts only ascii keys.
1461 bool Buffer::isClean() const
1463 return pimpl_->lyx_clean;
1467 bool Buffer::isBakClean() const
1469 return pimpl_->bak_clean;
1473 void Buffer::markClean() const
1475 if (!pimpl_->lyx_clean) {
1476 pimpl_->lyx_clean = true;
1479 // if the .lyx file has been saved, we don't need an
1481 pimpl_->bak_clean = true;
1485 void Buffer::markBakClean()
1487 pimpl_->bak_clean = true;
1491 void Buffer::setUnnamed(bool flag)
1493 pimpl_->unnamed = flag;
1497 bool Buffer::isUnnamed() const
1499 return pimpl_->unnamed;
1503 #ifdef WITH_WARNINGS
1504 #warning this function should be moved to buffer_pimpl.C
1506 void Buffer::markDirty()
1508 if (pimpl_->lyx_clean) {
1509 pimpl_->lyx_clean = false;
1512 pimpl_->bak_clean = false;
1514 DepClean::iterator it = pimpl_->dep_clean.begin();
1515 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1517 for (; it != end; ++it)
1522 string const & Buffer::fileName() const
1524 return pimpl_->filename;
1528 string const & Buffer::filePath() const
1530 return params().filepath;
1534 bool Buffer::isReadonly() const
1536 return pimpl_->read_only;
1540 void Buffer::setParentName(string const & name)
1542 params().parentname = name;
1546 Buffer const * Buffer::getMasterBuffer() const
1548 if (!params().parentname.empty()
1549 && theBufferList().exists(params().parentname)) {
1550 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1552 return buf->getMasterBuffer();
1559 Buffer * Buffer::getMasterBuffer()
1561 if (!params().parentname.empty()
1562 && theBufferList().exists(params().parentname)) {
1563 Buffer * buf = theBufferList().getBuffer(params().parentname);
1565 return buf->getMasterBuffer();
1572 MacroData const & Buffer::getMacro(docstring const & name) const
1574 return pimpl_->macros.get(name);
1578 bool Buffer::hasMacro(docstring const & name) const
1580 return pimpl_->macros.has(name);
1584 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1586 MacroTable::globalMacros().insert(name, data);
1587 pimpl_->macros.insert(name, data);
1591 void Buffer::buildMacros()
1593 // Start with global table.
1594 pimpl_->macros = MacroTable::globalMacros();
1597 ParagraphList const & pars = text().paragraphs();
1598 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1599 //lyxerr << "searching main par " << i
1600 // << " for macro definitions" << std::endl;
1601 InsetList const & insets = pars[i].insetlist;
1602 InsetList::const_iterator it = insets.begin();
1603 InsetList::const_iterator end = insets.end();
1604 for ( ; it != end; ++it) {
1605 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1606 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1607 MathMacroTemplate const & mac
1608 = static_cast<MathMacroTemplate const &>(*it->inset);
1609 insertMacro(mac.name(), mac.asMacroData());
1616 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1623 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1624 InsetBase::Code code)
1626 //FIXME: This does not work for child documents yet.
1627 BOOST_ASSERT(code == InsetBase::CITE_CODE || code == InsetBase::REF_CODE);
1628 // Check if the label 'from' appears more than once
1629 vector<docstring> labels;
1631 if (code == InsetBase::CITE_CODE) {
1632 vector<pair<string, string> > keys;
1633 fillWithBibKeys(keys);
1634 vector<pair<string, string> >::const_iterator bit = keys.begin();
1635 vector<pair<string, string> >::const_iterator bend = keys.end();
1637 for (; bit != bend; ++bit)
1639 labels.push_back(from_utf8(bit->first));
1641 getLabelList(labels);
1643 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1646 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1647 if (it->lyxCode() == code) {
1648 InsetCommand & inset = dynamic_cast<InsetCommand &>(*it);
1649 inset.replaceContents(to_utf8(from), to_utf8(to));
1655 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1656 pit_type par_end, bool full_source)
1658 OutputParams runparams;
1659 runparams.nice = true;
1660 runparams.flavor = OutputParams::LATEX;
1661 runparams.linelen = lyxrc.ascii_linelen;
1662 // No side effect of file copying and image conversion
1663 runparams.dryrun = true;
1665 /* Support for docbook temprarily commented out. */
1667 os << "% Preview source code\n\n";
1669 writeLaTeXSource(os, filePath(), runparams, true, true);
1671 writeDocBookSource(os, fileName(), runparams, false);
1674 runparams.par_begin = par_begin;
1675 runparams.par_end = par_end;
1676 if (par_begin + 1 == par_end)
1677 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1679 os << "% Preview source code from paragraph " << par_begin
1680 << " to " << par_end - 1 << "\n\n";
1681 // output paragraphs
1684 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1687 docbookParagraphs(paragraphs(), *this, os, runparams);
1693 ErrorList const & Buffer::errorList(string const & type) const
1695 static ErrorList const emptyErrorList;
1696 std::map<std::string, ErrorList>::const_iterator I = errorLists_.find(type);
1697 if (I == errorLists_.end())
1698 return emptyErrorList;
1704 ErrorList & Buffer::errorList(string const & type)
1706 return errorLists_[type];