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 "BiblioInfo.h"
17 #include "BranchList.h"
18 #include "buffer_funcs.h"
19 #include "BufferList.h"
20 #include "BufferParams.h"
25 #include "DocIterator.h"
27 #include "ErrorList.h"
30 #include "FuncRequest.h"
32 #include "InsetIterator.h"
35 #include "LaTeXFeatures.h"
36 #include "LyXAction.h"
44 #include "output_docbook.h"
45 #include "output_latex.h"
46 #include "Paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "ParIterator.h"
52 #include "TextClassList.h"
53 #include "TexStream.h"
54 #include "TocBackend.h"
57 #include "EmbeddedFiles.h"
59 #include "insets/InsetBibitem.h"
60 #include "insets/InsetBibtex.h"
61 #include "insets/InsetInclude.h"
62 #include "insets/InsetText.h"
64 #include "mathed/MathMacroTemplate.h"
65 #include "mathed/MacroTable.h"
66 #include "mathed/MathSupport.h"
68 #include "frontends/alert.h"
70 #include "graphics/Previews.h"
72 #include "support/types.h"
73 #include "support/lyxalgo.h"
74 #include "support/filetools.h"
75 #include "support/fs_extras.h"
76 #include "support/gzstream.h"
77 #include "support/lyxlib.h"
78 #include "support/os.h"
79 #include "support/Path.h"
80 #include "support/textutils.h"
81 #include "support/convert.h"
83 #include <boost/bind.hpp>
84 #include <boost/filesystem/exception.hpp>
85 #include <boost/filesystem/operations.hpp>
100 using std::ostringstream;
112 using support::addName;
113 using support::bformat;
114 using support::changeExtension;
115 using support::cmd_ret;
116 using support::createBufferTmpDir;
117 using support::destroyDir;
118 using support::FileName;
119 using support::getFormatFromContents;
120 using support::libFileSearch;
121 using support::latex_path;
122 using support::ltrim;
123 using support::makeAbsPath;
124 using support::makeDisplayPath;
125 using support::makeLatexName;
126 using support::onlyFilename;
127 using support::onlyPath;
128 using support::quoteName;
129 using support::removeAutosaveFile;
130 using support::rename;
131 using support::runCommand;
132 using support::split;
133 using support::subst;
134 using support::tempName;
137 using support::suffixIs;
139 namespace Alert = frontend::Alert;
140 namespace os = support::os;
141 namespace fs = boost::filesystem;
145 int const LYX_FORMAT = 283;
150 typedef std::map<string, bool> DepClean;
155 Impl(Buffer & parent, FileName const & file, bool readonly);
157 limited_stack<Undo> undostack;
158 limited_stack<Undo> redostack;
164 /// need to regenerate .tex?
168 mutable bool lyx_clean;
170 /// is autosave needed?
171 mutable bool bak_clean;
173 /// is this a unnamed file (New...)?
179 /// name of the file the buffer is associated with.
182 /** Set to true only when the file is fully loaded.
183 * Used to prevent the premature generation of previews
184 * and by the citation inset.
186 bool file_fully_loaded;
188 /// our Text that should be wrapped in an InsetText
195 TocBackend toc_backend;
197 /// Container for all sort of Buffer dependant errors.
198 map<string, ErrorList> errorLists;
200 /// all embedded files of this buffer
201 EmbeddedFiles embedded_files;
203 /// timestamp and checksum used to test if the file has been externally
204 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
206 unsigned long checksum_;
210 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
211 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
212 filename(file), file_fully_loaded(false), inset(params),
213 toc_backend(&parent), embedded_files(&parent), timestamp_(0), checksum_(0)
215 inset.setAutoBreakRows(true);
216 lyxvc.buffer(&parent);
217 temppath = createBufferTmpDir();
218 params.filepath = onlyPath(file.absFilename());
219 // FIXME: And now do something if temppath == string(), because we
220 // assume from now on that temppath points to a valid temp dir.
221 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
225 Buffer::Buffer(string const & file, bool readonly)
226 : pimpl_(new Impl(*this, FileName(file), readonly))
228 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
234 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
235 // here the buffer should take care that it is
236 // saved properly, before it goes into the void.
238 Buffer * master = getMasterBuffer();
239 if (master != this && use_gui)
240 // We are closing buf which was a child document so we
241 // must update the labels and section numbering of its master
243 updateLabels(*master);
245 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
246 Alert::warning(_("Could not remove temporary directory"),
247 bformat(_("Could not remove the temporary directory %1$s"),
248 from_utf8(temppath())));
251 // Remove any previewed LaTeX snippets associated with this buffer.
252 graphics::Previews::get().removeLoader(*this);
258 Text & Buffer::text() const
260 return const_cast<Text &>(pimpl_->inset.text_);
264 Inset & Buffer::inset() const
266 return const_cast<InsetText &>(pimpl_->inset);
270 limited_stack<Undo> & Buffer::undostack()
272 return pimpl_->undostack;
276 limited_stack<Undo> const & Buffer::undostack() const
278 return pimpl_->undostack;
282 limited_stack<Undo> & Buffer::redostack()
284 return pimpl_->redostack;
288 limited_stack<Undo> const & Buffer::redostack() const
290 return pimpl_->redostack;
294 BufferParams & Buffer::params()
296 return pimpl_->params;
300 BufferParams const & Buffer::params() const
302 return pimpl_->params;
306 ParagraphList & Buffer::paragraphs()
308 return text().paragraphs();
312 ParagraphList const & Buffer::paragraphs() const
314 return text().paragraphs();
318 LyXVC & Buffer::lyxvc()
320 return pimpl_->lyxvc;
324 LyXVC const & Buffer::lyxvc() const
326 return pimpl_->lyxvc;
330 string const & Buffer::temppath() const
332 return pimpl_->temppath;
336 TexRow & Buffer::texrow()
338 return pimpl_->texrow;
342 TexRow const & Buffer::texrow() const
344 return pimpl_->texrow;
348 TocBackend & Buffer::tocBackend()
350 return pimpl_->toc_backend;
354 TocBackend const & Buffer::tocBackend() const
356 return pimpl_->toc_backend;
360 EmbeddedFiles & Buffer::embeddedFiles()
362 return pimpl_->embedded_files;
366 EmbeddedFiles const & Buffer::embeddedFiles() const
368 return pimpl_->embedded_files;
372 string const Buffer::getLatexName(bool const no_path) const
374 string const name = changeExtension(makeLatexName(fileName()), ".tex");
375 return no_path ? onlyFilename(name) : name;
379 pair<Buffer::LogType, string> const Buffer::getLogName() const
381 string const filename = getLatexName(false);
383 if (filename.empty())
384 return make_pair(Buffer::latexlog, string());
386 string const path = temppath();
388 FileName const fname(addName(temppath(),
389 onlyFilename(changeExtension(filename,
391 FileName const bname(
392 addName(path, onlyFilename(
393 changeExtension(filename,
394 formats.extension("literate") + ".out"))));
396 // If no Latex log or Build log is newer, show Build log
398 if (fs::exists(bname.toFilesystemEncoding()) &&
399 (!fs::exists(fname.toFilesystemEncoding()) ||
400 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
401 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
402 return make_pair(Buffer::buildlog, bname.absFilename());
404 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
405 return make_pair(Buffer::latexlog, fname.absFilename());
409 void Buffer::setReadonly(bool const flag)
411 if (pimpl_->read_only != flag) {
412 pimpl_->read_only = flag;
418 void Buffer::setFileName(string const & newfile)
420 pimpl_->filename = makeAbsPath(newfile);
421 params().filepath = onlyPath(pimpl_->filename.absFilename());
422 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
427 // We'll remove this later. (Lgb)
430 void unknownClass(string const & unknown)
432 Alert::warning(_("Unknown document class"),
433 bformat(_("Using the default document class, because the "
434 "class %1$s is unknown."), from_utf8(unknown)));
440 int Buffer::readHeader(Lexer & lex)
442 int unknown_tokens = 0;
444 int begin_header_line = -1;
446 // Initialize parameters that may be/go lacking in header:
447 params().branchlist().clear();
448 params().preamble.erase();
449 params().options.erase();
450 params().float_placement.erase();
451 params().paperwidth.erase();
452 params().paperheight.erase();
453 params().leftmargin.erase();
454 params().rightmargin.erase();
455 params().topmargin.erase();
456 params().bottommargin.erase();
457 params().headheight.erase();
458 params().headsep.erase();
459 params().footskip.erase();
460 params().listings_params.clear();
461 params().clearLayoutModules();
463 for (int i = 0; i < 4; ++i) {
464 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
465 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
468 ErrorList & errorList = pimpl_->errorLists["Parse"];
472 string const token = lex.getString();
477 if (token == "\\end_header")
481 if (token == "\\begin_header") {
482 begin_header_line = line;
486 LYXERR(Debug::PARSER) << "Handling document header token: `"
487 << token << '\'' << endl;
489 string unknown = params().readToken(lex, token);
490 if (!unknown.empty()) {
491 if (unknown[0] != '\\' && token == "\\textclass") {
492 unknownClass(unknown);
495 docstring const s = bformat(_("Unknown token: "
499 errorList.push_back(ErrorItem(_("Document header error"),
504 if (begin_header_line) {
505 docstring const s = _("\\begin_header is missing");
506 errorList.push_back(ErrorItem(_("Document header error"),
510 return unknown_tokens;
515 // changed to be public and have one parameter
516 // Returns false if "\end_document" is not read (Asger)
517 bool Buffer::readDocument(Lexer & lex)
519 ErrorList & errorList = pimpl_->errorLists["Parse"];
523 string const token = lex.getString();
524 if (token != "\\begin_document") {
525 docstring const s = _("\\begin_document is missing");
526 errorList.push_back(ErrorItem(_("Document header error"),
530 // we are reading in a brand new document
531 BOOST_ASSERT(paragraphs().empty());
534 TextClass const & baseClass = textclasslist[params().getBaseClass()];
535 if (!baseClass.load(filePath())) {
536 string theclass = baseClass.name();
537 Alert::error(_("Can't load document class"), bformat(
538 _("Using the default document class, because the "
539 "class %1$s could not be loaded."), from_utf8(theclass)));
540 params().setBaseClass(defaultTextclass());
543 if (params().outputChanges) {
544 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
545 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
546 LaTeXFeatures::isAvailable("xcolor");
548 if (!dvipost && !xcolorsoul) {
549 Alert::warning(_("Changes not shown in LaTeX output"),
550 _("Changes will not be highlighted in LaTeX output, "
551 "because neither dvipost nor xcolor/soul are installed.\n"
552 "Please install these packages or redefine "
553 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
554 } else if (!xcolorsoul) {
555 Alert::warning(_("Changes not shown in LaTeX output"),
556 _("Changes will not be highlighted in LaTeX output "
557 "when using pdflatex, because xcolor and soul are not installed.\n"
558 "Please install both packages or redefine "
559 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
563 bool const res = text().read(*this, lex, errorList);
564 for_each(text().paragraphs().begin(),
565 text().paragraphs().end(),
566 bind(&Paragraph::setInsetOwner, _1, &inset()));
572 // needed to insert the selection
573 void Buffer::insertStringAsLines(ParagraphList & pars,
574 pit_type & pit, pos_type & pos,
575 Font const & fn, docstring const & str, bool autobreakrows)
579 // insert the string, don't insert doublespace
580 bool space_inserted = true;
581 for (docstring::const_iterator cit = str.begin();
582 cit != str.end(); ++cit) {
583 Paragraph & par = pars[pit];
585 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
586 breakParagraph(params(), pars, pit, pos,
587 par.layout()->isEnvironment());
590 space_inserted = true;
594 // do not insert consecutive spaces if !free_spacing
595 } else if ((*cit == ' ' || *cit == '\t') &&
596 space_inserted && !par.isFreeSpacing()) {
598 } else if (*cit == '\t') {
599 if (!par.isFreeSpacing()) {
600 // tabs are like spaces here
601 par.insertChar(pos, ' ', font, params().trackChanges);
603 space_inserted = true;
605 const pos_type n = 8 - pos % 8;
606 for (pos_type i = 0; i < n; ++i) {
607 par.insertChar(pos, ' ', font, params().trackChanges);
610 space_inserted = true;
612 } else if (!isPrintable(*cit)) {
613 // Ignore unprintables
616 // just insert the character
617 par.insertChar(pos, *cit, font, params().trackChanges);
619 space_inserted = (*cit == ' ');
626 bool Buffer::readString(std::string const & s)
628 params().compressed = false;
630 // remove dummy empty par
631 paragraphs().clear();
633 std::istringstream is(s);
635 FileName const name(tempName());
636 switch (readFile(lex, name, true)) {
640 // We need to call lyx2lyx, so write the input to a file
641 std::ofstream os(name.toFilesystemEncoding().c_str());
644 return readFile(name);
654 bool Buffer::readFile(FileName const & filename)
656 FileName fname(filename);
657 // Check if the file is compressed.
658 string format = getFormatFromContents(filename);
659 if (format == "zip") {
660 // decompress to a temp directory
661 LYXERR(Debug::FILES) << filename << " is in zip format. Unzip to " << temppath() << endl;
662 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
664 FileName manifest(addName(temppath(), "manifest.txt"));
665 FileName lyxfile(addName(temppath(),
666 onlyFilename(filename.toFilesystemEncoding())));
667 // if both manifest.txt and file.lyx exist, this is am embedded file
668 if (fs::exists(manifest.toFilesystemEncoding()) &&
669 fs::exists(lyxfile.toFilesystemEncoding())) {
670 params().embedded = true;
672 // read manifest file
673 ifstream is(manifest.toFilesystemEncoding().c_str());
674 is >> pimpl_->embedded_files;
676 LYXERR(Debug::FILES) << filename << " is a embedded file. Its manifest is:\n"
677 << pimpl_->embedded_files;
680 // The embedded lyx file can also be compressed, for backward compatibility
681 format = getFormatFromContents(fname);
682 if (format == "gzip" || format == "zip" || format == "compress") {
683 params().compressed = true;
686 // remove dummy empty par
687 paragraphs().clear();
690 if (readFile(lex, fname) != success)
697 bool Buffer::fully_loaded() const
699 return pimpl_->file_fully_loaded;
703 void Buffer::fully_loaded(bool const value)
705 pimpl_->file_fully_loaded = value;
709 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
712 BOOST_ASSERT(!filename.empty());
715 Alert::error(_("Document could not be read"),
716 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
721 string const token(lex.getString());
724 Alert::error(_("Document could not be read"),
725 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
729 // the first token _must_ be...
730 if (token != "\\lyxformat") {
731 lyxerr << "Token: " << token << endl;
733 Alert::error(_("Document format failure"),
734 bformat(_("%1$s is not a LyX document."),
735 from_utf8(filename.absFilename())));
740 string tmp_format = lex.getString();
741 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
742 // if present remove ".," from string.
743 string::size_type dot = tmp_format.find_first_of(".,");
744 //lyxerr << " dot found at " << dot << endl;
745 if (dot != string::npos)
746 tmp_format.erase(dot, 1);
747 int const file_format = convert<int>(tmp_format);
748 //lyxerr << "format: " << file_format << endl;
750 // save timestamp and checksum of the original disk file, making sure
751 // to not overwrite them with those of the file created in the tempdir
752 // when it has to be converted to the current format.
753 if (!pimpl_->checksum_) {
754 // Save the timestamp and checksum of disk file. If filename is an
755 // emergency file, save the timestamp and sum of the original lyx file
756 // because isExternallyModified will check for this file. (BUG4193)
757 string diskfile = filename.toFilesystemEncoding();
758 if (suffixIs(diskfile, ".emergency"))
759 diskfile = diskfile.substr(0, diskfile.size() - 10);
760 saveCheckSum(diskfile);
763 if (file_format != LYX_FORMAT) {
766 // lyx2lyx would fail
769 FileName const tmpfile(tempName());
770 if (tmpfile.empty()) {
771 Alert::error(_("Conversion failed"),
772 bformat(_("%1$s is from a different"
773 " version of LyX, but a temporary"
774 " file for converting it could"
776 from_utf8(filename.absFilename())));
779 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
780 if (lyx2lyx.empty()) {
781 Alert::error(_("Conversion script not found"),
782 bformat(_("%1$s is from a different"
783 " version of LyX, but the"
784 " conversion script lyx2lyx"
785 " could not be found."),
786 from_utf8(filename.absFilename())));
789 ostringstream command;
790 command << os::python()
791 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
792 << " -t " << convert<string>(LYX_FORMAT)
793 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
794 << ' ' << quoteName(filename.toFilesystemEncoding());
795 string const command_str = command.str();
797 LYXERR(Debug::INFO) << "Running '"
798 << command_str << '\''
801 cmd_ret const ret = runCommand(command_str);
802 if (ret.first != 0) {
803 Alert::error(_("Conversion script failed"),
804 bformat(_("%1$s is from a different version"
805 " of LyX, but the lyx2lyx script"
806 " failed to convert it."),
807 from_utf8(filename.absFilename())));
810 bool const ret = readFile(tmpfile);
811 // Do stuff with tmpfile name and buffer name here.
812 return ret ? success : failure;
817 if (readDocument(lex)) {
818 Alert::error(_("Document format failure"),
819 bformat(_("%1$s ended unexpectedly, which means"
820 " that it is probably corrupted."),
821 from_utf8(filename.absFilename())));
824 //lyxerr << "removing " << MacroTable::localMacros().size()
825 // << " temporary macro entries" << endl;
826 //MacroTable::localMacros().clear();
828 pimpl_->file_fully_loaded = true;
833 // Should probably be moved to somewhere else: BufferView? LyXView?
834 bool Buffer::save() const
836 // We don't need autosaves in the immediate future. (Asger)
837 resetAutosaveTimers();
839 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
842 bool madeBackup = false;
844 // make a backup if the file already exists
845 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
846 backupName = FileName(fileName() + '~');
847 if (!lyxrc.backupdir_path.empty())
848 backupName = FileName(addName(lyxrc.backupdir_path,
849 subst(os::internal_path(backupName.absFilename()), '/', '!')));
852 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
854 } catch (fs::filesystem_error const & fe) {
855 Alert::error(_("Backup failure"),
856 bformat(_("Cannot create backup file %1$s.\n"
857 "Please check whether the directory exists and is writeable."),
858 from_utf8(backupName.absFilename())));
859 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
863 // ask if the disk file has been externally modified (use checksum method)
864 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
865 docstring const file = makeDisplayPath(fileName(), 20);
866 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
867 "you want to overwrite this file?"), file);
868 int const ret = Alert::prompt(_("Overwrite modified file?"),
869 text, 1, 1, _("&Overwrite"), _("&Cancel"));
874 if (writeFile(pimpl_->filename)) {
876 removeAutosaveFile(fileName());
877 saveCheckSum(pimpl_->filename.toFilesystemEncoding());
880 // Saving failed, so backup is not backup
882 rename(backupName, pimpl_->filename);
888 bool Buffer::writeFile(FileName const & fname) const
890 if (pimpl_->read_only && fname == pimpl_->filename)
896 if (params().embedded)
897 // first write the .lyx file to the temporary directory
898 content = FileName(addName(temppath(),
899 onlyFilename(fname.toFilesystemEncoding())));
903 if (params().compressed) {
904 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
910 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
917 if (retval && params().embedded) {
918 // write file.lyx and all the embedded files to the zip file fname
919 // if embedding is enabled, and there is any embedded file
920 pimpl_->embedded_files.update();
921 return pimpl_->embedded_files.write(fname);
927 bool Buffer::write(ostream & ofs) const
930 // Use the standard "C" locale for file output.
931 ofs.imbue(std::locale::classic());
934 // The top of the file should not be written by params().
936 // write out a comment in the top of the file
937 ofs << "#LyX " << lyx_version
938 << " created this file. For more info see http://www.lyx.org/\n"
939 << "\\lyxformat " << LYX_FORMAT << "\n"
940 << "\\begin_document\n";
943 /// For each author, set 'used' to true if there is a change
944 /// by this author in the document; otherwise set it to 'false'.
945 AuthorList::Authors::const_iterator a_it = params().authors().begin();
946 AuthorList::Authors::const_iterator a_end = params().authors().end();
947 for (; a_it != a_end; ++a_it)
948 a_it->second.used(false);
950 ParIterator const end = par_iterator_end();
951 ParIterator it = par_iterator_begin();
952 for ( ; it != end; ++it)
953 it->checkAuthors(params().authors());
955 // now write out the buffer parameters.
956 ofs << "\\begin_header\n";
957 params().writeFile(ofs);
958 ofs << "\\end_header\n";
961 ofs << "\n\\begin_body\n";
962 text().write(*this, ofs);
963 ofs << "\n\\end_body\n";
965 // Write marker that shows file is complete
966 ofs << "\\end_document" << endl;
968 // Shouldn't really be needed....
971 // how to check if close went ok?
972 // Following is an attempt... (BE 20001011)
974 // good() returns false if any error occured, including some
976 // bad() returns true if something bad happened in the buffer,
977 // which should include file system full errors.
982 lyxerr << "File was not closed properly." << endl;
989 bool Buffer::makeLaTeXFile(FileName const & fname,
990 string const & original_path,
991 OutputParams const & runparams,
992 bool output_preamble, bool output_body)
994 string const encoding = runparams.encoding->iconvName();
995 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
996 << encoding << "..." << endl;
998 odocfstream ofs(encoding);
999 if (!openFileWrite(ofs, fname))
1002 //TexStream ts(ofs.rdbuf(), &texrow());
1004 bool failed_export = false;
1007 writeLaTeXSource(ofs, original_path,
1008 runparams, output_preamble, output_body);
1010 catch (iconv_codecvt_facet_exception & e) {
1011 lyxerr << "Caught iconv exception: " << e.what() << endl;
1012 failed_export = true;
1014 catch (std::exception const & e) {
1015 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1016 failed_export = true;
1019 lyxerr << "Caught some really weird exception..." << endl;
1020 LyX::cref().emergencyCleanup();
1026 failed_export = true;
1027 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1030 if (failed_export) {
1031 Alert::error(_("Encoding error"),
1032 _("Some characters of your document are probably not "
1033 "representable in the chosen encoding.\n"
1034 "Changing the document encoding to utf8 could help."));
1041 void Buffer::writeLaTeXSource(odocstream & os,
1042 string const & original_path,
1043 OutputParams const & runparams_in,
1044 bool const output_preamble, bool const output_body)
1046 OutputParams runparams = runparams_in;
1048 // validate the buffer.
1049 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
1050 LaTeXFeatures features(*this, params(), runparams);
1052 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
1054 // The starting paragraph of the coming rows is the
1055 // first paragraph of the document. (Asger)
1056 if (output_preamble && runparams.nice) {
1057 os << "%% LyX " << lyx_version << " created this file. "
1058 "For more info, see http://www.lyx.org/.\n"
1059 "%% Do not edit unless you really know what "
1064 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1065 // There are a few differences between nice LaTeX and usual files:
1066 // usual is \batchmode and has a
1067 // special input@path to allow the including of figures
1068 // with either \input or \includegraphics (what figinsets do).
1069 // input@path is set when the actual parameter
1070 // original_path is set. This is done for usual tex-file, but not
1071 // for nice-latex-file. (Matthias 250696)
1072 // Note that input@path is only needed for something the user does
1073 // in the preamble, included .tex files or ERT, files included by
1074 // LyX work without it.
1075 if (output_preamble) {
1076 if (!runparams.nice) {
1077 // code for usual, NOT nice-latex-file
1078 os << "\\batchmode\n"; // changed
1079 // from \nonstopmode
1082 if (!original_path.empty()) {
1084 // We don't know the encoding of inputpath
1085 docstring const inputpath = from_utf8(latex_path(original_path));
1086 os << "\\makeatletter\n"
1087 << "\\def\\input@path{{"
1088 << inputpath << "/}}\n"
1089 << "\\makeatother\n";
1095 // Write the preamble
1096 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1102 os << "\\begin{document}\n";
1104 } // output_preamble
1106 texrow().start(paragraphs().begin()->id(), 0);
1108 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1110 if (!lyxrc.language_auto_begin &&
1111 !params().language->babel().empty()) {
1113 os << from_utf8(subst(lyxrc.language_command_begin,
1115 params().language->babel()))
1120 Encoding const & encoding = params().encoding();
1121 if (encoding.package() == Encoding::CJK) {
1122 // Open a CJK environment, since in contrast to the encodings
1123 // handled by inputenc the document encoding is not set in
1124 // the preamble if it is handled by CJK.sty.
1125 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1130 // if we are doing a real file with body, even if this is the
1131 // child of some other buffer, let's cut the link here.
1132 // This happens for example if only a child document is printed.
1133 string save_parentname;
1134 if (output_preamble) {
1135 save_parentname = params().parentname;
1136 params().parentname.erase();
1139 loadChildDocuments(*this);
1142 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1144 // Restore the parenthood if needed
1145 if (output_preamble)
1146 params().parentname = save_parentname;
1148 // add this just in case after all the paragraphs
1152 if (encoding.package() == Encoding::CJK) {
1153 // Close the open CJK environment.
1154 // latexParagraphs will have opened one even if the last text
1156 os << "\\end{CJK}\n";
1160 if (!lyxrc.language_auto_end &&
1161 !params().language->babel().empty()) {
1162 os << from_utf8(subst(lyxrc.language_command_end,
1164 params().language->babel()))
1169 if (output_preamble) {
1170 os << "\\end{document}\n";
1173 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1175 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1178 runparams_in.encoding = runparams.encoding;
1180 // Just to be sure. (Asger)
1183 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1184 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1189 bool Buffer::isLatex() const
1191 return params().getTextClass().outputType() == LATEX;
1195 bool Buffer::isLiterate() const
1197 return params().getTextClass().outputType() == LITERATE;
1201 bool Buffer::isDocBook() const
1203 return params().getTextClass().outputType() == DOCBOOK;
1207 void Buffer::makeDocBookFile(FileName const & fname,
1208 OutputParams const & runparams,
1209 bool const body_only)
1211 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1215 if (!openFileWrite(ofs, fname))
1218 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1222 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1226 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1227 OutputParams const & runparams,
1228 bool const only_body)
1230 LaTeXFeatures features(*this, params(), runparams);
1235 TextClass const & tclass = params().getTextClass();
1236 string const top_element = tclass.latexname();
1239 if (runparams.flavor == OutputParams::XML)
1240 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1243 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1246 if (! tclass.class_header().empty())
1247 os << from_ascii(tclass.class_header());
1248 else if (runparams.flavor == OutputParams::XML)
1249 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1250 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1252 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1254 docstring preamble = from_utf8(params().preamble);
1255 if (runparams.flavor != OutputParams::XML ) {
1256 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1257 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1258 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1259 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1262 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1264 preamble += features.getIncludedFiles(name);
1265 preamble += features.getLyXSGMLEntities();
1267 if (!preamble.empty()) {
1268 os << "\n [ " << preamble << " ]";
1273 string top = top_element;
1275 if (runparams.flavor == OutputParams::XML)
1276 top += params().language->code();
1278 top += params().language->code().substr(0,2);
1281 if (!params().options.empty()) {
1283 top += params().options;
1286 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1287 << " file was created by LyX " << lyx_version
1288 << "\n See http://www.lyx.org/ for more information -->\n";
1290 params().getTextClass().counters().reset();
1292 loadChildDocuments(*this);
1294 sgml::openTag(os, top);
1296 docbookParagraphs(paragraphs(), *this, os, runparams);
1297 sgml::closeTag(os, top_element);
1301 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1302 // Other flags: -wall -v0 -x
1303 int Buffer::runChktex()
1307 // get LaTeX-Filename
1308 FileName const path(temppath());
1309 string const name = addName(path.absFilename(), getLatexName());
1310 string const org_path = filePath();
1312 support::Path p(path); // path to LaTeX file
1313 message(_("Running chktex..."));
1315 // Generate the LaTeX file if neccessary
1316 OutputParams runparams(¶ms().encoding());
1317 runparams.flavor = OutputParams::LATEX;
1318 runparams.nice = false;
1319 makeLaTeXFile(FileName(name), org_path, runparams);
1322 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1323 int const res = chktex.run(terr); // run chktex
1326 Alert::error(_("chktex failure"),
1327 _("Could not run chktex successfully."));
1328 } else if (res > 0) {
1329 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1330 // Clear out old errors
1332 // Fill-in the error list with the TeX errors
1333 bufferErrors(*this, terr, errorList);
1344 void Buffer::validate(LaTeXFeatures & features) const
1346 TextClass const & tclass = params().getTextClass();
1348 if (params().outputChanges) {
1349 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1350 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1351 LaTeXFeatures::isAvailable("xcolor");
1353 if (features.runparams().flavor == OutputParams::LATEX) {
1355 features.require("ct-dvipost");
1356 features.require("dvipost");
1357 } else if (xcolorsoul) {
1358 features.require("ct-xcolor-soul");
1359 features.require("soul");
1360 features.require("xcolor");
1362 features.require("ct-none");
1364 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1366 features.require("ct-xcolor-soul");
1367 features.require("soul");
1368 features.require("xcolor");
1369 features.require("pdfcolmk"); // improves color handling in PDF output
1371 features.require("ct-none");
1376 // AMS Style is at document level
1377 if (params().use_amsmath == BufferParams::package_on
1378 || tclass.provides("amsmath"))
1379 features.require("amsmath");
1380 if (params().use_esint == BufferParams::package_on)
1381 features.require("esint");
1383 loadChildDocuments(*this);
1385 for_each(paragraphs().begin(), paragraphs().end(),
1386 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1388 // the bullet shapes are buffer level not paragraph level
1389 // so they are tested here
1390 for (int i = 0; i < 4; ++i) {
1391 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1392 int const font = params().user_defined_bullet(i).getFont();
1394 int const c = params()
1395 .user_defined_bullet(i)
1402 features.require("latexsym");
1404 } else if (font == 1) {
1405 features.require("amssymb");
1406 } else if ((font >= 2 && font <= 5)) {
1407 features.require("pifont");
1412 if (lyxerr.debugging(Debug::LATEX)) {
1413 features.showStruct();
1418 void Buffer::getLabelList(vector<docstring> & list) const
1420 /// if this is a child document and the parent is already loaded
1421 /// Use the parent's list instead [ale990407]
1422 Buffer const * tmp = getMasterBuffer();
1424 lyxerr << "getMasterBuffer() failed!" << endl;
1428 tmp->getLabelList(list);
1432 loadChildDocuments(*this);
1434 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1435 it.nextInset()->getLabelList(*this, list);
1439 void Buffer::updateBibfilesCache()
1441 // if this is a child document and the parent is already loaded
1442 // update the parent's cache instead
1443 Buffer * tmp = getMasterBuffer();
1446 tmp->updateBibfilesCache();
1450 bibfilesCache_.clear();
1451 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1452 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1453 InsetBibtex const & inset =
1454 static_cast<InsetBibtex const &>(*it);
1455 vector<FileName> const bibfiles = inset.getFiles(*this);
1456 bibfilesCache_.insert(bibfilesCache_.end(),
1459 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1460 InsetInclude & inset =
1461 static_cast<InsetInclude &>(*it);
1462 inset.updateBibfilesCache(*this);
1463 vector<FileName> const & bibfiles =
1464 inset.getBibfilesCache(*this);
1465 bibfilesCache_.insert(bibfilesCache_.end(),
1473 vector<FileName> const & Buffer::getBibfilesCache() const
1475 // if this is a child document and the parent is already loaded
1476 // use the parent's cache instead
1477 Buffer const * tmp = getMasterBuffer();
1480 return tmp->getBibfilesCache();
1482 // We update the cache when first used instead of at loading time.
1483 if (bibfilesCache_.empty())
1484 const_cast<Buffer *>(this)->updateBibfilesCache();
1486 return bibfilesCache_;
1490 bool Buffer::isDepClean(string const & name) const
1492 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1493 if (it == pimpl_->dep_clean.end())
1499 void Buffer::markDepClean(string const & name)
1501 pimpl_->dep_clean[name] = true;
1505 bool Buffer::dispatch(string const & command, bool * result)
1507 return dispatch(lyxaction.lookupFunc(command), result);
1511 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1513 bool dispatched = true;
1515 switch (func.action) {
1516 case LFUN_BUFFER_EXPORT: {
1517 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1530 void Buffer::changeLanguage(Language const * from, Language const * to)
1535 for_each(par_iterator_begin(),
1537 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1541 bool Buffer::isMultiLingual() const
1543 ParConstIterator end = par_iterator_end();
1544 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1545 if (it->isMultiLingual(params()))
1552 ParIterator Buffer::getParFromID(int const id) const
1554 ParConstIterator it = par_iterator_begin();
1555 ParConstIterator const end = par_iterator_end();
1558 // John says this is called with id == -1 from undo
1559 lyxerr << "getParFromID(), id: " << id << endl;
1563 for (; it != end; ++it)
1571 bool Buffer::hasParWithID(int const id) const
1573 ParConstIterator const it = getParFromID(id);
1574 return it != par_iterator_end();
1578 ParIterator Buffer::par_iterator_begin()
1580 return lyx::par_iterator_begin(inset());
1584 ParIterator Buffer::par_iterator_end()
1586 return lyx::par_iterator_end(inset());
1590 ParConstIterator Buffer::par_iterator_begin() const
1592 return lyx::par_const_iterator_begin(inset());
1596 ParConstIterator Buffer::par_iterator_end() const
1598 return lyx::par_const_iterator_end(inset());
1602 Language const * Buffer::getLanguage() const
1604 return params().language;
1608 docstring const Buffer::B_(string const & l10n) const
1610 return params().B_(l10n);
1614 bool Buffer::isClean() const
1616 return pimpl_->lyx_clean;
1620 bool Buffer::isBakClean() const
1622 return pimpl_->bak_clean;
1626 bool Buffer::isExternallyModified(CheckMethod method) const
1628 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1629 // if method == timestamp, check timestamp before checksum
1630 return (method == checksum_method
1631 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1632 && pimpl_->checksum_ != sum(pimpl_->filename);
1636 void Buffer::saveCheckSum(string const & file) const
1638 if (fs::exists(file)) {
1639 pimpl_->timestamp_ = fs::last_write_time(file);
1640 pimpl_->checksum_ = sum(FileName(file));
1642 // in the case of save to a new file.
1643 pimpl_->timestamp_ = 0;
1644 pimpl_->checksum_ = 0;
1649 void Buffer::markClean() const
1651 if (!pimpl_->lyx_clean) {
1652 pimpl_->lyx_clean = true;
1655 // if the .lyx file has been saved, we don't need an
1657 pimpl_->bak_clean = true;
1661 void Buffer::markBakClean()
1663 pimpl_->bak_clean = true;
1667 void Buffer::setUnnamed(bool flag)
1669 pimpl_->unnamed = flag;
1673 bool Buffer::isUnnamed() const
1675 return pimpl_->unnamed;
1679 // FIXME: this function should be moved to buffer_pimpl.C
1680 void Buffer::markDirty()
1682 if (pimpl_->lyx_clean) {
1683 pimpl_->lyx_clean = false;
1686 pimpl_->bak_clean = false;
1688 DepClean::iterator it = pimpl_->dep_clean.begin();
1689 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1691 for (; it != end; ++it)
1696 string const Buffer::fileName() const
1698 return pimpl_->filename.absFilename();
1702 string const & Buffer::filePath() const
1704 return params().filepath;
1708 bool Buffer::isReadonly() const
1710 return pimpl_->read_only;
1714 void Buffer::setParentName(string const & name)
1716 if (name == pimpl_->filename.absFilename())
1717 // Avoids recursive include.
1718 params().parentname.clear();
1720 params().parentname = name;
1724 Buffer const * Buffer::getMasterBuffer() const
1726 if (!params().parentname.empty()
1727 && theBufferList().exists(params().parentname)) {
1728 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1729 //We need to check if the parent is us...
1730 //FIXME RECURSIVE INCLUDE
1731 //This is not sufficient, since recursive includes could be downstream.
1732 if (buf && buf != this)
1733 return buf->getMasterBuffer();
1740 Buffer * Buffer::getMasterBuffer()
1742 if (!params().parentname.empty()
1743 && theBufferList().exists(params().parentname)) {
1744 Buffer * buf = theBufferList().getBuffer(params().parentname);
1746 return buf->getMasterBuffer();
1753 MacroData const & Buffer::getMacro(docstring const & name) const
1755 return pimpl_->macros.get(name);
1759 bool Buffer::hasMacro(docstring const & name) const
1761 return pimpl_->macros.has(name);
1765 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1767 MacroTable::globalMacros().insert(name, data);
1768 pimpl_->macros.insert(name, data);
1772 void Buffer::buildMacros()
1774 // Start with global table.
1775 pimpl_->macros = MacroTable::globalMacros();
1778 ParagraphList const & pars = text().paragraphs();
1779 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1780 //lyxerr << "searching main par " << i
1781 // << " for macro definitions" << std::endl;
1782 InsetList const & insets = pars[i].insetlist;
1783 InsetList::const_iterator it = insets.begin();
1784 InsetList::const_iterator end = insets.end();
1785 for ( ; it != end; ++it) {
1786 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1787 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1788 MathMacroTemplate const & mac
1789 = static_cast<MathMacroTemplate const &>(*it->inset);
1790 insertMacro(mac.name(), mac.asMacroData());
1797 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1800 //FIXME: This does not work for child documents yet.
1801 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1802 // Check if the label 'from' appears more than once
1803 vector<docstring> labels;
1805 if (code == Inset::CITE_CODE) {
1807 keys.fillWithBibKeys(this);
1808 BiblioInfo::const_iterator bit = keys.begin();
1809 BiblioInfo::const_iterator bend = keys.end();
1811 for (; bit != bend; ++bit)
1813 labels.push_back(bit->first);
1815 getLabelList(labels);
1817 if (std::count(labels.begin(), labels.end(), from) > 1)
1820 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1821 if (it->lyxCode() == code) {
1822 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1823 inset.replaceContents(to_utf8(from), to_utf8(to));
1829 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1830 pit_type par_end, bool full_source)
1832 OutputParams runparams(¶ms().encoding());
1833 runparams.nice = true;
1834 runparams.flavor = OutputParams::LATEX;
1835 runparams.linelen = lyxrc.plaintext_linelen;
1836 // No side effect of file copying and image conversion
1837 runparams.dryrun = true;
1841 os << "% " << _("Preview source code") << "\n\n";
1845 writeLaTeXSource(os, filePath(), runparams, true, true);
1847 writeDocBookSource(os, fileName(), runparams, false);
1850 runparams.par_begin = par_begin;
1851 runparams.par_end = par_end;
1852 if (par_begin + 1 == par_end)
1854 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1858 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1859 convert<docstring>(par_begin),
1860 convert<docstring>(par_end - 1))
1864 // output paragraphs
1866 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1869 docbookParagraphs(paragraphs(), *this, os, runparams);
1875 ErrorList const & Buffer::errorList(string const & type) const
1877 static ErrorList const emptyErrorList;
1878 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1879 if (I == pimpl_->errorLists.end())
1880 return emptyErrorList;
1886 ErrorList & Buffer::errorList(string const & type)
1888 return pimpl_->errorLists[type];