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"
37 #include "LyXAction.h"
45 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
53 #include "TextClassList.h"
54 #include "TexStream.h"
55 #include "TocBackend.h"
58 #include "EmbeddedFiles.h"
59 #include "PDFOptions.h"
61 #include "insets/InsetBibitem.h"
62 #include "insets/InsetBibtex.h"
63 #include "insets/InsetInclude.h"
64 #include "insets/InsetText.h"
66 #include "mathed/MathMacroTemplate.h"
67 #include "mathed/MacroTable.h"
68 #include "mathed/MathSupport.h"
70 #include "frontends/alert.h"
72 #include "graphics/Previews.h"
74 #include "support/types.h"
75 #include "support/lyxalgo.h"
76 #include "support/filetools.h"
77 #include "support/fs_extras.h"
78 #include "support/gzstream.h"
79 #include "support/lyxlib.h"
80 #include "support/os.h"
81 #include "support/Path.h"
82 #include "support/textutils.h"
83 #include "support/convert.h"
85 #include <boost/bind.hpp>
86 #include <boost/filesystem/exception.hpp>
87 #include <boost/filesystem/operations.hpp>
102 using std::ostringstream;
114 using support::addName;
115 using support::bformat;
116 using support::changeExtension;
117 using support::cmd_ret;
118 using support::createBufferTmpDir;
119 using support::destroyDir;
120 using support::FileName;
121 using support::getFormatFromContents;
122 using support::libFileSearch;
123 using support::latex_path;
124 using support::ltrim;
125 using support::makeAbsPath;
126 using support::makeDisplayPath;
127 using support::makeLatexName;
128 using support::onlyFilename;
129 using support::onlyPath;
130 using support::quoteName;
131 using support::removeAutosaveFile;
132 using support::rename;
133 using support::runCommand;
134 using support::split;
135 using support::subst;
136 using support::tempName;
139 using support::suffixIs;
141 namespace Alert = frontend::Alert;
142 namespace os = support::os;
143 namespace fs = boost::filesystem;
147 int const LYX_FORMAT = 288; //RGH, command insets
152 typedef std::map<string, bool> DepClean;
157 Impl(Buffer & parent, FileName const & file, bool readonly);
159 limited_stack<Undo> undostack;
160 limited_stack<Undo> redostack;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
190 /// our Text that should be wrapped in an InsetText
197 TocBackend toc_backend;
199 /// Container for all sort of Buffer dependant errors.
200 map<string, ErrorList> errorLists;
202 /// all embedded files of this buffer
203 EmbeddedFiles embedded_files;
205 /// timestamp and checksum used to test if the file has been externally
206 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
208 unsigned long checksum_;
212 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
213 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
214 filename(file), file_fully_loaded(false), inset(params),
215 toc_backend(&parent), embedded_files(&parent), timestamp_(0), checksum_(0)
217 inset.setAutoBreakRows(true);
218 lyxvc.buffer(&parent);
219 temppath = createBufferTmpDir();
220 params.filepath = onlyPath(file.absFilename());
221 // FIXME: And now do something if temppath == string(), because we
222 // assume from now on that temppath points to a valid temp dir.
223 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
227 Buffer::Buffer(string const & file, bool readonly)
228 : pimpl_(new Impl(*this, FileName(file), readonly))
230 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
236 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
237 // here the buffer should take care that it is
238 // saved properly, before it goes into the void.
240 Buffer * master = getMasterBuffer();
241 if (master != this && use_gui)
242 // We are closing buf which was a child document so we
243 // must update the labels and section numbering of its master
245 updateLabels(*master);
247 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
248 Alert::warning(_("Could not remove temporary directory"),
249 bformat(_("Could not remove the temporary directory %1$s"),
250 from_utf8(temppath())));
253 // Remove any previewed LaTeX snippets associated with this buffer.
254 graphics::Previews::get().removeLoader(*this);
260 Text & Buffer::text() const
262 return const_cast<Text &>(pimpl_->inset.text_);
266 Inset & Buffer::inset() const
268 return const_cast<InsetText &>(pimpl_->inset);
272 limited_stack<Undo> & Buffer::undostack()
274 return pimpl_->undostack;
278 limited_stack<Undo> const & Buffer::undostack() const
280 return pimpl_->undostack;
284 limited_stack<Undo> & Buffer::redostack()
286 return pimpl_->redostack;
290 limited_stack<Undo> const & Buffer::redostack() const
292 return pimpl_->redostack;
296 BufferParams & Buffer::params()
298 return pimpl_->params;
302 BufferParams const & Buffer::params() const
304 return pimpl_->params;
308 ParagraphList & Buffer::paragraphs()
310 return text().paragraphs();
314 ParagraphList const & Buffer::paragraphs() const
316 return text().paragraphs();
320 LyXVC & Buffer::lyxvc()
322 return pimpl_->lyxvc;
326 LyXVC const & Buffer::lyxvc() const
328 return pimpl_->lyxvc;
332 string const & Buffer::temppath() const
334 return pimpl_->temppath;
338 TexRow & Buffer::texrow()
340 return pimpl_->texrow;
344 TexRow const & Buffer::texrow() const
346 return pimpl_->texrow;
350 TocBackend & Buffer::tocBackend()
352 return pimpl_->toc_backend;
356 TocBackend const & Buffer::tocBackend() const
358 return pimpl_->toc_backend;
362 EmbeddedFiles & Buffer::embeddedFiles()
364 return pimpl_->embedded_files;
368 EmbeddedFiles const & Buffer::embeddedFiles() const
370 return pimpl_->embedded_files;
374 string const Buffer::getLatexName(bool const no_path) const
376 string const name = changeExtension(makeLatexName(fileName()), ".tex");
377 return no_path ? onlyFilename(name) : name;
381 pair<Buffer::LogType, string> const Buffer::getLogName() const
383 string const filename = getLatexName(false);
385 if (filename.empty())
386 return make_pair(Buffer::latexlog, string());
388 string const path = temppath();
390 FileName const fname(addName(temppath(),
391 onlyFilename(changeExtension(filename,
393 FileName const bname(
394 addName(path, onlyFilename(
395 changeExtension(filename,
396 formats.extension("literate") + ".out"))));
398 // If no Latex log or Build log is newer, show Build log
400 if (fs::exists(bname.toFilesystemEncoding()) &&
401 (!fs::exists(fname.toFilesystemEncoding()) ||
402 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
403 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
404 return make_pair(Buffer::buildlog, bname.absFilename());
406 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
407 return make_pair(Buffer::latexlog, fname.absFilename());
411 void Buffer::setReadonly(bool const flag)
413 if (pimpl_->read_only != flag) {
414 pimpl_->read_only = flag;
420 void Buffer::setFileName(string const & newfile)
422 pimpl_->filename = makeAbsPath(newfile);
423 params().filepath = onlyPath(pimpl_->filename.absFilename());
424 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
429 // We'll remove this later. (Lgb)
432 void unknownClass(string const & unknown)
434 Alert::warning(_("Unknown document class"),
435 bformat(_("Using the default document class, because the "
436 "class %1$s is unknown."), from_utf8(unknown)));
442 int Buffer::readHeader(Lexer & lex)
444 int unknown_tokens = 0;
446 int begin_header_line = -1;
448 // Initialize parameters that may be/go lacking in header:
449 params().branchlist().clear();
450 params().preamble.erase();
451 params().options.erase();
452 params().float_placement.erase();
453 params().paperwidth.erase();
454 params().paperheight.erase();
455 params().leftmargin.erase();
456 params().rightmargin.erase();
457 params().topmargin.erase();
458 params().bottommargin.erase();
459 params().headheight.erase();
460 params().headsep.erase();
461 params().footskip.erase();
462 params().listings_params.clear();
463 params().clearLayoutModules();
464 params().pdfoptions().clear();
466 for (int i = 0; i < 4; ++i) {
467 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
468 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
471 ErrorList & errorList = pimpl_->errorLists["Parse"];
475 string const token = lex.getString();
480 if (token == "\\end_header")
484 if (token == "\\begin_header") {
485 begin_header_line = line;
489 LYXERR(Debug::PARSER) << "Handling document header token: `"
490 << token << '\'' << endl;
492 string unknown = params().readToken(lex, token);
493 if (!unknown.empty()) {
494 if (unknown[0] != '\\' && token == "\\textclass") {
495 unknownClass(unknown);
498 docstring const s = bformat(_("Unknown token: "
502 errorList.push_back(ErrorItem(_("Document header error"),
507 if (begin_header_line) {
508 docstring const s = _("\\begin_header is missing");
509 errorList.push_back(ErrorItem(_("Document header error"),
513 return unknown_tokens;
518 // changed to be public and have one parameter
519 // Returns false if "\end_document" is not read (Asger)
520 bool Buffer::readDocument(Lexer & lex)
522 ErrorList & errorList = pimpl_->errorLists["Parse"];
526 string const token = lex.getString();
527 if (token != "\\begin_document") {
528 docstring const s = _("\\begin_document is missing");
529 errorList.push_back(ErrorItem(_("Document header error"),
533 // we are reading in a brand new document
534 BOOST_ASSERT(paragraphs().empty());
537 TextClass const & baseClass = textclasslist[params().getBaseClass()];
538 if (!baseClass.load(filePath())) {
539 string theclass = baseClass.name();
540 Alert::error(_("Can't load document class"), bformat(
541 _("Using the default document class, because the "
542 "class %1$s could not be loaded."), from_utf8(theclass)));
543 params().setBaseClass(defaultTextclass());
546 if (params().outputChanges) {
547 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
548 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
549 LaTeXFeatures::isAvailable("xcolor");
551 if (!dvipost && !xcolorsoul) {
552 Alert::warning(_("Changes not shown in LaTeX output"),
553 _("Changes will not be highlighted in LaTeX output, "
554 "because neither dvipost nor xcolor/soul are installed.\n"
555 "Please install these packages or redefine "
556 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
557 } else if (!xcolorsoul) {
558 Alert::warning(_("Changes not shown in LaTeX output"),
559 _("Changes will not be highlighted in LaTeX output "
560 "when using pdflatex, because xcolor and soul are not installed.\n"
561 "Please install both packages or redefine "
562 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
565 // read manifest after header
566 embeddedFiles().readManifest(lex, errorList);
569 bool const res = text().read(*this, lex, errorList);
570 for_each(text().paragraphs().begin(),
571 text().paragraphs().end(),
572 bind(&Paragraph::setInsetOwner, _1, &inset()));
578 // needed to insert the selection
579 void Buffer::insertStringAsLines(ParagraphList & pars,
580 pit_type & pit, pos_type & pos,
581 Font const & fn, docstring const & str, bool autobreakrows)
585 // insert the string, don't insert doublespace
586 bool space_inserted = true;
587 for (docstring::const_iterator cit = str.begin();
588 cit != str.end(); ++cit) {
589 Paragraph & par = pars[pit];
591 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
592 breakParagraph(params(), pars, pit, pos,
593 par.layout()->isEnvironment());
596 space_inserted = true;
600 // do not insert consecutive spaces if !free_spacing
601 } else if ((*cit == ' ' || *cit == '\t') &&
602 space_inserted && !par.isFreeSpacing()) {
604 } else if (*cit == '\t') {
605 if (!par.isFreeSpacing()) {
606 // tabs are like spaces here
607 par.insertChar(pos, ' ', font, params().trackChanges);
609 space_inserted = true;
611 const pos_type n = 8 - pos % 8;
612 for (pos_type i = 0; i < n; ++i) {
613 par.insertChar(pos, ' ', font, params().trackChanges);
616 space_inserted = true;
618 } else if (!isPrintable(*cit)) {
619 // Ignore unprintables
622 // just insert the character
623 par.insertChar(pos, *cit, font, params().trackChanges);
625 space_inserted = (*cit == ' ');
632 bool Buffer::readString(std::string const & s)
634 params().compressed = false;
636 // remove dummy empty par
637 paragraphs().clear();
639 std::istringstream is(s);
641 FileName const name(tempName());
642 switch (readFile(lex, name, true)) {
646 // We need to call lyx2lyx, so write the input to a file
647 std::ofstream os(name.toFilesystemEncoding().c_str());
650 return readFile(name);
660 bool Buffer::readFile(FileName const & filename)
662 FileName fname(filename);
663 // Check if the file is compressed.
664 string format = getFormatFromContents(filename);
665 if (format == "zip") {
666 // decompress to a temp directory
667 LYXERR(Debug::FILES) << filename << " is in zip format. Unzip to " << temppath() << endl;
668 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
670 FileName lyxfile(addName(temppath(), "content.lyx"));
671 // if both manifest.txt and file.lyx exist, this is am embedded file
672 if (fs::exists(lyxfile.toFilesystemEncoding())) {
673 params().embedded = true;
677 // The embedded lyx file can also be compressed, for backward compatibility
678 format = getFormatFromContents(fname);
679 if (format == "gzip" || format == "zip" || format == "compress") {
680 params().compressed = true;
683 // remove dummy empty par
684 paragraphs().clear();
687 if (readFile(lex, fname) != success)
694 bool Buffer::fully_loaded() const
696 return pimpl_->file_fully_loaded;
700 void Buffer::fully_loaded(bool const value)
702 pimpl_->file_fully_loaded = value;
706 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
709 BOOST_ASSERT(!filename.empty());
712 Alert::error(_("Document could not be read"),
713 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
718 string const token(lex.getString());
721 Alert::error(_("Document could not be read"),
722 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
726 // the first token _must_ be...
727 if (token != "\\lyxformat") {
728 lyxerr << "Token: " << token << endl;
730 Alert::error(_("Document format failure"),
731 bformat(_("%1$s is not a LyX document."),
732 from_utf8(filename.absFilename())));
737 string tmp_format = lex.getString();
738 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
739 // if present remove ".," from string.
740 string::size_type dot = tmp_format.find_first_of(".,");
741 //lyxerr << " dot found at " << dot << endl;
742 if (dot != string::npos)
743 tmp_format.erase(dot, 1);
744 int const file_format = convert<int>(tmp_format);
745 //lyxerr << "format: " << file_format << endl;
747 // save timestamp and checksum of the original disk file, making sure
748 // to not overwrite them with those of the file created in the tempdir
749 // when it has to be converted to the current format.
750 if (!pimpl_->checksum_) {
751 // Save the timestamp and checksum of disk file. If filename is an
752 // emergency file, save the timestamp and sum of the original lyx file
753 // because isExternallyModified will check for this file. (BUG4193)
754 string diskfile = filename.toFilesystemEncoding();
755 if (suffixIs(diskfile, ".emergency"))
756 diskfile = diskfile.substr(0, diskfile.size() - 10);
757 saveCheckSum(diskfile);
760 if (file_format != LYX_FORMAT) {
763 // lyx2lyx would fail
766 FileName const tmpfile(tempName());
767 if (tmpfile.empty()) {
768 Alert::error(_("Conversion failed"),
769 bformat(_("%1$s is from a different"
770 " version of LyX, but a temporary"
771 " file for converting it could"
773 from_utf8(filename.absFilename())));
776 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
777 if (lyx2lyx.empty()) {
778 Alert::error(_("Conversion script not found"),
779 bformat(_("%1$s is from a different"
780 " version of LyX, but the"
781 " conversion script lyx2lyx"
782 " could not be found."),
783 from_utf8(filename.absFilename())));
786 ostringstream command;
787 command << os::python()
788 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
789 << " -t " << convert<string>(LYX_FORMAT)
790 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
791 << ' ' << quoteName(filename.toFilesystemEncoding());
792 string const command_str = command.str();
794 LYXERR(Debug::INFO) << "Running '"
795 << command_str << '\''
798 cmd_ret const ret = runCommand(command_str);
799 if (ret.first != 0) {
800 Alert::error(_("Conversion script failed"),
801 bformat(_("%1$s is from a different version"
802 " of LyX, but the lyx2lyx script"
803 " failed to convert it."),
804 from_utf8(filename.absFilename())));
807 bool const ret = readFile(tmpfile);
808 // Do stuff with tmpfile name and buffer name here.
809 return ret ? success : failure;
814 if (readDocument(lex)) {
815 Alert::error(_("Document format failure"),
816 bformat(_("%1$s ended unexpectedly, which means"
817 " that it is probably corrupted."),
818 from_utf8(filename.absFilename())));
821 //lyxerr << "removing " << MacroTable::localMacros().size()
822 // << " temporary macro entries" << endl;
823 //MacroTable::localMacros().clear();
825 pimpl_->file_fully_loaded = true;
830 // Should probably be moved to somewhere else: BufferView? LyXView?
831 bool Buffer::save() const
833 // We don't need autosaves in the immediate future. (Asger)
834 resetAutosaveTimers();
836 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
839 bool madeBackup = false;
841 // make a backup if the file already exists
842 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
843 backupName = FileName(fileName() + '~');
844 if (!lyxrc.backupdir_path.empty())
845 backupName = FileName(addName(lyxrc.backupdir_path,
846 subst(os::internal_path(backupName.absFilename()), '/', '!')));
849 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
851 } catch (fs::filesystem_error const & fe) {
852 Alert::error(_("Backup failure"),
853 bformat(_("Cannot create backup file %1$s.\n"
854 "Please check whether the directory exists and is writeable."),
855 from_utf8(backupName.absFilename())));
856 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
860 // ask if the disk file has been externally modified (use checksum method)
861 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
862 docstring const file = makeDisplayPath(fileName(), 20);
863 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
864 "you want to overwrite this file?"), file);
865 int const ret = Alert::prompt(_("Overwrite modified file?"),
866 text, 1, 1, _("&Overwrite"), _("&Cancel"));
871 if (writeFile(pimpl_->filename)) {
873 removeAutosaveFile(fileName());
874 saveCheckSum(pimpl_->filename.toFilesystemEncoding());
877 // Saving failed, so backup is not backup
879 rename(backupName, pimpl_->filename);
885 bool Buffer::writeFile(FileName const & fname) const
887 if (pimpl_->read_only && fname == pimpl_->filename)
893 if (params().embedded)
894 // first write the .lyx file to the temporary directory
895 content = FileName(addName(temppath(), "content.lyx"));
899 if (params().compressed) {
900 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
906 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
913 if (retval && params().embedded) {
914 // write file.lyx and all the embedded files to the zip file fname
915 // if embedding is enabled
916 return pimpl_->embedded_files.writeFile(fname);
922 bool Buffer::write(ostream & ofs) const
925 // Use the standard "C" locale for file output.
926 ofs.imbue(std::locale::classic());
929 // The top of the file should not be written by params().
931 // write out a comment in the top of the file
932 ofs << "#LyX " << lyx_version
933 << " created this file. For more info see http://www.lyx.org/\n"
934 << "\\lyxformat " << LYX_FORMAT << "\n"
935 << "\\begin_document\n";
938 /// For each author, set 'used' to true if there is a change
939 /// by this author in the document; otherwise set it to 'false'.
940 AuthorList::Authors::const_iterator a_it = params().authors().begin();
941 AuthorList::Authors::const_iterator a_end = params().authors().end();
942 for (; a_it != a_end; ++a_it)
943 a_it->second.used(false);
945 ParIterator const end = par_iterator_end();
946 ParIterator it = par_iterator_begin();
947 for ( ; it != end; ++it)
948 it->checkAuthors(params().authors());
950 // now write out the buffer parameters.
951 ofs << "\\begin_header\n";
952 params().writeFile(ofs);
953 ofs << "\\end_header\n";
955 // write the manifest after header
956 ofs << "\n\\begin_manifest\n";
957 pimpl_->embedded_files.update();
958 embeddedFiles().writeManifest(ofs);
959 ofs << "\\end_manifest\n";
962 ofs << "\n\\begin_body\n";
963 text().write(*this, ofs);
964 ofs << "\n\\end_body\n";
966 // Write marker that shows file is complete
967 ofs << "\\end_document" << endl;
969 // Shouldn't really be needed....
972 // how to check if close went ok?
973 // Following is an attempt... (BE 20001011)
975 // good() returns false if any error occured, including some
977 // bad() returns true if something bad happened in the buffer,
978 // which should include file system full errors.
983 lyxerr << "File was not closed properly." << endl;
990 bool Buffer::makeLaTeXFile(FileName const & fname,
991 string const & original_path,
992 OutputParams const & runparams,
993 bool output_preamble, bool output_body)
995 string const encoding = runparams.encoding->iconvName();
996 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
997 << encoding << "..." << endl;
999 odocfstream ofs(encoding);
1000 if (!openFileWrite(ofs, fname))
1003 //TexStream ts(ofs.rdbuf(), &texrow());
1005 bool failed_export = false;
1008 writeLaTeXSource(ofs, original_path,
1009 runparams, output_preamble, output_body);
1011 catch (iconv_codecvt_facet_exception & e) {
1012 lyxerr << "Caught iconv exception: " << e.what() << endl;
1013 failed_export = true;
1015 catch (std::exception const & e) {
1016 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1017 failed_export = true;
1020 lyxerr << "Caught some really weird exception..." << endl;
1021 LyX::cref().emergencyCleanup();
1027 failed_export = true;
1028 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1031 if (failed_export) {
1032 Alert::error(_("Encoding error"),
1033 _("Some characters of your document are probably not "
1034 "representable in the chosen encoding.\n"
1035 "Changing the document encoding to utf8 could help."));
1042 void Buffer::writeLaTeXSource(odocstream & os,
1043 string const & original_path,
1044 OutputParams const & runparams_in,
1045 bool const output_preamble, bool const output_body)
1047 OutputParams runparams = runparams_in;
1049 // validate the buffer.
1050 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
1051 LaTeXFeatures features(*this, params(), runparams);
1053 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
1055 // The starting paragraph of the coming rows is the
1056 // first paragraph of the document. (Asger)
1057 if (output_preamble && runparams.nice) {
1058 os << "%% LyX " << lyx_version << " created this file. "
1059 "For more info, see http://www.lyx.org/.\n"
1060 "%% Do not edit unless you really know what "
1065 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1066 // There are a few differences between nice LaTeX and usual files:
1067 // usual is \batchmode and has a
1068 // special input@path to allow the including of figures
1069 // with either \input or \includegraphics (what figinsets do).
1070 // input@path is set when the actual parameter
1071 // original_path is set. This is done for usual tex-file, but not
1072 // for nice-latex-file. (Matthias 250696)
1073 // Note that input@path is only needed for something the user does
1074 // in the preamble, included .tex files or ERT, files included by
1075 // LyX work without it.
1076 if (output_preamble) {
1077 if (!runparams.nice) {
1078 // code for usual, NOT nice-latex-file
1079 os << "\\batchmode\n"; // changed
1080 // from \nonstopmode
1083 if (!original_path.empty()) {
1085 // We don't know the encoding of inputpath
1086 docstring const inputpath = from_utf8(latex_path(original_path));
1087 os << "\\makeatletter\n"
1088 << "\\def\\input@path{{"
1089 << inputpath << "/}}\n"
1090 << "\\makeatother\n";
1096 // Write the preamble
1097 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1103 os << "\\begin{document}\n";
1105 } // output_preamble
1107 texrow().start(paragraphs().begin()->id(), 0);
1109 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1111 if (!lyxrc.language_auto_begin &&
1112 !params().language->babel().empty()) {
1114 os << from_utf8(subst(lyxrc.language_command_begin,
1116 params().language->babel()))
1121 Encoding const & encoding = params().encoding();
1122 if (encoding.package() == Encoding::CJK) {
1123 // Open a CJK environment, since in contrast to the encodings
1124 // handled by inputenc the document encoding is not set in
1125 // the preamble if it is handled by CJK.sty.
1126 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1131 // if we are doing a real file with body, even if this is the
1132 // child of some other buffer, let's cut the link here.
1133 // This happens for example if only a child document is printed.
1134 string save_parentname;
1135 if (output_preamble) {
1136 save_parentname = params().parentname;
1137 params().parentname.erase();
1140 loadChildDocuments(*this);
1143 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1145 // Restore the parenthood if needed
1146 if (output_preamble)
1147 params().parentname = save_parentname;
1149 // add this just in case after all the paragraphs
1153 if (encoding.package() == Encoding::CJK) {
1154 // Close the open CJK environment.
1155 // latexParagraphs will have opened one even if the last text
1157 os << "\\end{CJK}\n";
1161 if (!lyxrc.language_auto_end &&
1162 !params().language->babel().empty()) {
1163 os << from_utf8(subst(lyxrc.language_command_end,
1165 params().language->babel()))
1170 if (output_preamble) {
1171 os << "\\end{document}\n";
1174 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1176 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1179 runparams_in.encoding = runparams.encoding;
1181 // Just to be sure. (Asger)
1184 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1185 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1190 bool Buffer::isLatex() const
1192 return params().getTextClass().outputType() == LATEX;
1196 bool Buffer::isLiterate() const
1198 return params().getTextClass().outputType() == LITERATE;
1202 bool Buffer::isDocBook() const
1204 return params().getTextClass().outputType() == DOCBOOK;
1208 void Buffer::makeDocBookFile(FileName const & fname,
1209 OutputParams const & runparams,
1210 bool const body_only)
1212 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1216 if (!openFileWrite(ofs, fname))
1219 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1223 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1227 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1228 OutputParams const & runparams,
1229 bool const only_body)
1231 LaTeXFeatures features(*this, params(), runparams);
1236 TextClass const & tclass = params().getTextClass();
1237 string const top_element = tclass.latexname();
1240 if (runparams.flavor == OutputParams::XML)
1241 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1244 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1247 if (! tclass.class_header().empty())
1248 os << from_ascii(tclass.class_header());
1249 else if (runparams.flavor == OutputParams::XML)
1250 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1251 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1253 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1255 docstring preamble = from_utf8(params().preamble);
1256 if (runparams.flavor != OutputParams::XML ) {
1257 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1258 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1259 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1260 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1263 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1265 preamble += features.getIncludedFiles(name);
1266 preamble += features.getLyXSGMLEntities();
1268 if (!preamble.empty()) {
1269 os << "\n [ " << preamble << " ]";
1274 string top = top_element;
1276 if (runparams.flavor == OutputParams::XML)
1277 top += params().language->code();
1279 top += params().language->code().substr(0,2);
1282 if (!params().options.empty()) {
1284 top += params().options;
1287 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1288 << " file was created by LyX " << lyx_version
1289 << "\n See http://www.lyx.org/ for more information -->\n";
1291 params().getTextClass().counters().reset();
1293 loadChildDocuments(*this);
1295 sgml::openTag(os, top);
1297 docbookParagraphs(paragraphs(), *this, os, runparams);
1298 sgml::closeTag(os, top_element);
1302 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1303 // Other flags: -wall -v0 -x
1304 int Buffer::runChktex()
1308 // get LaTeX-Filename
1309 FileName const path(temppath());
1310 string const name = addName(path.absFilename(), getLatexName());
1311 string const org_path = filePath();
1313 support::Path p(path); // path to LaTeX file
1314 message(_("Running chktex..."));
1316 // Generate the LaTeX file if neccessary
1317 OutputParams runparams(¶ms().encoding());
1318 runparams.flavor = OutputParams::LATEX;
1319 runparams.nice = false;
1320 makeLaTeXFile(FileName(name), org_path, runparams);
1323 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1324 int const res = chktex.run(terr); // run chktex
1327 Alert::error(_("chktex failure"),
1328 _("Could not run chktex successfully."));
1329 } else if (res > 0) {
1330 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1331 // Clear out old errors
1333 // Fill-in the error list with the TeX errors
1334 bufferErrors(*this, terr, errorList);
1345 void Buffer::validate(LaTeXFeatures & features) const
1347 TextClass const & tclass = params().getTextClass();
1349 if (params().outputChanges) {
1350 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1351 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1352 LaTeXFeatures::isAvailable("xcolor");
1354 if (features.runparams().flavor == OutputParams::LATEX) {
1356 features.require("ct-dvipost");
1357 features.require("dvipost");
1358 } else if (xcolorsoul) {
1359 features.require("ct-xcolor-soul");
1360 features.require("soul");
1361 features.require("xcolor");
1363 features.require("ct-none");
1365 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1367 features.require("ct-xcolor-soul");
1368 features.require("soul");
1369 features.require("xcolor");
1370 features.require("pdfcolmk"); // improves color handling in PDF output
1372 features.require("ct-none");
1377 // AMS Style is at document level
1378 if (params().use_amsmath == BufferParams::package_on
1379 || tclass.provides("amsmath"))
1380 features.require("amsmath");
1381 if (params().use_esint == BufferParams::package_on)
1382 features.require("esint");
1384 loadChildDocuments(*this);
1386 for_each(paragraphs().begin(), paragraphs().end(),
1387 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1389 // the bullet shapes are buffer level not paragraph level
1390 // so they are tested here
1391 for (int i = 0; i < 4; ++i) {
1392 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1393 int const font = params().user_defined_bullet(i).getFont();
1395 int const c = params()
1396 .user_defined_bullet(i)
1403 features.require("latexsym");
1405 } else if (font == 1) {
1406 features.require("amssymb");
1407 } else if ((font >= 2 && font <= 5)) {
1408 features.require("pifont");
1413 if (lyxerr.debugging(Debug::LATEX)) {
1414 features.showStruct();
1419 void Buffer::getLabelList(vector<docstring> & list) const
1421 /// if this is a child document and the parent is already loaded
1422 /// Use the parent's list instead [ale990407]
1423 Buffer const * tmp = getMasterBuffer();
1425 lyxerr << "getMasterBuffer() failed!" << endl;
1429 tmp->getLabelList(list);
1433 loadChildDocuments(*this);
1435 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1436 it.nextInset()->getLabelList(*this, list);
1440 void Buffer::updateBibfilesCache()
1442 // if this is a child document and the parent is already loaded
1443 // update the parent's cache instead
1444 Buffer * tmp = getMasterBuffer();
1447 tmp->updateBibfilesCache();
1451 bibfilesCache_.clear();
1452 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1453 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1454 InsetBibtex const & inset =
1455 static_cast<InsetBibtex const &>(*it);
1456 vector<FileName> const bibfiles = inset.getFiles(*this);
1457 bibfilesCache_.insert(bibfilesCache_.end(),
1460 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1461 InsetInclude & inset =
1462 static_cast<InsetInclude &>(*it);
1463 inset.updateBibfilesCache(*this);
1464 vector<FileName> const & bibfiles =
1465 inset.getBibfilesCache(*this);
1466 bibfilesCache_.insert(bibfilesCache_.end(),
1474 vector<FileName> const & Buffer::getBibfilesCache() const
1476 // if this is a child document and the parent is already loaded
1477 // use the parent's cache instead
1478 Buffer const * tmp = getMasterBuffer();
1481 return tmp->getBibfilesCache();
1483 // We update the cache when first used instead of at loading time.
1484 if (bibfilesCache_.empty())
1485 const_cast<Buffer *>(this)->updateBibfilesCache();
1487 return bibfilesCache_;
1491 bool Buffer::isDepClean(string const & name) const
1493 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1494 if (it == pimpl_->dep_clean.end())
1500 void Buffer::markDepClean(string const & name)
1502 pimpl_->dep_clean[name] = true;
1506 bool Buffer::dispatch(string const & command, bool * result)
1508 return dispatch(lyxaction.lookupFunc(command), result);
1512 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1514 bool dispatched = true;
1516 switch (func.action) {
1517 case LFUN_BUFFER_EXPORT: {
1518 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1531 void Buffer::changeLanguage(Language const * from, Language const * to)
1536 for_each(par_iterator_begin(),
1538 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1542 bool Buffer::isMultiLingual() const
1544 ParConstIterator end = par_iterator_end();
1545 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1546 if (it->isMultiLingual(params()))
1553 ParIterator Buffer::getParFromID(int const id) const
1555 ParConstIterator it = par_iterator_begin();
1556 ParConstIterator const end = par_iterator_end();
1559 // John says this is called with id == -1 from undo
1560 lyxerr << "getParFromID(), id: " << id << endl;
1564 for (; it != end; ++it)
1572 bool Buffer::hasParWithID(int const id) const
1574 ParConstIterator const it = getParFromID(id);
1575 return it != par_iterator_end();
1579 ParIterator Buffer::par_iterator_begin()
1581 return lyx::par_iterator_begin(inset());
1585 ParIterator Buffer::par_iterator_end()
1587 return lyx::par_iterator_end(inset());
1591 ParConstIterator Buffer::par_iterator_begin() const
1593 return lyx::par_const_iterator_begin(inset());
1597 ParConstIterator Buffer::par_iterator_end() const
1599 return lyx::par_const_iterator_end(inset());
1603 Language const * Buffer::getLanguage() const
1605 return params().language;
1609 docstring const Buffer::B_(string const & l10n) const
1611 return params().B_(l10n);
1615 bool Buffer::isClean() const
1617 return pimpl_->lyx_clean;
1621 bool Buffer::isBakClean() const
1623 return pimpl_->bak_clean;
1627 bool Buffer::isExternallyModified(CheckMethod method) const
1629 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1630 // if method == timestamp, check timestamp before checksum
1631 return (method == checksum_method
1632 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1633 && pimpl_->checksum_ != sum(pimpl_->filename);
1637 void Buffer::saveCheckSum(string const & file) const
1639 if (fs::exists(file)) {
1640 pimpl_->timestamp_ = fs::last_write_time(file);
1641 pimpl_->checksum_ = sum(FileName(file));
1643 // in the case of save to a new file.
1644 pimpl_->timestamp_ = 0;
1645 pimpl_->checksum_ = 0;
1650 void Buffer::markClean() const
1652 if (!pimpl_->lyx_clean) {
1653 pimpl_->lyx_clean = true;
1656 // if the .lyx file has been saved, we don't need an
1658 pimpl_->bak_clean = true;
1662 void Buffer::markBakClean()
1664 pimpl_->bak_clean = true;
1668 void Buffer::setUnnamed(bool flag)
1670 pimpl_->unnamed = flag;
1674 bool Buffer::isUnnamed() const
1676 return pimpl_->unnamed;
1680 // FIXME: this function should be moved to buffer_pimpl.C
1681 void Buffer::markDirty()
1683 if (pimpl_->lyx_clean) {
1684 pimpl_->lyx_clean = false;
1687 pimpl_->bak_clean = false;
1689 DepClean::iterator it = pimpl_->dep_clean.begin();
1690 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1692 for (; it != end; ++it)
1697 string const Buffer::fileName() const
1699 return pimpl_->filename.absFilename();
1703 string const & Buffer::filePath() const
1705 return params().filepath;
1709 bool Buffer::isReadonly() const
1711 return pimpl_->read_only;
1715 void Buffer::setParentName(string const & name)
1717 if (name == pimpl_->filename.absFilename())
1718 // Avoids recursive include.
1719 params().parentname.clear();
1721 params().parentname = name;
1725 Buffer const * Buffer::getMasterBuffer() const
1727 if (!params().parentname.empty()
1728 && theBufferList().exists(params().parentname)) {
1729 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1730 //We need to check if the parent is us...
1731 //FIXME RECURSIVE INCLUDE
1732 //This is not sufficient, since recursive includes could be downstream.
1733 if (buf && buf != this)
1734 return buf->getMasterBuffer();
1741 Buffer * Buffer::getMasterBuffer()
1743 if (!params().parentname.empty()
1744 && theBufferList().exists(params().parentname)) {
1745 Buffer * buf = theBufferList().getBuffer(params().parentname);
1746 //We need to check if the parent is us...
1747 //FIXME RECURSIVE INCLUDE
1748 //This is not sufficient, since recursive includes could be downstream.
1749 if (buf && buf != this)
1750 return buf->getMasterBuffer();
1757 MacroData const & Buffer::getMacro(docstring const & name) const
1759 return pimpl_->macros.get(name);
1763 bool Buffer::hasMacro(docstring const & name) const
1765 return pimpl_->macros.has(name);
1769 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1771 MacroTable::globalMacros().insert(name, data);
1772 pimpl_->macros.insert(name, data);
1776 void Buffer::buildMacros()
1778 // Start with global table.
1779 pimpl_->macros = MacroTable::globalMacros();
1782 ParagraphList const & pars = text().paragraphs();
1783 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1784 //lyxerr << "searching main par " << i
1785 // << " for macro definitions" << std::endl;
1786 InsetList const & insets = pars[i].insetlist;
1787 InsetList::const_iterator it = insets.begin();
1788 InsetList::const_iterator end = insets.end();
1789 for ( ; it != end; ++it) {
1790 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1791 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1792 MathMacroTemplate const & mac
1793 = static_cast<MathMacroTemplate const &>(*it->inset);
1794 insertMacro(mac.name(), mac.asMacroData());
1801 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1804 //FIXME: This does not work for child documents yet.
1805 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1806 // Check if the label 'from' appears more than once
1807 vector<docstring> labels;
1809 if (code == Inset::CITE_CODE) {
1811 keys.fillWithBibKeys(this);
1812 BiblioInfo::const_iterator bit = keys.begin();
1813 BiblioInfo::const_iterator bend = keys.end();
1815 for (; bit != bend; ++bit)
1817 labels.push_back(bit->first);
1819 getLabelList(labels);
1821 if (std::count(labels.begin(), labels.end(), from) > 1)
1824 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1825 if (it->lyxCode() == code) {
1826 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1827 inset.replaceContents(to_utf8(from), to_utf8(to));
1833 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1834 pit_type par_end, bool full_source)
1836 OutputParams runparams(¶ms().encoding());
1837 runparams.nice = true;
1838 runparams.flavor = OutputParams::LATEX;
1839 runparams.linelen = lyxrc.plaintext_linelen;
1840 // No side effect of file copying and image conversion
1841 runparams.dryrun = true;
1845 os << "% " << _("Preview source code") << "\n\n";
1849 writeLaTeXSource(os, filePath(), runparams, true, true);
1851 writeDocBookSource(os, fileName(), runparams, false);
1854 runparams.par_begin = par_begin;
1855 runparams.par_end = par_end;
1856 if (par_begin + 1 == par_end)
1858 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1862 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1863 convert<docstring>(par_begin),
1864 convert<docstring>(par_end - 1))
1868 // output paragraphs
1870 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1873 docbookParagraphs(paragraphs(), *this, os, runparams);
1879 ErrorList const & Buffer::errorList(string const & type) const
1881 static ErrorList const emptyErrorList;
1882 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1883 if (I == pimpl_->errorLists.end())
1884 return emptyErrorList;
1890 ErrorList & Buffer::errorList(string const & type)
1892 return pimpl_->errorLists[type];