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::getFormatFromContents;
105 using support::isDirWriteable;
106 using support::libFileSearch;
107 using support::latex_path;
108 using support::ltrim;
109 using support::makeAbsPath;
110 using support::makeDisplayPath;
111 using support::makeLatexName;
112 using support::onlyFilename;
113 using support::onlyPath;
114 using support::quoteName;
115 using support::removeAutosaveFile;
116 using support::rename;
117 using support::runCommand;
118 using support::split;
119 using support::subst;
120 using support::tempName;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
125 namespace fs = boost::filesystem;
126 namespace io = boost::iostreams;
130 using std::make_pair;
136 using std::ostringstream;
146 int const LYX_FORMAT = 254;
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: "
463 from_utf8(lex.getString()));
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 string const format = getFormatFromContents(filename);
575 if (format == "gzip" || format == "zip" || format == "compress") {
576 params().compressed = true;
579 // remove dummy empty par
580 paragraphs().clear();
582 lex.setFile(filename);
583 if (!readFile(lex, filename))
586 // After we have read a file, we must ensure that the buffer
587 // language is set and used in the gui.
588 // If you know of a better place to put this, please tell me. (Lgb)
589 updateDocLang(params().language);
595 bool Buffer::fully_loaded() const
597 return pimpl_->file_fully_loaded;
601 void Buffer::fully_loaded(bool const value)
603 pimpl_->file_fully_loaded = value;
607 bool Buffer::readFile(LyXLex & lex, string const & filename)
609 BOOST_ASSERT(!filename.empty());
612 Alert::error(_("Document could not be read"),
613 bformat(_("%1$s could not be read."), from_utf8(filename)));
618 string const token(lex.getString());
621 Alert::error(_("Document could not be read"),
622 bformat(_("%1$s could not be read."), from_utf8(filename)));
626 // the first token _must_ be...
627 if (token != "\\lyxformat") {
628 lyxerr << "Token: " << token << endl;
630 Alert::error(_("Document format failure"),
631 bformat(_("%1$s is not a LyX document."),
632 from_utf8(filename)));
637 string tmp_format = lex.getString();
638 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
639 // if present remove ".," from string.
640 string::size_type dot = tmp_format.find_first_of(".,");
641 //lyxerr << " dot found at " << dot << endl;
642 if (dot != string::npos)
643 tmp_format.erase(dot, 1);
644 int const file_format = convert<int>(tmp_format);
645 //lyxerr << "format: " << file_format << endl;
647 if (file_format != LYX_FORMAT) {
648 string const tmpfile = tempName();
649 if (tmpfile.empty()) {
650 Alert::error(_("Conversion failed"),
651 bformat(_("%1$s is from an earlier"
652 " version of LyX, but a temporary"
653 " file for converting it could"
655 from_utf8(filename)));
658 string const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
659 if (lyx2lyx.empty()) {
660 Alert::error(_("Conversion script not found"),
661 bformat(_("%1$s is from an earlier"
662 " version of LyX, but the"
663 " conversion script lyx2lyx"
664 " could not be found."),
665 from_utf8(filename)));
668 ostringstream command;
669 command << os::python() << ' ' << quoteName(lyx2lyx)
670 << " -t " << convert<string>(LYX_FORMAT)
671 << " -o " << quoteName(tmpfile) << ' '
672 << quoteName(filename);
673 string const command_str = command.str();
675 lyxerr[Debug::INFO] << "Running '"
676 << command_str << '\''
679 cmd_ret const ret = runCommand(command_str);
680 if (ret.first != 0) {
681 Alert::error(_("Conversion script failed"),
682 bformat(_("%1$s is from an earlier version"
683 " of LyX, but the lyx2lyx script"
684 " failed to convert it."),
685 from_utf8(filename)));
688 bool const ret = readFile(tmpfile);
689 // Do stuff with tmpfile name and buffer name here.
695 if (readDocument(lex)) {
696 Alert::error(_("Document format failure"),
697 bformat(_("%1$s ended unexpectedly, which means"
698 " that it is probably corrupted."),
699 from_utf8(filename)));
702 //lyxerr << "removing " << MacroTable::localMacros().size()
703 // << " temporary macro entries" << endl;
704 //MacroTable::localMacros().clear();
706 pimpl_->file_fully_loaded = true;
711 // Should probably be moved to somewhere else: BufferView? LyXView?
712 bool Buffer::save() const
714 // We don't need autosaves in the immediate future. (Asger)
715 resetAutosaveTimers();
719 if (lyxrc.make_backup) {
720 s = fileName() + '~';
721 if (!lyxrc.backupdir_path.empty())
722 s = addName(lyxrc.backupdir_path,
723 subst(os::internal_path(s),'/','!'));
725 // It might very well be that this variant is just
726 // good enough. (Lgb)
727 // But to use this we need fs::copy_file to actually do a copy,
728 // even when the target file exists. (Lgb)
730 fs::copy_file(fileName(), s, false);
732 catch (fs::filesystem_error const & fe) {
733 Alert::error(_("Backup failure"),
734 bformat(_("LyX was not able to make a backup copy in %1$s.\n"
735 "Please check if the directory exists and is writeable."),
736 from_utf8(fs::path(s).branch_path().native_directory_string())));
737 lyxerr[Debug::DEBUG] << "Fs error: "
738 << fe.what() << endl;
742 if (writeFile(fileName())) {
744 removeAutosaveFile(fileName());
746 // Saving failed, so backup is not backup
747 if (lyxrc.make_backup)
748 rename(s, fileName());
755 bool Buffer::writeFile(string const & fname) const
757 if (pimpl_->read_only && fname == fileName())
762 if (params().compressed) {
763 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname));
767 retval = do_writeFile(ofs);
769 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
773 retval = do_writeFile(ofs);
780 bool Buffer::do_writeFile(ostream & ofs) const
783 // Use the standard "C" locale for file output.
784 ofs.imbue(std::locale::classic());
787 // The top of the file should not be written by params().
789 // write out a comment in the top of the file
790 ofs << "#LyX " << lyx_version
791 << " created this file. For more info see http://www.lyx.org/\n"
792 << "\\lyxformat " << LYX_FORMAT << "\n"
793 << "\\begin_document\n";
795 // now write out the buffer parameters.
796 ofs << "\\begin_header\n";
797 params().writeFile(ofs);
798 ofs << "\\end_header\n";
801 ofs << "\n\\begin_body\n";
802 text().write(*this, ofs);
803 ofs << "\n\\end_body\n";
805 // Write marker that shows file is complete
806 ofs << "\\end_document" << endl;
808 // Shouldn't really be needed....
811 // how to check if close went ok?
812 // Following is an attempt... (BE 20001011)
814 // good() returns false if any error occured, including some
816 // bad() returns true if something bad happened in the buffer,
817 // which should include file system full errors.
822 lyxerr << "File was not closed properly." << endl;
829 bool Buffer::makeLaTeXFile(string const & fname,
830 string const & original_path,
831 OutputParams const & runparams,
832 bool output_preamble, bool output_body)
835 if (params().inputenc == "auto")
836 encoding = params().language->encoding()->iconvName();
838 Encoding const * enc = encodings.getFromLaTeXName(params().inputenc);
840 encoding = enc->iconvName();
842 lyxerr << "Unknown inputenc value `"
844 << "'. Using `auto' instead." << endl;
845 encoding = params().language->encoding()->iconvName();
848 lyxerr[Debug::LATEX] << "makeLaTeXFile encoding: "
849 << encoding << "..." << endl;
851 odocfstream ofs(encoding);
852 if (!openFileWrite(ofs, fname))
856 writeLaTeXSource(ofs, original_path,
857 runparams, output_preamble, output_body);
859 catch (iconv_codecvt_facet_exception &) {
860 Alert::error(_("Encoding error"),
861 _("Some characters of your document are not "
862 "representable in the chosen encoding.\n"
863 "Changing the document encoding to utf8 could help."));
869 lyxerr << "File '" << fname << "' was not closed properly." << endl;
870 Alert::error(_("Error closing file"),
871 _("The output file could not be closed properly.\n"
872 " Probably some characters of your document are not "
873 "representable in the chosen encoding.\n"
874 "Changing the document encoding to utf8 could help."));
881 void Buffer::writeLaTeXSource(odocstream & os,
882 string const & original_path,
883 OutputParams const & runparams_in,
884 bool const output_preamble, bool const output_body)
886 OutputParams runparams = runparams_in;
888 // validate the buffer.
889 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
890 LaTeXFeatures features(*this, params(), runparams);
892 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
896 // The starting paragraph of the coming rows is the
897 // first paragraph of the document. (Asger)
898 texrow().start(paragraphs().begin()->id(), 0);
900 if (output_preamble && runparams.nice) {
901 os << "%% LyX " << lyx_version << " created this file. "
902 "For more info, see http://www.lyx.org/.\n"
903 "%% Do not edit unless you really know what "
908 lyxerr[Debug::INFO] << "lyx document header finished" << endl;
909 // There are a few differences between nice LaTeX and usual files:
910 // usual is \batchmode and has a
911 // special input@path to allow the including of figures
912 // with either \input or \includegraphics (what figinsets do).
913 // input@path is set when the actual parameter
914 // original_path is set. This is done for usual tex-file, but not
915 // for nice-latex-file. (Matthias 250696)
916 // Note that input@path is only needed for something the user does
917 // in the preamble, included .tex files or ERT, files included by
918 // LyX work without it.
919 if (output_preamble) {
920 if (!runparams.nice) {
921 // code for usual, NOT nice-latex-file
922 os << "\\batchmode\n"; // changed
926 if (!original_path.empty()) {
928 // We don't know the encoding of inputpath
929 docstring const inputpath = from_utf8(latex_path(original_path));
930 os << "\\makeatletter\n"
931 << "\\def\\input@path{{"
932 << inputpath << "/}}\n"
933 << "\\makeatother\n";
939 // Write the preamble
940 runparams.use_babel = params().writeLaTeX(os, features, texrow());
946 os << "\\begin{document}\n";
949 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
951 if (!lyxrc.language_auto_begin) {
953 os << from_utf8(subst(lyxrc.language_command_begin,
955 params().language->babel()))
960 // if we are doing a real file with body, even if this is the
961 // child of some other buffer, let's cut the link here.
962 // This happens for example if only a child document is printed.
963 string save_parentname;
964 if (output_preamble) {
965 save_parentname = params().parentname;
966 params().parentname.erase();
970 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
972 // Restore the parenthood if needed
974 params().parentname = save_parentname;
976 // add this just in case after all the paragraphs
980 if (!lyxrc.language_auto_end) {
981 os << from_utf8(subst(lyxrc.language_command_end,
983 params().language->babel()))
988 if (output_preamble) {
989 os << "\\end{document}\n";
992 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
994 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
998 // Just to be sure. (Asger)
1001 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1002 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1007 bool Buffer::isLatex() const
1009 return params().getLyXTextClass().outputType() == LATEX;
1013 bool Buffer::isLiterate() const
1015 return params().getLyXTextClass().outputType() == LITERATE;
1019 bool Buffer::isDocBook() const
1021 return params().getLyXTextClass().outputType() == DOCBOOK;
1025 void Buffer::makeDocBookFile(string const & fname,
1026 OutputParams const & runparams,
1027 bool const body_only)
1029 lyxerr[Debug::LATEX] << "makeDocBookFile..." << endl;
1033 if (!openFileWrite(ofs, fname))
1036 writeDocBookSource(ofs, fname, runparams, body_only);
1040 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1044 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1045 OutputParams const & runparams,
1046 bool const only_body)
1048 LaTeXFeatures features(*this, params(), runparams);
1053 LyXTextClass const & tclass = params().getLyXTextClass();
1054 string const top_element = tclass.latexname();
1057 if (runparams.flavor == OutputParams::XML)
1058 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1061 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1064 if (! tclass.class_header().empty())
1065 os << from_ascii(tclass.class_header());
1066 else if (runparams.flavor == OutputParams::XML)
1067 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1068 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1070 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1072 docstring preamble = from_utf8(params().preamble);
1073 if (runparams.flavor != OutputParams::XML ) {
1074 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1075 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1076 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1077 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1080 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1082 preamble += features.getIncludedFiles(name);
1083 preamble += features.getLyXSGMLEntities();
1085 if (!preamble.empty()) {
1086 os << "\n [ " << preamble << " ]";
1091 string top = top_element;
1093 if (runparams.flavor == OutputParams::XML)
1094 top += params().language->code();
1096 top += params().language->code().substr(0,2);
1099 if (!params().options.empty()) {
1101 top += params().options;
1104 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1105 << " file was created by LyX " << lyx_version
1106 << "\n See http://www.lyx.org/ for more information -->\n";
1108 params().getLyXTextClass().counters().reset();
1110 sgml::openTag(os, top);
1112 docbookParagraphs(paragraphs(), *this, os, runparams);
1113 sgml::closeTag(os, top_element);
1117 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1118 // Other flags: -wall -v0 -x
1119 int Buffer::runChktex()
1123 // get LaTeX-Filename
1124 string const name = getLatexName();
1125 string const path = temppath();
1126 string const org_path = filePath();
1128 support::Path p(path); // path to LaTeX file
1129 message(_("Running chktex..."));
1131 // Generate the LaTeX file if neccessary
1132 OutputParams runparams;
1133 runparams.flavor = OutputParams::LATEX;
1134 runparams.nice = false;
1135 makeLaTeXFile(name, org_path, runparams);
1138 Chktex chktex(lyxrc.chktex_command, name, filePath());
1139 int const res = chktex.run(terr); // run chktex
1142 Alert::error(_("chktex failure"),
1143 _("Could not run chktex successfully."));
1144 } else if (res > 0) {
1145 // Fill-in the error list with the TeX errors
1146 bufferErrors(*this, terr, errorLists_["ChkTex"]);
1157 void Buffer::validate(LaTeXFeatures & features) const
1159 LyXTextClass const & tclass = params().getLyXTextClass();
1161 if (features.isAvailable("dvipost") && params().outputChanges)
1162 features.require("dvipost");
1164 // AMS Style is at document level
1165 if (params().use_amsmath == BufferParams::package_on
1166 || tclass.provides(LyXTextClass::amsmath))
1167 features.require("amsmath");
1168 if (params().use_esint == BufferParams::package_on)
1169 features.require("esint");
1171 for_each(paragraphs().begin(), paragraphs().end(),
1172 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1174 // the bullet shapes are buffer level not paragraph level
1175 // so they are tested here
1176 for (int i = 0; i < 4; ++i) {
1177 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1178 int const font = params().user_defined_bullet(i).getFont();
1180 int const c = params()
1181 .user_defined_bullet(i)
1188 features.require("latexsym");
1190 } else if (font == 1) {
1191 features.require("amssymb");
1192 } else if ((font >= 2 && font <= 5)) {
1193 features.require("pifont");
1198 if (lyxerr.debugging(Debug::LATEX)) {
1199 features.showStruct();
1204 void Buffer::getLabelList(vector<docstring> & list) const
1206 /// if this is a child document and the parent is already loaded
1207 /// Use the parent's list instead [ale990407]
1208 Buffer const * tmp = getMasterBuffer();
1210 lyxerr << "getMasterBuffer() failed!" << endl;
1214 tmp->getLabelList(list);
1218 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1219 it.nextInset()->getLabelList(*this, list);
1223 // This is also a buffer property (ale)
1224 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1227 /// if this is a child document and the parent is already loaded
1228 /// use the parent's list instead [ale990412]
1229 Buffer const * tmp = getMasterBuffer();
1232 tmp->fillWithBibKeys(keys);
1236 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1237 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1238 InsetBibtex const & inset =
1239 dynamic_cast<InsetBibtex const &>(*it);
1240 inset.fillWithBibKeys(*this, keys);
1241 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1242 InsetInclude const & inset =
1243 dynamic_cast<InsetInclude const &>(*it);
1244 inset.fillWithBibKeys(*this, keys);
1245 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1246 InsetBibitem const & inset =
1247 dynamic_cast<InsetBibitem const &>(*it);
1248 string const key = inset.getContents();
1249 string const opt = inset.getOptions();
1250 string const ref; // = pit->asString(this, false);
1251 string const info = opt + "TheBibliographyRef" + ref;
1252 keys.push_back(pair<string, string>(key, info));
1258 void Buffer::updateBibfilesCache()
1260 // if this is a child document and the parent is already loaded
1261 // update the parent's cache instead
1262 Buffer * tmp = getMasterBuffer();
1265 tmp->updateBibfilesCache();
1269 bibfilesCache_.clear();
1270 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1271 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1272 InsetBibtex const & inset =
1273 dynamic_cast<InsetBibtex const &>(*it);
1274 vector<string> const bibfiles = inset.getFiles(*this);
1275 bibfilesCache_.insert(bibfilesCache_.end(),
1278 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1279 InsetInclude & inset =
1280 dynamic_cast<InsetInclude &>(*it);
1281 inset.updateBibfilesCache(*this);
1282 vector<string> const & bibfiles =
1283 inset.getBibfilesCache(*this);
1284 bibfilesCache_.insert(bibfilesCache_.end(),
1292 vector<string> const & Buffer::getBibfilesCache() const
1294 // if this is a child document and the parent is already loaded
1295 // use the parent's cache instead
1296 Buffer const * tmp = getMasterBuffer();
1299 return tmp->getBibfilesCache();
1301 return bibfilesCache_;
1305 bool Buffer::isDepClean(string const & name) const
1307 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1308 if (it == pimpl_->dep_clean.end())
1314 void Buffer::markDepClean(string const & name)
1316 pimpl_->dep_clean[name] = true;
1320 bool Buffer::dispatch(string const & command, bool * result)
1322 return dispatch(lyxaction.lookupFunc(command), result);
1326 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1328 bool dispatched = true;
1330 switch (func.action) {
1331 case LFUN_BUFFER_EXPORT: {
1332 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1345 void Buffer::changeLanguage(Language const * from, Language const * to)
1350 // Take care of l10n/i18n
1353 for_each(par_iterator_begin(),
1355 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1357 text().current_font.setLanguage(to);
1358 text().real_current_font.setLanguage(to);
1362 void Buffer::updateDocLang(Language const * nlang)
1364 BOOST_ASSERT(nlang);
1366 pimpl_->messages.reset(new Messages(nlang->code()));
1368 updateLabels(*this);
1372 bool Buffer::isMultiLingual() const
1374 ParConstIterator end = par_iterator_end();
1375 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1376 if (it->isMultiLingual(params()))
1383 ParIterator Buffer::getParFromID(int const id) const
1385 ParConstIterator it = par_iterator_begin();
1386 ParConstIterator const end = par_iterator_end();
1389 // John says this is called with id == -1 from undo
1390 lyxerr << "getParFromID(), id: " << id << endl;
1394 for (; it != end; ++it)
1402 bool Buffer::hasParWithID(int const id) const
1404 ParConstIterator const it = getParFromID(id);
1405 return it != par_iterator_end();
1409 ParIterator Buffer::par_iterator_begin()
1411 return lyx::par_iterator_begin(inset());
1415 ParIterator Buffer::par_iterator_end()
1417 return lyx::par_iterator_end(inset());
1421 ParConstIterator Buffer::par_iterator_begin() const
1423 return lyx::par_const_iterator_begin(inset());
1427 ParConstIterator Buffer::par_iterator_end() const
1429 return lyx::par_const_iterator_end(inset());
1433 Language const * Buffer::getLanguage() const
1435 return params().language;
1439 docstring const Buffer::B_(string const & l10n) const
1441 if (pimpl_->messages.get())
1442 return pimpl_->messages->get(l10n);
1448 docstring const Buffer::translateLabel(docstring const & label) const
1450 if (support::isAscii(label))
1451 // Probably standard layout, try to translate
1452 return B_(to_ascii(label));
1454 // This must be a user defined layout. We cannot translate
1455 // this, since gettext accepts only ascii keys.
1460 bool Buffer::isClean() const
1462 return pimpl_->lyx_clean;
1466 bool Buffer::isBakClean() const
1468 return pimpl_->bak_clean;
1472 void Buffer::markClean() const
1474 if (!pimpl_->lyx_clean) {
1475 pimpl_->lyx_clean = true;
1478 // if the .lyx file has been saved, we don't need an
1480 pimpl_->bak_clean = true;
1484 void Buffer::markBakClean()
1486 pimpl_->bak_clean = true;
1490 void Buffer::setUnnamed(bool flag)
1492 pimpl_->unnamed = flag;
1496 bool Buffer::isUnnamed() const
1498 return pimpl_->unnamed;
1502 #ifdef WITH_WARNINGS
1503 #warning this function should be moved to buffer_pimpl.C
1505 void Buffer::markDirty()
1507 if (pimpl_->lyx_clean) {
1508 pimpl_->lyx_clean = false;
1511 pimpl_->bak_clean = false;
1513 DepClean::iterator it = pimpl_->dep_clean.begin();
1514 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1516 for (; it != end; ++it)
1521 string const & Buffer::fileName() const
1523 return pimpl_->filename;
1527 string const & Buffer::filePath() const
1529 return params().filepath;
1533 bool Buffer::isReadonly() const
1535 return pimpl_->read_only;
1539 void Buffer::setParentName(string const & name)
1541 params().parentname = name;
1545 Buffer const * Buffer::getMasterBuffer() const
1547 if (!params().parentname.empty()
1548 && theBufferList().exists(params().parentname)) {
1549 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1551 return buf->getMasterBuffer();
1558 Buffer * Buffer::getMasterBuffer()
1560 if (!params().parentname.empty()
1561 && theBufferList().exists(params().parentname)) {
1562 Buffer * buf = theBufferList().getBuffer(params().parentname);
1564 return buf->getMasterBuffer();
1571 MacroData const & Buffer::getMacro(docstring const & name) const
1573 return pimpl_->macros.get(name);
1577 bool Buffer::hasMacro(docstring const & name) const
1579 return pimpl_->macros.has(name);
1583 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1585 MacroTable::globalMacros().insert(name, data);
1586 pimpl_->macros.insert(name, data);
1590 void Buffer::buildMacros()
1592 // Start with global table.
1593 pimpl_->macros = MacroTable::globalMacros();
1596 ParagraphList const & pars = text().paragraphs();
1597 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1598 //lyxerr << "searching main par " << i
1599 // << " for macro definitions" << std::endl;
1600 InsetList const & insets = pars[i].insetlist;
1601 InsetList::const_iterator it = insets.begin();
1602 InsetList::const_iterator end = insets.end();
1603 for ( ; it != end; ++it) {
1604 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1605 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1606 MathMacroTemplate const & mac
1607 = static_cast<MathMacroTemplate const &>(*it->inset);
1608 insertMacro(mac.name(), mac.asMacroData());
1615 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1622 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1623 InsetBase::Code code)
1625 //FIXME: This does not work for child documents yet.
1626 BOOST_ASSERT(code == InsetBase::CITE_CODE || code == InsetBase::REF_CODE);
1627 // Check if the label 'from' appears more than once
1628 vector<docstring> labels;
1630 if (code == InsetBase::CITE_CODE) {
1631 vector<pair<string, string> > keys;
1632 fillWithBibKeys(keys);
1633 vector<pair<string, string> >::const_iterator bit = keys.begin();
1634 vector<pair<string, string> >::const_iterator bend = keys.end();
1636 for (; bit != bend; ++bit)
1638 labels.push_back(from_utf8(bit->first));
1640 getLabelList(labels);
1642 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1645 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1646 if (it->lyxCode() == code) {
1647 InsetCommand & inset = dynamic_cast<InsetCommand &>(*it);
1648 inset.replaceContents(to_utf8(from), to_utf8(to));
1654 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1655 pit_type par_end, bool full_source)
1657 OutputParams runparams;
1658 runparams.nice = true;
1659 runparams.flavor = OutputParams::LATEX;
1660 runparams.linelen = lyxrc.ascii_linelen;
1661 // No side effect of file copying and image conversion
1662 runparams.dryrun = true;
1664 /* Support for docbook temprarily commented out. */
1666 os << "% Preview source code\n\n";
1668 writeLaTeXSource(os, filePath(), runparams, true, true);
1670 writeDocBookSource(os, fileName(), runparams, false);
1673 runparams.par_begin = par_begin;
1674 runparams.par_end = par_end;
1675 if (par_begin + 1 == par_end)
1676 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1678 os << "% Preview source code from paragraph " << par_begin
1679 << " to " << par_end - 1 << "\n\n";
1680 // output paragraphs
1683 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1686 docbookParagraphs(paragraphs(), *this, os, runparams);
1692 ErrorList const & Buffer::errorList(string const & type) const
1694 static ErrorList const emptyErrorList;
1695 std::map<std::string, ErrorList>::const_iterator I = errorLists_.find(type);
1696 if (I == errorLists_.end())
1697 return emptyErrorList;
1703 ErrorList & Buffer::errorList(string const & type)
1705 return errorLists_[type];