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>
95 using std::ostringstream;
106 using support::addName;
107 using support::bformat;
108 using support::changeExtension;
109 using support::cmd_ret;
110 using support::createBufferTmpDir;
111 using support::destroyDir;
112 using support::FileName;
113 using support::getFormatFromContents;
114 using support::libFileSearch;
115 using support::latex_path;
116 using support::ltrim;
117 using support::makeAbsPath;
118 using support::makeDisplayPath;
119 using support::makeLatexName;
120 using support::onlyFilename;
121 using support::onlyPath;
122 using support::quoteName;
123 using support::removeAutosaveFile;
124 using support::rename;
125 using support::runCommand;
126 using support::split;
127 using support::subst;
128 using support::tempName;
132 namespace Alert = frontend::Alert;
133 namespace os = support::os;
134 namespace fs = boost::filesystem;
138 int const LYX_FORMAT = 277;
143 typedef std::map<string, bool> DepClean;
148 Impl(Buffer & parent, FileName const & file, bool readonly);
150 limited_stack<Undo> undostack;
151 limited_stack<Undo> redostack;
157 /// need to regenerate .tex?
161 mutable bool lyx_clean;
163 /// is autosave needed?
164 mutable bool bak_clean;
166 /// is this a unnamed file (New...)?
172 /// name of the file the buffer is associated with.
175 /** Set to true only when the file is fully loaded.
176 * Used to prevent the premature generation of previews
177 * and by the citation inset.
179 bool file_fully_loaded;
181 /// our Text that should be wrapped in an InsetText
188 TocBackend toc_backend;
190 /// Container for all sort of Buffer dependant errors.
191 map<string, ErrorList> errorLists;
193 /// timestamp and checksum used to test if the file has been externally
194 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
196 unsigned long checksum_;
200 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
201 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
202 filename(file), file_fully_loaded(false), inset(params),
203 toc_backend(&parent), timestamp_(0), checksum_(0)
205 inset.setAutoBreakRows(true);
206 lyxvc.buffer(&parent);
207 temppath = createBufferTmpDir();
208 params.filepath = onlyPath(file.absFilename());
209 // FIXME: And now do something if temppath == string(), because we
210 // assume from now on that temppath points to a valid temp dir.
211 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
215 Buffer::Buffer(string const & file, bool readonly)
216 : pimpl_(new Impl(*this, FileName(file), readonly))
218 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
224 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
225 // here the buffer should take care that it is
226 // saved properly, before it goes into the void.
230 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
231 Alert::warning(_("Could not remove temporary directory"),
232 bformat(_("Could not remove the temporary directory %1$s"),
233 from_utf8(temppath())));
236 // Remove any previewed LaTeX snippets associated with this buffer.
237 graphics::Previews::get().removeLoader(*this);
241 Text & Buffer::text() const
243 return const_cast<Text &>(pimpl_->inset.text_);
247 Inset & Buffer::inset() const
249 return const_cast<InsetText &>(pimpl_->inset);
253 limited_stack<Undo> & Buffer::undostack()
255 return pimpl_->undostack;
259 limited_stack<Undo> const & Buffer::undostack() const
261 return pimpl_->undostack;
265 limited_stack<Undo> & Buffer::redostack()
267 return pimpl_->redostack;
271 limited_stack<Undo> const & Buffer::redostack() const
273 return pimpl_->redostack;
277 BufferParams & Buffer::params()
279 return pimpl_->params;
283 BufferParams const & Buffer::params() const
285 return pimpl_->params;
289 ParagraphList & Buffer::paragraphs()
291 return text().paragraphs();
295 ParagraphList const & Buffer::paragraphs() const
297 return text().paragraphs();
301 LyXVC & Buffer::lyxvc()
303 return pimpl_->lyxvc;
307 LyXVC const & Buffer::lyxvc() const
309 return pimpl_->lyxvc;
313 string const & Buffer::temppath() const
315 return pimpl_->temppath;
319 TexRow & Buffer::texrow()
321 return pimpl_->texrow;
325 TexRow const & Buffer::texrow() const
327 return pimpl_->texrow;
331 TocBackend & Buffer::tocBackend()
333 return pimpl_->toc_backend;
337 TocBackend const & Buffer::tocBackend() const
339 return pimpl_->toc_backend;
343 string const Buffer::getLatexName(bool const no_path) const
345 string const name = changeExtension(makeLatexName(fileName()), ".tex");
346 return no_path ? onlyFilename(name) : name;
350 pair<Buffer::LogType, string> const Buffer::getLogName() const
352 string const filename = getLatexName(false);
354 if (filename.empty())
355 return make_pair(Buffer::latexlog, string());
357 string const path = temppath();
359 FileName const fname(addName(temppath(),
360 onlyFilename(changeExtension(filename,
362 FileName const bname(
363 addName(path, onlyFilename(
364 changeExtension(filename,
365 formats.extension("literate") + ".out"))));
367 // If no Latex log or Build log is newer, show Build log
369 if (fs::exists(bname.toFilesystemEncoding()) &&
370 (!fs::exists(fname.toFilesystemEncoding()) ||
371 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
372 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
373 return make_pair(Buffer::buildlog, bname.absFilename());
375 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
376 return make_pair(Buffer::latexlog, fname.absFilename());
380 void Buffer::setReadonly(bool const flag)
382 if (pimpl_->read_only != flag) {
383 pimpl_->read_only = flag;
389 void Buffer::setFileName(string const & newfile)
391 pimpl_->filename = makeAbsPath(newfile);
392 params().filepath = onlyPath(pimpl_->filename.absFilename());
393 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
398 // We'll remove this later. (Lgb)
401 void unknownClass(string const & unknown)
403 Alert::warning(_("Unknown document class"),
404 bformat(_("Using the default document class, because the "
405 "class %1$s is unknown."), from_utf8(unknown)));
411 int Buffer::readHeader(Lexer & lex)
413 int unknown_tokens = 0;
415 int begin_header_line = -1;
417 // Initialize parameters that may be/go lacking in header:
418 params().branchlist().clear();
419 params().preamble.erase();
420 params().options.erase();
421 params().float_placement.erase();
422 params().paperwidth.erase();
423 params().paperheight.erase();
424 params().leftmargin.erase();
425 params().rightmargin.erase();
426 params().topmargin.erase();
427 params().bottommargin.erase();
428 params().headheight.erase();
429 params().headsep.erase();
430 params().footskip.erase();
431 params().listings_params.clear();
432 for (int i = 0; i < 4; ++i) {
433 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
434 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
437 ErrorList & errorList = pimpl_->errorLists["Parse"];
441 string const token = lex.getString();
446 if (token == "\\end_header")
450 if (token == "\\begin_header") {
451 begin_header_line = line;
455 LYXERR(Debug::PARSER) << "Handling document header token: `"
456 << token << '\'' << endl;
458 string unknown = params().readToken(lex, token);
459 if (!unknown.empty()) {
460 if (unknown[0] != '\\' && token == "\\textclass") {
461 unknownClass(unknown);
464 docstring const s = bformat(_("Unknown token: "
468 errorList.push_back(ErrorItem(_("Document header error"),
473 if (begin_header_line) {
474 docstring const s = _("\\begin_header is missing");
475 errorList.push_back(ErrorItem(_("Document header error"),
479 return unknown_tokens;
484 // changed to be public and have one parameter
485 // Returns false if "\end_document" is not read (Asger)
486 bool Buffer::readDocument(Lexer & lex)
488 ErrorList & errorList = pimpl_->errorLists["Parse"];
492 string const token = lex.getString();
493 if (token != "\\begin_document") {
494 docstring const s = _("\\begin_document is missing");
495 errorList.push_back(ErrorItem(_("Document header error"),
499 // we are reading in a brand new document
500 BOOST_ASSERT(paragraphs().empty());
503 if (!params().getTextClass().load(filePath())) {
504 string theclass = params().getTextClass().name();
505 Alert::error(_("Can't load document class"), bformat(
506 _("Using the default document class, because the "
507 "class %1$s could not be loaded."), from_utf8(theclass)));
508 params().textclass = 0;
511 if (params().outputChanges) {
512 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
513 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
514 LaTeXFeatures::isAvailable("xcolor");
516 if (!dvipost && !xcolorsoul) {
517 Alert::warning(_("Changes not shown in LaTeX output"),
518 _("Changes will not be highlighted in LaTeX output, "
519 "because neither dvipost nor xcolor/soul are installed.\n"
520 "Please install these packages or redefine "
521 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
522 } else if (!xcolorsoul) {
523 Alert::warning(_("Changes not shown in LaTeX output"),
524 _("Changes will not be highlighted in LaTeX output "
525 "when using pdflatex, because xcolor and soul are not installed.\n"
526 "Please install both packages or redefine "
527 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
531 bool const res = text().read(*this, lex, errorList);
532 for_each(text().paragraphs().begin(),
533 text().paragraphs().end(),
534 bind(&Paragraph::setInsetOwner, _1, &inset()));
540 // needed to insert the selection
541 void Buffer::insertStringAsLines(ParagraphList & pars,
542 pit_type & pit, pos_type & pos,
543 Font const & fn, docstring const & str, bool autobreakrows)
547 // insert the string, don't insert doublespace
548 bool space_inserted = true;
549 for (docstring::const_iterator cit = str.begin();
550 cit != str.end(); ++cit) {
551 Paragraph & par = pars[pit];
553 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
554 breakParagraph(params(), pars, pit, pos,
555 par.layout()->isEnvironment());
558 space_inserted = true;
562 // do not insert consecutive spaces if !free_spacing
563 } else if ((*cit == ' ' || *cit == '\t') &&
564 space_inserted && !par.isFreeSpacing()) {
566 } else if (*cit == '\t') {
567 if (!par.isFreeSpacing()) {
568 // tabs are like spaces here
569 par.insertChar(pos, ' ', font, params().trackChanges);
571 space_inserted = true;
573 const pos_type n = 8 - pos % 8;
574 for (pos_type i = 0; i < n; ++i) {
575 par.insertChar(pos, ' ', font, params().trackChanges);
578 space_inserted = true;
580 } else if (!isPrintable(*cit)) {
581 // Ignore unprintables
584 // just insert the character
585 par.insertChar(pos, *cit, font, params().trackChanges);
587 space_inserted = (*cit == ' ');
594 bool Buffer::readString(std::string const & s)
596 params().compressed = false;
598 // remove dummy empty par
599 paragraphs().clear();
601 std::istringstream is(s);
603 FileName const name(tempName());
604 switch (readFile(lex, name, true)) {
608 // We need to call lyx2lyx, so write the input to a file
609 std::ofstream os(name.toFilesystemEncoding().c_str());
612 return readFile(name);
622 bool Buffer::readFile(FileName const & filename)
624 // Check if the file is compressed.
625 string const format = getFormatFromContents(filename);
626 if (format == "gzip" || format == "zip" || format == "compress") {
627 params().compressed = true;
630 // remove dummy empty par
631 paragraphs().clear();
633 lex.setFile(filename);
634 if (readFile(lex, filename) != success)
641 bool Buffer::fully_loaded() const
643 return pimpl_->file_fully_loaded;
647 void Buffer::fully_loaded(bool const value)
649 pimpl_->file_fully_loaded = value;
653 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
656 BOOST_ASSERT(!filename.empty());
659 Alert::error(_("Document could not be read"),
660 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
665 string const token(lex.getString());
668 Alert::error(_("Document could not be read"),
669 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
673 // the first token _must_ be...
674 if (token != "\\lyxformat") {
675 lyxerr << "Token: " << token << endl;
677 Alert::error(_("Document format failure"),
678 bformat(_("%1$s is not a LyX document."),
679 from_utf8(filename.absFilename())));
684 string tmp_format = lex.getString();
685 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
686 // if present remove ".," from string.
687 string::size_type dot = tmp_format.find_first_of(".,");
688 //lyxerr << " dot found at " << dot << endl;
689 if (dot != string::npos)
690 tmp_format.erase(dot, 1);
691 int const file_format = convert<int>(tmp_format);
692 //lyxerr << "format: " << file_format << endl;
694 if (file_format != LYX_FORMAT) {
697 // lyx2lyx would fail
700 FileName const tmpfile(tempName());
701 if (tmpfile.empty()) {
702 Alert::error(_("Conversion failed"),
703 bformat(_("%1$s is from a different"
704 " version of LyX, but a temporary"
705 " file for converting it could"
707 from_utf8(filename.absFilename())));
710 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
711 if (lyx2lyx.empty()) {
712 Alert::error(_("Conversion script not found"),
713 bformat(_("%1$s is from a different"
714 " version of LyX, but the"
715 " conversion script lyx2lyx"
716 " could not be found."),
717 from_utf8(filename.absFilename())));
720 ostringstream command;
721 command << os::python()
722 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
723 << " -t " << convert<string>(LYX_FORMAT)
724 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
725 << ' ' << quoteName(filename.toFilesystemEncoding());
726 string const command_str = command.str();
728 LYXERR(Debug::INFO) << "Running '"
729 << command_str << '\''
732 cmd_ret const ret = runCommand(command_str);
733 if (ret.first != 0) {
734 Alert::error(_("Conversion script failed"),
735 bformat(_("%1$s is from a different version"
736 " of LyX, but the lyx2lyx script"
737 " failed to convert it."),
738 from_utf8(filename.absFilename())));
741 bool const ret = readFile(tmpfile);
742 // Do stuff with tmpfile name and buffer name here.
743 return ret ? success : failure;
748 if (readDocument(lex)) {
749 Alert::error(_("Document format failure"),
750 bformat(_("%1$s ended unexpectedly, which means"
751 " that it is probably corrupted."),
752 from_utf8(filename.absFilename())));
755 //lyxerr << "removing " << MacroTable::localMacros().size()
756 // << " temporary macro entries" << endl;
757 //MacroTable::localMacros().clear();
759 pimpl_->file_fully_loaded = true;
760 // save the timestamp and checksum of disk file
761 pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
762 pimpl_->checksum_ = sum(filename);
767 // Should probably be moved to somewhere else: BufferView? LyXView?
768 bool Buffer::save() const
770 // We don't need autosaves in the immediate future. (Asger)
771 resetAutosaveTimers();
773 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
776 bool madeBackup = false;
778 // make a backup if the file already exists
779 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
780 backupName = FileName(fileName() + '~');
781 if (!lyxrc.backupdir_path.empty())
782 backupName = FileName(addName(lyxrc.backupdir_path,
783 subst(os::internal_path(backupName.absFilename()), '/', '!')));
786 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
788 } catch (fs::filesystem_error const & fe) {
789 Alert::error(_("Backup failure"),
790 bformat(_("Cannot create backup file %1$s.\n"
791 "Please check whether the directory exists and is writeable."),
792 from_utf8(backupName.absFilename())));
793 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
797 // ask if the disk file has been externally modified (use checksum method)
798 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
799 docstring const file = makeDisplayPath(fileName(), 20);
800 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
801 "you want to overwrite this file?"), file);
802 int const ret = Alert::prompt(_("Overwrite modified file?"),
803 text, 1, 1, _("&Overwrite"), _("&Cancel"));
808 if (writeFile(pimpl_->filename)) {
810 removeAutosaveFile(fileName());
811 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
812 pimpl_->checksum_ = sum(pimpl_->filename);
815 // Saving failed, so backup is not backup
817 rename(backupName, pimpl_->filename);
823 bool Buffer::writeFile(FileName const & fname) const
825 if (pimpl_->read_only && fname == pimpl_->filename)
830 if (params().compressed) {
831 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
837 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
848 bool Buffer::write(ostream & ofs) const
851 // Use the standard "C" locale for file output.
852 ofs.imbue(std::locale::classic());
855 // The top of the file should not be written by params().
857 // write out a comment in the top of the file
858 ofs << "#LyX " << lyx_version
859 << " created this file. For more info see http://www.lyx.org/\n"
860 << "\\lyxformat " << LYX_FORMAT << "\n"
861 << "\\begin_document\n";
864 /// For each author, set 'used' to true if there is a change
865 /// by this author in the document; otherwise set it to 'false'.
866 AuthorList::Authors::const_iterator a_it = params().authors().begin();
867 AuthorList::Authors::const_iterator a_end = params().authors().end();
868 for (; a_it != a_end; ++a_it)
869 a_it->second.used(false);
871 ParIterator const end = par_iterator_end();
872 ParIterator it = par_iterator_begin();
873 for ( ; it != end; ++it)
874 it->checkAuthors(params().authors());
876 // now write out the buffer parameters.
877 ofs << "\\begin_header\n";
878 params().writeFile(ofs);
879 ofs << "\\end_header\n";
882 ofs << "\n\\begin_body\n";
883 text().write(*this, ofs);
884 ofs << "\n\\end_body\n";
886 // Write marker that shows file is complete
887 ofs << "\\end_document" << endl;
889 // Shouldn't really be needed....
892 // how to check if close went ok?
893 // Following is an attempt... (BE 20001011)
895 // good() returns false if any error occured, including some
897 // bad() returns true if something bad happened in the buffer,
898 // which should include file system full errors.
903 lyxerr << "File was not closed properly." << endl;
910 bool Buffer::makeLaTeXFile(FileName const & fname,
911 string const & original_path,
912 OutputParams const & runparams,
913 bool output_preamble, bool output_body)
915 string const encoding = runparams.encoding->iconvName();
916 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
917 << encoding << "..." << endl;
919 odocfstream ofs(encoding);
920 if (!openFileWrite(ofs, fname))
923 bool failed_export = false;
925 writeLaTeXSource(ofs, original_path,
926 runparams, output_preamble, output_body);
928 catch (iconv_codecvt_facet_exception & e) {
929 lyxerr << "Caught iconv exception: " << e.what() << endl;
930 failed_export = true;
932 catch (std::exception const & e) {
933 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
934 failed_export = true;
937 lyxerr << "Caught some really weird exception..." << endl;
938 LyX::cref().emergencyCleanup();
944 failed_export = true;
945 lyxerr << "File '" << fname << "' was not closed properly." << endl;
949 Alert::error(_("Encoding error"),
950 _("Some characters of your document are probably not "
951 "representable in the chosen encoding.\n"
952 "Changing the document encoding to utf8 could help."));
959 void Buffer::writeLaTeXSource(odocstream & os,
960 string const & original_path,
961 OutputParams const & runparams_in,
962 bool const output_preamble, bool const output_body)
964 OutputParams runparams = runparams_in;
966 // validate the buffer.
967 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
968 LaTeXFeatures features(*this, params(), runparams);
970 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
974 // The starting paragraph of the coming rows is the
975 // first paragraph of the document. (Asger)
976 texrow().start(paragraphs().begin()->id(), 0);
978 if (output_preamble && runparams.nice) {
979 os << "%% LyX " << lyx_version << " created this file. "
980 "For more info, see http://www.lyx.org/.\n"
981 "%% Do not edit unless you really know what "
986 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
987 // There are a few differences between nice LaTeX and usual files:
988 // usual is \batchmode and has a
989 // special input@path to allow the including of figures
990 // with either \input or \includegraphics (what figinsets do).
991 // input@path is set when the actual parameter
992 // original_path is set. This is done for usual tex-file, but not
993 // for nice-latex-file. (Matthias 250696)
994 // Note that input@path is only needed for something the user does
995 // in the preamble, included .tex files or ERT, files included by
996 // LyX work without it.
997 if (output_preamble) {
998 if (!runparams.nice) {
999 // code for usual, NOT nice-latex-file
1000 os << "\\batchmode\n"; // changed
1001 // from \nonstopmode
1004 if (!original_path.empty()) {
1006 // We don't know the encoding of inputpath
1007 docstring const inputpath = from_utf8(latex_path(original_path));
1008 os << "\\makeatletter\n"
1009 << "\\def\\input@path{{"
1010 << inputpath << "/}}\n"
1011 << "\\makeatother\n";
1017 // Write the preamble
1018 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1024 os << "\\begin{document}\n";
1026 } // output_preamble
1027 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1029 if (!lyxrc.language_auto_begin &&
1030 !params().language->babel().empty()) {
1032 os << from_utf8(subst(lyxrc.language_command_begin,
1034 params().language->babel()))
1039 Encoding const & encoding = params().encoding();
1040 if (encoding.package() == Encoding::CJK) {
1041 // Open a CJK environment, since in contrast to the encodings
1042 // handled by inputenc the document encoding is not set in
1043 // the preamble if it is handled by CJK.sty.
1044 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1049 // if we are doing a real file with body, even if this is the
1050 // child of some other buffer, let's cut the link here.
1051 // This happens for example if only a child document is printed.
1052 string save_parentname;
1053 if (output_preamble) {
1054 save_parentname = params().parentname;
1055 params().parentname.erase();
1059 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1061 // Restore the parenthood if needed
1062 if (output_preamble)
1063 params().parentname = save_parentname;
1065 // add this just in case after all the paragraphs
1069 if (encoding.package() == Encoding::CJK) {
1070 // Close the open CJK environment.
1071 // latexParagraphs will have opened one even if the last text
1073 os << "\\end{CJK}\n";
1077 if (!lyxrc.language_auto_end &&
1078 !params().language->babel().empty()) {
1079 os << from_utf8(subst(lyxrc.language_command_end,
1081 params().language->babel()))
1086 if (output_preamble) {
1087 os << "\\end{document}\n";
1090 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1092 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1095 runparams_in.encoding = runparams.encoding;
1097 // Just to be sure. (Asger)
1100 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1101 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1106 bool Buffer::isLatex() const
1108 return params().getTextClass().outputType() == LATEX;
1112 bool Buffer::isLiterate() const
1114 return params().getTextClass().outputType() == LITERATE;
1118 bool Buffer::isDocBook() const
1120 return params().getTextClass().outputType() == DOCBOOK;
1124 void Buffer::makeDocBookFile(FileName const & fname,
1125 OutputParams const & runparams,
1126 bool const body_only)
1128 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1132 if (!openFileWrite(ofs, fname))
1135 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1139 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1143 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1144 OutputParams const & runparams,
1145 bool const only_body)
1147 LaTeXFeatures features(*this, params(), runparams);
1152 TextClass const & tclass = params().getTextClass();
1153 string const top_element = tclass.latexname();
1156 if (runparams.flavor == OutputParams::XML)
1157 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1160 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1163 if (! tclass.class_header().empty())
1164 os << from_ascii(tclass.class_header());
1165 else if (runparams.flavor == OutputParams::XML)
1166 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1167 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1169 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1171 docstring preamble = from_utf8(params().preamble);
1172 if (runparams.flavor != OutputParams::XML ) {
1173 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1174 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1175 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1176 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1179 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1181 preamble += features.getIncludedFiles(name);
1182 preamble += features.getLyXSGMLEntities();
1184 if (!preamble.empty()) {
1185 os << "\n [ " << preamble << " ]";
1190 string top = top_element;
1192 if (runparams.flavor == OutputParams::XML)
1193 top += params().language->code();
1195 top += params().language->code().substr(0,2);
1198 if (!params().options.empty()) {
1200 top += params().options;
1203 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1204 << " file was created by LyX " << lyx_version
1205 << "\n See http://www.lyx.org/ for more information -->\n";
1207 params().getTextClass().counters().reset();
1209 sgml::openTag(os, top);
1211 docbookParagraphs(paragraphs(), *this, os, runparams);
1212 sgml::closeTag(os, top_element);
1216 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1217 // Other flags: -wall -v0 -x
1218 int Buffer::runChktex()
1222 // get LaTeX-Filename
1223 FileName const path(temppath());
1224 string const name = addName(path.absFilename(), getLatexName());
1225 string const org_path = filePath();
1227 support::Path p(path); // path to LaTeX file
1228 message(_("Running chktex..."));
1230 // Generate the LaTeX file if neccessary
1231 OutputParams runparams(¶ms().encoding());
1232 runparams.flavor = OutputParams::LATEX;
1233 runparams.nice = false;
1234 makeLaTeXFile(FileName(name), org_path, runparams);
1237 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1238 int const res = chktex.run(terr); // run chktex
1241 Alert::error(_("chktex failure"),
1242 _("Could not run chktex successfully."));
1243 } else if (res > 0) {
1244 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1245 // Clear out old errors
1247 // Fill-in the error list with the TeX errors
1248 bufferErrors(*this, terr, errorList);
1259 void Buffer::validate(LaTeXFeatures & features) const
1261 TextClass const & tclass = params().getTextClass();
1263 if (params().outputChanges) {
1264 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1265 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1266 LaTeXFeatures::isAvailable("xcolor");
1268 if (features.runparams().flavor == OutputParams::LATEX) {
1270 features.require("ct-dvipost");
1271 features.require("dvipost");
1272 } else if (xcolorsoul) {
1273 features.require("ct-xcolor-soul");
1274 features.require("soul");
1275 features.require("xcolor");
1277 features.require("ct-none");
1279 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1281 features.require("ct-xcolor-soul");
1282 features.require("soul");
1283 features.require("xcolor");
1284 features.require("pdfcolmk"); // improves color handling in PDF output
1286 features.require("ct-none");
1291 // AMS Style is at document level
1292 if (params().use_amsmath == BufferParams::package_on
1293 || tclass.provides("amsmath"))
1294 features.require("amsmath");
1295 if (params().use_esint == BufferParams::package_on)
1296 features.require("esint");
1298 for_each(paragraphs().begin(), paragraphs().end(),
1299 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1301 // the bullet shapes are buffer level not paragraph level
1302 // so they are tested here
1303 for (int i = 0; i < 4; ++i) {
1304 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1305 int const font = params().user_defined_bullet(i).getFont();
1307 int const c = params()
1308 .user_defined_bullet(i)
1315 features.require("latexsym");
1317 } else if (font == 1) {
1318 features.require("amssymb");
1319 } else if ((font >= 2 && font <= 5)) {
1320 features.require("pifont");
1325 if (lyxerr.debugging(Debug::LATEX)) {
1326 features.showStruct();
1331 void Buffer::getLabelList(vector<docstring> & list) const
1333 /// if this is a child document and the parent is already loaded
1334 /// Use the parent's list instead [ale990407]
1335 Buffer const * tmp = getMasterBuffer();
1337 lyxerr << "getMasterBuffer() failed!" << endl;
1341 tmp->getLabelList(list);
1345 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1346 it.nextInset()->getLabelList(*this, list);
1350 // This is also a buffer property (ale)
1351 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1354 /// if this is a child document and the parent is already loaded
1355 /// use the parent's list instead [ale990412]
1356 Buffer const * tmp = getMasterBuffer();
1359 tmp->fillWithBibKeys(keys);
1363 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1364 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1365 InsetBibtex const & inset =
1366 static_cast<InsetBibtex const &>(*it);
1367 inset.fillWithBibKeys(*this, keys);
1368 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1369 InsetInclude const & inset =
1370 static_cast<InsetInclude const &>(*it);
1371 inset.fillWithBibKeys(*this, keys);
1372 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1373 InsetBibitem const & inset =
1374 static_cast<InsetBibitem const &>(*it);
1376 string const key = to_utf8(inset.getParam("key"));
1377 docstring const label = inset.getParam("label");
1378 DocIterator doc_it(it); doc_it.forwardPos();
1379 docstring const ref = doc_it.paragraph().asString(*this, false);
1380 docstring const info = label + "TheBibliographyRef" + ref;
1381 keys.push_back(pair<string, docstring>(key, info));
1387 void Buffer::updateBibfilesCache()
1389 // if this is a child document and the parent is already loaded
1390 // update the parent's cache instead
1391 Buffer * tmp = getMasterBuffer();
1394 tmp->updateBibfilesCache();
1398 bibfilesCache_.clear();
1399 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1400 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1401 InsetBibtex const & inset =
1402 static_cast<InsetBibtex const &>(*it);
1403 vector<FileName> const bibfiles = inset.getFiles(*this);
1404 bibfilesCache_.insert(bibfilesCache_.end(),
1407 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1408 InsetInclude & inset =
1409 static_cast<InsetInclude &>(*it);
1410 inset.updateBibfilesCache(*this);
1411 vector<FileName> const & bibfiles =
1412 inset.getBibfilesCache(*this);
1413 bibfilesCache_.insert(bibfilesCache_.end(),
1421 vector<FileName> const & Buffer::getBibfilesCache() const
1423 // if this is a child document and the parent is already loaded
1424 // use the parent's cache instead
1425 Buffer const * tmp = getMasterBuffer();
1428 return tmp->getBibfilesCache();
1430 // We update the cache when first used instead of at loading time.
1431 if (bibfilesCache_.empty())
1432 const_cast<Buffer *>(this)->updateBibfilesCache();
1434 return bibfilesCache_;
1438 bool Buffer::isDepClean(string const & name) const
1440 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1441 if (it == pimpl_->dep_clean.end())
1447 void Buffer::markDepClean(string const & name)
1449 pimpl_->dep_clean[name] = true;
1453 bool Buffer::dispatch(string const & command, bool * result)
1455 return dispatch(lyxaction.lookupFunc(command), result);
1459 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1461 bool dispatched = true;
1463 switch (func.action) {
1464 case LFUN_BUFFER_EXPORT: {
1465 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1478 void Buffer::changeLanguage(Language const * from, Language const * to)
1483 for_each(par_iterator_begin(),
1485 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1487 text().current_font.setLanguage(to);
1488 text().real_current_font.setLanguage(to);
1492 bool Buffer::isMultiLingual() const
1494 ParConstIterator end = par_iterator_end();
1495 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1496 if (it->isMultiLingual(params()))
1503 ParIterator Buffer::getParFromID(int const id) const
1505 ParConstIterator it = par_iterator_begin();
1506 ParConstIterator const end = par_iterator_end();
1509 // John says this is called with id == -1 from undo
1510 lyxerr << "getParFromID(), id: " << id << endl;
1514 for (; it != end; ++it)
1522 bool Buffer::hasParWithID(int const id) const
1524 ParConstIterator const it = getParFromID(id);
1525 return it != par_iterator_end();
1529 ParIterator Buffer::par_iterator_begin()
1531 return lyx::par_iterator_begin(inset());
1535 ParIterator Buffer::par_iterator_end()
1537 return lyx::par_iterator_end(inset());
1541 ParConstIterator Buffer::par_iterator_begin() const
1543 return lyx::par_const_iterator_begin(inset());
1547 ParConstIterator Buffer::par_iterator_end() const
1549 return lyx::par_const_iterator_end(inset());
1553 Language const * Buffer::getLanguage() const
1555 return params().language;
1559 docstring const Buffer::B_(string const & l10n) const
1561 return params().B_(l10n);
1565 bool Buffer::isClean() const
1567 return pimpl_->lyx_clean;
1571 bool Buffer::isBakClean() const
1573 return pimpl_->bak_clean;
1577 bool Buffer::isExternallyModified(CheckMethod method) const
1579 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1580 // if method == timestamp, check timestamp before checksum
1581 return (method == checksum_method
1582 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1583 && pimpl_->checksum_ != sum(pimpl_->filename);
1587 void Buffer::markClean() const
1589 if (!pimpl_->lyx_clean) {
1590 pimpl_->lyx_clean = true;
1593 // if the .lyx file has been saved, we don't need an
1595 pimpl_->bak_clean = true;
1599 void Buffer::markBakClean()
1601 pimpl_->bak_clean = true;
1605 void Buffer::setUnnamed(bool flag)
1607 pimpl_->unnamed = flag;
1611 bool Buffer::isUnnamed() const
1613 return pimpl_->unnamed;
1617 // FIXME: this function should be moved to buffer_pimpl.C
1618 void Buffer::markDirty()
1620 if (pimpl_->lyx_clean) {
1621 pimpl_->lyx_clean = false;
1624 pimpl_->bak_clean = false;
1626 DepClean::iterator it = pimpl_->dep_clean.begin();
1627 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1629 for (; it != end; ++it)
1634 string const Buffer::fileName() const
1636 return pimpl_->filename.absFilename();
1640 string const & Buffer::filePath() const
1642 return params().filepath;
1646 bool Buffer::isReadonly() const
1648 return pimpl_->read_only;
1652 void Buffer::setParentName(string const & name)
1654 if (name == pimpl_->filename.absFilename())
1655 // Avoids recursive include.
1656 params().parentname.clear();
1658 params().parentname = name;
1662 Buffer const * Buffer::getMasterBuffer() const
1664 if (!params().parentname.empty()
1665 && theBufferList().exists(params().parentname)) {
1666 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1667 //We need to check if the parent is us...
1668 //FIXME RECURSIVE INCLUDE
1669 //This is not sufficient, since recursive includes could be downstream.
1670 if (buf && buf != this)
1671 return buf->getMasterBuffer();
1678 Buffer * Buffer::getMasterBuffer()
1680 if (!params().parentname.empty()
1681 && theBufferList().exists(params().parentname)) {
1682 Buffer * buf = theBufferList().getBuffer(params().parentname);
1684 return buf->getMasterBuffer();
1691 MacroData const & Buffer::getMacro(docstring const & name) const
1693 return pimpl_->macros.get(name);
1697 bool Buffer::hasMacro(docstring const & name) const
1699 return pimpl_->macros.has(name);
1703 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1705 MacroTable::globalMacros().insert(name, data);
1706 pimpl_->macros.insert(name, data);
1710 void Buffer::buildMacros()
1712 // Start with global table.
1713 pimpl_->macros = MacroTable::globalMacros();
1716 ParagraphList const & pars = text().paragraphs();
1717 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1718 //lyxerr << "searching main par " << i
1719 // << " for macro definitions" << std::endl;
1720 InsetList const & insets = pars[i].insetlist;
1721 InsetList::const_iterator it = insets.begin();
1722 InsetList::const_iterator end = insets.end();
1723 for ( ; it != end; ++it) {
1724 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1725 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1726 MathMacroTemplate const & mac
1727 = static_cast<MathMacroTemplate const &>(*it->inset);
1728 insertMacro(mac.name(), mac.asMacroData());
1735 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1742 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1745 //FIXME: This does not work for child documents yet.
1746 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1747 // Check if the label 'from' appears more than once
1748 vector<docstring> labels;
1750 if (code == Inset::CITE_CODE) {
1751 vector<pair<string, docstring> > keys;
1752 fillWithBibKeys(keys);
1753 vector<pair<string, docstring> >::const_iterator bit = keys.begin();
1754 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1756 for (; bit != bend; ++bit)
1758 labels.push_back(from_utf8(bit->first));
1760 getLabelList(labels);
1762 if (std::count(labels.begin(), labels.end(), from) > 1)
1765 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1766 if (it->lyxCode() == code) {
1767 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1768 inset.replaceContents(to_utf8(from), to_utf8(to));
1774 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1775 pit_type par_end, bool full_source)
1777 OutputParams runparams(¶ms().encoding());
1778 runparams.nice = true;
1779 runparams.flavor = OutputParams::LATEX;
1780 runparams.linelen = lyxrc.plaintext_linelen;
1781 // No side effect of file copying and image conversion
1782 runparams.dryrun = true;
1785 os << "% " << _("Preview source code") << "\n\n";
1787 writeLaTeXSource(os, filePath(), runparams, true, true);
1789 writeDocBookSource(os, fileName(), runparams, false);
1792 runparams.par_begin = par_begin;
1793 runparams.par_end = par_end;
1794 if (par_begin + 1 == par_end)
1796 << bformat(_("Preview source code for paragraph %1$s"), par_begin)
1800 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1801 convert<docstring>(par_begin),
1802 convert<docstring>(par_end - 1))
1804 // output paragraphs
1807 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1810 docbookParagraphs(paragraphs(), *this, os, runparams);
1816 ErrorList const & Buffer::errorList(string const & type) const
1818 static ErrorList const emptyErrorList;
1819 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1820 if (I == pimpl_->errorLists.end())
1821 return emptyErrorList;
1827 ErrorList & Buffer::errorList(string const & type)
1829 return pimpl_->errorLists[type];