3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
16 #include "BranchList.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
25 #include "ErrorList.h"
28 #include "FuncRequest.h"
30 #include "InsetIterator.h"
33 #include "LaTeXFeatures.h"
34 #include "LyXAction.h"
41 #include "output_docbook.h"
42 #include "output_latex.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "TocBackend.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetBibtex.h"
55 #include "insets/InsetInclude.h"
56 #include "insets/InsetText.h"
58 #include "mathed/MathMacroTemplate.h"
59 #include "mathed/MacroTable.h"
60 #include "mathed/MathSupport.h"
62 #include "frontends/alert.h"
64 #include "graphics/Previews.h"
66 #include "support/types.h"
67 #include "support/lyxalgo.h"
68 #include "support/filetools.h"
69 #include "support/fs_extras.h"
70 #include "support/lyxlib.h"
71 #include "support/os.h"
72 #include "support/Path.h"
73 #include "support/textutils.h"
74 #include "support/convert.h"
76 #include <boost/iostreams/filtering_stream.hpp>
77 #include <boost/iostreams/filter/gzip.hpp>
78 #include <boost/iostreams/device/file.hpp>
79 #include <boost/bind.hpp>
80 #include <boost/filesystem/exception.hpp>
81 #include <boost/filesystem/operations.hpp>
83 #if defined (HAVE_UTIME_H)
85 #elif defined (HAVE_SYS_UTIME_H)
86 #include <sys/utime.h>
97 using support::addName;
98 using support::bformat;
99 using support::changeExtension;
100 using support::cmd_ret;
101 using support::createBufferTmpDir;
102 using support::destroyDir;
103 using support::FileName;
104 using support::getFormatFromContents;
105 using support::libFileSearch;
106 using support::latex_path;
107 using support::ltrim;
108 using support::makeAbsPath;
109 using support::makeDisplayPath;
110 using support::makeLatexName;
111 using support::onlyFilename;
112 using support::onlyPath;
113 using support::quoteName;
114 using support::removeAutosaveFile;
115 using support::rename;
116 using support::runCommand;
117 using support::split;
118 using support::subst;
119 using support::tempName;
122 namespace Alert = frontend::Alert;
123 namespace os = support::os;
124 namespace fs = boost::filesystem;
125 namespace io = boost::iostreams;
129 using std::make_pair;
134 using std::ostringstream;
144 int const LYX_FORMAT = 269;
149 typedef std::map<string, bool> DepClean;
154 Impl(Buffer & parent, FileName const & file, bool readonly);
156 limited_stack<Undo> undostack;
157 limited_stack<Undo> redostack;
163 /// need to regenerate .tex?
167 mutable bool lyx_clean;
169 /// is autosave needed?
170 mutable bool bak_clean;
172 /// is this a unnamed file (New...)?
178 /// name of the file the buffer is associated with.
181 /** Set to true only when the file is fully loaded.
182 * Used to prevent the premature generation of previews
183 * and by the citation inset.
185 bool file_fully_loaded;
187 /// our Text that should be wrapped in an InsetText
194 TocBackend toc_backend;
198 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
199 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
200 filename(file), file_fully_loaded(false), inset(params),
203 inset.setAutoBreakRows(true);
204 lyxvc.buffer(&parent);
205 temppath = createBufferTmpDir();
206 params.filepath = onlyPath(file.absFilename());
207 // FIXME: And now do something if temppath == string(), because we
208 // assume from now on that temppath points to a valid temp dir.
209 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
213 Buffer::Buffer(string const & file, bool readonly)
214 : pimpl_(new Impl(*this, FileName(file), readonly))
216 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
222 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
223 // here the buffer should take care that it is
224 // saved properly, before it goes into the void.
228 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
229 Alert::warning(_("Could not remove temporary directory"),
230 bformat(_("Could not remove the temporary directory %1$s"),
231 from_utf8(temppath())));
234 // Remove any previewed LaTeX snippets associated with this buffer.
235 graphics::Previews::get().removeLoader(*this);
239 Text & Buffer::text() const
241 return const_cast<Text &>(pimpl_->inset.text_);
245 Inset & Buffer::inset() const
247 return const_cast<InsetText &>(pimpl_->inset);
251 limited_stack<Undo> & Buffer::undostack()
253 return pimpl_->undostack;
257 limited_stack<Undo> const & Buffer::undostack() const
259 return pimpl_->undostack;
263 limited_stack<Undo> & Buffer::redostack()
265 return pimpl_->redostack;
269 limited_stack<Undo> const & Buffer::redostack() const
271 return pimpl_->redostack;
275 BufferParams & Buffer::params()
277 return pimpl_->params;
281 BufferParams const & Buffer::params() const
283 return pimpl_->params;
287 ParagraphList & Buffer::paragraphs()
289 return text().paragraphs();
293 ParagraphList const & Buffer::paragraphs() const
295 return text().paragraphs();
299 LyXVC & Buffer::lyxvc()
301 return pimpl_->lyxvc;
305 LyXVC const & Buffer::lyxvc() const
307 return pimpl_->lyxvc;
311 string const & Buffer::temppath() const
313 return pimpl_->temppath;
317 TexRow & Buffer::texrow()
319 return pimpl_->texrow;
323 TexRow const & Buffer::texrow() const
325 return pimpl_->texrow;
329 TocBackend & Buffer::tocBackend()
331 return pimpl_->toc_backend;
335 TocBackend const & Buffer::tocBackend() const
337 return pimpl_->toc_backend;
341 string const Buffer::getLatexName(bool const no_path) const
343 string const name = changeExtension(makeLatexName(fileName()), ".tex");
344 return no_path ? onlyFilename(name) : name;
348 pair<Buffer::LogType, string> const Buffer::getLogName() const
350 string const filename = getLatexName(false);
352 if (filename.empty())
353 return make_pair(Buffer::latexlog, string());
355 string const path = temppath();
357 FileName const fname(addName(temppath(),
358 onlyFilename(changeExtension(filename,
360 FileName const bname(
361 addName(path, onlyFilename(
362 changeExtension(filename,
363 formats.extension("literate") + ".out"))));
365 // If no Latex log or Build log is newer, show Build log
367 if (fs::exists(bname.toFilesystemEncoding()) &&
368 (!fs::exists(fname.toFilesystemEncoding()) ||
369 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
370 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
371 return make_pair(Buffer::buildlog, bname.absFilename());
373 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
374 return make_pair(Buffer::latexlog, fname.absFilename());
378 void Buffer::setReadonly(bool const flag)
380 if (pimpl_->read_only != flag) {
381 pimpl_->read_only = flag;
387 void Buffer::setFileName(string const & newfile)
389 pimpl_->filename = makeAbsPath(newfile);
390 params().filepath = onlyPath(pimpl_->filename.absFilename());
391 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
396 // We'll remove this later. (Lgb)
399 void unknownClass(string const & unknown)
401 Alert::warning(_("Unknown document class"),
402 bformat(_("Using the default document class, because the "
403 "class %1$s is unknown."), from_utf8(unknown)));
409 int Buffer::readHeader(Lexer & lex)
411 int unknown_tokens = 0;
413 int begin_header_line = -1;
415 // Initialize parameters that may be/go lacking in header:
416 params().branchlist().clear();
417 params().preamble.erase();
418 params().options.erase();
419 params().float_placement.erase();
420 params().paperwidth.erase();
421 params().paperheight.erase();
422 params().leftmargin.erase();
423 params().rightmargin.erase();
424 params().topmargin.erase();
425 params().bottommargin.erase();
426 params().headheight.erase();
427 params().headsep.erase();
428 params().footskip.erase();
429 for (int i = 0; i < 4; ++i) {
430 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
431 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
434 ErrorList & errorList = errorLists_["Parse"];
438 string const token = lex.getString();
443 if (token == "\\end_header")
447 if (token == "\\begin_header") {
448 begin_header_line = line;
452 LYXERR(Debug::PARSER) << "Handling document header token: `"
453 << token << '\'' << endl;
455 string unknown = params().readToken(lex, token);
456 if (!unknown.empty()) {
457 if (unknown[0] != '\\' && token == "\\textclass") {
458 unknownClass(unknown);
461 docstring const s = bformat(_("Unknown token: "
465 errorList.push_back(ErrorItem(_("Document header error"),
470 if (begin_header_line) {
471 docstring const s = _("\\begin_header is missing");
472 errorList.push_back(ErrorItem(_("Document header error"),
476 return unknown_tokens;
481 // changed to be public and have one parameter
482 // Returns false if "\end_document" is not read (Asger)
483 bool Buffer::readDocument(Lexer & lex)
485 ErrorList & errorList = errorLists_["Parse"];
489 string const token = lex.getString();
490 if (token != "\\begin_document") {
491 docstring const s = _("\\begin_document is missing");
492 errorList.push_back(ErrorItem(_("Document header error"),
496 // we are reading in a brand new document
497 BOOST_ASSERT(paragraphs().empty());
500 if (!params().getTextClass().load(filePath())) {
501 string theclass = params().getTextClass().name();
502 Alert::error(_("Can't load document class"), bformat(
503 _("Using the default document class, because the "
504 "class %1$s could not be loaded."), from_utf8(theclass)));
505 params().textclass = 0;
508 if (params().outputChanges) {
509 if (!LaTeXFeatures::isAvailable("dvipost")) {
510 Alert::warning(_("Changes not shown in LaTeX output"),
511 _("Changes will not be highlighted in LaTeX output, "
512 "because dvipost is not installed.\n"
513 "If you are familiar with TeX, consider redefining "
514 "\\lyxinserted and \\lyxdeleted in the LaTeX preamble."));
516 Alert::warning(_("Changes not shown in LaTeX output"),
517 _("Changes will not be highlighted in LaTeX output "
518 "when using pdflatex.\n"
519 "If you are familiar with TeX, consider redefining "
520 "\\lyxinserted and \\lyxdeleted in the LaTeX preamble."));
524 bool const res = text().read(*this, lex, errorList);
525 for_each(text().paragraphs().begin(),
526 text().paragraphs().end(),
527 bind(&Paragraph::setInsetOwner, _1, &inset()));
533 // needed to insert the selection
534 void Buffer::insertStringAsLines(ParagraphList & pars,
535 pit_type & pit, pos_type & pos,
536 Font const & fn, docstring const & str, bool autobreakrows)
540 // insert the string, don't insert doublespace
541 bool space_inserted = true;
542 for (docstring::const_iterator cit = str.begin();
543 cit != str.end(); ++cit) {
544 Paragraph & par = pars[pit];
546 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
547 breakParagraph(params(), pars, pit, pos,
548 par.layout()->isEnvironment());
551 space_inserted = true;
555 // do not insert consecutive spaces if !free_spacing
556 } else if ((*cit == ' ' || *cit == '\t') &&
557 space_inserted && !par.isFreeSpacing()) {
559 } else if (*cit == '\t') {
560 if (!par.isFreeSpacing()) {
561 // tabs are like spaces here
562 par.insertChar(pos, ' ', font, params().trackChanges);
564 space_inserted = true;
566 const pos_type n = 8 - pos % 8;
567 for (pos_type i = 0; i < n; ++i) {
568 par.insertChar(pos, ' ', font, params().trackChanges);
571 space_inserted = true;
573 } else if (!isPrintable(*cit)) {
574 // Ignore unprintables
577 // just insert the character
578 par.insertChar(pos, *cit, font, params().trackChanges);
580 space_inserted = (*cit == ' ');
587 bool Buffer::readString(std::string const & s)
589 params().compressed = false;
591 // remove dummy empty par
592 paragraphs().clear();
594 std::istringstream is(s);
596 FileName const name(tempName());
597 switch (readFile(lex, name, true)) {
601 // We need to call lyx2lyx, so write the input to a file
602 std::ofstream os(name.toFilesystemEncoding().c_str());
605 return readFile(name);
615 bool Buffer::readFile(FileName const & filename)
617 // Check if the file is compressed.
618 string const format = getFormatFromContents(filename);
619 if (format == "gzip" || format == "zip" || format == "compress") {
620 params().compressed = true;
623 // remove dummy empty par
624 paragraphs().clear();
626 lex.setFile(filename);
627 if (readFile(lex, filename) != success)
634 bool Buffer::fully_loaded() const
636 return pimpl_->file_fully_loaded;
640 void Buffer::fully_loaded(bool const value)
642 pimpl_->file_fully_loaded = value;
646 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
649 BOOST_ASSERT(!filename.empty());
652 Alert::error(_("Document could not be read"),
653 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
658 string const token(lex.getString());
661 Alert::error(_("Document could not be read"),
662 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
666 // the first token _must_ be...
667 if (token != "\\lyxformat") {
668 lyxerr << "Token: " << token << endl;
670 Alert::error(_("Document format failure"),
671 bformat(_("%1$s is not a LyX document."),
672 from_utf8(filename.absFilename())));
677 string tmp_format = lex.getString();
678 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
679 // if present remove ".," from string.
680 string::size_type dot = tmp_format.find_first_of(".,");
681 //lyxerr << " dot found at " << dot << endl;
682 if (dot != string::npos)
683 tmp_format.erase(dot, 1);
684 int const file_format = convert<int>(tmp_format);
685 //lyxerr << "format: " << file_format << endl;
687 if (file_format != LYX_FORMAT) {
690 // lyx2lyx would fail
693 FileName const tmpfile(tempName());
694 if (tmpfile.empty()) {
695 Alert::error(_("Conversion failed"),
696 bformat(_("%1$s is from a different"
697 " version of LyX, but a temporary"
698 " file for converting it could"
700 from_utf8(filename.absFilename())));
703 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
704 if (lyx2lyx.empty()) {
705 Alert::error(_("Conversion script not found"),
706 bformat(_("%1$s is from a different"
707 " version of LyX, but the"
708 " conversion script lyx2lyx"
709 " could not be found."),
710 from_utf8(filename.absFilename())));
713 ostringstream command;
714 command << os::python()
715 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
716 << " -t " << convert<string>(LYX_FORMAT)
717 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
718 << ' ' << quoteName(filename.toFilesystemEncoding());
719 string const command_str = command.str();
721 LYXERR(Debug::INFO) << "Running '"
722 << command_str << '\''
725 cmd_ret const ret = runCommand(command_str);
726 if (ret.first != 0) {
727 Alert::error(_("Conversion script failed"),
728 bformat(_("%1$s is from a different version"
729 " of LyX, but the lyx2lyx script"
730 " failed to convert it."),
731 from_utf8(filename.absFilename())));
734 bool const ret = readFile(tmpfile);
735 // Do stuff with tmpfile name and buffer name here.
736 return ret ? success : failure;
741 if (readDocument(lex)) {
742 Alert::error(_("Document format failure"),
743 bformat(_("%1$s ended unexpectedly, which means"
744 " that it is probably corrupted."),
745 from_utf8(filename.absFilename())));
748 //lyxerr << "removing " << MacroTable::localMacros().size()
749 // << " temporary macro entries" << endl;
750 //MacroTable::localMacros().clear();
752 pimpl_->file_fully_loaded = true;
757 // Should probably be moved to somewhere else: BufferView? LyXView?
758 bool Buffer::save() const
760 // We don't need autosaves in the immediate future. (Asger)
761 resetAutosaveTimers();
763 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
766 bool madeBackup = false;
768 // make a backup if the file already exists
769 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
770 backupName = FileName(fileName() + '~');
771 if (!lyxrc.backupdir_path.empty())
772 backupName = FileName(addName(lyxrc.backupdir_path,
773 subst(os::internal_path(backupName.absFilename()), '/', '!')));
776 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
778 } catch (fs::filesystem_error const & fe) {
779 Alert::error(_("Backup failure"),
780 bformat(_("Cannot create backup file %1$s.\n"
781 "Please check whether the directory exists and is writeable."),
782 from_utf8(backupName.absFilename())));
783 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
787 if (writeFile(pimpl_->filename)) {
789 removeAutosaveFile(fileName());
792 // Saving failed, so backup is not backup
794 rename(backupName, pimpl_->filename);
800 bool Buffer::writeFile(FileName const & fname) const
802 if (pimpl_->read_only && fname == pimpl_->filename)
807 if (params().compressed) {
808 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
814 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
825 bool Buffer::write(ostream & ofs) const
828 // Use the standard "C" locale for file output.
829 ofs.imbue(std::locale::classic());
832 // The top of the file should not be written by params().
834 // write out a comment in the top of the file
835 ofs << "#LyX " << lyx_version
836 << " created this file. For more info see http://www.lyx.org/\n"
837 << "\\lyxformat " << LYX_FORMAT << "\n"
838 << "\\begin_document\n";
840 // now write out the buffer parameters.
841 ofs << "\\begin_header\n";
842 params().writeFile(ofs);
843 ofs << "\\end_header\n";
846 ofs << "\n\\begin_body\n";
847 text().write(*this, ofs);
848 ofs << "\n\\end_body\n";
850 // Write marker that shows file is complete
851 ofs << "\\end_document" << endl;
853 // Shouldn't really be needed....
856 // how to check if close went ok?
857 // Following is an attempt... (BE 20001011)
859 // good() returns false if any error occured, including some
861 // bad() returns true if something bad happened in the buffer,
862 // which should include file system full errors.
867 lyxerr << "File was not closed properly." << endl;
874 bool Buffer::makeLaTeXFile(FileName const & fname,
875 string const & original_path,
876 OutputParams const & runparams,
877 bool output_preamble, bool output_body)
879 string const encoding = runparams.encoding->iconvName();
880 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
881 << encoding << "..." << endl;
883 odocfstream ofs(encoding);
884 if (!openFileWrite(ofs, fname))
888 writeLaTeXSource(ofs, original_path,
889 runparams, output_preamble, output_body);
891 catch (iconv_codecvt_facet_exception &) {
892 Alert::error(_("Encoding error"),
893 _("Some characters of your document are not "
894 "representable in the chosen encoding.\n"
895 "Changing the document encoding to utf8 could help."));
901 lyxerr << "File '" << fname << "' was not closed properly." << endl;
902 Alert::error(_("Error closing file"),
903 _("The output file could not be closed properly.\n"
904 " Probably some characters of your document are not "
905 "representable in the chosen encoding.\n"
906 "Changing the document encoding to utf8 could help."));
913 void Buffer::writeLaTeXSource(odocstream & os,
914 string const & original_path,
915 OutputParams const & runparams_in,
916 bool const output_preamble, bool const output_body)
918 OutputParams runparams = runparams_in;
920 // validate the buffer.
921 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
922 LaTeXFeatures features(*this, params(), runparams);
924 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
928 // The starting paragraph of the coming rows is the
929 // first paragraph of the document. (Asger)
930 texrow().start(paragraphs().begin()->id(), 0);
932 if (output_preamble && runparams.nice) {
933 os << "%% LyX " << lyx_version << " created this file. "
934 "For more info, see http://www.lyx.org/.\n"
935 "%% Do not edit unless you really know what "
940 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
941 // There are a few differences between nice LaTeX and usual files:
942 // usual is \batchmode and has a
943 // special input@path to allow the including of figures
944 // with either \input or \includegraphics (what figinsets do).
945 // input@path is set when the actual parameter
946 // original_path is set. This is done for usual tex-file, but not
947 // for nice-latex-file. (Matthias 250696)
948 // Note that input@path is only needed for something the user does
949 // in the preamble, included .tex files or ERT, files included by
950 // LyX work without it.
951 if (output_preamble) {
952 if (!runparams.nice) {
953 // code for usual, NOT nice-latex-file
954 os << "\\batchmode\n"; // changed
958 if (!original_path.empty()) {
960 // We don't know the encoding of inputpath
961 docstring const inputpath = from_utf8(latex_path(original_path));
962 os << "\\makeatletter\n"
963 << "\\def\\input@path{{"
964 << inputpath << "/}}\n"
965 << "\\makeatother\n";
971 // Write the preamble
972 runparams.use_babel = params().writeLaTeX(os, features, texrow());
978 os << "\\begin{document}\n";
981 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
983 if (!lyxrc.language_auto_begin &&
984 !params().language->babel().empty()) {
986 os << from_utf8(subst(lyxrc.language_command_begin,
988 params().language->babel()))
993 Encoding const & encoding = params().encoding();
994 if (encoding.package() == Encoding::CJK) {
995 // Open a CJK environment, since in contrast to the encodings
996 // handled by inputenc the document encoding is not set in
997 // the preamble if it is handled by CJK.sty.
998 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1003 // if we are doing a real file with body, even if this is the
1004 // child of some other buffer, let's cut the link here.
1005 // This happens for example if only a child document is printed.
1006 string save_parentname;
1007 if (output_preamble) {
1008 save_parentname = params().parentname;
1009 params().parentname.erase();
1013 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1015 // Restore the parenthood if needed
1016 if (output_preamble)
1017 params().parentname = save_parentname;
1019 // add this just in case after all the paragraphs
1023 if (encoding.package() == Encoding::CJK) {
1024 // Close the open CJK environment.
1025 // latexParagraphs will have opened one even if the last text
1027 os << "\\end{CJK}\n";
1031 if (!lyxrc.language_auto_end &&
1032 !params().language->babel().empty()) {
1033 os << from_utf8(subst(lyxrc.language_command_end,
1035 params().language->babel()))
1040 if (output_preamble) {
1041 os << "\\end{document}\n";
1044 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1046 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1049 runparams_in.encoding = runparams.encoding;
1051 // Just to be sure. (Asger)
1054 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1055 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1060 bool Buffer::isLatex() const
1062 return params().getTextClass().outputType() == LATEX;
1066 bool Buffer::isLiterate() const
1068 return params().getTextClass().outputType() == LITERATE;
1072 bool Buffer::isDocBook() const
1074 return params().getTextClass().outputType() == DOCBOOK;
1078 void Buffer::makeDocBookFile(FileName const & fname,
1079 OutputParams const & runparams,
1080 bool const body_only)
1082 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1086 if (!openFileWrite(ofs, fname))
1089 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1093 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1097 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1098 OutputParams const & runparams,
1099 bool const only_body)
1101 LaTeXFeatures features(*this, params(), runparams);
1106 TextClass const & tclass = params().getTextClass();
1107 string const top_element = tclass.latexname();
1110 if (runparams.flavor == OutputParams::XML)
1111 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1114 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1117 if (! tclass.class_header().empty())
1118 os << from_ascii(tclass.class_header());
1119 else if (runparams.flavor == OutputParams::XML)
1120 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1121 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1123 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1125 docstring preamble = from_utf8(params().preamble);
1126 if (runparams.flavor != OutputParams::XML ) {
1127 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1128 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1129 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1130 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1133 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1135 preamble += features.getIncludedFiles(name);
1136 preamble += features.getLyXSGMLEntities();
1138 if (!preamble.empty()) {
1139 os << "\n [ " << preamble << " ]";
1144 string top = top_element;
1146 if (runparams.flavor == OutputParams::XML)
1147 top += params().language->code();
1149 top += params().language->code().substr(0,2);
1152 if (!params().options.empty()) {
1154 top += params().options;
1157 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1158 << " file was created by LyX " << lyx_version
1159 << "\n See http://www.lyx.org/ for more information -->\n";
1161 params().getTextClass().counters().reset();
1163 sgml::openTag(os, top);
1165 docbookParagraphs(paragraphs(), *this, os, runparams);
1166 sgml::closeTag(os, top_element);
1170 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1171 // Other flags: -wall -v0 -x
1172 int Buffer::runChktex()
1176 // get LaTeX-Filename
1177 FileName const path(temppath());
1178 string const name = addName(path.absFilename(), getLatexName());
1179 string const org_path = filePath();
1181 support::Path p(path); // path to LaTeX file
1182 message(_("Running chktex..."));
1184 // Generate the LaTeX file if neccessary
1185 OutputParams runparams(¶ms().encoding());
1186 runparams.flavor = OutputParams::LATEX;
1187 runparams.nice = false;
1188 makeLaTeXFile(FileName(name), org_path, runparams);
1191 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1192 int const res = chktex.run(terr); // run chktex
1195 Alert::error(_("chktex failure"),
1196 _("Could not run chktex successfully."));
1197 } else if (res > 0) {
1198 ErrorList & errorList = errorLists_["ChkTeX"];
1199 // Clear out old errors
1201 // Fill-in the error list with the TeX errors
1202 bufferErrors(*this, terr, errorList);
1213 void Buffer::validate(LaTeXFeatures & features) const
1215 TextClass const & tclass = params().getTextClass();
1217 if (params().outputChanges) {
1218 if (features.runparams().flavor == OutputParams::LATEX) {
1219 if (LaTeXFeatures::isAvailable("dvipost")) {
1220 features.require("dvipost");
1222 features.require("ct-none");
1224 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1225 features.require("ct-none");
1229 // AMS Style is at document level
1230 if (params().use_amsmath == BufferParams::package_on
1231 || tclass.provides("amsmath"))
1232 features.require("amsmath");
1233 if (params().use_esint == BufferParams::package_on)
1234 features.require("esint");
1236 for_each(paragraphs().begin(), paragraphs().end(),
1237 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1239 // the bullet shapes are buffer level not paragraph level
1240 // so they are tested here
1241 for (int i = 0; i < 4; ++i) {
1242 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1243 int const font = params().user_defined_bullet(i).getFont();
1245 int const c = params()
1246 .user_defined_bullet(i)
1253 features.require("latexsym");
1255 } else if (font == 1) {
1256 features.require("amssymb");
1257 } else if ((font >= 2 && font <= 5)) {
1258 features.require("pifont");
1263 if (lyxerr.debugging(Debug::LATEX)) {
1264 features.showStruct();
1269 void Buffer::getLabelList(vector<docstring> & list) const
1271 /// if this is a child document and the parent is already loaded
1272 /// Use the parent's list instead [ale990407]
1273 Buffer const * tmp = getMasterBuffer();
1275 lyxerr << "getMasterBuffer() failed!" << endl;
1279 tmp->getLabelList(list);
1283 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1284 it.nextInset()->getLabelList(*this, list);
1288 // This is also a buffer property (ale)
1289 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1292 /// if this is a child document and the parent is already loaded
1293 /// use the parent's list instead [ale990412]
1294 Buffer const * tmp = getMasterBuffer();
1297 tmp->fillWithBibKeys(keys);
1301 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1302 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1303 InsetBibtex const & inset =
1304 static_cast<InsetBibtex const &>(*it);
1305 inset.fillWithBibKeys(*this, keys);
1306 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1307 InsetInclude const & inset =
1308 static_cast<InsetInclude const &>(*it);
1309 inset.fillWithBibKeys(*this, keys);
1310 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1311 InsetBibitem const & inset =
1312 static_cast<InsetBibitem const &>(*it);
1314 string const key = to_utf8(inset.getParam("key"));
1315 docstring const label = inset.getParam("label");
1316 DocIterator doc_it(it); doc_it.forwardPos();
1317 docstring const ref = doc_it.paragraph().asString(*this, false);
1318 docstring const info = label + "TheBibliographyRef" + ref;
1319 keys.push_back(pair<string, docstring>(key, info));
1325 void Buffer::updateBibfilesCache()
1327 // if this is a child document and the parent is already loaded
1328 // update the parent's cache instead
1329 Buffer * tmp = getMasterBuffer();
1332 tmp->updateBibfilesCache();
1336 bibfilesCache_.clear();
1337 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1338 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1339 InsetBibtex const & inset =
1340 static_cast<InsetBibtex const &>(*it);
1341 vector<FileName> const bibfiles = inset.getFiles(*this);
1342 bibfilesCache_.insert(bibfilesCache_.end(),
1345 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1346 InsetInclude & inset =
1347 static_cast<InsetInclude &>(*it);
1348 inset.updateBibfilesCache(*this);
1349 vector<FileName> const & bibfiles =
1350 inset.getBibfilesCache(*this);
1351 bibfilesCache_.insert(bibfilesCache_.end(),
1359 vector<FileName> const & Buffer::getBibfilesCache() const
1361 // if this is a child document and the parent is already loaded
1362 // use the parent's cache instead
1363 Buffer const * tmp = getMasterBuffer();
1366 return tmp->getBibfilesCache();
1368 // We update the cache when first used instead of at loading time.
1369 if (bibfilesCache_.empty())
1370 const_cast<Buffer *>(this)->updateBibfilesCache();
1372 return bibfilesCache_;
1376 bool Buffer::isDepClean(string const & name) const
1378 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1379 if (it == pimpl_->dep_clean.end())
1385 void Buffer::markDepClean(string const & name)
1387 pimpl_->dep_clean[name] = true;
1391 bool Buffer::dispatch(string const & command, bool * result)
1393 return dispatch(lyxaction.lookupFunc(command), result);
1397 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1399 bool dispatched = true;
1401 switch (func.action) {
1402 case LFUN_BUFFER_EXPORT: {
1403 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1416 void Buffer::changeLanguage(Language const * from, Language const * to)
1421 for_each(par_iterator_begin(),
1423 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1425 text().current_font.setLanguage(to);
1426 text().real_current_font.setLanguage(to);
1430 bool Buffer::isMultiLingual() const
1432 ParConstIterator end = par_iterator_end();
1433 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1434 if (it->isMultiLingual(params()))
1441 ParIterator Buffer::getParFromID(int const id) const
1443 ParConstIterator it = par_iterator_begin();
1444 ParConstIterator const end = par_iterator_end();
1447 // John says this is called with id == -1 from undo
1448 lyxerr << "getParFromID(), id: " << id << endl;
1452 for (; it != end; ++it)
1460 bool Buffer::hasParWithID(int const id) const
1462 ParConstIterator const it = getParFromID(id);
1463 return it != par_iterator_end();
1467 ParIterator Buffer::par_iterator_begin()
1469 return lyx::par_iterator_begin(inset());
1473 ParIterator Buffer::par_iterator_end()
1475 return lyx::par_iterator_end(inset());
1479 ParConstIterator Buffer::par_iterator_begin() const
1481 return lyx::par_const_iterator_begin(inset());
1485 ParConstIterator Buffer::par_iterator_end() const
1487 return lyx::par_const_iterator_end(inset());
1491 Language const * Buffer::getLanguage() const
1493 return params().language;
1497 docstring const Buffer::B_(string const & l10n) const
1499 return params().B_(l10n);
1503 bool Buffer::isClean() const
1505 return pimpl_->lyx_clean;
1509 bool Buffer::isBakClean() const
1511 return pimpl_->bak_clean;
1515 void Buffer::markClean() const
1517 if (!pimpl_->lyx_clean) {
1518 pimpl_->lyx_clean = true;
1521 // if the .lyx file has been saved, we don't need an
1523 pimpl_->bak_clean = true;
1527 void Buffer::markBakClean()
1529 pimpl_->bak_clean = true;
1533 void Buffer::setUnnamed(bool flag)
1535 pimpl_->unnamed = flag;
1539 bool Buffer::isUnnamed() const
1541 return pimpl_->unnamed;
1545 #ifdef WITH_WARNINGS
1546 #warning this function should be moved to buffer_pimpl.C
1548 void Buffer::markDirty()
1550 if (pimpl_->lyx_clean) {
1551 pimpl_->lyx_clean = false;
1554 pimpl_->bak_clean = false;
1556 DepClean::iterator it = pimpl_->dep_clean.begin();
1557 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1559 for (; it != end; ++it)
1564 string const Buffer::fileName() const
1566 return pimpl_->filename.absFilename();
1570 string const & Buffer::filePath() const
1572 return params().filepath;
1576 bool Buffer::isReadonly() const
1578 return pimpl_->read_only;
1582 void Buffer::setParentName(string const & name)
1584 params().parentname = name;
1588 Buffer const * Buffer::getMasterBuffer() const
1590 if (!params().parentname.empty()
1591 && theBufferList().exists(params().parentname)) {
1592 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1594 return buf->getMasterBuffer();
1601 Buffer * Buffer::getMasterBuffer()
1603 if (!params().parentname.empty()
1604 && theBufferList().exists(params().parentname)) {
1605 Buffer * buf = theBufferList().getBuffer(params().parentname);
1607 return buf->getMasterBuffer();
1614 MacroData const & Buffer::getMacro(docstring const & name) const
1616 return pimpl_->macros.get(name);
1620 bool Buffer::hasMacro(docstring const & name) const
1622 return pimpl_->macros.has(name);
1626 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1628 MacroTable::globalMacros().insert(name, data);
1629 pimpl_->macros.insert(name, data);
1633 void Buffer::buildMacros()
1635 // Start with global table.
1636 pimpl_->macros = MacroTable::globalMacros();
1639 ParagraphList const & pars = text().paragraphs();
1640 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1641 //lyxerr << "searching main par " << i
1642 // << " for macro definitions" << std::endl;
1643 InsetList const & insets = pars[i].insetlist;
1644 InsetList::const_iterator it = insets.begin();
1645 InsetList::const_iterator end = insets.end();
1646 for ( ; it != end; ++it) {
1647 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1648 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1649 MathMacroTemplate const & mac
1650 = static_cast<MathMacroTemplate const &>(*it->inset);
1651 insertMacro(mac.name(), mac.asMacroData());
1658 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1665 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1668 //FIXME: This does not work for child documents yet.
1669 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1670 // Check if the label 'from' appears more than once
1671 vector<docstring> labels;
1673 if (code == Inset::CITE_CODE) {
1674 vector<pair<string, docstring> > keys;
1675 fillWithBibKeys(keys);
1676 vector<pair<string, docstring> >::const_iterator bit = keys.begin();
1677 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1679 for (; bit != bend; ++bit)
1681 labels.push_back(from_utf8(bit->first));
1683 getLabelList(labels);
1685 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1688 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1689 if (it->lyxCode() == code) {
1690 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1691 inset.replaceContents(to_utf8(from), to_utf8(to));
1697 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1698 pit_type par_end, bool full_source)
1700 OutputParams runparams(¶ms().encoding());
1701 runparams.nice = true;
1702 runparams.flavor = OutputParams::LATEX;
1703 runparams.linelen = lyxrc.plaintext_linelen;
1704 // No side effect of file copying and image conversion
1705 runparams.dryrun = true;
1708 os << "% Preview source code\n\n";
1710 writeLaTeXSource(os, filePath(), runparams, true, true);
1712 writeDocBookSource(os, fileName(), runparams, false);
1715 runparams.par_begin = par_begin;
1716 runparams.par_end = par_end;
1717 if (par_begin + 1 == par_end)
1718 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1720 os << "% Preview source code from paragraph " << par_begin
1721 << " to " << par_end - 1 << "\n\n";
1722 // output paragraphs
1725 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1728 docbookParagraphs(paragraphs(), *this, os, runparams);
1734 ErrorList const & Buffer::errorList(string const & type) const
1736 static ErrorList const emptyErrorList;
1737 std::map<string, ErrorList>::const_iterator I = errorLists_.find(type);
1738 if (I == errorLists_.end())
1739 return emptyErrorList;
1745 ErrorList & Buffer::errorList(string const & type)
1747 return errorLists_[type];