3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
16 #include "BranchList.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
25 #include "ErrorList.h"
28 #include "FuncRequest.h"
30 #include "InsetIterator.h"
33 #include "LaTeXFeatures.h"
34 #include "LyXAction.h"
42 #include "output_docbook.h"
43 #include "output_latex.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
50 #include "TocBackend.h"
54 #include "insets/InsetBibitem.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetInclude.h"
57 #include "insets/InsetText.h"
59 #include "mathed/MathMacroTemplate.h"
60 #include "mathed/MacroTable.h"
61 #include "mathed/MathSupport.h"
63 #include "frontends/alert.h"
65 #include "graphics/Previews.h"
67 #include "support/types.h"
68 #include "support/lyxalgo.h"
69 #include "support/filetools.h"
70 #include "support/fs_extras.h"
71 #include "support/lyxlib.h"
72 #include "support/os.h"
73 #include "support/Path.h"
74 #include "support/textutils.h"
75 #include "support/convert.h"
77 #include <boost/iostreams/filtering_stream.hpp>
78 #include <boost/iostreams/filter/gzip.hpp>
79 #include <boost/iostreams/device/file.hpp>
80 #include <boost/bind.hpp>
81 #include <boost/filesystem/exception.hpp>
82 #include <boost/filesystem/operations.hpp>
84 #if defined (HAVE_UTIME_H)
86 #elif defined (HAVE_SYS_UTIME_H)
87 #include <sys/utime.h>
98 using support::addName;
99 using support::bformat;
100 using support::changeExtension;
101 using support::cmd_ret;
102 using support::createBufferTmpDir;
103 using support::destroyDir;
104 using support::FileName;
105 using support::getFormatFromContents;
106 using support::libFileSearch;
107 using support::latex_path;
108 using support::ltrim;
109 using support::makeAbsPath;
110 using support::makeDisplayPath;
111 using support::makeLatexName;
112 using support::onlyFilename;
113 using support::onlyPath;
114 using support::quoteName;
115 using support::removeAutosaveFile;
116 using support::rename;
117 using support::runCommand;
118 using support::split;
119 using support::subst;
120 using support::tempName;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
125 namespace fs = boost::filesystem;
126 namespace io = boost::iostreams;
130 using std::make_pair;
135 using std::ostringstream;
145 int const LYX_FORMAT = 271;
150 typedef std::map<string, bool> DepClean;
155 Impl(Buffer & parent, FileName 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 /** Set to true only when the file is fully loaded.
183 * Used to prevent the premature generation of previews
184 * and by the citation inset.
186 bool file_fully_loaded;
188 /// our Text that should be wrapped in an InsetText
195 TocBackend toc_backend;
199 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
200 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
201 filename(file), file_fully_loaded(false), inset(params),
204 inset.setAutoBreakRows(true);
205 lyxvc.buffer(&parent);
206 temppath = createBufferTmpDir();
207 params.filepath = onlyPath(file.absFilename());
208 // FIXME: And now do something if temppath == string(), because we
209 // assume from now on that temppath points to a valid temp dir.
210 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
214 Buffer::Buffer(string const & file, bool readonly)
215 : pimpl_(new Impl(*this, FileName(file), readonly))
217 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
223 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
224 // here the buffer should take care that it is
225 // saved properly, before it goes into the void.
229 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
230 Alert::warning(_("Could not remove temporary directory"),
231 bformat(_("Could not remove the temporary directory %1$s"),
232 from_utf8(temppath())));
235 // Remove any previewed LaTeX snippets associated with this buffer.
236 graphics::Previews::get().removeLoader(*this);
240 Text & Buffer::text() const
242 return const_cast<Text &>(pimpl_->inset.text_);
246 Inset & Buffer::inset() const
248 return const_cast<InsetText &>(pimpl_->inset);
252 limited_stack<Undo> & Buffer::undostack()
254 return pimpl_->undostack;
258 limited_stack<Undo> const & Buffer::undostack() const
260 return pimpl_->undostack;
264 limited_stack<Undo> & Buffer::redostack()
266 return pimpl_->redostack;
270 limited_stack<Undo> const & Buffer::redostack() const
272 return pimpl_->redostack;
276 BufferParams & Buffer::params()
278 return pimpl_->params;
282 BufferParams const & Buffer::params() const
284 return pimpl_->params;
288 ParagraphList & Buffer::paragraphs()
290 return text().paragraphs();
294 ParagraphList const & Buffer::paragraphs() const
296 return text().paragraphs();
300 LyXVC & Buffer::lyxvc()
302 return pimpl_->lyxvc;
306 LyXVC const & Buffer::lyxvc() const
308 return pimpl_->lyxvc;
312 string const & Buffer::temppath() const
314 return pimpl_->temppath;
318 TexRow & Buffer::texrow()
320 return pimpl_->texrow;
324 TexRow const & Buffer::texrow() const
326 return pimpl_->texrow;
330 TocBackend & Buffer::tocBackend()
332 return pimpl_->toc_backend;
336 TocBackend const & Buffer::tocBackend() const
338 return pimpl_->toc_backend;
342 string const Buffer::getLatexName(bool const no_path) const
344 string const name = changeExtension(makeLatexName(fileName()), ".tex");
345 return no_path ? onlyFilename(name) : name;
349 pair<Buffer::LogType, string> const Buffer::getLogName() const
351 string const filename = getLatexName(false);
353 if (filename.empty())
354 return make_pair(Buffer::latexlog, string());
356 string const path = temppath();
358 FileName const fname(addName(temppath(),
359 onlyFilename(changeExtension(filename,
361 FileName const bname(
362 addName(path, onlyFilename(
363 changeExtension(filename,
364 formats.extension("literate") + ".out"))));
366 // If no Latex log or Build log is newer, show Build log
368 if (fs::exists(bname.toFilesystemEncoding()) &&
369 (!fs::exists(fname.toFilesystemEncoding()) ||
370 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
371 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
372 return make_pair(Buffer::buildlog, bname.absFilename());
374 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
375 return make_pair(Buffer::latexlog, fname.absFilename());
379 void Buffer::setReadonly(bool const flag)
381 if (pimpl_->read_only != flag) {
382 pimpl_->read_only = flag;
388 void Buffer::setFileName(string const & newfile)
390 pimpl_->filename = makeAbsPath(newfile);
391 params().filepath = onlyPath(pimpl_->filename.absFilename());
392 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
397 // We'll remove this later. (Lgb)
400 void unknownClass(string const & unknown)
402 Alert::warning(_("Unknown document class"),
403 bformat(_("Using the default document class, because the "
404 "class %1$s is unknown."), from_utf8(unknown)));
410 int Buffer::readHeader(Lexer & lex)
412 int unknown_tokens = 0;
414 int begin_header_line = -1;
416 // Initialize parameters that may be/go lacking in header:
417 params().branchlist().clear();
418 params().preamble.erase();
419 params().options.erase();
420 params().float_placement.erase();
421 params().paperwidth.erase();
422 params().paperheight.erase();
423 params().leftmargin.erase();
424 params().rightmargin.erase();
425 params().topmargin.erase();
426 params().bottommargin.erase();
427 params().headheight.erase();
428 params().headsep.erase();
429 params().footskip.erase();
430 params().listings_params.clear();
431 for (int i = 0; i < 4; ++i) {
432 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
433 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
436 ErrorList & errorList = errorLists_["Parse"];
440 string const token = lex.getString();
445 if (token == "\\end_header")
449 if (token == "\\begin_header") {
450 begin_header_line = line;
454 LYXERR(Debug::PARSER) << "Handling document header token: `"
455 << token << '\'' << endl;
457 string unknown = params().readToken(lex, token);
458 if (!unknown.empty()) {
459 if (unknown[0] != '\\' && token == "\\textclass") {
460 unknownClass(unknown);
463 docstring const s = bformat(_("Unknown token: "
467 errorList.push_back(ErrorItem(_("Document header error"),
472 if (begin_header_line) {
473 docstring const s = _("\\begin_header is missing");
474 errorList.push_back(ErrorItem(_("Document header error"),
478 return unknown_tokens;
483 // changed to be public and have one parameter
484 // Returns false if "\end_document" is not read (Asger)
485 bool Buffer::readDocument(Lexer & lex)
487 ErrorList & errorList = errorLists_["Parse"];
491 string const token = lex.getString();
492 if (token != "\\begin_document") {
493 docstring const s = _("\\begin_document is missing");
494 errorList.push_back(ErrorItem(_("Document header error"),
498 // we are reading in a brand new document
499 BOOST_ASSERT(paragraphs().empty());
502 if (!params().getTextClass().load(filePath())) {
503 string theclass = params().getTextClass().name();
504 Alert::error(_("Can't load document class"), bformat(
505 _("Using the default document class, because the "
506 "class %1$s could not be loaded."), from_utf8(theclass)));
507 params().textclass = 0;
510 if (params().outputChanges) {
511 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
512 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
513 LaTeXFeatures::isAvailable("xcolor");
515 if (!dvipost && !xcolorsoul) {
516 Alert::warning(_("Changes not shown in LaTeX output"),
517 _("Changes will not be highlighted in LaTeX output, "
518 "because neither dvipost nor xcolor/soul are installed.\n"
519 "Please install these packages or redefine "
520 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
521 } else if (!xcolorsoul) {
522 Alert::warning(_("Changes not shown in LaTeX output"),
523 _("Changes will not be highlighted in LaTeX output "
524 "when using pdflatex, because xcolor and soul are not installed.\n"
525 "Please install both packages or redefine "
526 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
530 bool const res = text().read(*this, lex, errorList);
531 for_each(text().paragraphs().begin(),
532 text().paragraphs().end(),
533 bind(&Paragraph::setInsetOwner, _1, &inset()));
539 // needed to insert the selection
540 void Buffer::insertStringAsLines(ParagraphList & pars,
541 pit_type & pit, pos_type & pos,
542 Font const & fn, docstring const & str, bool autobreakrows)
546 // insert the string, don't insert doublespace
547 bool space_inserted = true;
548 for (docstring::const_iterator cit = str.begin();
549 cit != str.end(); ++cit) {
550 Paragraph & par = pars[pit];
552 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
553 breakParagraph(params(), pars, pit, pos,
554 par.layout()->isEnvironment());
557 space_inserted = true;
561 // do not insert consecutive spaces if !free_spacing
562 } else if ((*cit == ' ' || *cit == '\t') &&
563 space_inserted && !par.isFreeSpacing()) {
565 } else if (*cit == '\t') {
566 if (!par.isFreeSpacing()) {
567 // tabs are like spaces here
568 par.insertChar(pos, ' ', font, params().trackChanges);
570 space_inserted = true;
572 const pos_type n = 8 - pos % 8;
573 for (pos_type i = 0; i < n; ++i) {
574 par.insertChar(pos, ' ', font, params().trackChanges);
577 space_inserted = true;
579 } else if (!isPrintable(*cit)) {
580 // Ignore unprintables
583 // just insert the character
584 par.insertChar(pos, *cit, font, params().trackChanges);
586 space_inserted = (*cit == ' ');
593 bool Buffer::readString(std::string const & s)
595 params().compressed = false;
597 // remove dummy empty par
598 paragraphs().clear();
600 std::istringstream is(s);
602 FileName const name(tempName());
603 switch (readFile(lex, name, true)) {
607 // We need to call lyx2lyx, so write the input to a file
608 std::ofstream os(name.toFilesystemEncoding().c_str());
611 return readFile(name);
621 bool Buffer::readFile(FileName const & filename)
623 // Check if the file is compressed.
624 string const format = getFormatFromContents(filename);
625 if (format == "gzip" || format == "zip" || format == "compress") {
626 params().compressed = true;
629 // remove dummy empty par
630 paragraphs().clear();
632 lex.setFile(filename);
633 if (readFile(lex, filename) != success)
640 bool Buffer::fully_loaded() const
642 return pimpl_->file_fully_loaded;
646 void Buffer::fully_loaded(bool const value)
648 pimpl_->file_fully_loaded = value;
652 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
655 BOOST_ASSERT(!filename.empty());
658 Alert::error(_("Document could not be read"),
659 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
664 string const token(lex.getString());
667 Alert::error(_("Document could not be read"),
668 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
672 // the first token _must_ be...
673 if (token != "\\lyxformat") {
674 lyxerr << "Token: " << token << endl;
676 Alert::error(_("Document format failure"),
677 bformat(_("%1$s is not a LyX document."),
678 from_utf8(filename.absFilename())));
683 string tmp_format = lex.getString();
684 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
685 // if present remove ".," from string.
686 string::size_type dot = tmp_format.find_first_of(".,");
687 //lyxerr << " dot found at " << dot << endl;
688 if (dot != string::npos)
689 tmp_format.erase(dot, 1);
690 int const file_format = convert<int>(tmp_format);
691 //lyxerr << "format: " << file_format << endl;
693 if (file_format != LYX_FORMAT) {
696 // lyx2lyx would fail
699 FileName const tmpfile(tempName());
700 if (tmpfile.empty()) {
701 Alert::error(_("Conversion failed"),
702 bformat(_("%1$s is from a different"
703 " version of LyX, but a temporary"
704 " file for converting it could"
706 from_utf8(filename.absFilename())));
709 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
710 if (lyx2lyx.empty()) {
711 Alert::error(_("Conversion script not found"),
712 bformat(_("%1$s is from a different"
713 " version of LyX, but the"
714 " conversion script lyx2lyx"
715 " could not be found."),
716 from_utf8(filename.absFilename())));
719 ostringstream command;
720 command << os::python()
721 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
722 << " -t " << convert<string>(LYX_FORMAT)
723 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
724 << ' ' << quoteName(filename.toFilesystemEncoding());
725 string const command_str = command.str();
727 LYXERR(Debug::INFO) << "Running '"
728 << command_str << '\''
731 cmd_ret const ret = runCommand(command_str);
732 if (ret.first != 0) {
733 Alert::error(_("Conversion script failed"),
734 bformat(_("%1$s is from a different version"
735 " of LyX, but the lyx2lyx script"
736 " failed to convert it."),
737 from_utf8(filename.absFilename())));
740 bool const ret = readFile(tmpfile);
741 // Do stuff with tmpfile name and buffer name here.
742 return ret ? success : failure;
747 if (readDocument(lex)) {
748 Alert::error(_("Document format failure"),
749 bformat(_("%1$s ended unexpectedly, which means"
750 " that it is probably corrupted."),
751 from_utf8(filename.absFilename())));
754 //lyxerr << "removing " << MacroTable::localMacros().size()
755 // << " temporary macro entries" << endl;
756 //MacroTable::localMacros().clear();
758 pimpl_->file_fully_loaded = true;
763 // Should probably be moved to somewhere else: BufferView? LyXView?
764 bool Buffer::save() const
766 // We don't need autosaves in the immediate future. (Asger)
767 resetAutosaveTimers();
769 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
772 bool madeBackup = false;
774 // make a backup if the file already exists
775 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
776 backupName = FileName(fileName() + '~');
777 if (!lyxrc.backupdir_path.empty())
778 backupName = FileName(addName(lyxrc.backupdir_path,
779 subst(os::internal_path(backupName.absFilename()), '/', '!')));
782 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
784 } catch (fs::filesystem_error const & fe) {
785 Alert::error(_("Backup failure"),
786 bformat(_("Cannot create backup file %1$s.\n"
787 "Please check whether the directory exists and is writeable."),
788 from_utf8(backupName.absFilename())));
789 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
793 if (writeFile(pimpl_->filename)) {
795 removeAutosaveFile(fileName());
798 // Saving failed, so backup is not backup
800 rename(backupName, pimpl_->filename);
806 bool Buffer::writeFile(FileName const & fname) const
808 if (pimpl_->read_only && fname == pimpl_->filename)
813 if (params().compressed) {
814 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
820 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
831 bool Buffer::write(ostream & ofs) const
834 // Use the standard "C" locale for file output.
835 ofs.imbue(std::locale::classic());
838 // The top of the file should not be written by params().
840 // write out a comment in the top of the file
841 ofs << "#LyX " << lyx_version
842 << " created this file. For more info see http://www.lyx.org/\n"
843 << "\\lyxformat " << LYX_FORMAT << "\n"
844 << "\\begin_document\n";
846 // now write out the buffer parameters.
847 ofs << "\\begin_header\n";
848 params().writeFile(ofs);
849 ofs << "\\end_header\n";
852 ofs << "\n\\begin_body\n";
853 text().write(*this, ofs);
854 ofs << "\n\\end_body\n";
856 // Write marker that shows file is complete
857 ofs << "\\end_document" << endl;
859 // Shouldn't really be needed....
862 // how to check if close went ok?
863 // Following is an attempt... (BE 20001011)
865 // good() returns false if any error occured, including some
867 // bad() returns true if something bad happened in the buffer,
868 // which should include file system full errors.
873 lyxerr << "File was not closed properly." << endl;
880 bool Buffer::makeLaTeXFile(FileName const & fname,
881 string const & original_path,
882 OutputParams const & runparams,
883 bool output_preamble, bool output_body)
885 string const encoding = runparams.encoding->iconvName();
886 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
887 << encoding << "..." << endl;
889 odocfstream ofs(encoding);
890 if (!openFileWrite(ofs, fname))
893 bool failed_export = false;
895 writeLaTeXSource(ofs, original_path,
896 runparams, output_preamble, output_body);
898 catch (iconv_codecvt_facet_exception & e) {
899 lyxerr << "Caught iconv exception: " << e.what() << endl;
900 failed_export = true;
902 catch (std::exception const & e) {
903 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
904 failed_export = true;
907 lyxerr << "Caught some really weird exception..." << endl;
908 LyX::cref().emergencyCleanup();
914 failed_export = true;
915 lyxerr << "File '" << fname << "' was not closed properly." << endl;
919 Alert::error(_("Encoding error"),
920 _("Some characters of your document are probably not "
921 "representable in the chosen encoding.\n"
922 "Changing the document encoding to utf8 could help."));
929 void Buffer::writeLaTeXSource(odocstream & os,
930 string const & original_path,
931 OutputParams const & runparams_in,
932 bool const output_preamble, bool const output_body)
934 OutputParams runparams = runparams_in;
936 // validate the buffer.
937 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
938 LaTeXFeatures features(*this, params(), runparams);
940 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
944 // The starting paragraph of the coming rows is the
945 // first paragraph of the document. (Asger)
946 texrow().start(paragraphs().begin()->id(), 0);
948 if (output_preamble && runparams.nice) {
949 os << "%% LyX " << lyx_version << " created this file. "
950 "For more info, see http://www.lyx.org/.\n"
951 "%% Do not edit unless you really know what "
956 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
957 // There are a few differences between nice LaTeX and usual files:
958 // usual is \batchmode and has a
959 // special input@path to allow the including of figures
960 // with either \input or \includegraphics (what figinsets do).
961 // input@path is set when the actual parameter
962 // original_path is set. This is done for usual tex-file, but not
963 // for nice-latex-file. (Matthias 250696)
964 // Note that input@path is only needed for something the user does
965 // in the preamble, included .tex files or ERT, files included by
966 // LyX work without it.
967 if (output_preamble) {
968 if (!runparams.nice) {
969 // code for usual, NOT nice-latex-file
970 os << "\\batchmode\n"; // changed
974 if (!original_path.empty()) {
976 // We don't know the encoding of inputpath
977 docstring const inputpath = from_utf8(latex_path(original_path));
978 os << "\\makeatletter\n"
979 << "\\def\\input@path{{"
980 << inputpath << "/}}\n"
981 << "\\makeatother\n";
987 // Write the preamble
988 runparams.use_babel = params().writeLaTeX(os, features, texrow());
994 os << "\\begin{document}\n";
997 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
999 if (!lyxrc.language_auto_begin &&
1000 !params().language->babel().empty()) {
1002 os << from_utf8(subst(lyxrc.language_command_begin,
1004 params().language->babel()))
1009 Encoding const & encoding = params().encoding();
1010 if (encoding.package() == Encoding::CJK) {
1011 // Open a CJK environment, since in contrast to the encodings
1012 // handled by inputenc the document encoding is not set in
1013 // the preamble if it is handled by CJK.sty.
1014 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1019 // if we are doing a real file with body, even if this is the
1020 // child of some other buffer, let's cut the link here.
1021 // This happens for example if only a child document is printed.
1022 string save_parentname;
1023 if (output_preamble) {
1024 save_parentname = params().parentname;
1025 params().parentname.erase();
1029 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1031 // Restore the parenthood if needed
1032 if (output_preamble)
1033 params().parentname = save_parentname;
1035 // add this just in case after all the paragraphs
1039 if (encoding.package() == Encoding::CJK) {
1040 // Close the open CJK environment.
1041 // latexParagraphs will have opened one even if the last text
1043 os << "\\end{CJK}\n";
1047 if (!lyxrc.language_auto_end &&
1048 !params().language->babel().empty()) {
1049 os << from_utf8(subst(lyxrc.language_command_end,
1051 params().language->babel()))
1056 if (output_preamble) {
1057 os << "\\end{document}\n";
1060 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1062 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1065 runparams_in.encoding = runparams.encoding;
1067 // Just to be sure. (Asger)
1070 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1071 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1076 bool Buffer::isLatex() const
1078 return params().getTextClass().outputType() == LATEX;
1082 bool Buffer::isLiterate() const
1084 return params().getTextClass().outputType() == LITERATE;
1088 bool Buffer::isDocBook() const
1090 return params().getTextClass().outputType() == DOCBOOK;
1094 void Buffer::makeDocBookFile(FileName const & fname,
1095 OutputParams const & runparams,
1096 bool const body_only)
1098 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1102 if (!openFileWrite(ofs, fname))
1105 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1109 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1113 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1114 OutputParams const & runparams,
1115 bool const only_body)
1117 LaTeXFeatures features(*this, params(), runparams);
1122 TextClass const & tclass = params().getTextClass();
1123 string const top_element = tclass.latexname();
1126 if (runparams.flavor == OutputParams::XML)
1127 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1130 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1133 if (! tclass.class_header().empty())
1134 os << from_ascii(tclass.class_header());
1135 else if (runparams.flavor == OutputParams::XML)
1136 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1137 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1139 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1141 docstring preamble = from_utf8(params().preamble);
1142 if (runparams.flavor != OutputParams::XML ) {
1143 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1144 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1145 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1146 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1149 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1151 preamble += features.getIncludedFiles(name);
1152 preamble += features.getLyXSGMLEntities();
1154 if (!preamble.empty()) {
1155 os << "\n [ " << preamble << " ]";
1160 string top = top_element;
1162 if (runparams.flavor == OutputParams::XML)
1163 top += params().language->code();
1165 top += params().language->code().substr(0,2);
1168 if (!params().options.empty()) {
1170 top += params().options;
1173 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1174 << " file was created by LyX " << lyx_version
1175 << "\n See http://www.lyx.org/ for more information -->\n";
1177 params().getTextClass().counters().reset();
1179 sgml::openTag(os, top);
1181 docbookParagraphs(paragraphs(), *this, os, runparams);
1182 sgml::closeTag(os, top_element);
1186 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1187 // Other flags: -wall -v0 -x
1188 int Buffer::runChktex()
1192 // get LaTeX-Filename
1193 FileName const path(temppath());
1194 string const name = addName(path.absFilename(), getLatexName());
1195 string const org_path = filePath();
1197 support::Path p(path); // path to LaTeX file
1198 message(_("Running chktex..."));
1200 // Generate the LaTeX file if neccessary
1201 OutputParams runparams(¶ms().encoding());
1202 runparams.flavor = OutputParams::LATEX;
1203 runparams.nice = false;
1204 makeLaTeXFile(FileName(name), org_path, runparams);
1207 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1208 int const res = chktex.run(terr); // run chktex
1211 Alert::error(_("chktex failure"),
1212 _("Could not run chktex successfully."));
1213 } else if (res > 0) {
1214 ErrorList & errorList = errorLists_["ChkTeX"];
1215 // Clear out old errors
1217 // Fill-in the error list with the TeX errors
1218 bufferErrors(*this, terr, errorList);
1229 void Buffer::validate(LaTeXFeatures & features) const
1231 TextClass const & tclass = params().getTextClass();
1233 if (params().outputChanges) {
1234 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1235 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1236 LaTeXFeatures::isAvailable("xcolor");
1238 if (features.runparams().flavor == OutputParams::LATEX) {
1240 features.require("ct-dvipost");
1241 features.require("dvipost");
1242 } else if (xcolorsoul) {
1243 features.require("ct-xcolor-soul");
1244 features.require("soul");
1245 features.require("xcolor");
1247 features.require("ct-none");
1249 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1251 features.require("ct-xcolor-soul");
1252 features.require("soul");
1253 features.require("xcolor");
1254 features.require("pdfcolmk"); // improves color handling in PDF output
1256 features.require("ct-none");
1261 // AMS Style is at document level
1262 if (params().use_amsmath == BufferParams::package_on
1263 || tclass.provides("amsmath"))
1264 features.require("amsmath");
1265 if (params().use_esint == BufferParams::package_on)
1266 features.require("esint");
1268 for_each(paragraphs().begin(), paragraphs().end(),
1269 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1271 // the bullet shapes are buffer level not paragraph level
1272 // so they are tested here
1273 for (int i = 0; i < 4; ++i) {
1274 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1275 int const font = params().user_defined_bullet(i).getFont();
1277 int const c = params()
1278 .user_defined_bullet(i)
1285 features.require("latexsym");
1287 } else if (font == 1) {
1288 features.require("amssymb");
1289 } else if ((font >= 2 && font <= 5)) {
1290 features.require("pifont");
1295 if (lyxerr.debugging(Debug::LATEX)) {
1296 features.showStruct();
1301 void Buffer::getLabelList(vector<docstring> & list) const
1303 /// if this is a child document and the parent is already loaded
1304 /// Use the parent's list instead [ale990407]
1305 Buffer const * tmp = getMasterBuffer();
1307 lyxerr << "getMasterBuffer() failed!" << endl;
1311 tmp->getLabelList(list);
1315 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1316 it.nextInset()->getLabelList(*this, list);
1320 // This is also a buffer property (ale)
1321 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1324 /// if this is a child document and the parent is already loaded
1325 /// use the parent's list instead [ale990412]
1326 Buffer const * tmp = getMasterBuffer();
1329 tmp->fillWithBibKeys(keys);
1333 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1334 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1335 InsetBibtex const & inset =
1336 static_cast<InsetBibtex const &>(*it);
1337 inset.fillWithBibKeys(*this, keys);
1338 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1339 InsetInclude const & inset =
1340 static_cast<InsetInclude const &>(*it);
1341 inset.fillWithBibKeys(*this, keys);
1342 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1343 InsetBibitem const & inset =
1344 static_cast<InsetBibitem const &>(*it);
1346 string const key = to_utf8(inset.getParam("key"));
1347 docstring const label = inset.getParam("label");
1348 DocIterator doc_it(it); doc_it.forwardPos();
1349 docstring const ref = doc_it.paragraph().asString(*this, false);
1350 docstring const info = label + "TheBibliographyRef" + ref;
1351 keys.push_back(pair<string, docstring>(key, info));
1357 void Buffer::updateBibfilesCache()
1359 // if this is a child document and the parent is already loaded
1360 // update the parent's cache instead
1361 Buffer * tmp = getMasterBuffer();
1364 tmp->updateBibfilesCache();
1368 bibfilesCache_.clear();
1369 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1370 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1371 InsetBibtex const & inset =
1372 static_cast<InsetBibtex const &>(*it);
1373 vector<FileName> const bibfiles = inset.getFiles(*this);
1374 bibfilesCache_.insert(bibfilesCache_.end(),
1377 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1378 InsetInclude & inset =
1379 static_cast<InsetInclude &>(*it);
1380 inset.updateBibfilesCache(*this);
1381 vector<FileName> const & bibfiles =
1382 inset.getBibfilesCache(*this);
1383 bibfilesCache_.insert(bibfilesCache_.end(),
1391 vector<FileName> const & Buffer::getBibfilesCache() const
1393 // if this is a child document and the parent is already loaded
1394 // use the parent's cache instead
1395 Buffer const * tmp = getMasterBuffer();
1398 return tmp->getBibfilesCache();
1400 // We update the cache when first used instead of at loading time.
1401 if (bibfilesCache_.empty())
1402 const_cast<Buffer *>(this)->updateBibfilesCache();
1404 return bibfilesCache_;
1408 bool Buffer::isDepClean(string const & name) const
1410 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1411 if (it == pimpl_->dep_clean.end())
1417 void Buffer::markDepClean(string const & name)
1419 pimpl_->dep_clean[name] = true;
1423 bool Buffer::dispatch(string const & command, bool * result)
1425 return dispatch(lyxaction.lookupFunc(command), result);
1429 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1431 bool dispatched = true;
1433 switch (func.action) {
1434 case LFUN_BUFFER_EXPORT: {
1435 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1448 void Buffer::changeLanguage(Language const * from, Language const * to)
1453 for_each(par_iterator_begin(),
1455 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1457 text().current_font.setLanguage(to);
1458 text().real_current_font.setLanguage(to);
1462 bool Buffer::isMultiLingual() const
1464 ParConstIterator end = par_iterator_end();
1465 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1466 if (it->isMultiLingual(params()))
1473 ParIterator Buffer::getParFromID(int const id) const
1475 ParConstIterator it = par_iterator_begin();
1476 ParConstIterator const end = par_iterator_end();
1479 // John says this is called with id == -1 from undo
1480 lyxerr << "getParFromID(), id: " << id << endl;
1484 for (; it != end; ++it)
1492 bool Buffer::hasParWithID(int const id) const
1494 ParConstIterator const it = getParFromID(id);
1495 return it != par_iterator_end();
1499 ParIterator Buffer::par_iterator_begin()
1501 return lyx::par_iterator_begin(inset());
1505 ParIterator Buffer::par_iterator_end()
1507 return lyx::par_iterator_end(inset());
1511 ParConstIterator Buffer::par_iterator_begin() const
1513 return lyx::par_const_iterator_begin(inset());
1517 ParConstIterator Buffer::par_iterator_end() const
1519 return lyx::par_const_iterator_end(inset());
1523 Language const * Buffer::getLanguage() const
1525 return params().language;
1529 docstring const Buffer::B_(string const & l10n) const
1531 return params().B_(l10n);
1535 bool Buffer::isClean() const
1537 return pimpl_->lyx_clean;
1541 bool Buffer::isBakClean() const
1543 return pimpl_->bak_clean;
1547 void Buffer::markClean() const
1549 if (!pimpl_->lyx_clean) {
1550 pimpl_->lyx_clean = true;
1553 // if the .lyx file has been saved, we don't need an
1555 pimpl_->bak_clean = true;
1559 void Buffer::markBakClean()
1561 pimpl_->bak_clean = true;
1565 void Buffer::setUnnamed(bool flag)
1567 pimpl_->unnamed = flag;
1571 bool Buffer::isUnnamed() const
1573 return pimpl_->unnamed;
1577 #ifdef WITH_WARNINGS
1578 #warning this function should be moved to buffer_pimpl.C
1580 void Buffer::markDirty()
1582 if (pimpl_->lyx_clean) {
1583 pimpl_->lyx_clean = false;
1586 pimpl_->bak_clean = false;
1588 DepClean::iterator it = pimpl_->dep_clean.begin();
1589 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1591 for (; it != end; ++it)
1596 string const Buffer::fileName() const
1598 return pimpl_->filename.absFilename();
1602 string const & Buffer::filePath() const
1604 return params().filepath;
1608 bool Buffer::isReadonly() const
1610 return pimpl_->read_only;
1614 void Buffer::setParentName(string const & name)
1616 params().parentname = name;
1620 Buffer const * Buffer::getMasterBuffer() const
1622 if (!params().parentname.empty()
1623 && theBufferList().exists(params().parentname)) {
1624 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1625 //We need to check if the parent is us...
1626 //FIXME RECURSIVE INCLUDE
1627 //This is not sufficient, since recursive includes could be downstream.
1628 if (buf && buf != this)
1629 return buf->getMasterBuffer();
1636 Buffer * Buffer::getMasterBuffer()
1638 if (!params().parentname.empty()
1639 && theBufferList().exists(params().parentname)) {
1640 Buffer * buf = theBufferList().getBuffer(params().parentname);
1642 return buf->getMasterBuffer();
1649 MacroData const & Buffer::getMacro(docstring const & name) const
1651 return pimpl_->macros.get(name);
1655 bool Buffer::hasMacro(docstring const & name) const
1657 return pimpl_->macros.has(name);
1661 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1663 MacroTable::globalMacros().insert(name, data);
1664 pimpl_->macros.insert(name, data);
1668 void Buffer::buildMacros()
1670 // Start with global table.
1671 pimpl_->macros = MacroTable::globalMacros();
1674 ParagraphList const & pars = text().paragraphs();
1675 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1676 //lyxerr << "searching main par " << i
1677 // << " for macro definitions" << std::endl;
1678 InsetList const & insets = pars[i].insetlist;
1679 InsetList::const_iterator it = insets.begin();
1680 InsetList::const_iterator end = insets.end();
1681 for ( ; it != end; ++it) {
1682 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1683 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1684 MathMacroTemplate const & mac
1685 = static_cast<MathMacroTemplate const &>(*it->inset);
1686 insertMacro(mac.name(), mac.asMacroData());
1693 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1700 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1703 //FIXME: This does not work for child documents yet.
1704 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1705 // Check if the label 'from' appears more than once
1706 vector<docstring> labels;
1708 if (code == Inset::CITE_CODE) {
1709 vector<pair<string, docstring> > keys;
1710 fillWithBibKeys(keys);
1711 vector<pair<string, docstring> >::const_iterator bit = keys.begin();
1712 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1714 for (; bit != bend; ++bit)
1716 labels.push_back(from_utf8(bit->first));
1718 getLabelList(labels);
1720 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1723 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1724 if (it->lyxCode() == code) {
1725 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1726 inset.replaceContents(to_utf8(from), to_utf8(to));
1732 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1733 pit_type par_end, bool full_source)
1735 OutputParams runparams(¶ms().encoding());
1736 runparams.nice = true;
1737 runparams.flavor = OutputParams::LATEX;
1738 runparams.linelen = lyxrc.plaintext_linelen;
1739 // No side effect of file copying and image conversion
1740 runparams.dryrun = true;
1743 os << "% " << _("Preview source code") << "\n\n";
1745 writeLaTeXSource(os, filePath(), runparams, true, true);
1747 writeDocBookSource(os, fileName(), runparams, false);
1750 runparams.par_begin = par_begin;
1751 runparams.par_end = par_end;
1752 if (par_begin + 1 == par_end)
1754 << bformat(_("Preview source code for paragraph %1$s"), par_begin)
1758 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1759 convert<docstring>(par_begin),
1760 convert<docstring>(par_end - 1))
1762 // output paragraphs
1765 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1768 docbookParagraphs(paragraphs(), *this, os, runparams);
1774 ErrorList const & Buffer::errorList(string const & type) const
1776 static ErrorList const emptyErrorList;
1777 std::map<string, ErrorList>::const_iterator I = errorLists_.find(type);
1778 if (I == errorLists_.end())
1779 return emptyErrorList;
1785 ErrorList & Buffer::errorList(string const & type)
1787 return errorLists_[type];