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"
53 #include "insets/insetbibitem.h"
54 #include "insets/insetbibtex.h"
55 #include "insets/insetinclude.h"
56 #include "insets/insettext.h"
58 #include "mathed/MathMacroTemplate.h"
59 #include "mathed/MathMacroTable.h"
60 #include "mathed/MathSupport.h"
62 #include "frontends/Alert.h"
64 #include "graphics/Previews.h"
66 #include "support/types.h"
67 #include "support/lyxalgo.h"
68 #include "support/filetools.h"
69 #include "support/fs_extras.h"
70 #include "support/lyxlib.h"
71 #include "support/os.h"
72 #include "support/path.h"
73 #include "support/textutils.h"
74 #include "support/convert.h"
76 #include <boost/iostreams/filtering_stream.hpp>
77 #include <boost/iostreams/filter/gzip.hpp>
78 #include <boost/iostreams/device/file.hpp>
79 #include <boost/bind.hpp>
80 #include <boost/filesystem/exception.hpp>
81 #include <boost/filesystem/operations.hpp>
83 #if defined (HAVE_UTIME_H)
85 #elif defined (HAVE_SYS_UTIME_H)
86 #include <sys/utime.h>
97 using support::addName;
98 using support::bformat;
99 using support::changeExtension;
100 using support::cmd_ret;
101 using support::createBufferTmpDir;
102 using support::destroyDir;
103 using support::getFormatFromContents;
104 using support::isDirWriteable;
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;
135 using std::ostringstream;
145 int const LYX_FORMAT = 252;
150 typedef std::map<string, bool> DepClean;
155 Impl(Buffer & parent, string const & file, bool readonly);
157 limited_stack<Undo> undostack;
158 limited_stack<Undo> redostack;
164 /// need to regenerate .tex?
168 mutable bool lyx_clean;
170 /// is autosave needed?
171 mutable bool bak_clean;
173 /// is this a unnamed file (New...)?
179 /// name of the file the buffer is associated with.
182 boost::scoped_ptr<Messages> messages;
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
190 /// our LyXText that should be wrapped in an InsetText
198 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
199 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
200 filename(file), file_fully_loaded(false),
203 inset.setAutoBreakRows(true);
204 lyxvc.buffer(&parent);
205 temppath = createBufferTmpDir();
206 params.filepath = onlyPath(file);
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, 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(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 LyXText & Buffer::text() const
241 return const_cast<LyXText &>(pimpl_->inset.text_);
245 InsetBase & 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 string const Buffer::getLatexName(bool const no_path) const
331 string const name = changeExtension(makeLatexName(fileName()), ".tex");
332 return no_path ? onlyFilename(name) : name;
336 pair<Buffer::LogType, string> const Buffer::getLogName() const
338 string const filename = getLatexName(false);
340 if (filename.empty())
341 return make_pair(Buffer::latexlog, string());
343 string const path = temppath();
345 string const fname = addName(path,
346 onlyFilename(changeExtension(filename,
349 addName(path, onlyFilename(
350 changeExtension(filename,
351 formats.extension("literate") + ".out")));
353 // If no Latex log or Build log is newer, show Build log
355 if (fs::exists(bname) &&
356 (!fs::exists(fname) || fs::last_write_time(fname) < fs::last_write_time(bname))) {
357 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
358 return make_pair(Buffer::buildlog, bname);
360 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
361 return make_pair(Buffer::latexlog, fname);
365 void Buffer::setReadonly(bool const flag)
367 if (pimpl_->read_only != flag) {
368 pimpl_->read_only = flag;
374 void Buffer::setFileName(string const & newfile)
376 pimpl_->filename = makeAbsPath(newfile);
377 params().filepath = onlyPath(pimpl_->filename);
378 setReadonly(fs::is_readonly(pimpl_->filename));
383 // We'll remove this later. (Lgb)
386 void unknownClass(string const & unknown)
388 Alert::warning(_("Unknown document class"),
389 bformat(_("Using the default document class, because the "
390 "class %1$s is unknown."), from_utf8(unknown)));
396 int Buffer::readHeader(LyXLex & lex)
398 int unknown_tokens = 0;
400 int begin_header_line = -1;
402 // Initialize parameters that may be/go lacking in header:
403 params().branchlist().clear();
404 params().preamble.erase();
405 params().options.erase();
406 params().float_placement.erase();
407 params().paperwidth.erase();
408 params().paperheight.erase();
409 params().leftmargin.erase();
410 params().rightmargin.erase();
411 params().topmargin.erase();
412 params().bottommargin.erase();
413 params().headheight.erase();
414 params().headsep.erase();
415 params().footskip.erase();
417 ErrorList & errorList = errorLists_["Parse"];
421 string const token = lex.getString();
426 if (token == "\\end_header")
430 if (token == "\\begin_header") {
431 begin_header_line = line;
435 lyxerr[Debug::PARSER] << "Handling document header token: `"
436 << token << '\'' << endl;
438 string unknown = params().readToken(lex, token);
439 if (!unknown.empty()) {
440 if (unknown[0] != '\\' && token == "\\textclass") {
441 unknownClass(unknown);
444 docstring const s = bformat(_("Unknown token: "
447 from_utf8(lex.getString()));
448 errorList.push_back(ErrorItem(_("Document header error"),
453 if (begin_header_line) {
454 docstring const s = _("\\begin_header is missing");
455 errorList.push_back(ErrorItem(_("Document header error"),
459 return unknown_tokens;
464 // changed to be public and have one parameter
465 // Returns false if "\end_document" is not read (Asger)
466 bool Buffer::readDocument(LyXLex & lex)
468 ErrorList & errorList = errorLists_["Parse"];
472 string const token = lex.getString();
473 if (token != "\\begin_document") {
474 docstring const s = _("\\begin_document is missing");
475 errorList.push_back(ErrorItem(_("Document header error"),
479 // we are reading in a brand new document
480 BOOST_ASSERT(paragraphs().empty());
483 if (!params().getLyXTextClass().load(filePath())) {
484 string theclass = params().getLyXTextClass().name();
485 Alert::error(_("Can't load document class"), bformat(
486 _("Using the default document class, because the "
487 " class %1$s could not be loaded."), from_utf8(theclass)));
488 params().textclass = 0;
491 bool const res = text().read(*this, lex, errorList);
492 for_each(text().paragraphs().begin(),
493 text().paragraphs().end(),
494 bind(&Paragraph::setInsetOwner, _1, &inset()));
495 updateBibfilesCache();
501 // needed to insert the selection
502 void Buffer::insertStringAsLines(ParagraphList & pars,
503 pit_type & pit, pos_type & pos,
504 LyXFont const & fn, docstring const & str, bool autobreakrows)
508 // insert the string, don't insert doublespace
509 bool space_inserted = true;
510 for (docstring::const_iterator cit = str.begin();
511 cit != str.end(); ++cit) {
512 Paragraph & par = pars[pit];
514 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
515 breakParagraph(params(), pars, pit, pos,
516 par.layout()->isEnvironment());
519 space_inserted = true;
523 // do not insert consecutive spaces if !free_spacing
524 } else if ((*cit == ' ' || *cit == '\t') &&
525 space_inserted && !par.isFreeSpacing()) {
527 } else if (*cit == '\t') {
528 if (!par.isFreeSpacing()) {
529 // tabs are like spaces here
530 par.insertChar(pos, ' ', font, params().trackChanges);
532 space_inserted = true;
534 const pos_type n = 8 - pos % 8;
535 for (pos_type i = 0; i < n; ++i) {
536 par.insertChar(pos, ' ', font, params().trackChanges);
539 space_inserted = true;
541 /* FIXME: not needed anymore?
542 } else if (!isPrintable(*cit)) {
543 // Ignore unprintables
547 // just insert the character
548 par.insertChar(pos, *cit, font, params().trackChanges);
550 space_inserted = (*cit == ' ');
557 bool Buffer::readFile(string const & filename)
559 // Check if the file is compressed.
560 string const format = getFormatFromContents(filename);
561 if (format == "gzip" || format == "zip" || format == "compress") {
562 params().compressed = true;
565 // remove dummy empty par
566 paragraphs().clear();
568 lex.setFile(filename);
569 if (!readFile(lex, filename))
572 // After we have read a file, we must ensure that the buffer
573 // language is set and used in the gui.
574 // If you know of a better place to put this, please tell me. (Lgb)
575 updateDocLang(params().language);
581 bool Buffer::fully_loaded() const
583 return pimpl_->file_fully_loaded;
587 void Buffer::fully_loaded(bool const value)
589 pimpl_->file_fully_loaded = value;
593 bool Buffer::readFile(LyXLex & lex, string const & filename)
595 BOOST_ASSERT(!filename.empty());
598 Alert::error(_("Document could not be read"),
599 bformat(_("%1$s could not be read."), from_utf8(filename)));
604 string const token(lex.getString());
607 Alert::error(_("Document could not be read"),
608 bformat(_("%1$s could not be read."), from_utf8(filename)));
612 // the first token _must_ be...
613 if (token != "\\lyxformat") {
614 lyxerr << "Token: " << token << endl;
616 Alert::error(_("Document format failure"),
617 bformat(_("%1$s is not a LyX document."),
618 from_utf8(filename)));
623 string tmp_format = lex.getString();
624 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
625 // if present remove ".," from string.
626 string::size_type dot = tmp_format.find_first_of(".,");
627 //lyxerr << " dot found at " << dot << endl;
628 if (dot != string::npos)
629 tmp_format.erase(dot, 1);
630 int const file_format = convert<int>(tmp_format);
631 //lyxerr << "format: " << file_format << endl;
633 if (file_format != LYX_FORMAT) {
634 string const tmpfile = tempName();
635 if (tmpfile.empty()) {
636 Alert::error(_("Conversion failed"),
637 bformat(_("%1$s is from an earlier"
638 " version of LyX, but a temporary"
639 " file for converting it could"
641 from_utf8(filename)));
644 string const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
645 if (lyx2lyx.empty()) {
646 Alert::error(_("Conversion script not found"),
647 bformat(_("%1$s is from an earlier"
648 " version of LyX, but the"
649 " conversion script lyx2lyx"
650 " could not be found."),
651 from_utf8(filename)));
654 ostringstream command;
655 command << os::python() << ' ' << quoteName(lyx2lyx)
656 << " -t " << convert<string>(LYX_FORMAT)
657 << " -o " << quoteName(tmpfile) << ' '
658 << quoteName(filename);
659 string const command_str = command.str();
661 lyxerr[Debug::INFO] << "Running '"
662 << command_str << '\''
665 cmd_ret const ret = runCommand(command_str);
666 if (ret.first != 0) {
667 Alert::error(_("Conversion script failed"),
668 bformat(_("%1$s is from an earlier version"
669 " of LyX, but the lyx2lyx script"
670 " failed to convert it."),
671 from_utf8(filename)));
674 bool const ret = readFile(tmpfile);
675 // Do stuff with tmpfile name and buffer name here.
681 if (readDocument(lex)) {
682 Alert::error(_("Document format failure"),
683 bformat(_("%1$s ended unexpectedly, which means"
684 " that it is probably corrupted."),
685 from_utf8(filename)));
688 //lyxerr << "removing " << MacroTable::localMacros().size()
689 // << " temporary macro entries" << endl;
690 //MacroTable::localMacros().clear();
692 pimpl_->file_fully_loaded = true;
697 // Should probably be moved to somewhere else: BufferView? LyXView?
698 bool Buffer::save() const
700 // We don't need autosaves in the immediate future. (Asger)
701 resetAutosaveTimers();
705 if (lyxrc.make_backup) {
706 s = fileName() + '~';
707 if (!lyxrc.backupdir_path.empty())
708 s = addName(lyxrc.backupdir_path,
709 subst(os::internal_path(s),'/','!'));
711 // It might very well be that this variant is just
712 // good enough. (Lgb)
713 // But to use this we need fs::copy_file to actually do a copy,
714 // even when the target file exists. (Lgb)
716 fs::copy_file(fileName(), s, false);
718 catch (fs::filesystem_error const & fe) {
719 Alert::error(_("Backup failure"),
720 bformat(_("LyX was not able to make a backup copy in %1$s.\n"
721 "Please check if the directory exists and is writeable."),
722 from_utf8(fs::path(s).branch_path().native_directory_string())));
723 lyxerr[Debug::DEBUG] << "Fs error: "
724 << fe.what() << endl;
728 if (writeFile(fileName())) {
730 removeAutosaveFile(fileName());
732 // Saving failed, so backup is not backup
733 if (lyxrc.make_backup)
734 rename(s, fileName());
741 bool Buffer::writeFile(string const & fname) const
743 if (pimpl_->read_only && fname == fileName())
748 if (params().compressed) {
749 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname));
753 retval = do_writeFile(ofs);
755 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
759 retval = do_writeFile(ofs);
766 bool Buffer::do_writeFile(ostream & ofs) const
769 // Use the standard "C" locale for file output.
770 ofs.imbue(std::locale::classic());
773 // The top of the file should not be written by params().
775 // write out a comment in the top of the file
776 ofs << "#LyX " << lyx_version
777 << " created this file. For more info see http://www.lyx.org/\n"
778 << "\\lyxformat " << LYX_FORMAT << "\n"
779 << "\\begin_document\n";
781 // now write out the buffer parameters.
782 ofs << "\\begin_header\n";
783 params().writeFile(ofs);
784 ofs << "\\end_header\n";
787 ofs << "\n\\begin_body\n";
788 text().write(*this, ofs);
789 ofs << "\n\\end_body\n";
791 // Write marker that shows file is complete
792 ofs << "\\end_document" << endl;
794 // Shouldn't really be needed....
797 // how to check if close went ok?
798 // Following is an attempt... (BE 20001011)
800 // good() returns false if any error occured, including some
802 // bad() returns true if something bad happened in the buffer,
803 // which should include file system full errors.
808 lyxerr << "File was not closed properly." << endl;
815 bool Buffer::makeLaTeXFile(string const & fname,
816 string const & original_path,
817 OutputParams const & runparams,
818 bool output_preamble, bool output_body)
820 string const encoding = (params().inputenc == "auto") ?
821 params().language->encoding()->iconvName() :
822 encodings.getEncoding(params().inputenc)->iconvName();
823 lyxerr[Debug::LATEX] << "makeLaTeXFile encoding: "
824 << encoding << "..." << endl;
826 odocfstream ofs(encoding);
827 if (!openFileWrite(ofs, fname))
831 writeLaTeXSource(ofs, original_path,
832 runparams, output_preamble, output_body);
834 catch (iconv_codecvt_facet_exception &) {
835 Alert::error(_("Encoding error"),
836 _("Some characters of your document are not "
837 "representable in the chosen encoding.\n"
838 "Changing the document encoding to utf8 could help."));
844 lyxerr << "File '" << fname << "' was not closed properly." << endl;
845 Alert::error(_("Error closing file"),
846 _("The output file could not be closed properly.\n"
847 " Probably some characters of your document are not "
848 "representable in the chosen encoding.\n"
849 "Changing the document encoding to utf8 could help."));
856 void Buffer::writeLaTeXSource(odocstream & os,
857 string const & original_path,
858 OutputParams const & runparams_in,
859 bool const output_preamble, bool const output_body)
861 OutputParams runparams = runparams_in;
863 // validate the buffer.
864 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
865 LaTeXFeatures features(*this, params(), runparams);
867 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
871 // The starting paragraph of the coming rows is the
872 // first paragraph of the document. (Asger)
873 texrow().start(paragraphs().begin()->id(), 0);
875 if (output_preamble && runparams.nice) {
876 os << "%% LyX " << lyx_version << " created this file. "
877 "For more info, see http://www.lyx.org/.\n"
878 "%% Do not edit unless you really know what "
883 lyxerr[Debug::INFO] << "lyx document header finished" << endl;
884 // There are a few differences between nice LaTeX and usual files:
885 // usual is \batchmode and has a
886 // special input@path to allow the including of figures
887 // with either \input or \includegraphics (what figinsets do).
888 // input@path is set when the actual parameter
889 // original_path is set. This is done for usual tex-file, but not
890 // for nice-latex-file. (Matthias 250696)
891 // Note that input@path is only needed for something the user does
892 // in the preamble, included .tex files or ERT, files included by
893 // LyX work without it.
894 if (output_preamble) {
895 if (!runparams.nice) {
896 // code for usual, NOT nice-latex-file
897 os << "\\batchmode\n"; // changed
901 if (!original_path.empty()) {
903 // We don't know the encoding of inputpath
904 docstring const inputpath = from_utf8(latex_path(original_path));
905 os << "\\makeatletter\n"
906 << "\\def\\input@path{{"
907 << inputpath << "/}}\n"
908 << "\\makeatother\n";
914 // Write the preamble
915 runparams.use_babel = params().writeLaTeX(os, features, texrow());
921 os << "\\begin{document}\n";
924 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
926 if (!lyxrc.language_auto_begin) {
928 os << from_utf8(subst(lyxrc.language_command_begin,
930 params().language->babel()))
935 // if we are doing a real file with body, even if this is the
936 // child of some other buffer, let's cut the link here.
937 // This happens for example if only a child document is printed.
938 string save_parentname;
939 if (output_preamble) {
940 save_parentname = params().parentname;
941 params().parentname.erase();
945 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
947 // Restore the parenthood if needed
949 params().parentname = save_parentname;
951 // add this just in case after all the paragraphs
955 if (!lyxrc.language_auto_end) {
956 os << from_utf8(subst(lyxrc.language_command_end,
958 params().language->babel()))
963 if (output_preamble) {
964 os << "\\end{document}\n";
967 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
969 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
973 // Just to be sure. (Asger)
976 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
977 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
982 bool Buffer::isLatex() const
984 return params().getLyXTextClass().outputType() == LATEX;
988 bool Buffer::isLiterate() const
990 return params().getLyXTextClass().outputType() == LITERATE;
994 bool Buffer::isDocBook() const
996 return params().getLyXTextClass().outputType() == DOCBOOK;
1000 void Buffer::makeDocBookFile(string const & fname,
1001 OutputParams const & runparams,
1002 bool const body_only)
1004 lyxerr[Debug::LATEX] << "makeDocBookFile..." << endl;
1008 if (!openFileWrite(ofs, fname))
1011 writeDocBookSource(ofs, fname, runparams, body_only);
1015 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1019 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1020 OutputParams const & runparams,
1021 bool const only_body)
1023 LaTeXFeatures features(*this, params(), runparams);
1028 LyXTextClass const & tclass = params().getLyXTextClass();
1029 string const top_element = tclass.latexname();
1032 if (runparams.flavor == OutputParams::XML)
1033 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1036 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1039 if (! tclass.class_header().empty())
1040 os << from_ascii(tclass.class_header());
1041 else if (runparams.flavor == OutputParams::XML)
1042 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1043 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1045 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1047 docstring preamble = from_utf8(params().preamble);
1048 if (runparams.flavor != OutputParams::XML ) {
1049 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1050 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1051 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1052 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1055 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1057 preamble += features.getIncludedFiles(name);
1058 preamble += features.getLyXSGMLEntities();
1060 if (!preamble.empty()) {
1061 os << "\n [ " << preamble << " ]";
1066 string top = top_element;
1068 if (runparams.flavor == OutputParams::XML)
1069 top += params().language->code();
1071 top += params().language->code().substr(0,2);
1074 if (!params().options.empty()) {
1076 top += params().options;
1079 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1080 << " file was created by LyX " << lyx_version
1081 << "\n See http://www.lyx.org/ for more information -->\n";
1083 params().getLyXTextClass().counters().reset();
1085 sgml::openTag(os, top);
1087 docbookParagraphs(paragraphs(), *this, os, runparams);
1088 sgml::closeTag(os, top_element);
1092 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1093 // Other flags: -wall -v0 -x
1094 int Buffer::runChktex()
1098 // get LaTeX-Filename
1099 string const name = getLatexName();
1100 string const path = temppath();
1101 string const org_path = filePath();
1103 support::Path p(path); // path to LaTeX file
1104 message(_("Running chktex..."));
1106 // Generate the LaTeX file if neccessary
1107 OutputParams runparams;
1108 runparams.flavor = OutputParams::LATEX;
1109 runparams.nice = false;
1110 makeLaTeXFile(name, org_path, runparams);
1113 Chktex chktex(lyxrc.chktex_command, name, filePath());
1114 int const res = chktex.run(terr); // run chktex
1117 Alert::error(_("chktex failure"),
1118 _("Could not run chktex successfully."));
1119 } else if (res > 0) {
1120 // Fill-in the error list with the TeX errors
1121 bufferErrors(*this, terr, errorLists_["ChkTex"]);
1132 void Buffer::validate(LaTeXFeatures & features) const
1134 LyXTextClass const & tclass = params().getLyXTextClass();
1136 if (features.isAvailable("dvipost") && params().outputChanges)
1137 features.require("dvipost");
1139 // AMS Style is at document level
1140 if (params().use_amsmath == BufferParams::AMS_ON
1141 || tclass.provides(LyXTextClass::amsmath))
1142 features.require("amsmath");
1144 for_each(paragraphs().begin(), paragraphs().end(),
1145 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1147 // the bullet shapes are buffer level not paragraph level
1148 // so they are tested here
1149 for (int i = 0; i < 4; ++i) {
1150 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1151 int const font = params().user_defined_bullet(i).getFont();
1153 int const c = params()
1154 .user_defined_bullet(i)
1161 features.require("latexsym");
1163 } else if (font == 1) {
1164 features.require("amssymb");
1165 } else if ((font >= 2 && font <= 5)) {
1166 features.require("pifont");
1171 if (lyxerr.debugging(Debug::LATEX)) {
1172 features.showStruct();
1177 void Buffer::getLabelList(vector<docstring> & list) const
1179 /// if this is a child document and the parent is already loaded
1180 /// Use the parent's list instead [ale990407]
1181 Buffer const * tmp = getMasterBuffer();
1183 lyxerr << "getMasterBuffer() failed!" << endl;
1187 tmp->getLabelList(list);
1191 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1192 it.nextInset()->getLabelList(*this, list);
1196 // This is also a buffer property (ale)
1197 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1200 /// if this is a child document and the parent is already loaded
1201 /// use the parent's list instead [ale990412]
1202 Buffer const * tmp = getMasterBuffer();
1205 tmp->fillWithBibKeys(keys);
1209 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1210 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1211 InsetBibtex const & inset =
1212 dynamic_cast<InsetBibtex const &>(*it);
1213 inset.fillWithBibKeys(*this, keys);
1214 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1215 InsetInclude const & inset =
1216 dynamic_cast<InsetInclude const &>(*it);
1217 inset.fillWithBibKeys(*this, keys);
1218 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1219 InsetBibitem const & inset =
1220 dynamic_cast<InsetBibitem const &>(*it);
1221 string const key = inset.getContents();
1222 string const opt = inset.getOptions();
1223 string const ref; // = pit->asString(this, false);
1224 string const info = opt + "TheBibliographyRef" + ref;
1225 keys.push_back(pair<string, string>(key, info));
1231 void Buffer::updateBibfilesCache()
1233 // if this is a child document and the parent is already loaded
1234 // update the parent's cache instead
1235 Buffer * tmp = getMasterBuffer();
1238 tmp->updateBibfilesCache();
1242 bibfilesCache_.clear();
1243 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1244 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1245 InsetBibtex const & inset =
1246 dynamic_cast<InsetBibtex const &>(*it);
1247 vector<string> const bibfiles = inset.getFiles(*this);
1248 bibfilesCache_.insert(bibfilesCache_.end(),
1251 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1252 InsetInclude & inset =
1253 dynamic_cast<InsetInclude &>(*it);
1254 inset.updateBibfilesCache(*this);
1255 vector<string> const & bibfiles =
1256 inset.getBibfilesCache(*this);
1257 bibfilesCache_.insert(bibfilesCache_.end(),
1265 vector<string> const & Buffer::getBibfilesCache() const
1267 // if this is a child document and the parent is already loaded
1268 // use the parent's cache instead
1269 Buffer const * tmp = getMasterBuffer();
1272 return tmp->getBibfilesCache();
1274 return bibfilesCache_;
1278 bool Buffer::isDepClean(string const & name) const
1280 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1281 if (it == pimpl_->dep_clean.end())
1287 void Buffer::markDepClean(string const & name)
1289 pimpl_->dep_clean[name] = true;
1293 bool Buffer::dispatch(string const & command, bool * result)
1295 return dispatch(lyxaction.lookupFunc(command), result);
1299 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1301 bool dispatched = true;
1303 switch (func.action) {
1304 case LFUN_BUFFER_EXPORT: {
1305 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1318 void Buffer::changeLanguage(Language const * from, Language const * to)
1323 // Take care of l10n/i18n
1326 for_each(par_iterator_begin(),
1328 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1330 text().current_font.setLanguage(to);
1331 text().real_current_font.setLanguage(to);
1335 void Buffer::updateDocLang(Language const * nlang)
1337 BOOST_ASSERT(nlang);
1339 pimpl_->messages.reset(new Messages(nlang->code()));
1341 updateLabels(*this);
1345 bool Buffer::isMultiLingual() const
1347 ParConstIterator end = par_iterator_end();
1348 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1349 if (it->isMultiLingual(params()))
1356 ParIterator Buffer::getParFromID(int const id) const
1358 ParConstIterator it = par_iterator_begin();
1359 ParConstIterator const end = par_iterator_end();
1362 // John says this is called with id == -1 from undo
1363 lyxerr << "getParFromID(), id: " << id << endl;
1367 for (; it != end; ++it)
1375 bool Buffer::hasParWithID(int const id) const
1377 ParConstIterator const it = getParFromID(id);
1378 return it != par_iterator_end();
1382 ParIterator Buffer::par_iterator_begin()
1384 return lyx::par_iterator_begin(inset());
1388 ParIterator Buffer::par_iterator_end()
1390 return lyx::par_iterator_end(inset());
1394 ParConstIterator Buffer::par_iterator_begin() const
1396 return lyx::par_const_iterator_begin(inset());
1400 ParConstIterator Buffer::par_iterator_end() const
1402 return lyx::par_const_iterator_end(inset());
1406 Language const * Buffer::getLanguage() const
1408 return params().language;
1412 docstring const Buffer::B_(string const & l10n) const
1414 if (pimpl_->messages.get())
1415 return pimpl_->messages->get(l10n);
1421 bool Buffer::isClean() const
1423 return pimpl_->lyx_clean;
1427 bool Buffer::isBakClean() const
1429 return pimpl_->bak_clean;
1433 void Buffer::markClean() const
1435 if (!pimpl_->lyx_clean) {
1436 pimpl_->lyx_clean = true;
1439 // if the .lyx file has been saved, we don't need an
1441 pimpl_->bak_clean = true;
1445 void Buffer::markBakClean()
1447 pimpl_->bak_clean = true;
1451 void Buffer::setUnnamed(bool flag)
1453 pimpl_->unnamed = flag;
1457 bool Buffer::isUnnamed() const
1459 return pimpl_->unnamed;
1463 #ifdef WITH_WARNINGS
1464 #warning this function should be moved to buffer_pimpl.C
1466 void Buffer::markDirty()
1468 if (pimpl_->lyx_clean) {
1469 pimpl_->lyx_clean = false;
1472 pimpl_->bak_clean = false;
1474 DepClean::iterator it = pimpl_->dep_clean.begin();
1475 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1477 for (; it != end; ++it)
1482 string const & Buffer::fileName() const
1484 return pimpl_->filename;
1488 string const & Buffer::filePath() const
1490 return params().filepath;
1494 bool Buffer::isReadonly() const
1496 return pimpl_->read_only;
1500 void Buffer::setParentName(string const & name)
1502 params().parentname = name;
1506 Buffer const * Buffer::getMasterBuffer() const
1508 if (!params().parentname.empty()
1509 && theBufferList().exists(params().parentname)) {
1510 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1512 return buf->getMasterBuffer();
1519 Buffer * Buffer::getMasterBuffer()
1521 if (!params().parentname.empty()
1522 && theBufferList().exists(params().parentname)) {
1523 Buffer * buf = theBufferList().getBuffer(params().parentname);
1525 return buf->getMasterBuffer();
1532 MacroData const & Buffer::getMacro(docstring const & name) const
1534 return pimpl_->macros.get(name);
1538 bool Buffer::hasMacro(docstring const & name) const
1540 return pimpl_->macros.has(name);
1544 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1546 MacroTable::globalMacros().insert(name, data);
1547 pimpl_->macros.insert(name, data);
1551 void Buffer::buildMacros()
1553 // Start with global table.
1554 pimpl_->macros = MacroTable::globalMacros();
1557 ParagraphList const & pars = text().paragraphs();
1558 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1559 //lyxerr << "searching main par " << i
1560 // << " for macro definitions" << std::endl;
1561 InsetList const & insets = pars[i].insetlist;
1562 InsetList::const_iterator it = insets.begin();
1563 InsetList::const_iterator end = insets.end();
1564 for ( ; it != end; ++it) {
1565 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1566 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1567 MathMacroTemplate const & mac
1568 = static_cast<MathMacroTemplate const &>(*it->inset);
1569 insertMacro(mac.name(), mac.asMacroData());
1576 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1583 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1584 InsetBase::Code code)
1586 //FIXME: This does not work for child documents yet.
1587 BOOST_ASSERT(code == InsetBase::CITE_CODE || code == InsetBase::REF_CODE);
1588 // Check if the label 'from' appears more than once
1589 vector<docstring> labels;
1591 if (code == InsetBase::CITE_CODE) {
1592 vector<pair<string, string> > keys;
1593 fillWithBibKeys(keys);
1594 vector<pair<string, string> >::const_iterator bit = keys.begin();
1595 vector<pair<string, string> >::const_iterator bend = keys.end();
1597 for (; bit != bend; ++bit)
1599 labels.push_back(from_utf8(bit->first));
1601 getLabelList(labels);
1604 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1607 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1608 if (it->lyxCode() == code) {
1609 InsetCommand & inset = dynamic_cast<InsetCommand &>(*it);
1610 inset.replaceContents(to_utf8(from), to_utf8(to));
1616 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1617 pit_type par_end, bool full_source)
1619 OutputParams runparams;
1620 runparams.nice = true;
1621 runparams.flavor = OutputParams::LATEX;
1622 runparams.linelen = lyxrc.ascii_linelen;
1623 // No side effect of file copying and image conversion
1624 runparams.dryrun = true;
1626 /* Support for docbook temprarily commented out. */
1628 os << "% Preview source code\n\n";
1630 writeLaTeXSource(os, filePath(), runparams, true, true);
1632 writeDocBookSource(os, fileName(), runparams, false);
1635 runparams.par_begin = par_begin;
1636 runparams.par_end = par_end;
1637 if (par_begin + 1 == par_end)
1638 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1640 os << "% Preview source code from paragraph " << par_begin
1641 << " to " << par_end - 1 << "\n\n";
1642 // output paragraphs
1645 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1648 docbookParagraphs(paragraphs(), *this, os, runparams);
1654 ErrorList const & Buffer::errorList(string const & type) const
1656 static ErrorList const emptyErrorList;
1657 std::map<std::string, ErrorList>::const_iterator I = errorLists_.find(type);
1658 if (I == errorLists_.end())
1659 return emptyErrorList;
1665 ErrorList & Buffer::errorList(string const & type)
1667 return errorLists_[type];