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/gzstream.h"
72 #include "support/lyxlib.h"
73 #include "support/os.h"
74 #include "support/Path.h"
75 #include "support/textutils.h"
76 #include "support/convert.h"
78 #include <boost/bind.hpp>
79 #include <boost/filesystem/exception.hpp>
80 #include <boost/filesystem/operations.hpp>
82 #if defined (HAVE_UTIME_H)
84 #elif defined (HAVE_SYS_UTIME_H)
85 #include <sys/utime.h>
100 using std::ostringstream;
110 using support::addName;
111 using support::bformat;
112 using support::changeExtension;
113 using support::cmd_ret;
114 using support::createBufferTmpDir;
115 using support::destroyDir;
116 using support::FileName;
117 using support::getFormatFromContents;
118 using support::libFileSearch;
119 using support::latex_path;
120 using support::ltrim;
121 using support::makeAbsPath;
122 using support::makeDisplayPath;
123 using support::makeLatexName;
124 using support::onlyFilename;
125 using support::onlyPath;
126 using support::quoteName;
127 using support::removeAutosaveFile;
128 using support::rename;
129 using support::runCommand;
130 using support::split;
131 using support::subst;
132 using support::tempName;
135 namespace Alert = frontend::Alert;
136 namespace os = support::os;
137 namespace fs = boost::filesystem;
141 int const LYX_FORMAT = 276;
146 typedef std::map<string, bool> DepClean;
151 Impl(Buffer & parent, FileName const & file, bool readonly);
153 limited_stack<Undo> undostack;
154 limited_stack<Undo> redostack;
160 /// need to regenerate .tex?
164 mutable bool lyx_clean;
166 /// is autosave needed?
167 mutable bool bak_clean;
169 /// is this a unnamed file (New...)?
175 /// name of the file the buffer is associated with.
178 /** Set to true only when the file is fully loaded.
179 * Used to prevent the premature generation of previews
180 * and by the citation inset.
182 bool file_fully_loaded;
184 /// our Text that should be wrapped in an InsetText
191 TocBackend toc_backend;
193 /// Container for all sort of Buffer dependant errors.
194 map<string, ErrorList> errorLists;
198 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
199 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
200 filename(file), file_fully_loaded(false), inset(params),
203 inset.setAutoBreakRows(true);
204 lyxvc.buffer(&parent);
205 temppath = createBufferTmpDir();
206 params.filepath = onlyPath(file.absFilename());
207 // FIXME: And now do something if temppath == string(), because we
208 // assume from now on that temppath points to a valid temp dir.
209 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
213 Buffer::Buffer(string const & file, bool readonly)
214 : pimpl_(new Impl(*this, FileName(file), readonly))
216 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
222 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
223 // here the buffer should take care that it is
224 // saved properly, before it goes into the void.
228 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
229 Alert::warning(_("Could not remove temporary directory"),
230 bformat(_("Could not remove the temporary directory %1$s"),
231 from_utf8(temppath())));
234 // Remove any previewed LaTeX snippets associated with this buffer.
235 graphics::Previews::get().removeLoader(*this);
239 Text & Buffer::text() const
241 return const_cast<Text &>(pimpl_->inset.text_);
245 Inset & Buffer::inset() const
247 return const_cast<InsetText &>(pimpl_->inset);
251 limited_stack<Undo> & Buffer::undostack()
253 return pimpl_->undostack;
257 limited_stack<Undo> const & Buffer::undostack() const
259 return pimpl_->undostack;
263 limited_stack<Undo> & Buffer::redostack()
265 return pimpl_->redostack;
269 limited_stack<Undo> const & Buffer::redostack() const
271 return pimpl_->redostack;
275 BufferParams & Buffer::params()
277 return pimpl_->params;
281 BufferParams const & Buffer::params() const
283 return pimpl_->params;
287 ParagraphList & Buffer::paragraphs()
289 return text().paragraphs();
293 ParagraphList const & Buffer::paragraphs() const
295 return text().paragraphs();
299 LyXVC & Buffer::lyxvc()
301 return pimpl_->lyxvc;
305 LyXVC const & Buffer::lyxvc() const
307 return pimpl_->lyxvc;
311 string const & Buffer::temppath() const
313 return pimpl_->temppath;
317 TexRow & Buffer::texrow()
319 return pimpl_->texrow;
323 TexRow const & Buffer::texrow() const
325 return pimpl_->texrow;
329 TocBackend & Buffer::tocBackend()
331 return pimpl_->toc_backend;
335 TocBackend const & Buffer::tocBackend() const
337 return pimpl_->toc_backend;
341 string const Buffer::getLatexName(bool const no_path) const
343 string const name = changeExtension(makeLatexName(fileName()), ".tex");
344 return no_path ? onlyFilename(name) : name;
348 pair<Buffer::LogType, string> const Buffer::getLogName() const
350 string const filename = getLatexName(false);
352 if (filename.empty())
353 return make_pair(Buffer::latexlog, string());
355 string const path = temppath();
357 FileName const fname(addName(temppath(),
358 onlyFilename(changeExtension(filename,
360 FileName const bname(
361 addName(path, onlyFilename(
362 changeExtension(filename,
363 formats.extension("literate") + ".out"))));
365 // If no Latex log or Build log is newer, show Build log
367 if (fs::exists(bname.toFilesystemEncoding()) &&
368 (!fs::exists(fname.toFilesystemEncoding()) ||
369 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
370 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
371 return make_pair(Buffer::buildlog, bname.absFilename());
373 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
374 return make_pair(Buffer::latexlog, fname.absFilename());
378 void Buffer::setReadonly(bool const flag)
380 if (pimpl_->read_only != flag) {
381 pimpl_->read_only = flag;
387 void Buffer::setFileName(string const & newfile)
389 pimpl_->filename = makeAbsPath(newfile);
390 params().filepath = onlyPath(pimpl_->filename.absFilename());
391 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
396 // We'll remove this later. (Lgb)
399 void unknownClass(string const & unknown)
401 Alert::warning(_("Unknown document class"),
402 bformat(_("Using the default document class, because the "
403 "class %1$s is unknown."), from_utf8(unknown)));
409 int Buffer::readHeader(Lexer & lex)
411 int unknown_tokens = 0;
413 int begin_header_line = -1;
415 // Initialize parameters that may be/go lacking in header:
416 params().branchlist().clear();
417 params().preamble.erase();
418 params().options.erase();
419 params().float_placement.erase();
420 params().paperwidth.erase();
421 params().paperheight.erase();
422 params().leftmargin.erase();
423 params().rightmargin.erase();
424 params().topmargin.erase();
425 params().bottommargin.erase();
426 params().headheight.erase();
427 params().headsep.erase();
428 params().footskip.erase();
429 params().listings_params.clear();
430 for (int i = 0; i < 4; ++i) {
431 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
432 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
435 ErrorList & errorList = pimpl_->errorLists["Parse"];
439 string const token = lex.getString();
444 if (token == "\\end_header")
448 if (token == "\\begin_header") {
449 begin_header_line = line;
453 LYXERR(Debug::PARSER) << "Handling document header token: `"
454 << token << '\'' << endl;
456 string unknown = params().readToken(lex, token);
457 if (!unknown.empty()) {
458 if (unknown[0] != '\\' && token == "\\textclass") {
459 unknownClass(unknown);
462 docstring const s = bformat(_("Unknown token: "
466 errorList.push_back(ErrorItem(_("Document header error"),
471 if (begin_header_line) {
472 docstring const s = _("\\begin_header is missing");
473 errorList.push_back(ErrorItem(_("Document header error"),
477 return unknown_tokens;
482 // changed to be public and have one parameter
483 // Returns false if "\end_document" is not read (Asger)
484 bool Buffer::readDocument(Lexer & lex)
486 ErrorList & errorList = pimpl_->errorLists["Parse"];
490 string const token = lex.getString();
491 if (token != "\\begin_document") {
492 docstring const s = _("\\begin_document is missing");
493 errorList.push_back(ErrorItem(_("Document header error"),
497 // we are reading in a brand new document
498 BOOST_ASSERT(paragraphs().empty());
501 if (!params().getTextClass().load(filePath())) {
502 string theclass = params().getTextClass().name();
503 Alert::error(_("Can't load document class"), bformat(
504 _("Using the default document class, because the "
505 "class %1$s could not be loaded."), from_utf8(theclass)));
506 params().textclass = 0;
509 if (params().outputChanges) {
510 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
511 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
512 LaTeXFeatures::isAvailable("xcolor");
514 if (!dvipost && !xcolorsoul) {
515 Alert::warning(_("Changes not shown in LaTeX output"),
516 _("Changes will not be highlighted in LaTeX output, "
517 "because neither dvipost nor xcolor/soul are installed.\n"
518 "Please install these packages or redefine "
519 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
520 } else if (!xcolorsoul) {
521 Alert::warning(_("Changes not shown in LaTeX output"),
522 _("Changes will not be highlighted in LaTeX output "
523 "when using pdflatex, because xcolor and soul are not installed.\n"
524 "Please install both packages or redefine "
525 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
529 bool const res = text().read(*this, lex, errorList);
530 for_each(text().paragraphs().begin(),
531 text().paragraphs().end(),
532 bind(&Paragraph::setInsetOwner, _1, &inset()));
538 // needed to insert the selection
539 void Buffer::insertStringAsLines(ParagraphList & pars,
540 pit_type & pit, pos_type & pos,
541 Font const & fn, docstring const & str, bool autobreakrows)
545 // insert the string, don't insert doublespace
546 bool space_inserted = true;
547 for (docstring::const_iterator cit = str.begin();
548 cit != str.end(); ++cit) {
549 Paragraph & par = pars[pit];
551 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
552 breakParagraph(params(), pars, pit, pos,
553 par.layout()->isEnvironment());
556 space_inserted = true;
560 // do not insert consecutive spaces if !free_spacing
561 } else if ((*cit == ' ' || *cit == '\t') &&
562 space_inserted && !par.isFreeSpacing()) {
564 } else if (*cit == '\t') {
565 if (!par.isFreeSpacing()) {
566 // tabs are like spaces here
567 par.insertChar(pos, ' ', font, params().trackChanges);
569 space_inserted = true;
571 const pos_type n = 8 - pos % 8;
572 for (pos_type i = 0; i < n; ++i) {
573 par.insertChar(pos, ' ', font, params().trackChanges);
576 space_inserted = true;
578 } else if (!isPrintable(*cit)) {
579 // Ignore unprintables
582 // just insert the character
583 par.insertChar(pos, *cit, font, params().trackChanges);
585 space_inserted = (*cit == ' ');
592 bool Buffer::readString(std::string const & s)
594 params().compressed = false;
596 // remove dummy empty par
597 paragraphs().clear();
599 std::istringstream is(s);
601 FileName const name(tempName());
602 switch (readFile(lex, name, true)) {
606 // We need to call lyx2lyx, so write the input to a file
607 std::ofstream os(name.toFilesystemEncoding().c_str());
610 return readFile(name);
620 bool Buffer::readFile(FileName const & filename)
622 // Check if the file is compressed.
623 string const format = getFormatFromContents(filename);
624 if (format == "gzip" || format == "zip" || format == "compress") {
625 params().compressed = true;
628 // remove dummy empty par
629 paragraphs().clear();
631 lex.setFile(filename);
632 if (readFile(lex, filename) != success)
639 bool Buffer::fully_loaded() const
641 return pimpl_->file_fully_loaded;
645 void Buffer::fully_loaded(bool const value)
647 pimpl_->file_fully_loaded = value;
651 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
654 BOOST_ASSERT(!filename.empty());
657 Alert::error(_("Document could not be read"),
658 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
663 string const token(lex.getString());
666 Alert::error(_("Document could not be read"),
667 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
671 // the first token _must_ be...
672 if (token != "\\lyxformat") {
673 lyxerr << "Token: " << token << endl;
675 Alert::error(_("Document format failure"),
676 bformat(_("%1$s is not a LyX document."),
677 from_utf8(filename.absFilename())));
682 string tmp_format = lex.getString();
683 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
684 // if present remove ".," from string.
685 string::size_type dot = tmp_format.find_first_of(".,");
686 //lyxerr << " dot found at " << dot << endl;
687 if (dot != string::npos)
688 tmp_format.erase(dot, 1);
689 int const file_format = convert<int>(tmp_format);
690 //lyxerr << "format: " << file_format << endl;
692 if (file_format != LYX_FORMAT) {
695 // lyx2lyx would fail
698 FileName const tmpfile(tempName());
699 if (tmpfile.empty()) {
700 Alert::error(_("Conversion failed"),
701 bformat(_("%1$s is from a different"
702 " version of LyX, but a temporary"
703 " file for converting it could"
705 from_utf8(filename.absFilename())));
708 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
709 if (lyx2lyx.empty()) {
710 Alert::error(_("Conversion script not found"),
711 bformat(_("%1$s is from a different"
712 " version of LyX, but the"
713 " conversion script lyx2lyx"
714 " could not be found."),
715 from_utf8(filename.absFilename())));
718 ostringstream command;
719 command << os::python()
720 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
721 << " -t " << convert<string>(LYX_FORMAT)
722 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
723 << ' ' << quoteName(filename.toFilesystemEncoding());
724 string const command_str = command.str();
726 LYXERR(Debug::INFO) << "Running '"
727 << command_str << '\''
730 cmd_ret const ret = runCommand(command_str);
731 if (ret.first != 0) {
732 Alert::error(_("Conversion script failed"),
733 bformat(_("%1$s is from a different version"
734 " of LyX, but the lyx2lyx script"
735 " failed to convert it."),
736 from_utf8(filename.absFilename())));
739 bool const ret = readFile(tmpfile);
740 // Do stuff with tmpfile name and buffer name here.
741 return ret ? success : failure;
746 if (readDocument(lex)) {
747 Alert::error(_("Document format failure"),
748 bformat(_("%1$s ended unexpectedly, which means"
749 " that it is probably corrupted."),
750 from_utf8(filename.absFilename())));
753 //lyxerr << "removing " << MacroTable::localMacros().size()
754 // << " temporary macro entries" << endl;
755 //MacroTable::localMacros().clear();
757 pimpl_->file_fully_loaded = true;
762 // Should probably be moved to somewhere else: BufferView? LyXView?
763 bool Buffer::save() const
765 // We don't need autosaves in the immediate future. (Asger)
766 resetAutosaveTimers();
768 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
771 bool madeBackup = false;
773 // make a backup if the file already exists
774 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
775 backupName = FileName(fileName() + '~');
776 if (!lyxrc.backupdir_path.empty())
777 backupName = FileName(addName(lyxrc.backupdir_path,
778 subst(os::internal_path(backupName.absFilename()), '/', '!')));
781 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
783 } catch (fs::filesystem_error const & fe) {
784 Alert::error(_("Backup failure"),
785 bformat(_("Cannot create backup file %1$s.\n"
786 "Please check whether the directory exists and is writeable."),
787 from_utf8(backupName.absFilename())));
788 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
792 if (writeFile(pimpl_->filename)) {
794 removeAutosaveFile(fileName());
797 // Saving failed, so backup is not backup
799 rename(backupName, pimpl_->filename);
805 bool Buffer::writeFile(FileName const & fname) const
807 if (pimpl_->read_only && fname == pimpl_->filename)
812 if (params().compressed) {
813 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
819 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
830 bool Buffer::write(ostream & ofs) const
833 // Use the standard "C" locale for file output.
834 ofs.imbue(std::locale::classic());
837 // The top of the file should not be written by params().
839 // write out a comment in the top of the file
840 ofs << "#LyX " << lyx_version
841 << " created this file. For more info see http://www.lyx.org/\n"
842 << "\\lyxformat " << LYX_FORMAT << "\n"
843 << "\\begin_document\n";
846 /// For each author, set 'used' to true if there is a change
847 /// by this author in the document; otherwise set it to 'false'.
848 AuthorList::Authors::const_iterator a_it = params().authors().begin();
849 AuthorList::Authors::const_iterator a_end = params().authors().end();
850 for (; a_it != a_end; ++a_it)
851 a_it->second.used(false);
853 ParIterator const end = par_iterator_end();
854 ParIterator it = par_iterator_begin();
855 for ( ; it != end; ++it)
856 it->checkAuthors(params().authors());
858 // now write out the buffer parameters.
859 ofs << "\\begin_header\n";
860 params().writeFile(ofs);
861 ofs << "\\end_header\n";
864 ofs << "\n\\begin_body\n";
865 text().write(*this, ofs);
866 ofs << "\n\\end_body\n";
868 // Write marker that shows file is complete
869 ofs << "\\end_document" << endl;
871 // Shouldn't really be needed....
874 // how to check if close went ok?
875 // Following is an attempt... (BE 20001011)
877 // good() returns false if any error occured, including some
879 // bad() returns true if something bad happened in the buffer,
880 // which should include file system full errors.
885 lyxerr << "File was not closed properly." << endl;
892 bool Buffer::makeLaTeXFile(FileName const & fname,
893 string const & original_path,
894 OutputParams const & runparams,
895 bool output_preamble, bool output_body)
897 string const encoding = runparams.encoding->iconvName();
898 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
899 << encoding << "..." << endl;
901 odocfstream ofs(encoding);
902 if (!openFileWrite(ofs, fname))
905 bool failed_export = false;
907 writeLaTeXSource(ofs, original_path,
908 runparams, output_preamble, output_body);
910 catch (iconv_codecvt_facet_exception & e) {
911 lyxerr << "Caught iconv exception: " << e.what() << endl;
912 failed_export = true;
914 catch (std::exception const & e) {
915 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
916 failed_export = true;
919 lyxerr << "Caught some really weird exception..." << endl;
920 LyX::cref().emergencyCleanup();
926 failed_export = true;
927 lyxerr << "File '" << fname << "' was not closed properly." << endl;
931 Alert::error(_("Encoding error"),
932 _("Some characters of your document are probably not "
933 "representable in the chosen encoding.\n"
934 "Changing the document encoding to utf8 could help."));
941 void Buffer::writeLaTeXSource(odocstream & os,
942 string const & original_path,
943 OutputParams const & runparams_in,
944 bool const output_preamble, bool const output_body)
946 OutputParams runparams = runparams_in;
948 // validate the buffer.
949 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
950 LaTeXFeatures features(*this, params(), runparams);
952 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
956 // The starting paragraph of the coming rows is the
957 // first paragraph of the document. (Asger)
958 texrow().start(paragraphs().begin()->id(), 0);
960 if (output_preamble && runparams.nice) {
961 os << "%% LyX " << lyx_version << " created this file. "
962 "For more info, see http://www.lyx.org/.\n"
963 "%% Do not edit unless you really know what "
968 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
969 // There are a few differences between nice LaTeX and usual files:
970 // usual is \batchmode and has a
971 // special input@path to allow the including of figures
972 // with either \input or \includegraphics (what figinsets do).
973 // input@path is set when the actual parameter
974 // original_path is set. This is done for usual tex-file, but not
975 // for nice-latex-file. (Matthias 250696)
976 // Note that input@path is only needed for something the user does
977 // in the preamble, included .tex files or ERT, files included by
978 // LyX work without it.
979 if (output_preamble) {
980 if (!runparams.nice) {
981 // code for usual, NOT nice-latex-file
982 os << "\\batchmode\n"; // changed
986 if (!original_path.empty()) {
988 // We don't know the encoding of inputpath
989 docstring const inputpath = from_utf8(latex_path(original_path));
990 os << "\\makeatletter\n"
991 << "\\def\\input@path{{"
992 << inputpath << "/}}\n"
993 << "\\makeatother\n";
999 // Write the preamble
1000 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1006 os << "\\begin{document}\n";
1008 } // output_preamble
1009 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1011 if (!lyxrc.language_auto_begin &&
1012 !params().language->babel().empty()) {
1014 os << from_utf8(subst(lyxrc.language_command_begin,
1016 params().language->babel()))
1021 Encoding const & encoding = params().encoding();
1022 if (encoding.package() == Encoding::CJK) {
1023 // Open a CJK environment, since in contrast to the encodings
1024 // handled by inputenc the document encoding is not set in
1025 // the preamble if it is handled by CJK.sty.
1026 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1031 // if we are doing a real file with body, even if this is the
1032 // child of some other buffer, let's cut the link here.
1033 // This happens for example if only a child document is printed.
1034 string save_parentname;
1035 if (output_preamble) {
1036 save_parentname = params().parentname;
1037 params().parentname.erase();
1041 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1043 // Restore the parenthood if needed
1044 if (output_preamble)
1045 params().parentname = save_parentname;
1047 // add this just in case after all the paragraphs
1051 if (encoding.package() == Encoding::CJK) {
1052 // Close the open CJK environment.
1053 // latexParagraphs will have opened one even if the last text
1055 os << "\\end{CJK}\n";
1059 if (!lyxrc.language_auto_end &&
1060 !params().language->babel().empty()) {
1061 os << from_utf8(subst(lyxrc.language_command_end,
1063 params().language->babel()))
1068 if (output_preamble) {
1069 os << "\\end{document}\n";
1072 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1074 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1077 runparams_in.encoding = runparams.encoding;
1079 // Just to be sure. (Asger)
1082 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1083 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1088 bool Buffer::isLatex() const
1090 return params().getTextClass().outputType() == LATEX;
1094 bool Buffer::isLiterate() const
1096 return params().getTextClass().outputType() == LITERATE;
1100 bool Buffer::isDocBook() const
1102 return params().getTextClass().outputType() == DOCBOOK;
1106 void Buffer::makeDocBookFile(FileName const & fname,
1107 OutputParams const & runparams,
1108 bool const body_only)
1110 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1114 if (!openFileWrite(ofs, fname))
1117 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1121 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1125 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1126 OutputParams const & runparams,
1127 bool const only_body)
1129 LaTeXFeatures features(*this, params(), runparams);
1134 TextClass const & tclass = params().getTextClass();
1135 string const top_element = tclass.latexname();
1138 if (runparams.flavor == OutputParams::XML)
1139 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1142 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1145 if (! tclass.class_header().empty())
1146 os << from_ascii(tclass.class_header());
1147 else if (runparams.flavor == OutputParams::XML)
1148 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1149 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1151 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1153 docstring preamble = from_utf8(params().preamble);
1154 if (runparams.flavor != OutputParams::XML ) {
1155 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1156 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1157 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1158 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1161 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1163 preamble += features.getIncludedFiles(name);
1164 preamble += features.getLyXSGMLEntities();
1166 if (!preamble.empty()) {
1167 os << "\n [ " << preamble << " ]";
1172 string top = top_element;
1174 if (runparams.flavor == OutputParams::XML)
1175 top += params().language->code();
1177 top += params().language->code().substr(0,2);
1180 if (!params().options.empty()) {
1182 top += params().options;
1185 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1186 << " file was created by LyX " << lyx_version
1187 << "\n See http://www.lyx.org/ for more information -->\n";
1189 params().getTextClass().counters().reset();
1191 sgml::openTag(os, top);
1193 docbookParagraphs(paragraphs(), *this, os, runparams);
1194 sgml::closeTag(os, top_element);
1198 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1199 // Other flags: -wall -v0 -x
1200 int Buffer::runChktex()
1204 // get LaTeX-Filename
1205 FileName const path(temppath());
1206 string const name = addName(path.absFilename(), getLatexName());
1207 string const org_path = filePath();
1209 support::Path p(path); // path to LaTeX file
1210 message(_("Running chktex..."));
1212 // Generate the LaTeX file if neccessary
1213 OutputParams runparams(¶ms().encoding());
1214 runparams.flavor = OutputParams::LATEX;
1215 runparams.nice = false;
1216 makeLaTeXFile(FileName(name), org_path, runparams);
1219 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1220 int const res = chktex.run(terr); // run chktex
1223 Alert::error(_("chktex failure"),
1224 _("Could not run chktex successfully."));
1225 } else if (res > 0) {
1226 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1227 // Clear out old errors
1229 // Fill-in the error list with the TeX errors
1230 bufferErrors(*this, terr, errorList);
1241 void Buffer::validate(LaTeXFeatures & features) const
1243 TextClass const & tclass = params().getTextClass();
1245 if (params().outputChanges) {
1246 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1247 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1248 LaTeXFeatures::isAvailable("xcolor");
1250 if (features.runparams().flavor == OutputParams::LATEX) {
1252 features.require("ct-dvipost");
1253 features.require("dvipost");
1254 } else if (xcolorsoul) {
1255 features.require("ct-xcolor-soul");
1256 features.require("soul");
1257 features.require("xcolor");
1259 features.require("ct-none");
1261 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1263 features.require("ct-xcolor-soul");
1264 features.require("soul");
1265 features.require("xcolor");
1266 features.require("pdfcolmk"); // improves color handling in PDF output
1268 features.require("ct-none");
1273 // AMS Style is at document level
1274 if (params().use_amsmath == BufferParams::package_on
1275 || tclass.provides("amsmath"))
1276 features.require("amsmath");
1277 if (params().use_esint == BufferParams::package_on)
1278 features.require("esint");
1280 for_each(paragraphs().begin(), paragraphs().end(),
1281 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1283 // the bullet shapes are buffer level not paragraph level
1284 // so they are tested here
1285 for (int i = 0; i < 4; ++i) {
1286 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1287 int const font = params().user_defined_bullet(i).getFont();
1289 int const c = params()
1290 .user_defined_bullet(i)
1297 features.require("latexsym");
1299 } else if (font == 1) {
1300 features.require("amssymb");
1301 } else if ((font >= 2 && font <= 5)) {
1302 features.require("pifont");
1307 if (lyxerr.debugging(Debug::LATEX)) {
1308 features.showStruct();
1313 void Buffer::getLabelList(vector<docstring> & list) const
1315 /// if this is a child document and the parent is already loaded
1316 /// Use the parent's list instead [ale990407]
1317 Buffer const * tmp = getMasterBuffer();
1319 lyxerr << "getMasterBuffer() failed!" << endl;
1323 tmp->getLabelList(list);
1327 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1328 it.nextInset()->getLabelList(*this, list);
1332 // This is also a buffer property (ale)
1333 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1336 /// if this is a child document and the parent is already loaded
1337 /// use the parent's list instead [ale990412]
1338 Buffer const * tmp = getMasterBuffer();
1341 tmp->fillWithBibKeys(keys);
1345 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1346 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1347 InsetBibtex const & inset =
1348 static_cast<InsetBibtex const &>(*it);
1349 inset.fillWithBibKeys(*this, keys);
1350 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1351 InsetInclude const & inset =
1352 static_cast<InsetInclude const &>(*it);
1353 inset.fillWithBibKeys(*this, keys);
1354 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1355 InsetBibitem const & inset =
1356 static_cast<InsetBibitem const &>(*it);
1358 string const key = to_utf8(inset.getParam("key"));
1359 docstring const label = inset.getParam("label");
1360 DocIterator doc_it(it); doc_it.forwardPos();
1361 docstring const ref = doc_it.paragraph().asString(*this, false);
1362 docstring const info = label + "TheBibliographyRef" + ref;
1363 keys.push_back(pair<string, docstring>(key, info));
1369 void Buffer::updateBibfilesCache()
1371 // if this is a child document and the parent is already loaded
1372 // update the parent's cache instead
1373 Buffer * tmp = getMasterBuffer();
1376 tmp->updateBibfilesCache();
1380 bibfilesCache_.clear();
1381 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1382 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1383 InsetBibtex const & inset =
1384 static_cast<InsetBibtex const &>(*it);
1385 vector<FileName> const bibfiles = inset.getFiles(*this);
1386 bibfilesCache_.insert(bibfilesCache_.end(),
1389 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1390 InsetInclude & inset =
1391 static_cast<InsetInclude &>(*it);
1392 inset.updateBibfilesCache(*this);
1393 vector<FileName> const & bibfiles =
1394 inset.getBibfilesCache(*this);
1395 bibfilesCache_.insert(bibfilesCache_.end(),
1403 vector<FileName> const & Buffer::getBibfilesCache() const
1405 // if this is a child document and the parent is already loaded
1406 // use the parent's cache instead
1407 Buffer const * tmp = getMasterBuffer();
1410 return tmp->getBibfilesCache();
1412 // We update the cache when first used instead of at loading time.
1413 if (bibfilesCache_.empty())
1414 const_cast<Buffer *>(this)->updateBibfilesCache();
1416 return bibfilesCache_;
1420 bool Buffer::isDepClean(string const & name) const
1422 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1423 if (it == pimpl_->dep_clean.end())
1429 void Buffer::markDepClean(string const & name)
1431 pimpl_->dep_clean[name] = true;
1435 bool Buffer::dispatch(string const & command, bool * result)
1437 return dispatch(lyxaction.lookupFunc(command), result);
1441 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1443 bool dispatched = true;
1445 switch (func.action) {
1446 case LFUN_BUFFER_EXPORT: {
1447 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1460 void Buffer::changeLanguage(Language const * from, Language const * to)
1465 for_each(par_iterator_begin(),
1467 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1469 text().current_font.setLanguage(to);
1470 text().real_current_font.setLanguage(to);
1474 bool Buffer::isMultiLingual() const
1476 ParConstIterator end = par_iterator_end();
1477 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1478 if (it->isMultiLingual(params()))
1485 ParIterator Buffer::getParFromID(int const id) const
1487 ParConstIterator it = par_iterator_begin();
1488 ParConstIterator const end = par_iterator_end();
1491 // John says this is called with id == -1 from undo
1492 lyxerr << "getParFromID(), id: " << id << endl;
1496 for (; it != end; ++it)
1504 bool Buffer::hasParWithID(int const id) const
1506 ParConstIterator const it = getParFromID(id);
1507 return it != par_iterator_end();
1511 ParIterator Buffer::par_iterator_begin()
1513 return lyx::par_iterator_begin(inset());
1517 ParIterator Buffer::par_iterator_end()
1519 return lyx::par_iterator_end(inset());
1523 ParConstIterator Buffer::par_iterator_begin() const
1525 return lyx::par_const_iterator_begin(inset());
1529 ParConstIterator Buffer::par_iterator_end() const
1531 return lyx::par_const_iterator_end(inset());
1535 Language const * Buffer::getLanguage() const
1537 return params().language;
1541 docstring const Buffer::B_(string const & l10n) const
1543 return params().B_(l10n);
1547 bool Buffer::isClean() const
1549 return pimpl_->lyx_clean;
1553 bool Buffer::isBakClean() const
1555 return pimpl_->bak_clean;
1559 void Buffer::markClean() const
1561 if (!pimpl_->lyx_clean) {
1562 pimpl_->lyx_clean = true;
1565 // if the .lyx file has been saved, we don't need an
1567 pimpl_->bak_clean = true;
1571 void Buffer::markBakClean()
1573 pimpl_->bak_clean = true;
1577 void Buffer::setUnnamed(bool flag)
1579 pimpl_->unnamed = flag;
1583 bool Buffer::isUnnamed() const
1585 return pimpl_->unnamed;
1589 #ifdef WITH_WARNINGS
1590 #warning this function should be moved to buffer_pimpl.C
1592 void Buffer::markDirty()
1594 if (pimpl_->lyx_clean) {
1595 pimpl_->lyx_clean = false;
1598 pimpl_->bak_clean = false;
1600 DepClean::iterator it = pimpl_->dep_clean.begin();
1601 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1603 for (; it != end; ++it)
1608 string const Buffer::fileName() const
1610 return pimpl_->filename.absFilename();
1614 string const & Buffer::filePath() const
1616 return params().filepath;
1620 bool Buffer::isReadonly() const
1622 return pimpl_->read_only;
1626 void Buffer::setParentName(string const & name)
1628 if (name == pimpl_->filename.absFilename())
1629 // Avoids recursive include.
1630 params().parentname.clear();
1632 params().parentname = name;
1636 Buffer const * Buffer::getMasterBuffer() const
1638 if (!params().parentname.empty()
1639 && theBufferList().exists(params().parentname)) {
1640 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1641 //We need to check if the parent is us...
1642 //FIXME RECURSIVE INCLUDE
1643 //This is not sufficient, since recursive includes could be downstream.
1644 if (buf && buf != this)
1645 return buf->getMasterBuffer();
1652 Buffer * Buffer::getMasterBuffer()
1654 if (!params().parentname.empty()
1655 && theBufferList().exists(params().parentname)) {
1656 Buffer * buf = theBufferList().getBuffer(params().parentname);
1658 return buf->getMasterBuffer();
1665 MacroData const & Buffer::getMacro(docstring const & name) const
1667 return pimpl_->macros.get(name);
1671 bool Buffer::hasMacro(docstring const & name) const
1673 return pimpl_->macros.has(name);
1677 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1679 MacroTable::globalMacros().insert(name, data);
1680 pimpl_->macros.insert(name, data);
1684 void Buffer::buildMacros()
1686 // Start with global table.
1687 pimpl_->macros = MacroTable::globalMacros();
1690 ParagraphList const & pars = text().paragraphs();
1691 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1692 //lyxerr << "searching main par " << i
1693 // << " for macro definitions" << std::endl;
1694 InsetList const & insets = pars[i].insetlist;
1695 InsetList::const_iterator it = insets.begin();
1696 InsetList::const_iterator end = insets.end();
1697 for ( ; it != end; ++it) {
1698 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1699 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1700 MathMacroTemplate const & mac
1701 = static_cast<MathMacroTemplate const &>(*it->inset);
1702 insertMacro(mac.name(), mac.asMacroData());
1709 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1716 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1719 //FIXME: This does not work for child documents yet.
1720 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1721 // Check if the label 'from' appears more than once
1722 vector<docstring> labels;
1724 if (code == Inset::CITE_CODE) {
1725 vector<pair<string, docstring> > keys;
1726 fillWithBibKeys(keys);
1727 vector<pair<string, docstring> >::const_iterator bit = keys.begin();
1728 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1730 for (; bit != bend; ++bit)
1732 labels.push_back(from_utf8(bit->first));
1734 getLabelList(labels);
1736 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1739 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1740 if (it->lyxCode() == code) {
1741 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1742 inset.replaceContents(to_utf8(from), to_utf8(to));
1748 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1749 pit_type par_end, bool full_source)
1751 OutputParams runparams(¶ms().encoding());
1752 runparams.nice = true;
1753 runparams.flavor = OutputParams::LATEX;
1754 runparams.linelen = lyxrc.plaintext_linelen;
1755 // No side effect of file copying and image conversion
1756 runparams.dryrun = true;
1759 os << "% " << _("Preview source code") << "\n\n";
1761 writeLaTeXSource(os, filePath(), runparams, true, true);
1763 writeDocBookSource(os, fileName(), runparams, false);
1766 runparams.par_begin = par_begin;
1767 runparams.par_end = par_end;
1768 if (par_begin + 1 == par_end)
1770 << bformat(_("Preview source code for paragraph %1$s"), par_begin)
1774 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1775 convert<docstring>(par_begin),
1776 convert<docstring>(par_end - 1))
1778 // output paragraphs
1781 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1784 docbookParagraphs(paragraphs(), *this, os, runparams);
1790 ErrorList const & Buffer::errorList(string const & type) const
1792 static ErrorList const emptyErrorList;
1793 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1794 if (I == pimpl_->errorLists.end())
1795 return emptyErrorList;
1801 ErrorList & Buffer::errorList(string const & type)
1803 return pimpl_->errorLists[type];