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"
71 #include "frontends/WorkAreaManager.h"
73 #include "graphics/Previews.h"
75 #include "support/types.h"
76 #include "support/lyxalgo.h"
77 #include "support/filetools.h"
78 #include "support/fs_extras.h"
79 #include "support/gzstream.h"
80 #include "support/lyxlib.h"
81 #include "support/os.h"
82 #include "support/Path.h"
83 #include "support/textutils.h"
84 #include "support/convert.h"
86 #include <boost/bind.hpp>
87 #include <boost/filesystem/exception.hpp>
88 #include <boost/filesystem/operations.hpp>
103 using std::ostringstream;
115 using support::addName;
116 using support::bformat;
117 using support::changeExtension;
118 using support::cmd_ret;
119 using support::createBufferTmpDir;
120 using support::destroyDir;
121 using support::FileName;
122 using support::getFormatFromContents;
123 using support::libFileSearch;
124 using support::latex_path;
125 using support::ltrim;
126 using support::makeAbsPath;
127 using support::makeDisplayPath;
128 using support::makeLatexName;
129 using support::onlyFilename;
130 using support::onlyPath;
131 using support::quoteName;
132 using support::removeAutosaveFile;
133 using support::rename;
134 using support::runCommand;
135 using support::split;
136 using support::subst;
137 using support::tempName;
140 using support::suffixIs;
142 namespace Alert = frontend::Alert;
143 namespace os = support::os;
144 namespace fs = boost::filesystem;
148 int const LYX_FORMAT = 288; //RGH, command insets
153 typedef std::map<string, bool> DepClean;
158 Impl(Buffer & parent, FileName const & file, bool readonly);
160 limited_stack<Undo> undostack;
161 limited_stack<Undo> redostack;
167 /// need to regenerate .tex?
171 mutable bool lyx_clean;
173 /// is autosave needed?
174 mutable bool bak_clean;
176 /// is this a unnamed file (New...)?
182 /// name of the file the buffer is associated with.
185 /** Set to true only when the file is fully loaded.
186 * Used to prevent the premature generation of previews
187 * and by the citation inset.
189 bool file_fully_loaded;
191 /// our Text that should be wrapped in an InsetText
198 TocBackend toc_backend;
200 /// Container for all sort of Buffer dependant errors.
201 map<string, ErrorList> errorLists;
203 /// all embedded files of this buffer
204 EmbeddedFiles embedded_files;
206 /// timestamp and checksum used to test if the file has been externally
207 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
209 unsigned long checksum_;
212 frontend::WorkAreaManager * wa_;
216 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
217 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
218 filename(file), file_fully_loaded(false), inset(params),
219 toc_backend(&parent), embedded_files(&parent), timestamp_(0),
222 inset.setAutoBreakRows(true);
223 lyxvc.buffer(&parent);
224 temppath = createBufferTmpDir();
225 params.filepath = onlyPath(file.absFilename());
226 // FIXME: And now do something if temppath == string(), because we
227 // assume from now on that temppath points to a valid temp dir.
228 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
231 wa_ = new frontend::WorkAreaManager;
235 Buffer::Buffer(string const & file, bool readonly)
236 : pimpl_(new Impl(*this, FileName(file), readonly))
238 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
244 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
245 // here the buffer should take care that it is
246 // saved properly, before it goes into the void.
248 Buffer * master = getMasterBuffer();
249 if (master != this && use_gui)
250 // We are closing buf which was a child document so we
251 // must update the labels and section numbering of its master
253 updateLabels(*master);
255 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
256 Alert::warning(_("Could not remove temporary directory"),
257 bformat(_("Could not remove the temporary directory %1$s"),
258 from_utf8(temppath())));
261 // Remove any previewed LaTeX snippets associated with this buffer.
262 graphics::Previews::get().removeLoader(*this);
265 pimpl_->wa_->closeAll();
271 void Buffer::changed()
274 pimpl_->wa_->redrawAll();
278 frontend::WorkAreaManager * Buffer::workAreaManager() const
283 Text & Buffer::text() const
285 return const_cast<Text &>(pimpl_->inset.text_);
289 Inset & Buffer::inset() const
291 return const_cast<InsetText &>(pimpl_->inset);
295 limited_stack<Undo> & Buffer::undostack()
297 return pimpl_->undostack;
301 limited_stack<Undo> const & Buffer::undostack() const
303 return pimpl_->undostack;
307 limited_stack<Undo> & Buffer::redostack()
309 return pimpl_->redostack;
313 limited_stack<Undo> const & Buffer::redostack() const
315 return pimpl_->redostack;
319 BufferParams & Buffer::params()
321 return pimpl_->params;
325 BufferParams const & Buffer::params() const
327 return pimpl_->params;
331 ParagraphList & Buffer::paragraphs()
333 return text().paragraphs();
337 ParagraphList const & Buffer::paragraphs() const
339 return text().paragraphs();
343 LyXVC & Buffer::lyxvc()
345 return pimpl_->lyxvc;
349 LyXVC const & Buffer::lyxvc() const
351 return pimpl_->lyxvc;
355 string const & Buffer::temppath() const
357 return pimpl_->temppath;
361 TexRow & Buffer::texrow()
363 return pimpl_->texrow;
367 TexRow const & Buffer::texrow() const
369 return pimpl_->texrow;
373 TocBackend & Buffer::tocBackend()
375 return pimpl_->toc_backend;
379 TocBackend const & Buffer::tocBackend() const
381 return pimpl_->toc_backend;
385 EmbeddedFiles & Buffer::embeddedFiles()
387 return pimpl_->embedded_files;
391 EmbeddedFiles const & Buffer::embeddedFiles() const
393 return pimpl_->embedded_files;
397 string const Buffer::getLatexName(bool const no_path) const
399 string const name = changeExtension(makeLatexName(fileName()), ".tex");
400 return no_path ? onlyFilename(name) : name;
404 pair<Buffer::LogType, string> const Buffer::getLogName() const
406 string const filename = getLatexName(false);
408 if (filename.empty())
409 return make_pair(Buffer::latexlog, string());
411 string const path = temppath();
413 FileName const fname(addName(temppath(),
414 onlyFilename(changeExtension(filename,
416 FileName const bname(
417 addName(path, onlyFilename(
418 changeExtension(filename,
419 formats.extension("literate") + ".out"))));
421 // If no Latex log or Build log is newer, show Build log
423 if (fs::exists(bname.toFilesystemEncoding()) &&
424 (!fs::exists(fname.toFilesystemEncoding()) ||
425 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
426 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
427 return make_pair(Buffer::buildlog, bname.absFilename());
429 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
430 return make_pair(Buffer::latexlog, fname.absFilename());
434 void Buffer::setReadonly(bool const flag)
436 if (pimpl_->read_only != flag) {
437 pimpl_->read_only = flag;
443 void Buffer::setFileName(string const & newfile)
445 pimpl_->filename = makeAbsPath(newfile);
446 params().filepath = onlyPath(pimpl_->filename.absFilename());
447 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
452 // We'll remove this later. (Lgb)
455 void unknownClass(string const & unknown)
457 Alert::warning(_("Unknown document class"),
458 bformat(_("Using the default document class, because the "
459 "class %1$s is unknown."), from_utf8(unknown)));
465 int Buffer::readHeader(Lexer & lex)
467 int unknown_tokens = 0;
469 int begin_header_line = -1;
471 // Initialize parameters that may be/go lacking in header:
472 params().branchlist().clear();
473 params().preamble.erase();
474 params().options.erase();
475 params().float_placement.erase();
476 params().paperwidth.erase();
477 params().paperheight.erase();
478 params().leftmargin.erase();
479 params().rightmargin.erase();
480 params().topmargin.erase();
481 params().bottommargin.erase();
482 params().headheight.erase();
483 params().headsep.erase();
484 params().footskip.erase();
485 params().listings_params.clear();
486 params().clearLayoutModules();
487 params().pdfoptions().clear();
489 for (int i = 0; i < 4; ++i) {
490 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
491 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
494 ErrorList & errorList = pimpl_->errorLists["Parse"];
498 string const token = lex.getString();
503 if (token == "\\end_header")
507 if (token == "\\begin_header") {
508 begin_header_line = line;
512 LYXERR(Debug::PARSER) << "Handling document header token: `"
513 << token << '\'' << endl;
515 string unknown = params().readToken(lex, token);
516 if (!unknown.empty()) {
517 if (unknown[0] != '\\' && token == "\\textclass") {
518 unknownClass(unknown);
521 docstring const s = bformat(_("Unknown token: "
525 errorList.push_back(ErrorItem(_("Document header error"),
530 if (begin_header_line) {
531 docstring const s = _("\\begin_header is missing");
532 errorList.push_back(ErrorItem(_("Document header error"),
536 return unknown_tokens;
541 // changed to be public and have one parameter
542 // Returns false if "\end_document" is not read (Asger)
543 bool Buffer::readDocument(Lexer & lex)
545 ErrorList & errorList = pimpl_->errorLists["Parse"];
549 string const token = lex.getString();
550 if (token != "\\begin_document") {
551 docstring const s = _("\\begin_document is missing");
552 errorList.push_back(ErrorItem(_("Document header error"),
556 // we are reading in a brand new document
557 BOOST_ASSERT(paragraphs().empty());
560 TextClass const & baseClass = textclasslist[params().getBaseClass()];
561 if (!baseClass.load(filePath())) {
562 string theclass = baseClass.name();
563 Alert::error(_("Can't load document class"), bformat(
564 _("Using the default document class, because the "
565 "class %1$s could not be loaded."), from_utf8(theclass)));
566 params().setBaseClass(defaultTextclass());
569 if (params().outputChanges) {
570 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
571 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
572 LaTeXFeatures::isAvailable("xcolor");
574 if (!dvipost && !xcolorsoul) {
575 Alert::warning(_("Changes not shown in LaTeX output"),
576 _("Changes will not be highlighted in LaTeX output, "
577 "because neither dvipost nor xcolor/soul are installed.\n"
578 "Please install these packages or redefine "
579 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
580 } else if (!xcolorsoul) {
581 Alert::warning(_("Changes not shown in LaTeX output"),
582 _("Changes will not be highlighted in LaTeX output "
583 "when using pdflatex, because xcolor and soul are not installed.\n"
584 "Please install both packages or redefine "
585 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
588 // read manifest after header
589 embeddedFiles().readManifest(lex, errorList);
592 bool const res = text().read(*this, lex, errorList);
593 for_each(text().paragraphs().begin(),
594 text().paragraphs().end(),
595 bind(&Paragraph::setInsetOwner, _1, &inset()));
601 // needed to insert the selection
602 void Buffer::insertStringAsLines(ParagraphList & pars,
603 pit_type & pit, pos_type & pos,
604 Font const & fn, docstring const & str, bool autobreakrows)
608 // insert the string, don't insert doublespace
609 bool space_inserted = true;
610 for (docstring::const_iterator cit = str.begin();
611 cit != str.end(); ++cit) {
612 Paragraph & par = pars[pit];
614 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
615 breakParagraph(params(), pars, pit, pos,
616 par.layout()->isEnvironment());
619 space_inserted = true;
623 // do not insert consecutive spaces if !free_spacing
624 } else if ((*cit == ' ' || *cit == '\t') &&
625 space_inserted && !par.isFreeSpacing()) {
627 } else if (*cit == '\t') {
628 if (!par.isFreeSpacing()) {
629 // tabs are like spaces here
630 par.insertChar(pos, ' ', font, params().trackChanges);
632 space_inserted = true;
634 const pos_type n = 8 - pos % 8;
635 for (pos_type i = 0; i < n; ++i) {
636 par.insertChar(pos, ' ', font, params().trackChanges);
639 space_inserted = true;
641 } else if (!isPrintable(*cit)) {
642 // Ignore unprintables
645 // just insert the character
646 par.insertChar(pos, *cit, font, params().trackChanges);
648 space_inserted = (*cit == ' ');
655 bool Buffer::readString(std::string const & s)
657 params().compressed = false;
659 // remove dummy empty par
660 paragraphs().clear();
662 std::istringstream is(s);
664 FileName const name(tempName());
665 switch (readFile(lex, name, true)) {
669 // We need to call lyx2lyx, so write the input to a file
670 std::ofstream os(name.toFilesystemEncoding().c_str());
673 return readFile(name);
683 bool Buffer::readFile(FileName const & filename)
685 FileName fname(filename);
686 // Check if the file is compressed.
687 string format = getFormatFromContents(filename);
688 if (format == "zip") {
689 // decompress to a temp directory
690 LYXERR(Debug::FILES) << filename << " is in zip format. Unzip to " << temppath() << endl;
691 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
693 FileName lyxfile(addName(temppath(), "content.lyx"));
694 // if both manifest.txt and file.lyx exist, this is am embedded file
695 if (fs::exists(lyxfile.toFilesystemEncoding())) {
696 params().embedded = true;
700 // The embedded lyx file can also be compressed, for backward compatibility
701 format = getFormatFromContents(fname);
702 if (format == "gzip" || format == "zip" || format == "compress") {
703 params().compressed = true;
706 // remove dummy empty par
707 paragraphs().clear();
710 if (readFile(lex, fname) != success)
717 bool Buffer::fully_loaded() const
719 return pimpl_->file_fully_loaded;
723 void Buffer::fully_loaded(bool const value)
725 pimpl_->file_fully_loaded = value;
729 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
732 BOOST_ASSERT(!filename.empty());
735 Alert::error(_("Document could not be read"),
736 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
741 string const token(lex.getString());
744 Alert::error(_("Document could not be read"),
745 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
749 // the first token _must_ be...
750 if (token != "\\lyxformat") {
751 lyxerr << "Token: " << token << endl;
753 Alert::error(_("Document format failure"),
754 bformat(_("%1$s is not a LyX document."),
755 from_utf8(filename.absFilename())));
760 string tmp_format = lex.getString();
761 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
762 // if present remove ".," from string.
763 string::size_type dot = tmp_format.find_first_of(".,");
764 //lyxerr << " dot found at " << dot << endl;
765 if (dot != string::npos)
766 tmp_format.erase(dot, 1);
767 int const file_format = convert<int>(tmp_format);
768 //lyxerr << "format: " << file_format << endl;
770 // save timestamp and checksum of the original disk file, making sure
771 // to not overwrite them with those of the file created in the tempdir
772 // when it has to be converted to the current format.
773 if (!pimpl_->checksum_) {
774 // Save the timestamp and checksum of disk file. If filename is an
775 // emergency file, save the timestamp and sum of the original lyx file
776 // because isExternallyModified will check for this file. (BUG4193)
777 string diskfile = filename.toFilesystemEncoding();
778 if (suffixIs(diskfile, ".emergency"))
779 diskfile = diskfile.substr(0, diskfile.size() - 10);
780 saveCheckSum(diskfile);
783 if (file_format != LYX_FORMAT) {
786 // lyx2lyx would fail
789 FileName const tmpfile(tempName());
790 if (tmpfile.empty()) {
791 Alert::error(_("Conversion failed"),
792 bformat(_("%1$s is from a different"
793 " version of LyX, but a temporary"
794 " file for converting it could"
796 from_utf8(filename.absFilename())));
799 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
800 if (lyx2lyx.empty()) {
801 Alert::error(_("Conversion script not found"),
802 bformat(_("%1$s is from a different"
803 " version of LyX, but the"
804 " conversion script lyx2lyx"
805 " could not be found."),
806 from_utf8(filename.absFilename())));
809 ostringstream command;
810 command << os::python()
811 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
812 << " -t " << convert<string>(LYX_FORMAT)
813 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
814 << ' ' << quoteName(filename.toFilesystemEncoding());
815 string const command_str = command.str();
817 LYXERR(Debug::INFO) << "Running '"
818 << command_str << '\''
821 cmd_ret const ret = runCommand(command_str);
822 if (ret.first != 0) {
823 Alert::error(_("Conversion script failed"),
824 bformat(_("%1$s is from a different version"
825 " of LyX, but the lyx2lyx script"
826 " failed to convert it."),
827 from_utf8(filename.absFilename())));
830 bool const ret = readFile(tmpfile);
831 // Do stuff with tmpfile name and buffer name here.
832 return ret ? success : failure;
837 if (readDocument(lex)) {
838 Alert::error(_("Document format failure"),
839 bformat(_("%1$s ended unexpectedly, which means"
840 " that it is probably corrupted."),
841 from_utf8(filename.absFilename())));
844 //lyxerr << "removing " << MacroTable::localMacros().size()
845 // << " temporary macro entries" << endl;
846 //MacroTable::localMacros().clear();
848 pimpl_->file_fully_loaded = true;
853 // Should probably be moved to somewhere else: BufferView? LyXView?
854 bool Buffer::save() const
856 // We don't need autosaves in the immediate future. (Asger)
857 resetAutosaveTimers();
859 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
862 bool madeBackup = false;
864 // make a backup if the file already exists
865 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
866 backupName = FileName(fileName() + '~');
867 if (!lyxrc.backupdir_path.empty())
868 backupName = FileName(addName(lyxrc.backupdir_path,
869 subst(os::internal_path(backupName.absFilename()), '/', '!')));
872 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
874 } catch (fs::filesystem_error const & fe) {
875 Alert::error(_("Backup failure"),
876 bformat(_("Cannot create backup file %1$s.\n"
877 "Please check whether the directory exists and is writeable."),
878 from_utf8(backupName.absFilename())));
879 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
883 // ask if the disk file has been externally modified (use checksum method)
884 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
885 docstring const file = makeDisplayPath(fileName(), 20);
886 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
887 "you want to overwrite this file?"), file);
888 int const ret = Alert::prompt(_("Overwrite modified file?"),
889 text, 1, 1, _("&Overwrite"), _("&Cancel"));
894 if (writeFile(pimpl_->filename)) {
896 removeAutosaveFile(fileName());
897 saveCheckSum(pimpl_->filename.toFilesystemEncoding());
900 // Saving failed, so backup is not backup
902 rename(backupName, pimpl_->filename);
908 bool Buffer::writeFile(FileName const & fname) const
910 if (pimpl_->read_only && fname == pimpl_->filename)
916 if (params().embedded)
917 // first write the .lyx file to the temporary directory
918 content = FileName(addName(temppath(), "content.lyx"));
922 if (params().compressed) {
923 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
929 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
936 if (retval && params().embedded) {
937 // write file.lyx and all the embedded files to the zip file fname
938 // if embedding is enabled
939 return pimpl_->embedded_files.writeFile(fname);
945 bool Buffer::write(ostream & ofs) const
948 // Use the standard "C" locale for file output.
949 ofs.imbue(std::locale::classic());
952 // The top of the file should not be written by params().
954 // write out a comment in the top of the file
955 ofs << "#LyX " << lyx_version
956 << " created this file. For more info see http://www.lyx.org/\n"
957 << "\\lyxformat " << LYX_FORMAT << "\n"
958 << "\\begin_document\n";
961 /// For each author, set 'used' to true if there is a change
962 /// by this author in the document; otherwise set it to 'false'.
963 AuthorList::Authors::const_iterator a_it = params().authors().begin();
964 AuthorList::Authors::const_iterator a_end = params().authors().end();
965 for (; a_it != a_end; ++a_it)
966 a_it->second.used(false);
968 ParIterator const end = par_iterator_end();
969 ParIterator it = par_iterator_begin();
970 for ( ; it != end; ++it)
971 it->checkAuthors(params().authors());
973 // now write out the buffer parameters.
974 ofs << "\\begin_header\n";
975 params().writeFile(ofs);
976 ofs << "\\end_header\n";
978 // write the manifest after header
979 ofs << "\n\\begin_manifest\n";
980 pimpl_->embedded_files.update();
981 embeddedFiles().writeManifest(ofs);
982 ofs << "\\end_manifest\n";
985 ofs << "\n\\begin_body\n";
986 text().write(*this, ofs);
987 ofs << "\n\\end_body\n";
989 // Write marker that shows file is complete
990 ofs << "\\end_document" << endl;
992 // Shouldn't really be needed....
995 // how to check if close went ok?
996 // Following is an attempt... (BE 20001011)
998 // good() returns false if any error occured, including some
1000 // bad() returns true if something bad happened in the buffer,
1001 // which should include file system full errors.
1006 lyxerr << "File was not closed properly." << endl;
1013 bool Buffer::makeLaTeXFile(FileName const & fname,
1014 string const & original_path,
1015 OutputParams const & runparams,
1016 bool output_preamble, bool output_body)
1018 string const encoding = runparams.encoding->iconvName();
1019 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
1020 << encoding << "..." << endl;
1022 odocfstream ofs(encoding);
1023 if (!openFileWrite(ofs, fname))
1026 //TexStream ts(ofs.rdbuf(), &texrow());
1028 bool failed_export = false;
1031 writeLaTeXSource(ofs, original_path,
1032 runparams, output_preamble, output_body);
1034 catch (iconv_codecvt_facet_exception & e) {
1035 lyxerr << "Caught iconv exception: " << e.what() << endl;
1036 failed_export = true;
1038 catch (std::exception const & e) {
1039 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1040 failed_export = true;
1043 lyxerr << "Caught some really weird exception..." << endl;
1044 LyX::cref().emergencyCleanup();
1050 failed_export = true;
1051 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1054 if (failed_export) {
1055 Alert::error(_("Encoding error"),
1056 _("Some characters of your document are probably not "
1057 "representable in the chosen encoding.\n"
1058 "Changing the document encoding to utf8 could help."));
1065 void Buffer::writeLaTeXSource(odocstream & os,
1066 string const & original_path,
1067 OutputParams const & runparams_in,
1068 bool const output_preamble, bool const output_body)
1070 OutputParams runparams = runparams_in;
1072 // validate the buffer.
1073 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
1074 LaTeXFeatures features(*this, params(), runparams);
1076 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
1078 // The starting paragraph of the coming rows is the
1079 // first paragraph of the document. (Asger)
1080 if (output_preamble && runparams.nice) {
1081 os << "%% LyX " << lyx_version << " created this file. "
1082 "For more info, see http://www.lyx.org/.\n"
1083 "%% Do not edit unless you really know what "
1088 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1089 // There are a few differences between nice LaTeX and usual files:
1090 // usual is \batchmode and has a
1091 // special input@path to allow the including of figures
1092 // with either \input or \includegraphics (what figinsets do).
1093 // input@path is set when the actual parameter
1094 // original_path is set. This is done for usual tex-file, but not
1095 // for nice-latex-file. (Matthias 250696)
1096 // Note that input@path is only needed for something the user does
1097 // in the preamble, included .tex files or ERT, files included by
1098 // LyX work without it.
1099 if (output_preamble) {
1100 if (!runparams.nice) {
1101 // code for usual, NOT nice-latex-file
1102 os << "\\batchmode\n"; // changed
1103 // from \nonstopmode
1106 if (!original_path.empty()) {
1108 // We don't know the encoding of inputpath
1109 docstring const inputpath = from_utf8(latex_path(original_path));
1110 os << "\\makeatletter\n"
1111 << "\\def\\input@path{{"
1112 << inputpath << "/}}\n"
1113 << "\\makeatother\n";
1119 // Write the preamble
1120 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1126 os << "\\begin{document}\n";
1128 } // output_preamble
1130 texrow().start(paragraphs().begin()->id(), 0);
1132 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1134 if (!lyxrc.language_auto_begin &&
1135 !params().language->babel().empty()) {
1137 os << from_utf8(subst(lyxrc.language_command_begin,
1139 params().language->babel()))
1144 Encoding const & encoding = params().encoding();
1145 if (encoding.package() == Encoding::CJK) {
1146 // Open a CJK environment, since in contrast to the encodings
1147 // handled by inputenc the document encoding is not set in
1148 // the preamble if it is handled by CJK.sty.
1149 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1154 // if we are doing a real file with body, even if this is the
1155 // child of some other buffer, let's cut the link here.
1156 // This happens for example if only a child document is printed.
1157 string save_parentname;
1158 if (output_preamble) {
1159 save_parentname = params().parentname;
1160 params().parentname.erase();
1163 loadChildDocuments(*this);
1166 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1168 // Restore the parenthood if needed
1169 if (output_preamble)
1170 params().parentname = save_parentname;
1172 // add this just in case after all the paragraphs
1176 if (encoding.package() == Encoding::CJK) {
1177 // Close the open CJK environment.
1178 // latexParagraphs will have opened one even if the last text
1180 os << "\\end{CJK}\n";
1184 if (!lyxrc.language_auto_end &&
1185 !params().language->babel().empty()) {
1186 os << from_utf8(subst(lyxrc.language_command_end,
1188 params().language->babel()))
1193 if (output_preamble) {
1194 os << "\\end{document}\n";
1197 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1199 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1202 runparams_in.encoding = runparams.encoding;
1204 // Just to be sure. (Asger)
1207 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1208 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1213 bool Buffer::isLatex() const
1215 return params().getTextClass().outputType() == LATEX;
1219 bool Buffer::isLiterate() const
1221 return params().getTextClass().outputType() == LITERATE;
1225 bool Buffer::isDocBook() const
1227 return params().getTextClass().outputType() == DOCBOOK;
1231 void Buffer::makeDocBookFile(FileName const & fname,
1232 OutputParams const & runparams,
1233 bool const body_only)
1235 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1239 if (!openFileWrite(ofs, fname))
1242 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1246 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1250 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1251 OutputParams const & runparams,
1252 bool const only_body)
1254 LaTeXFeatures features(*this, params(), runparams);
1259 TextClass const & tclass = params().getTextClass();
1260 string const top_element = tclass.latexname();
1263 if (runparams.flavor == OutputParams::XML)
1264 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1267 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1270 if (! tclass.class_header().empty())
1271 os << from_ascii(tclass.class_header());
1272 else if (runparams.flavor == OutputParams::XML)
1273 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1274 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1276 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1278 docstring preamble = from_utf8(params().preamble);
1279 if (runparams.flavor != OutputParams::XML ) {
1280 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1281 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1282 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1283 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1286 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1288 preamble += features.getIncludedFiles(name);
1289 preamble += features.getLyXSGMLEntities();
1291 if (!preamble.empty()) {
1292 os << "\n [ " << preamble << " ]";
1297 string top = top_element;
1299 if (runparams.flavor == OutputParams::XML)
1300 top += params().language->code();
1302 top += params().language->code().substr(0,2);
1305 if (!params().options.empty()) {
1307 top += params().options;
1310 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1311 << " file was created by LyX " << lyx_version
1312 << "\n See http://www.lyx.org/ for more information -->\n";
1314 params().getTextClass().counters().reset();
1316 loadChildDocuments(*this);
1318 sgml::openTag(os, top);
1320 docbookParagraphs(paragraphs(), *this, os, runparams);
1321 sgml::closeTag(os, top_element);
1325 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1326 // Other flags: -wall -v0 -x
1327 int Buffer::runChktex()
1331 // get LaTeX-Filename
1332 FileName const path(temppath());
1333 string const name = addName(path.absFilename(), getLatexName());
1334 string const org_path = filePath();
1336 support::Path p(path); // path to LaTeX file
1337 message(_("Running chktex..."));
1339 // Generate the LaTeX file if neccessary
1340 OutputParams runparams(¶ms().encoding());
1341 runparams.flavor = OutputParams::LATEX;
1342 runparams.nice = false;
1343 makeLaTeXFile(FileName(name), org_path, runparams);
1346 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1347 int const res = chktex.run(terr); // run chktex
1350 Alert::error(_("chktex failure"),
1351 _("Could not run chktex successfully."));
1352 } else if (res > 0) {
1353 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1354 // Clear out old errors
1356 // Fill-in the error list with the TeX errors
1357 bufferErrors(*this, terr, errorList);
1368 void Buffer::validate(LaTeXFeatures & features) const
1370 TextClass const & tclass = params().getTextClass();
1372 if (params().outputChanges) {
1373 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1374 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1375 LaTeXFeatures::isAvailable("xcolor");
1377 if (features.runparams().flavor == OutputParams::LATEX) {
1379 features.require("ct-dvipost");
1380 features.require("dvipost");
1381 } else if (xcolorsoul) {
1382 features.require("ct-xcolor-soul");
1383 features.require("soul");
1384 features.require("xcolor");
1386 features.require("ct-none");
1388 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1390 features.require("ct-xcolor-soul");
1391 features.require("soul");
1392 features.require("xcolor");
1393 features.require("pdfcolmk"); // improves color handling in PDF output
1395 features.require("ct-none");
1400 // AMS Style is at document level
1401 if (params().use_amsmath == BufferParams::package_on
1402 || tclass.provides("amsmath"))
1403 features.require("amsmath");
1404 if (params().use_esint == BufferParams::package_on)
1405 features.require("esint");
1407 loadChildDocuments(*this);
1409 for_each(paragraphs().begin(), paragraphs().end(),
1410 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1412 // the bullet shapes are buffer level not paragraph level
1413 // so they are tested here
1414 for (int i = 0; i < 4; ++i) {
1415 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1416 int const font = params().user_defined_bullet(i).getFont();
1418 int const c = params()
1419 .user_defined_bullet(i)
1426 features.require("latexsym");
1428 } else if (font == 1) {
1429 features.require("amssymb");
1430 } else if ((font >= 2 && font <= 5)) {
1431 features.require("pifont");
1436 if (lyxerr.debugging(Debug::LATEX)) {
1437 features.showStruct();
1442 void Buffer::getLabelList(vector<docstring> & list) const
1444 /// if this is a child document and the parent is already loaded
1445 /// Use the parent's list instead [ale990407]
1446 Buffer const * tmp = getMasterBuffer();
1448 lyxerr << "getMasterBuffer() failed!" << endl;
1452 tmp->getLabelList(list);
1456 loadChildDocuments(*this);
1458 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1459 it.nextInset()->getLabelList(*this, list);
1463 void Buffer::updateBibfilesCache()
1465 // if this is a child document and the parent is already loaded
1466 // update the parent's cache instead
1467 Buffer * tmp = getMasterBuffer();
1470 tmp->updateBibfilesCache();
1474 bibfilesCache_.clear();
1475 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1476 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1477 InsetBibtex const & inset =
1478 static_cast<InsetBibtex const &>(*it);
1479 vector<FileName> const bibfiles = inset.getFiles(*this);
1480 bibfilesCache_.insert(bibfilesCache_.end(),
1483 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1484 InsetInclude & inset =
1485 static_cast<InsetInclude &>(*it);
1486 inset.updateBibfilesCache(*this);
1487 vector<FileName> const & bibfiles =
1488 inset.getBibfilesCache(*this);
1489 bibfilesCache_.insert(bibfilesCache_.end(),
1497 vector<FileName> const & Buffer::getBibfilesCache() const
1499 // if this is a child document and the parent is already loaded
1500 // use the parent's cache instead
1501 Buffer const * tmp = getMasterBuffer();
1504 return tmp->getBibfilesCache();
1506 // We update the cache when first used instead of at loading time.
1507 if (bibfilesCache_.empty())
1508 const_cast<Buffer *>(this)->updateBibfilesCache();
1510 return bibfilesCache_;
1514 bool Buffer::isDepClean(string const & name) const
1516 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1517 if (it == pimpl_->dep_clean.end())
1523 void Buffer::markDepClean(string const & name)
1525 pimpl_->dep_clean[name] = true;
1529 bool Buffer::dispatch(string const & command, bool * result)
1531 return dispatch(lyxaction.lookupFunc(command), result);
1535 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1537 bool dispatched = true;
1539 switch (func.action) {
1540 case LFUN_BUFFER_EXPORT: {
1541 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1554 void Buffer::changeLanguage(Language const * from, Language const * to)
1559 for_each(par_iterator_begin(),
1561 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1565 bool Buffer::isMultiLingual() const
1567 ParConstIterator end = par_iterator_end();
1568 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1569 if (it->isMultiLingual(params()))
1576 ParIterator Buffer::getParFromID(int const id) const
1578 ParConstIterator it = par_iterator_begin();
1579 ParConstIterator const end = par_iterator_end();
1582 // John says this is called with id == -1 from undo
1583 lyxerr << "getParFromID(), id: " << id << endl;
1587 for (; it != end; ++it)
1595 bool Buffer::hasParWithID(int const id) const
1597 ParConstIterator const it = getParFromID(id);
1598 return it != par_iterator_end();
1602 ParIterator Buffer::par_iterator_begin()
1604 return lyx::par_iterator_begin(inset());
1608 ParIterator Buffer::par_iterator_end()
1610 return lyx::par_iterator_end(inset());
1614 ParConstIterator Buffer::par_iterator_begin() const
1616 return lyx::par_const_iterator_begin(inset());
1620 ParConstIterator Buffer::par_iterator_end() const
1622 return lyx::par_const_iterator_end(inset());
1626 Language const * Buffer::getLanguage() const
1628 return params().language;
1632 docstring const Buffer::B_(string const & l10n) const
1634 return params().B_(l10n);
1638 bool Buffer::isClean() const
1640 return pimpl_->lyx_clean;
1644 bool Buffer::isBakClean() const
1646 return pimpl_->bak_clean;
1650 bool Buffer::isExternallyModified(CheckMethod method) const
1652 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1653 // if method == timestamp, check timestamp before checksum
1654 return (method == checksum_method
1655 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1656 && pimpl_->checksum_ != sum(pimpl_->filename);
1660 void Buffer::saveCheckSum(string const & file) const
1662 if (fs::exists(file)) {
1663 pimpl_->timestamp_ = fs::last_write_time(file);
1664 pimpl_->checksum_ = sum(FileName(file));
1666 // in the case of save to a new file.
1667 pimpl_->timestamp_ = 0;
1668 pimpl_->checksum_ = 0;
1673 void Buffer::markClean() const
1675 if (!pimpl_->lyx_clean) {
1676 pimpl_->lyx_clean = true;
1679 // if the .lyx file has been saved, we don't need an
1681 pimpl_->bak_clean = true;
1685 void Buffer::markBakClean()
1687 pimpl_->bak_clean = true;
1691 void Buffer::setUnnamed(bool flag)
1693 pimpl_->unnamed = flag;
1697 bool Buffer::isUnnamed() const
1699 return pimpl_->unnamed;
1703 // FIXME: this function should be moved to buffer_pimpl.C
1704 void Buffer::markDirty()
1706 if (pimpl_->lyx_clean) {
1707 pimpl_->lyx_clean = false;
1710 pimpl_->bak_clean = false;
1712 DepClean::iterator it = pimpl_->dep_clean.begin();
1713 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1715 for (; it != end; ++it)
1720 string const Buffer::fileName() const
1722 return pimpl_->filename.absFilename();
1726 string const & Buffer::filePath() const
1728 return params().filepath;
1732 bool Buffer::isReadonly() const
1734 return pimpl_->read_only;
1738 void Buffer::setParentName(string const & name)
1740 if (name == pimpl_->filename.absFilename())
1741 // Avoids recursive include.
1742 params().parentname.clear();
1744 params().parentname = name;
1748 Buffer const * Buffer::getMasterBuffer() const
1750 if (!params().parentname.empty()
1751 && theBufferList().exists(params().parentname)) {
1752 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1753 //We need to check if the parent is us...
1754 //FIXME RECURSIVE INCLUDE
1755 //This is not sufficient, since recursive includes could be downstream.
1756 if (buf && buf != this)
1757 return buf->getMasterBuffer();
1764 Buffer * Buffer::getMasterBuffer()
1766 if (!params().parentname.empty()
1767 && theBufferList().exists(params().parentname)) {
1768 Buffer * buf = theBufferList().getBuffer(params().parentname);
1769 //We need to check if the parent is us...
1770 //FIXME RECURSIVE INCLUDE
1771 //This is not sufficient, since recursive includes could be downstream.
1772 if (buf && buf != this)
1773 return buf->getMasterBuffer();
1780 MacroData const & Buffer::getMacro(docstring const & name) const
1782 return pimpl_->macros.get(name);
1786 bool Buffer::hasMacro(docstring const & name) const
1788 return pimpl_->macros.has(name);
1792 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1794 MacroTable::globalMacros().insert(name, data);
1795 pimpl_->macros.insert(name, data);
1799 void Buffer::buildMacros()
1801 // Start with global table.
1802 pimpl_->macros = MacroTable::globalMacros();
1805 ParagraphList const & pars = text().paragraphs();
1806 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1807 //lyxerr << "searching main par " << i
1808 // << " for macro definitions" << std::endl;
1809 InsetList const & insets = pars[i].insetlist;
1810 InsetList::const_iterator it = insets.begin();
1811 InsetList::const_iterator end = insets.end();
1812 for ( ; it != end; ++it) {
1813 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1814 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1815 MathMacroTemplate const & mac
1816 = static_cast<MathMacroTemplate const &>(*it->inset);
1817 insertMacro(mac.name(), mac.asMacroData());
1824 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1827 //FIXME: This does not work for child documents yet.
1828 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1829 // Check if the label 'from' appears more than once
1830 vector<docstring> labels;
1832 if (code == Inset::CITE_CODE) {
1834 keys.fillWithBibKeys(this);
1835 BiblioInfo::const_iterator bit = keys.begin();
1836 BiblioInfo::const_iterator bend = keys.end();
1838 for (; bit != bend; ++bit)
1840 labels.push_back(bit->first);
1842 getLabelList(labels);
1844 if (std::count(labels.begin(), labels.end(), from) > 1)
1847 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1848 if (it->lyxCode() == code) {
1849 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1850 inset.replaceContents(to_utf8(from), to_utf8(to));
1856 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1857 pit_type par_end, bool full_source)
1859 OutputParams runparams(¶ms().encoding());
1860 runparams.nice = true;
1861 runparams.flavor = OutputParams::LATEX;
1862 runparams.linelen = lyxrc.plaintext_linelen;
1863 // No side effect of file copying and image conversion
1864 runparams.dryrun = true;
1868 os << "% " << _("Preview source code") << "\n\n";
1872 writeLaTeXSource(os, filePath(), runparams, true, true);
1874 writeDocBookSource(os, fileName(), runparams, false);
1877 runparams.par_begin = par_begin;
1878 runparams.par_end = par_end;
1879 if (par_begin + 1 == par_end)
1881 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1885 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1886 convert<docstring>(par_begin),
1887 convert<docstring>(par_end - 1))
1891 // output paragraphs
1893 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1896 docbookParagraphs(paragraphs(), *this, os, runparams);
1902 ErrorList const & Buffer::errorList(string const & type) const
1904 static ErrorList const emptyErrorList;
1905 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1906 if (I == pimpl_->errorLists.end())
1907 return emptyErrorList;
1913 ErrorList & Buffer::errorList(string const & type)
1915 return pimpl_->errorLists[type];