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;
111 using support::addName;
112 using support::bformat;
113 using support::changeExtension;
114 using support::cmd_ret;
115 using support::createBufferTmpDir;
116 using support::destroyDir;
117 using support::FileName;
118 using support::getFormatFromContents;
119 using support::libFileSearch;
120 using support::latex_path;
121 using support::ltrim;
122 using support::makeAbsPath;
123 using support::makeDisplayPath;
124 using support::makeLatexName;
125 using support::onlyFilename;
126 using support::onlyPath;
127 using support::quoteName;
128 using support::removeAutosaveFile;
129 using support::rename;
130 using support::runCommand;
131 using support::split;
132 using support::subst;
133 using support::tempName;
137 namespace Alert = frontend::Alert;
138 namespace os = support::os;
139 namespace fs = boost::filesystem;
143 int const LYX_FORMAT = 276;
148 typedef std::map<string, bool> DepClean;
153 Impl(Buffer & parent, FileName const & file, bool readonly);
155 limited_stack<Undo> undostack;
156 limited_stack<Undo> redostack;
162 /// need to regenerate .tex?
166 mutable bool lyx_clean;
168 /// is autosave needed?
169 mutable bool bak_clean;
171 /// is this a unnamed file (New...)?
177 /// name of the file the buffer is associated with.
180 /** Set to true only when the file is fully loaded.
181 * Used to prevent the premature generation of previews
182 * and by the citation inset.
184 bool file_fully_loaded;
186 /// our Text that should be wrapped in an InsetText
193 TocBackend toc_backend;
195 /// Container for all sort of Buffer dependant errors.
196 map<string, ErrorList> errorLists;
198 /// timestamp and checksum used to test if the file has been externally
199 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
201 unsigned long checksum_;
205 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
206 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
207 filename(file), file_fully_loaded(false), inset(params),
208 timestamp_(0), checksum_(0), toc_backend(&parent)
210 inset.setAutoBreakRows(true);
211 lyxvc.buffer(&parent);
212 temppath = createBufferTmpDir();
213 params.filepath = onlyPath(file.absFilename());
214 // FIXME: And now do something if temppath == string(), because we
215 // assume from now on that temppath points to a valid temp dir.
216 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
220 Buffer::Buffer(string const & file, bool readonly)
221 : pimpl_(new Impl(*this, FileName(file), readonly))
223 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
229 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
230 // here the buffer should take care that it is
231 // saved properly, before it goes into the void.
235 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
236 Alert::warning(_("Could not remove temporary directory"),
237 bformat(_("Could not remove the temporary directory %1$s"),
238 from_utf8(temppath())));
241 // Remove any previewed LaTeX snippets associated with this buffer.
242 graphics::Previews::get().removeLoader(*this);
246 Text & Buffer::text() const
248 return const_cast<Text &>(pimpl_->inset.text_);
252 Inset & Buffer::inset() const
254 return const_cast<InsetText &>(pimpl_->inset);
258 limited_stack<Undo> & Buffer::undostack()
260 return pimpl_->undostack;
264 limited_stack<Undo> const & Buffer::undostack() const
266 return pimpl_->undostack;
270 limited_stack<Undo> & Buffer::redostack()
272 return pimpl_->redostack;
276 limited_stack<Undo> const & Buffer::redostack() const
278 return pimpl_->redostack;
282 BufferParams & Buffer::params()
284 return pimpl_->params;
288 BufferParams const & Buffer::params() const
290 return pimpl_->params;
294 ParagraphList & Buffer::paragraphs()
296 return text().paragraphs();
300 ParagraphList const & Buffer::paragraphs() const
302 return text().paragraphs();
306 LyXVC & Buffer::lyxvc()
308 return pimpl_->lyxvc;
312 LyXVC const & Buffer::lyxvc() const
314 return pimpl_->lyxvc;
318 string const & Buffer::temppath() const
320 return pimpl_->temppath;
324 TexRow & Buffer::texrow()
326 return pimpl_->texrow;
330 TexRow const & Buffer::texrow() const
332 return pimpl_->texrow;
336 TocBackend & Buffer::tocBackend()
338 return pimpl_->toc_backend;
342 TocBackend const & Buffer::tocBackend() const
344 return pimpl_->toc_backend;
348 string const Buffer::getLatexName(bool const no_path) const
350 string const name = changeExtension(makeLatexName(fileName()), ".tex");
351 return no_path ? onlyFilename(name) : name;
355 pair<Buffer::LogType, string> const Buffer::getLogName() const
357 string const filename = getLatexName(false);
359 if (filename.empty())
360 return make_pair(Buffer::latexlog, string());
362 string const path = temppath();
364 FileName const fname(addName(temppath(),
365 onlyFilename(changeExtension(filename,
367 FileName const bname(
368 addName(path, onlyFilename(
369 changeExtension(filename,
370 formats.extension("literate") + ".out"))));
372 // If no Latex log or Build log is newer, show Build log
374 if (fs::exists(bname.toFilesystemEncoding()) &&
375 (!fs::exists(fname.toFilesystemEncoding()) ||
376 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
377 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
378 return make_pair(Buffer::buildlog, bname.absFilename());
380 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
381 return make_pair(Buffer::latexlog, fname.absFilename());
385 void Buffer::setReadonly(bool const flag)
387 if (pimpl_->read_only != flag) {
388 pimpl_->read_only = flag;
394 void Buffer::setFileName(string const & newfile)
396 pimpl_->filename = makeAbsPath(newfile);
397 params().filepath = onlyPath(pimpl_->filename.absFilename());
398 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
403 // We'll remove this later. (Lgb)
406 void unknownClass(string const & unknown)
408 Alert::warning(_("Unknown document class"),
409 bformat(_("Using the default document class, because the "
410 "class %1$s is unknown."), from_utf8(unknown)));
416 int Buffer::readHeader(Lexer & lex)
418 int unknown_tokens = 0;
420 int begin_header_line = -1;
422 // Initialize parameters that may be/go lacking in header:
423 params().branchlist().clear();
424 params().preamble.erase();
425 params().options.erase();
426 params().float_placement.erase();
427 params().paperwidth.erase();
428 params().paperheight.erase();
429 params().leftmargin.erase();
430 params().rightmargin.erase();
431 params().topmargin.erase();
432 params().bottommargin.erase();
433 params().headheight.erase();
434 params().headsep.erase();
435 params().footskip.erase();
436 params().listings_params.clear();
437 for (int i = 0; i < 4; ++i) {
438 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
439 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
442 ErrorList & errorList = pimpl_->errorLists["Parse"];
446 string const token = lex.getString();
451 if (token == "\\end_header")
455 if (token == "\\begin_header") {
456 begin_header_line = line;
460 LYXERR(Debug::PARSER) << "Handling document header token: `"
461 << token << '\'' << endl;
463 string unknown = params().readToken(lex, token);
464 if (!unknown.empty()) {
465 if (unknown[0] != '\\' && token == "\\textclass") {
466 unknownClass(unknown);
469 docstring const s = bformat(_("Unknown token: "
473 errorList.push_back(ErrorItem(_("Document header error"),
478 if (begin_header_line) {
479 docstring const s = _("\\begin_header is missing");
480 errorList.push_back(ErrorItem(_("Document header error"),
484 return unknown_tokens;
489 // changed to be public and have one parameter
490 // Returns false if "\end_document" is not read (Asger)
491 bool Buffer::readDocument(Lexer & lex)
493 ErrorList & errorList = pimpl_->errorLists["Parse"];
497 string const token = lex.getString();
498 if (token != "\\begin_document") {
499 docstring const s = _("\\begin_document is missing");
500 errorList.push_back(ErrorItem(_("Document header error"),
504 // we are reading in a brand new document
505 BOOST_ASSERT(paragraphs().empty());
508 if (!params().getTextClass().load(filePath())) {
509 string theclass = params().getTextClass().name();
510 Alert::error(_("Can't load document class"), bformat(
511 _("Using the default document class, because the "
512 "class %1$s could not be loaded."), from_utf8(theclass)));
513 params().textclass = 0;
516 if (params().outputChanges) {
517 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
518 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
519 LaTeXFeatures::isAvailable("xcolor");
521 if (!dvipost && !xcolorsoul) {
522 Alert::warning(_("Changes not shown in LaTeX output"),
523 _("Changes will not be highlighted in LaTeX output, "
524 "because neither dvipost nor xcolor/soul are installed.\n"
525 "Please install these packages or redefine "
526 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
527 } else if (!xcolorsoul) {
528 Alert::warning(_("Changes not shown in LaTeX output"),
529 _("Changes will not be highlighted in LaTeX output "
530 "when using pdflatex, because xcolor and soul are not installed.\n"
531 "Please install both packages or redefine "
532 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
536 bool const res = text().read(*this, lex, errorList);
537 for_each(text().paragraphs().begin(),
538 text().paragraphs().end(),
539 bind(&Paragraph::setInsetOwner, _1, &inset()));
545 // needed to insert the selection
546 void Buffer::insertStringAsLines(ParagraphList & pars,
547 pit_type & pit, pos_type & pos,
548 Font const & fn, docstring const & str, bool autobreakrows)
552 // insert the string, don't insert doublespace
553 bool space_inserted = true;
554 for (docstring::const_iterator cit = str.begin();
555 cit != str.end(); ++cit) {
556 Paragraph & par = pars[pit];
558 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
559 breakParagraph(params(), pars, pit, pos,
560 par.layout()->isEnvironment());
563 space_inserted = true;
567 // do not insert consecutive spaces if !free_spacing
568 } else if ((*cit == ' ' || *cit == '\t') &&
569 space_inserted && !par.isFreeSpacing()) {
571 } else if (*cit == '\t') {
572 if (!par.isFreeSpacing()) {
573 // tabs are like spaces here
574 par.insertChar(pos, ' ', font, params().trackChanges);
576 space_inserted = true;
578 const pos_type n = 8 - pos % 8;
579 for (pos_type i = 0; i < n; ++i) {
580 par.insertChar(pos, ' ', font, params().trackChanges);
583 space_inserted = true;
585 } else if (!isPrintable(*cit)) {
586 // Ignore unprintables
589 // just insert the character
590 par.insertChar(pos, *cit, font, params().trackChanges);
592 space_inserted = (*cit == ' ');
599 bool Buffer::readString(std::string const & s)
601 params().compressed = false;
603 // remove dummy empty par
604 paragraphs().clear();
606 std::istringstream is(s);
608 FileName const name(tempName());
609 switch (readFile(lex, name, true)) {
613 // We need to call lyx2lyx, so write the input to a file
614 std::ofstream os(name.toFilesystemEncoding().c_str());
617 return readFile(name);
627 bool Buffer::readFile(FileName const & filename)
629 // Check if the file is compressed.
630 string const format = getFormatFromContents(filename);
631 if (format == "gzip" || format == "zip" || format == "compress") {
632 params().compressed = true;
635 // remove dummy empty par
636 paragraphs().clear();
638 lex.setFile(filename);
639 if (readFile(lex, filename) != success)
646 bool Buffer::fully_loaded() const
648 return pimpl_->file_fully_loaded;
652 void Buffer::fully_loaded(bool const value)
654 pimpl_->file_fully_loaded = value;
658 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
661 BOOST_ASSERT(!filename.empty());
664 Alert::error(_("Document could not be read"),
665 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
670 string const token(lex.getString());
673 Alert::error(_("Document could not be read"),
674 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
678 // the first token _must_ be...
679 if (token != "\\lyxformat") {
680 lyxerr << "Token: " << token << endl;
682 Alert::error(_("Document format failure"),
683 bformat(_("%1$s is not a LyX document."),
684 from_utf8(filename.absFilename())));
689 string tmp_format = lex.getString();
690 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
691 // if present remove ".," from string.
692 string::size_type dot = tmp_format.find_first_of(".,");
693 //lyxerr << " dot found at " << dot << endl;
694 if (dot != string::npos)
695 tmp_format.erase(dot, 1);
696 int const file_format = convert<int>(tmp_format);
697 //lyxerr << "format: " << file_format << endl;
699 if (file_format != LYX_FORMAT) {
702 // lyx2lyx would fail
705 FileName const tmpfile(tempName());
706 if (tmpfile.empty()) {
707 Alert::error(_("Conversion failed"),
708 bformat(_("%1$s is from a different"
709 " version of LyX, but a temporary"
710 " file for converting it could"
712 from_utf8(filename.absFilename())));
715 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
716 if (lyx2lyx.empty()) {
717 Alert::error(_("Conversion script not found"),
718 bformat(_("%1$s is from a different"
719 " version of LyX, but the"
720 " conversion script lyx2lyx"
721 " could not be found."),
722 from_utf8(filename.absFilename())));
725 ostringstream command;
726 command << os::python()
727 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
728 << " -t " << convert<string>(LYX_FORMAT)
729 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
730 << ' ' << quoteName(filename.toFilesystemEncoding());
731 string const command_str = command.str();
733 LYXERR(Debug::INFO) << "Running '"
734 << command_str << '\''
737 cmd_ret const ret = runCommand(command_str);
738 if (ret.first != 0) {
739 Alert::error(_("Conversion script failed"),
740 bformat(_("%1$s is from a different version"
741 " of LyX, but the lyx2lyx script"
742 " failed to convert it."),
743 from_utf8(filename.absFilename())));
746 bool const ret = readFile(tmpfile);
747 // Do stuff with tmpfile name and buffer name here.
748 return ret ? success : failure;
753 if (readDocument(lex)) {
754 Alert::error(_("Document format failure"),
755 bformat(_("%1$s ended unexpectedly, which means"
756 " that it is probably corrupted."),
757 from_utf8(filename.absFilename())));
760 //lyxerr << "removing " << MacroTable::localMacros().size()
761 // << " temporary macro entries" << endl;
762 //MacroTable::localMacros().clear();
764 pimpl_->file_fully_loaded = true;
765 // save the timestamp and checksum of disk file
766 pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
767 pimpl_->checksum_ = sum(filename);
772 // Should probably be moved to somewhere else: BufferView? LyXView?
773 bool Buffer::save() const
775 // We don't need autosaves in the immediate future. (Asger)
776 resetAutosaveTimers();
778 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
781 bool madeBackup = false;
783 // make a backup if the file already exists
784 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
785 backupName = FileName(fileName() + '~');
786 if (!lyxrc.backupdir_path.empty())
787 backupName = FileName(addName(lyxrc.backupdir_path,
788 subst(os::internal_path(backupName.absFilename()), '/', '!')));
791 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
793 } catch (fs::filesystem_error const & fe) {
794 Alert::error(_("Backup failure"),
795 bformat(_("Cannot create backup file %1$s.\n"
796 "Please check whether the directory exists and is writeable."),
797 from_utf8(backupName.absFilename())));
798 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
802 // ask if the disk file has been externally modified (use checksum method)
803 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
804 docstring const file = makeDisplayPath(fileName(), 20);
805 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
806 "you want to overwrite this file?"), file);
807 int const ret = Alert::prompt(_("Overwrite modified file?"),
808 text, 1, 1, _("&Overwrite"), _("&Cancel"));
813 if (writeFile(pimpl_->filename)) {
815 removeAutosaveFile(fileName());
816 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
817 pimpl_->checksum_ = sum(pimpl_->filename);
820 // Saving failed, so backup is not backup
822 rename(backupName, pimpl_->filename);
828 bool Buffer::writeFile(FileName const & fname) const
830 if (pimpl_->read_only && fname == pimpl_->filename)
835 if (params().compressed) {
836 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
842 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
853 bool Buffer::write(ostream & ofs) const
856 // Use the standard "C" locale for file output.
857 ofs.imbue(std::locale::classic());
860 // The top of the file should not be written by params().
862 // write out a comment in the top of the file
863 ofs << "#LyX " << lyx_version
864 << " created this file. For more info see http://www.lyx.org/\n"
865 << "\\lyxformat " << LYX_FORMAT << "\n"
866 << "\\begin_document\n";
869 /// For each author, set 'used' to true if there is a change
870 /// by this author in the document; otherwise set it to 'false'.
871 AuthorList::Authors::const_iterator a_it = params().authors().begin();
872 AuthorList::Authors::const_iterator a_end = params().authors().end();
873 for (; a_it != a_end; ++a_it)
874 a_it->second.used(false);
876 ParIterator const end = par_iterator_end();
877 ParIterator it = par_iterator_begin();
878 for ( ; it != end; ++it)
879 it->checkAuthors(params().authors());
881 // now write out the buffer parameters.
882 ofs << "\\begin_header\n";
883 params().writeFile(ofs);
884 ofs << "\\end_header\n";
887 ofs << "\n\\begin_body\n";
888 text().write(*this, ofs);
889 ofs << "\n\\end_body\n";
891 // Write marker that shows file is complete
892 ofs << "\\end_document" << endl;
894 // Shouldn't really be needed....
897 // how to check if close went ok?
898 // Following is an attempt... (BE 20001011)
900 // good() returns false if any error occured, including some
902 // bad() returns true if something bad happened in the buffer,
903 // which should include file system full errors.
908 lyxerr << "File was not closed properly." << endl;
915 bool Buffer::makeLaTeXFile(FileName const & fname,
916 string const & original_path,
917 OutputParams const & runparams,
918 bool output_preamble, bool output_body)
920 string const encoding = runparams.encoding->iconvName();
921 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
922 << encoding << "..." << endl;
924 odocfstream ofs(encoding);
925 if (!openFileWrite(ofs, fname))
928 bool failed_export = false;
930 writeLaTeXSource(ofs, original_path,
931 runparams, output_preamble, output_body);
933 catch (iconv_codecvt_facet_exception & e) {
934 lyxerr << "Caught iconv exception: " << e.what() << endl;
935 failed_export = true;
937 catch (std::exception const & e) {
938 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
939 failed_export = true;
942 lyxerr << "Caught some really weird exception..." << endl;
943 LyX::cref().emergencyCleanup();
949 failed_export = true;
950 lyxerr << "File '" << fname << "' was not closed properly." << endl;
954 Alert::error(_("Encoding error"),
955 _("Some characters of your document are probably not "
956 "representable in the chosen encoding.\n"
957 "Changing the document encoding to utf8 could help."));
964 void Buffer::writeLaTeXSource(odocstream & os,
965 string const & original_path,
966 OutputParams const & runparams_in,
967 bool const output_preamble, bool const output_body)
969 OutputParams runparams = runparams_in;
971 // validate the buffer.
972 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
973 LaTeXFeatures features(*this, params(), runparams);
975 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
979 // The starting paragraph of the coming rows is the
980 // first paragraph of the document. (Asger)
981 texrow().start(paragraphs().begin()->id(), 0);
983 if (output_preamble && runparams.nice) {
984 os << "%% LyX " << lyx_version << " created this file. "
985 "For more info, see http://www.lyx.org/.\n"
986 "%% Do not edit unless you really know what "
991 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
992 // There are a few differences between nice LaTeX and usual files:
993 // usual is \batchmode and has a
994 // special input@path to allow the including of figures
995 // with either \input or \includegraphics (what figinsets do).
996 // input@path is set when the actual parameter
997 // original_path is set. This is done for usual tex-file, but not
998 // for nice-latex-file. (Matthias 250696)
999 // Note that input@path is only needed for something the user does
1000 // in the preamble, included .tex files or ERT, files included by
1001 // LyX work without it.
1002 if (output_preamble) {
1003 if (!runparams.nice) {
1004 // code for usual, NOT nice-latex-file
1005 os << "\\batchmode\n"; // changed
1006 // from \nonstopmode
1009 if (!original_path.empty()) {
1011 // We don't know the encoding of inputpath
1012 docstring const inputpath = from_utf8(latex_path(original_path));
1013 os << "\\makeatletter\n"
1014 << "\\def\\input@path{{"
1015 << inputpath << "/}}\n"
1016 << "\\makeatother\n";
1022 // Write the preamble
1023 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1029 os << "\\begin{document}\n";
1031 } // output_preamble
1032 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1034 if (!lyxrc.language_auto_begin &&
1035 !params().language->babel().empty()) {
1037 os << from_utf8(subst(lyxrc.language_command_begin,
1039 params().language->babel()))
1044 Encoding const & encoding = params().encoding();
1045 if (encoding.package() == Encoding::CJK) {
1046 // Open a CJK environment, since in contrast to the encodings
1047 // handled by inputenc the document encoding is not set in
1048 // the preamble if it is handled by CJK.sty.
1049 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1054 // if we are doing a real file with body, even if this is the
1055 // child of some other buffer, let's cut the link here.
1056 // This happens for example if only a child document is printed.
1057 string save_parentname;
1058 if (output_preamble) {
1059 save_parentname = params().parentname;
1060 params().parentname.erase();
1064 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1066 // Restore the parenthood if needed
1067 if (output_preamble)
1068 params().parentname = save_parentname;
1070 // add this just in case after all the paragraphs
1074 if (encoding.package() == Encoding::CJK) {
1075 // Close the open CJK environment.
1076 // latexParagraphs will have opened one even if the last text
1078 os << "\\end{CJK}\n";
1082 if (!lyxrc.language_auto_end &&
1083 !params().language->babel().empty()) {
1084 os << from_utf8(subst(lyxrc.language_command_end,
1086 params().language->babel()))
1091 if (output_preamble) {
1092 os << "\\end{document}\n";
1095 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1097 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1100 runparams_in.encoding = runparams.encoding;
1102 // Just to be sure. (Asger)
1105 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1106 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1111 bool Buffer::isLatex() const
1113 return params().getTextClass().outputType() == LATEX;
1117 bool Buffer::isLiterate() const
1119 return params().getTextClass().outputType() == LITERATE;
1123 bool Buffer::isDocBook() const
1125 return params().getTextClass().outputType() == DOCBOOK;
1129 void Buffer::makeDocBookFile(FileName const & fname,
1130 OutputParams const & runparams,
1131 bool const body_only)
1133 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1137 if (!openFileWrite(ofs, fname))
1140 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1144 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1148 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1149 OutputParams const & runparams,
1150 bool const only_body)
1152 LaTeXFeatures features(*this, params(), runparams);
1157 TextClass const & tclass = params().getTextClass();
1158 string const top_element = tclass.latexname();
1161 if (runparams.flavor == OutputParams::XML)
1162 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1165 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1168 if (! tclass.class_header().empty())
1169 os << from_ascii(tclass.class_header());
1170 else if (runparams.flavor == OutputParams::XML)
1171 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1172 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1174 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1176 docstring preamble = from_utf8(params().preamble);
1177 if (runparams.flavor != OutputParams::XML ) {
1178 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1179 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1180 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1181 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1184 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1186 preamble += features.getIncludedFiles(name);
1187 preamble += features.getLyXSGMLEntities();
1189 if (!preamble.empty()) {
1190 os << "\n [ " << preamble << " ]";
1195 string top = top_element;
1197 if (runparams.flavor == OutputParams::XML)
1198 top += params().language->code();
1200 top += params().language->code().substr(0,2);
1203 if (!params().options.empty()) {
1205 top += params().options;
1208 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1209 << " file was created by LyX " << lyx_version
1210 << "\n See http://www.lyx.org/ for more information -->\n";
1212 params().getTextClass().counters().reset();
1214 sgml::openTag(os, top);
1216 docbookParagraphs(paragraphs(), *this, os, runparams);
1217 sgml::closeTag(os, top_element);
1221 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1222 // Other flags: -wall -v0 -x
1223 int Buffer::runChktex()
1227 // get LaTeX-Filename
1228 FileName const path(temppath());
1229 string const name = addName(path.absFilename(), getLatexName());
1230 string const org_path = filePath();
1232 support::Path p(path); // path to LaTeX file
1233 message(_("Running chktex..."));
1235 // Generate the LaTeX file if neccessary
1236 OutputParams runparams(¶ms().encoding());
1237 runparams.flavor = OutputParams::LATEX;
1238 runparams.nice = false;
1239 makeLaTeXFile(FileName(name), org_path, runparams);
1242 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1243 int const res = chktex.run(terr); // run chktex
1246 Alert::error(_("chktex failure"),
1247 _("Could not run chktex successfully."));
1248 } else if (res > 0) {
1249 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1250 // Clear out old errors
1252 // Fill-in the error list with the TeX errors
1253 bufferErrors(*this, terr, errorList);
1264 void Buffer::validate(LaTeXFeatures & features) const
1266 TextClass const & tclass = params().getTextClass();
1268 if (params().outputChanges) {
1269 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1270 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1271 LaTeXFeatures::isAvailable("xcolor");
1273 if (features.runparams().flavor == OutputParams::LATEX) {
1275 features.require("ct-dvipost");
1276 features.require("dvipost");
1277 } else if (xcolorsoul) {
1278 features.require("ct-xcolor-soul");
1279 features.require("soul");
1280 features.require("xcolor");
1282 features.require("ct-none");
1284 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1286 features.require("ct-xcolor-soul");
1287 features.require("soul");
1288 features.require("xcolor");
1289 features.require("pdfcolmk"); // improves color handling in PDF output
1291 features.require("ct-none");
1296 // AMS Style is at document level
1297 if (params().use_amsmath == BufferParams::package_on
1298 || tclass.provides("amsmath"))
1299 features.require("amsmath");
1300 if (params().use_esint == BufferParams::package_on)
1301 features.require("esint");
1303 for_each(paragraphs().begin(), paragraphs().end(),
1304 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1306 // the bullet shapes are buffer level not paragraph level
1307 // so they are tested here
1308 for (int i = 0; i < 4; ++i) {
1309 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1310 int const font = params().user_defined_bullet(i).getFont();
1312 int const c = params()
1313 .user_defined_bullet(i)
1320 features.require("latexsym");
1322 } else if (font == 1) {
1323 features.require("amssymb");
1324 } else if ((font >= 2 && font <= 5)) {
1325 features.require("pifont");
1330 if (lyxerr.debugging(Debug::LATEX)) {
1331 features.showStruct();
1336 void Buffer::getLabelList(vector<docstring> & list) const
1338 /// if this is a child document and the parent is already loaded
1339 /// Use the parent's list instead [ale990407]
1340 Buffer const * tmp = getMasterBuffer();
1342 lyxerr << "getMasterBuffer() failed!" << endl;
1346 tmp->getLabelList(list);
1350 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1351 it.nextInset()->getLabelList(*this, list);
1355 // This is also a buffer property (ale)
1356 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1359 /// if this is a child document and the parent is already loaded
1360 /// use the parent's list instead [ale990412]
1361 Buffer const * tmp = getMasterBuffer();
1364 tmp->fillWithBibKeys(keys);
1368 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1369 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1370 InsetBibtex const & inset =
1371 static_cast<InsetBibtex const &>(*it);
1372 inset.fillWithBibKeys(*this, keys);
1373 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1374 InsetInclude const & inset =
1375 static_cast<InsetInclude const &>(*it);
1376 inset.fillWithBibKeys(*this, keys);
1377 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1378 InsetBibitem const & inset =
1379 static_cast<InsetBibitem const &>(*it);
1381 string const key = to_utf8(inset.getParam("key"));
1382 docstring const label = inset.getParam("label");
1383 DocIterator doc_it(it); doc_it.forwardPos();
1384 docstring const ref = doc_it.paragraph().asString(*this, false);
1385 docstring const info = label + "TheBibliographyRef" + ref;
1386 keys.push_back(pair<string, docstring>(key, info));
1392 void Buffer::updateBibfilesCache()
1394 // if this is a child document and the parent is already loaded
1395 // update the parent's cache instead
1396 Buffer * tmp = getMasterBuffer();
1399 tmp->updateBibfilesCache();
1403 bibfilesCache_.clear();
1404 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1405 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1406 InsetBibtex const & inset =
1407 static_cast<InsetBibtex const &>(*it);
1408 vector<FileName> const bibfiles = inset.getFiles(*this);
1409 bibfilesCache_.insert(bibfilesCache_.end(),
1412 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1413 InsetInclude & inset =
1414 static_cast<InsetInclude &>(*it);
1415 inset.updateBibfilesCache(*this);
1416 vector<FileName> const & bibfiles =
1417 inset.getBibfilesCache(*this);
1418 bibfilesCache_.insert(bibfilesCache_.end(),
1426 vector<FileName> const & Buffer::getBibfilesCache() const
1428 // if this is a child document and the parent is already loaded
1429 // use the parent's cache instead
1430 Buffer const * tmp = getMasterBuffer();
1433 return tmp->getBibfilesCache();
1435 // We update the cache when first used instead of at loading time.
1436 if (bibfilesCache_.empty())
1437 const_cast<Buffer *>(this)->updateBibfilesCache();
1439 return bibfilesCache_;
1443 bool Buffer::isDepClean(string const & name) const
1445 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1446 if (it == pimpl_->dep_clean.end())
1452 void Buffer::markDepClean(string const & name)
1454 pimpl_->dep_clean[name] = true;
1458 bool Buffer::dispatch(string const & command, bool * result)
1460 return dispatch(lyxaction.lookupFunc(command), result);
1464 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1466 bool dispatched = true;
1468 switch (func.action) {
1469 case LFUN_BUFFER_EXPORT: {
1470 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1483 void Buffer::changeLanguage(Language const * from, Language const * to)
1488 for_each(par_iterator_begin(),
1490 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1492 text().current_font.setLanguage(to);
1493 text().real_current_font.setLanguage(to);
1497 bool Buffer::isMultiLingual() const
1499 ParConstIterator end = par_iterator_end();
1500 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1501 if (it->isMultiLingual(params()))
1508 ParIterator Buffer::getParFromID(int const id) const
1510 ParConstIterator it = par_iterator_begin();
1511 ParConstIterator const end = par_iterator_end();
1514 // John says this is called with id == -1 from undo
1515 lyxerr << "getParFromID(), id: " << id << endl;
1519 for (; it != end; ++it)
1527 bool Buffer::hasParWithID(int const id) const
1529 ParConstIterator const it = getParFromID(id);
1530 return it != par_iterator_end();
1534 ParIterator Buffer::par_iterator_begin()
1536 return lyx::par_iterator_begin(inset());
1540 ParIterator Buffer::par_iterator_end()
1542 return lyx::par_iterator_end(inset());
1546 ParConstIterator Buffer::par_iterator_begin() const
1548 return lyx::par_const_iterator_begin(inset());
1552 ParConstIterator Buffer::par_iterator_end() const
1554 return lyx::par_const_iterator_end(inset());
1558 Language const * Buffer::getLanguage() const
1560 return params().language;
1564 docstring const Buffer::B_(string const & l10n) const
1566 return params().B_(l10n);
1570 bool Buffer::isClean() const
1572 return pimpl_->lyx_clean;
1576 bool Buffer::isBakClean() const
1578 return pimpl_->bak_clean;
1582 bool Buffer::isExternallyModified(CheckMethod method) const
1584 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1585 // if method == timestamp, check timestamp before checksum
1586 return (method == checksum_method
1587 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1588 && pimpl_->checksum_ != sum(pimpl_->filename);
1592 void Buffer::markClean() const
1594 if (!pimpl_->lyx_clean) {
1595 pimpl_->lyx_clean = true;
1598 // if the .lyx file has been saved, we don't need an
1600 pimpl_->bak_clean = true;
1604 void Buffer::markBakClean()
1606 pimpl_->bak_clean = true;
1610 void Buffer::setUnnamed(bool flag)
1612 pimpl_->unnamed = flag;
1616 bool Buffer::isUnnamed() const
1618 return pimpl_->unnamed;
1622 #ifdef WITH_WARNINGS
1623 #warning this function should be moved to buffer_pimpl.C
1625 void Buffer::markDirty()
1627 if (pimpl_->lyx_clean) {
1628 pimpl_->lyx_clean = false;
1631 pimpl_->bak_clean = false;
1633 DepClean::iterator it = pimpl_->dep_clean.begin();
1634 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1636 for (; it != end; ++it)
1641 string const Buffer::fileName() const
1643 return pimpl_->filename.absFilename();
1647 string const & Buffer::filePath() const
1649 return params().filepath;
1653 bool Buffer::isReadonly() const
1655 return pimpl_->read_only;
1659 void Buffer::setParentName(string const & name)
1661 if (name == pimpl_->filename.absFilename())
1662 // Avoids recursive include.
1663 params().parentname.clear();
1665 params().parentname = name;
1669 Buffer const * Buffer::getMasterBuffer() const
1671 if (!params().parentname.empty()
1672 && theBufferList().exists(params().parentname)) {
1673 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1674 //We need to check if the parent is us...
1675 //FIXME RECURSIVE INCLUDE
1676 //This is not sufficient, since recursive includes could be downstream.
1677 if (buf && buf != this)
1678 return buf->getMasterBuffer();
1685 Buffer * Buffer::getMasterBuffer()
1687 if (!params().parentname.empty()
1688 && theBufferList().exists(params().parentname)) {
1689 Buffer * buf = theBufferList().getBuffer(params().parentname);
1691 return buf->getMasterBuffer();
1698 MacroData const & Buffer::getMacro(docstring const & name) const
1700 return pimpl_->macros.get(name);
1704 bool Buffer::hasMacro(docstring const & name) const
1706 return pimpl_->macros.has(name);
1710 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1712 MacroTable::globalMacros().insert(name, data);
1713 pimpl_->macros.insert(name, data);
1717 void Buffer::buildMacros()
1719 // Start with global table.
1720 pimpl_->macros = MacroTable::globalMacros();
1723 ParagraphList const & pars = text().paragraphs();
1724 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1725 //lyxerr << "searching main par " << i
1726 // << " for macro definitions" << std::endl;
1727 InsetList const & insets = pars[i].insetlist;
1728 InsetList::const_iterator it = insets.begin();
1729 InsetList::const_iterator end = insets.end();
1730 for ( ; it != end; ++it) {
1731 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1732 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1733 MathMacroTemplate const & mac
1734 = static_cast<MathMacroTemplate const &>(*it->inset);
1735 insertMacro(mac.name(), mac.asMacroData());
1742 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1749 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1752 //FIXME: This does not work for child documents yet.
1753 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1754 // Check if the label 'from' appears more than once
1755 vector<docstring> labels;
1757 if (code == Inset::CITE_CODE) {
1758 vector<pair<string, docstring> > keys;
1759 fillWithBibKeys(keys);
1760 vector<pair<string, docstring> >::const_iterator bit = keys.begin();
1761 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1763 for (; bit != bend; ++bit)
1765 labels.push_back(from_utf8(bit->first));
1767 getLabelList(labels);
1769 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1772 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1773 if (it->lyxCode() == code) {
1774 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1775 inset.replaceContents(to_utf8(from), to_utf8(to));
1781 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1782 pit_type par_end, bool full_source)
1784 OutputParams runparams(¶ms().encoding());
1785 runparams.nice = true;
1786 runparams.flavor = OutputParams::LATEX;
1787 runparams.linelen = lyxrc.plaintext_linelen;
1788 // No side effect of file copying and image conversion
1789 runparams.dryrun = true;
1792 os << "% " << _("Preview source code") << "\n\n";
1794 writeLaTeXSource(os, filePath(), runparams, true, true);
1796 writeDocBookSource(os, fileName(), runparams, false);
1799 runparams.par_begin = par_begin;
1800 runparams.par_end = par_end;
1801 if (par_begin + 1 == par_end)
1803 << bformat(_("Preview source code for paragraph %1$s"), par_begin)
1807 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1808 convert<docstring>(par_begin),
1809 convert<docstring>(par_end - 1))
1811 // output paragraphs
1814 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1817 docbookParagraphs(paragraphs(), *this, os, runparams);
1823 ErrorList const & Buffer::errorList(string const & type) const
1825 static ErrorList const emptyErrorList;
1826 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1827 if (I == pimpl_->errorLists.end())
1828 return emptyErrorList;
1834 ErrorList & Buffer::errorList(string const & type)
1836 return pimpl_->errorLists[type];