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 void Buffer::makeLaTeXFile(string const & fname,
816 string const & original_path,
817 OutputParams const & runparams,
818 bool output_preamble, bool output_body)
820 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
823 // This creates an utf8 encoded file, but the inputenc commands
824 // specify other encodings
826 if (!openFileWrite(ofs, fname))
829 writeLaTeXSource(ofs, original_path,
830 runparams, output_preamble, output_body);
834 lyxerr << "File '" << fname << "' was not closed properly." << endl;
838 void Buffer::writeLaTeXSource(odocstream & os,
839 string const & original_path,
840 OutputParams const & runparams_in,
841 bool const output_preamble, bool const output_body)
843 OutputParams runparams = runparams_in;
845 // validate the buffer.
846 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
847 LaTeXFeatures features(*this, params(), runparams);
849 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
853 // The starting paragraph of the coming rows is the
854 // first paragraph of the document. (Asger)
855 texrow().start(paragraphs().begin()->id(), 0);
857 if (output_preamble && runparams.nice) {
858 os << "%% LyX " << lyx_version << " created this file. "
859 "For more info, see http://www.lyx.org/.\n"
860 "%% Do not edit unless you really know what "
865 lyxerr[Debug::INFO] << "lyx document header finished" << endl;
866 // There are a few differences between nice LaTeX and usual files:
867 // usual is \batchmode and has a
868 // special input@path to allow the including of figures
869 // with either \input or \includegraphics (what figinsets do).
870 // input@path is set when the actual parameter
871 // original_path is set. This is done for usual tex-file, but not
872 // for nice-latex-file. (Matthias 250696)
873 // Note that input@path is only needed for something the user does
874 // in the preamble, included .tex files or ERT, files included by
875 // LyX work without it.
876 if (output_preamble) {
877 if (!runparams.nice) {
878 // code for usual, NOT nice-latex-file
879 os << "\\batchmode\n"; // changed
883 if (!original_path.empty()) {
885 // We don't know the encoding of inputpath
886 docstring const inputpath = from_utf8(latex_path(original_path));
887 os << "\\makeatletter\n"
888 << "\\def\\input@path{{"
889 << inputpath << "/}}\n"
890 << "\\makeatother\n";
896 // Write the preamble
897 runparams.use_babel = params().writeLaTeX(os, features, texrow());
903 os << "\\begin{document}\n";
906 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
908 if (!lyxrc.language_auto_begin) {
910 os << from_utf8(subst(lyxrc.language_command_begin,
912 params().language->babel()))
917 // if we are doing a real file with body, even if this is the
918 // child of some other buffer, let's cut the link here.
919 // This happens for example if only a child document is printed.
920 string save_parentname;
921 if (output_preamble) {
922 save_parentname = params().parentname;
923 params().parentname.erase();
927 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
929 // Restore the parenthood if needed
931 params().parentname = save_parentname;
933 // add this just in case after all the paragraphs
937 if (!lyxrc.language_auto_end) {
938 os << from_utf8(subst(lyxrc.language_command_end,
940 params().language->babel()))
945 if (output_preamble) {
946 os << "\\end{document}\n";
949 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
951 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
955 // Just to be sure. (Asger)
958 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
959 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
964 bool Buffer::isLatex() const
966 return params().getLyXTextClass().outputType() == LATEX;
970 bool Buffer::isLiterate() const
972 return params().getLyXTextClass().outputType() == LITERATE;
976 bool Buffer::isDocBook() const
978 return params().getLyXTextClass().outputType() == DOCBOOK;
982 void Buffer::makeDocBookFile(string const & fname,
983 OutputParams const & runparams,
984 bool const body_only)
986 lyxerr[Debug::LATEX] << "makeDocBookFile..." << endl;
990 if (!openFileWrite(ofs, fname))
993 writeDocBookSource(ofs, fname, runparams, body_only);
997 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1001 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1002 OutputParams const & runparams,
1003 bool const only_body)
1005 LaTeXFeatures features(*this, params(), runparams);
1010 LyXTextClass const & tclass = params().getLyXTextClass();
1011 string const top_element = tclass.latexname();
1014 if (runparams.flavor == OutputParams::XML)
1015 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1018 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1021 if (! tclass.class_header().empty())
1022 os << from_ascii(tclass.class_header());
1023 else if (runparams.flavor == OutputParams::XML)
1024 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1025 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1027 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1029 docstring preamble = from_utf8(params().preamble);
1030 if (runparams.flavor != OutputParams::XML ) {
1031 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1032 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1033 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1034 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1037 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1039 preamble += features.getIncludedFiles(name);
1040 preamble += features.getLyXSGMLEntities();
1042 if (!preamble.empty()) {
1043 os << "\n [ " << preamble << " ]";
1048 string top = top_element;
1050 if (runparams.flavor == OutputParams::XML)
1051 top += params().language->code();
1053 top += params().language->code().substr(0,2);
1056 if (!params().options.empty()) {
1058 top += params().options;
1061 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1062 << " file was created by LyX " << lyx_version
1063 << "\n See http://www.lyx.org/ for more information -->\n";
1065 params().getLyXTextClass().counters().reset();
1067 sgml::openTag(os, top);
1069 docbookParagraphs(paragraphs(), *this, os, runparams);
1070 sgml::closeTag(os, top_element);
1074 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1075 // Other flags: -wall -v0 -x
1076 int Buffer::runChktex()
1080 // get LaTeX-Filename
1081 string const name = getLatexName();
1082 string const path = temppath();
1083 string const org_path = filePath();
1085 support::Path p(path); // path to LaTeX file
1086 message(_("Running chktex..."));
1088 // Generate the LaTeX file if neccessary
1089 OutputParams runparams;
1090 runparams.flavor = OutputParams::LATEX;
1091 runparams.nice = false;
1092 makeLaTeXFile(name, org_path, runparams);
1095 Chktex chktex(lyxrc.chktex_command, name, filePath());
1096 int const res = chktex.run(terr); // run chktex
1099 Alert::error(_("chktex failure"),
1100 _("Could not run chktex successfully."));
1101 } else if (res > 0) {
1102 // Fill-in the error list with the TeX errors
1103 bufferErrors(*this, terr, errorLists_["ChkTex"]);
1114 void Buffer::validate(LaTeXFeatures & features) const
1116 LyXTextClass const & tclass = params().getLyXTextClass();
1118 if (features.isAvailable("dvipost") && params().outputChanges)
1119 features.require("dvipost");
1121 // AMS Style is at document level
1122 if (params().use_amsmath == BufferParams::AMS_ON
1123 || tclass.provides(LyXTextClass::amsmath))
1124 features.require("amsmath");
1126 for_each(paragraphs().begin(), paragraphs().end(),
1127 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1129 // the bullet shapes are buffer level not paragraph level
1130 // so they are tested here
1131 for (int i = 0; i < 4; ++i) {
1132 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1133 int const font = params().user_defined_bullet(i).getFont();
1135 int const c = params()
1136 .user_defined_bullet(i)
1143 features.require("latexsym");
1145 } else if (font == 1) {
1146 features.require("amssymb");
1147 } else if ((font >= 2 && font <= 5)) {
1148 features.require("pifont");
1153 if (lyxerr.debugging(Debug::LATEX)) {
1154 features.showStruct();
1159 void Buffer::getLabelList(vector<docstring> & list) const
1161 /// if this is a child document and the parent is already loaded
1162 /// Use the parent's list instead [ale990407]
1163 Buffer const * tmp = getMasterBuffer();
1165 lyxerr << "getMasterBuffer() failed!" << endl;
1169 tmp->getLabelList(list);
1173 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1174 it.nextInset()->getLabelList(*this, list);
1178 // This is also a buffer property (ale)
1179 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1182 /// if this is a child document and the parent is already loaded
1183 /// use the parent's list instead [ale990412]
1184 Buffer const * tmp = getMasterBuffer();
1187 tmp->fillWithBibKeys(keys);
1191 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1192 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1193 InsetBibtex const & inset =
1194 dynamic_cast<InsetBibtex const &>(*it);
1195 inset.fillWithBibKeys(*this, keys);
1196 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1197 InsetInclude const & inset =
1198 dynamic_cast<InsetInclude const &>(*it);
1199 inset.fillWithBibKeys(*this, keys);
1200 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1201 InsetBibitem const & inset =
1202 dynamic_cast<InsetBibitem const &>(*it);
1203 string const key = inset.getContents();
1204 string const opt = inset.getOptions();
1205 string const ref; // = pit->asString(this, false);
1206 string const info = opt + "TheBibliographyRef" + ref;
1207 keys.push_back(pair<string, string>(key, info));
1213 void Buffer::updateBibfilesCache()
1215 // if this is a child document and the parent is already loaded
1216 // update the parent's cache instead
1217 Buffer * tmp = getMasterBuffer();
1220 tmp->updateBibfilesCache();
1224 bibfilesCache_.clear();
1225 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1226 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1227 InsetBibtex const & inset =
1228 dynamic_cast<InsetBibtex const &>(*it);
1229 vector<string> const bibfiles = inset.getFiles(*this);
1230 bibfilesCache_.insert(bibfilesCache_.end(),
1233 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1234 InsetInclude & inset =
1235 dynamic_cast<InsetInclude &>(*it);
1236 inset.updateBibfilesCache(*this);
1237 vector<string> const & bibfiles =
1238 inset.getBibfilesCache(*this);
1239 bibfilesCache_.insert(bibfilesCache_.end(),
1247 vector<string> const & Buffer::getBibfilesCache() const
1249 // if this is a child document and the parent is already loaded
1250 // use the parent's cache instead
1251 Buffer const * tmp = getMasterBuffer();
1254 return tmp->getBibfilesCache();
1256 return bibfilesCache_;
1260 bool Buffer::isDepClean(string const & name) const
1262 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1263 if (it == pimpl_->dep_clean.end())
1269 void Buffer::markDepClean(string const & name)
1271 pimpl_->dep_clean[name] = true;
1275 bool Buffer::dispatch(string const & command, bool * result)
1277 return dispatch(lyxaction.lookupFunc(command), result);
1281 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1283 bool dispatched = true;
1285 switch (func.action) {
1286 case LFUN_BUFFER_EXPORT: {
1287 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1300 void Buffer::changeLanguage(Language const * from, Language const * to)
1305 // Take care of l10n/i18n
1308 for_each(par_iterator_begin(),
1310 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1312 text().current_font.setLanguage(to);
1313 text().real_current_font.setLanguage(to);
1317 void Buffer::updateDocLang(Language const * nlang)
1319 BOOST_ASSERT(nlang);
1321 pimpl_->messages.reset(new Messages(nlang->code()));
1323 updateLabels(*this);
1327 bool Buffer::isMultiLingual() const
1329 ParConstIterator end = par_iterator_end();
1330 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1331 if (it->isMultiLingual(params()))
1338 ParIterator Buffer::getParFromID(int const id) const
1340 ParConstIterator it = par_iterator_begin();
1341 ParConstIterator const end = par_iterator_end();
1344 // John says this is called with id == -1 from undo
1345 lyxerr << "getParFromID(), id: " << id << endl;
1349 for (; it != end; ++it)
1357 bool Buffer::hasParWithID(int const id) const
1359 ParConstIterator const it = getParFromID(id);
1360 return it != par_iterator_end();
1364 ParIterator Buffer::par_iterator_begin()
1366 return lyx::par_iterator_begin(inset());
1370 ParIterator Buffer::par_iterator_end()
1372 return lyx::par_iterator_end(inset());
1376 ParConstIterator Buffer::par_iterator_begin() const
1378 return lyx::par_const_iterator_begin(inset());
1382 ParConstIterator Buffer::par_iterator_end() const
1384 return lyx::par_const_iterator_end(inset());
1388 Language const * Buffer::getLanguage() const
1390 return params().language;
1394 docstring const Buffer::B_(string const & l10n) const
1396 if (pimpl_->messages.get())
1397 return pimpl_->messages->get(l10n);
1403 bool Buffer::isClean() const
1405 return pimpl_->lyx_clean;
1409 bool Buffer::isBakClean() const
1411 return pimpl_->bak_clean;
1415 void Buffer::markClean() const
1417 if (!pimpl_->lyx_clean) {
1418 pimpl_->lyx_clean = true;
1421 // if the .lyx file has been saved, we don't need an
1423 pimpl_->bak_clean = true;
1427 void Buffer::markBakClean()
1429 pimpl_->bak_clean = true;
1433 void Buffer::setUnnamed(bool flag)
1435 pimpl_->unnamed = flag;
1439 bool Buffer::isUnnamed() const
1441 return pimpl_->unnamed;
1445 #ifdef WITH_WARNINGS
1446 #warning this function should be moved to buffer_pimpl.C
1448 void Buffer::markDirty()
1450 if (pimpl_->lyx_clean) {
1451 pimpl_->lyx_clean = false;
1454 pimpl_->bak_clean = false;
1456 DepClean::iterator it = pimpl_->dep_clean.begin();
1457 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1459 for (; it != end; ++it)
1464 string const & Buffer::fileName() const
1466 return pimpl_->filename;
1470 string const & Buffer::filePath() const
1472 return params().filepath;
1476 bool Buffer::isReadonly() const
1478 return pimpl_->read_only;
1482 void Buffer::setParentName(string const & name)
1484 params().parentname = name;
1488 Buffer const * Buffer::getMasterBuffer() const
1490 if (!params().parentname.empty()
1491 && theBufferList().exists(params().parentname)) {
1492 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1494 return buf->getMasterBuffer();
1501 Buffer * Buffer::getMasterBuffer()
1503 if (!params().parentname.empty()
1504 && theBufferList().exists(params().parentname)) {
1505 Buffer * buf = theBufferList().getBuffer(params().parentname);
1507 return buf->getMasterBuffer();
1514 MacroData const & Buffer::getMacro(docstring const & name) const
1516 return pimpl_->macros.get(name);
1520 bool Buffer::hasMacro(docstring const & name) const
1522 return pimpl_->macros.has(name);
1526 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1528 MacroTable::globalMacros().insert(name, data);
1529 pimpl_->macros.insert(name, data);
1533 void Buffer::buildMacros()
1535 // Start with global table.
1536 pimpl_->macros = MacroTable::globalMacros();
1539 ParagraphList const & pars = text().paragraphs();
1540 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1541 //lyxerr << "searching main par " << i
1542 // << " for macro definitions" << std::endl;
1543 InsetList const & insets = pars[i].insetlist;
1544 InsetList::const_iterator it = insets.begin();
1545 InsetList::const_iterator end = insets.end();
1546 for ( ; it != end; ++it) {
1547 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1548 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1549 MathMacroTemplate const & mac
1550 = static_cast<MathMacroTemplate const &>(*it->inset);
1551 insertMacro(mac.name(), mac.asMacroData());
1558 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1565 void Buffer::changeRefsIfUnique(string const & from, string const & to, InsetBase::Code code)
1567 //FIXME: This does not work for child documents yet.
1568 BOOST_ASSERT(code == InsetBase::CITE_CODE || code == InsetBase::REF_CODE);
1569 // Check if the label 'from' appears more than once
1570 vector<docstring> labels;
1572 if (code == InsetBase::CITE_CODE) {
1573 vector<pair<string, string> > keys;
1574 fillWithBibKeys(keys);
1575 vector<pair<string, string> >::const_iterator bit = keys.begin();
1576 vector<pair<string, string> >::const_iterator bend = keys.end();
1578 for (; bit != bend; ++bit)
1580 labels.push_back(from_utf8(bit->first));
1582 getLabelList(labels);
1585 if (lyx::count(labels.begin(), labels.end(), from_utf8(from)) > 1)
1588 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1589 if (it->lyxCode() == code) {
1590 InsetCommand & inset = dynamic_cast<InsetCommand &>(*it);
1591 inset.replaceContents(from, to);
1597 void Buffer::getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end, bool full_source)
1599 OutputParams runparams;
1600 runparams.nice = true;
1601 runparams.flavor = OutputParams::LATEX;
1602 runparams.linelen = lyxrc.ascii_linelen;
1603 // No side effect of file copying and image conversion
1604 runparams.dryrun = true;
1606 /* Support for docbook temprarily commented out. */
1608 os << "% Preview source code\n\n";
1610 writeLaTeXSource(os, filePath(), runparams, true, true);
1612 writeDocBookSource(os, fileName(), runparams, false);
1615 runparams.par_begin = par_begin;
1616 runparams.par_end = par_end;
1617 if (par_begin + 1 == par_end)
1618 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1620 os << "% Preview source code from paragraph " << par_begin << " to " << par_end - 1 << "\n\n";
1621 // output paragraphs
1624 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1627 docbookParagraphs(paragraphs(), *this, os, runparams);
1633 ErrorList const & Buffer::errorList(string const & type) const
1635 static ErrorList const emptyErrorList;
1636 std::map<std::string, ErrorList>::const_iterator I = errorLists_.find(type);
1637 if (I == errorLists_.end())
1638 return emptyErrorList;
1644 ErrorList & Buffer::errorList(string const & type)
1646 return errorLists_[type];