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();
272 void Buffer::changed()
275 pimpl_->wa_->redrawAll();
279 frontend::WorkAreaManager * Buffer::workAreaManager() const
284 Text & Buffer::text() const
286 return const_cast<Text &>(pimpl_->inset.text_);
290 Inset & Buffer::inset() const
292 return const_cast<InsetText &>(pimpl_->inset);
296 limited_stack<Undo> & Buffer::undostack()
298 return pimpl_->undostack;
302 limited_stack<Undo> const & Buffer::undostack() const
304 return pimpl_->undostack;
308 limited_stack<Undo> & Buffer::redostack()
310 return pimpl_->redostack;
314 limited_stack<Undo> const & Buffer::redostack() const
316 return pimpl_->redostack;
320 BufferParams & Buffer::params()
322 return pimpl_->params;
326 BufferParams const & Buffer::params() const
328 return pimpl_->params;
332 ParagraphList & Buffer::paragraphs()
334 return text().paragraphs();
338 ParagraphList const & Buffer::paragraphs() const
340 return text().paragraphs();
344 LyXVC & Buffer::lyxvc()
346 return pimpl_->lyxvc;
350 LyXVC const & Buffer::lyxvc() const
352 return pimpl_->lyxvc;
356 string const & Buffer::temppath() const
358 return pimpl_->temppath;
362 TexRow & Buffer::texrow()
364 return pimpl_->texrow;
368 TexRow const & Buffer::texrow() const
370 return pimpl_->texrow;
374 TocBackend & Buffer::tocBackend()
376 return pimpl_->toc_backend;
380 TocBackend const & Buffer::tocBackend() const
382 return pimpl_->toc_backend;
386 EmbeddedFiles & Buffer::embeddedFiles()
388 return pimpl_->embedded_files;
392 EmbeddedFiles const & Buffer::embeddedFiles() const
394 return pimpl_->embedded_files;
398 string const Buffer::getLatexName(bool const no_path) const
400 string const name = changeExtension(makeLatexName(fileName()), ".tex");
401 return no_path ? onlyFilename(name) : name;
405 pair<Buffer::LogType, string> const Buffer::getLogName() const
407 string const filename = getLatexName(false);
409 if (filename.empty())
410 return make_pair(Buffer::latexlog, string());
412 string const path = temppath();
414 FileName const fname(addName(temppath(),
415 onlyFilename(changeExtension(filename,
417 FileName const bname(
418 addName(path, onlyFilename(
419 changeExtension(filename,
420 formats.extension("literate") + ".out"))));
422 // If no Latex log or Build log is newer, show Build log
424 if (fs::exists(bname.toFilesystemEncoding()) &&
425 (!fs::exists(fname.toFilesystemEncoding()) ||
426 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
427 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
428 return make_pair(Buffer::buildlog, bname.absFilename());
430 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
431 return make_pair(Buffer::latexlog, fname.absFilename());
435 void Buffer::setReadonly(bool const flag)
437 if (pimpl_->read_only != flag) {
438 pimpl_->read_only = flag;
444 void Buffer::setFileName(string const & newfile)
446 pimpl_->filename = makeAbsPath(newfile);
447 params().filepath = onlyPath(pimpl_->filename.absFilename());
448 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
453 // We'll remove this later. (Lgb)
456 void unknownClass(string const & unknown)
458 Alert::warning(_("Unknown document class"),
459 bformat(_("Using the default document class, because the "
460 "class %1$s is unknown."), from_utf8(unknown)));
466 int Buffer::readHeader(Lexer & lex)
468 int unknown_tokens = 0;
470 int begin_header_line = -1;
472 // Initialize parameters that may be/go lacking in header:
473 params().branchlist().clear();
474 params().preamble.erase();
475 params().options.erase();
476 params().float_placement.erase();
477 params().paperwidth.erase();
478 params().paperheight.erase();
479 params().leftmargin.erase();
480 params().rightmargin.erase();
481 params().topmargin.erase();
482 params().bottommargin.erase();
483 params().headheight.erase();
484 params().headsep.erase();
485 params().footskip.erase();
486 params().listings_params.clear();
487 params().clearLayoutModules();
488 params().pdfoptions().clear();
490 for (int i = 0; i < 4; ++i) {
491 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
492 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
495 ErrorList & errorList = pimpl_->errorLists["Parse"];
499 string const token = lex.getString();
504 if (token == "\\end_header")
508 if (token == "\\begin_header") {
509 begin_header_line = line;
513 LYXERR(Debug::PARSER) << "Handling document header token: `"
514 << token << '\'' << endl;
516 string unknown = params().readToken(lex, token);
517 if (!unknown.empty()) {
518 if (unknown[0] != '\\' && token == "\\textclass") {
519 unknownClass(unknown);
522 docstring const s = bformat(_("Unknown token: "
526 errorList.push_back(ErrorItem(_("Document header error"),
531 if (begin_header_line) {
532 docstring const s = _("\\begin_header is missing");
533 errorList.push_back(ErrorItem(_("Document header error"),
537 return unknown_tokens;
542 // changed to be public and have one parameter
543 // Returns false if "\end_document" is not read (Asger)
544 bool Buffer::readDocument(Lexer & lex)
546 ErrorList & errorList = pimpl_->errorLists["Parse"];
550 string const token = lex.getString();
551 if (token != "\\begin_document") {
552 docstring const s = _("\\begin_document is missing");
553 errorList.push_back(ErrorItem(_("Document header error"),
557 // we are reading in a brand new document
558 BOOST_ASSERT(paragraphs().empty());
561 TextClass const & baseClass = textclasslist[params().getBaseClass()];
562 if (!baseClass.load(filePath())) {
563 string theclass = baseClass.name();
564 Alert::error(_("Can't load document class"), bformat(
565 _("Using the default document class, because the "
566 "class %1$s could not be loaded."), from_utf8(theclass)));
567 params().setBaseClass(defaultTextclass());
570 if (params().outputChanges) {
571 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
572 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
573 LaTeXFeatures::isAvailable("xcolor");
575 if (!dvipost && !xcolorsoul) {
576 Alert::warning(_("Changes not shown in LaTeX output"),
577 _("Changes will not be highlighted in LaTeX output, "
578 "because neither dvipost nor xcolor/soul are installed.\n"
579 "Please install these packages or redefine "
580 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
581 } else if (!xcolorsoul) {
582 Alert::warning(_("Changes not shown in LaTeX output"),
583 _("Changes will not be highlighted in LaTeX output "
584 "when using pdflatex, because xcolor and soul are not installed.\n"
585 "Please install both packages or redefine "
586 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
589 // read manifest after header
590 embeddedFiles().readManifest(lex, errorList);
593 bool const res = text().read(*this, lex, errorList);
594 for_each(text().paragraphs().begin(),
595 text().paragraphs().end(),
596 bind(&Paragraph::setInsetOwner, _1, &inset()));
602 // needed to insert the selection
603 void Buffer::insertStringAsLines(ParagraphList & pars,
604 pit_type & pit, pos_type & pos,
605 Font const & fn, docstring const & str, bool autobreakrows)
609 // insert the string, don't insert doublespace
610 bool space_inserted = true;
611 for (docstring::const_iterator cit = str.begin();
612 cit != str.end(); ++cit) {
613 Paragraph & par = pars[pit];
615 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
616 breakParagraph(params(), pars, pit, pos,
617 par.layout()->isEnvironment());
620 space_inserted = true;
624 // do not insert consecutive spaces if !free_spacing
625 } else if ((*cit == ' ' || *cit == '\t') &&
626 space_inserted && !par.isFreeSpacing()) {
628 } else if (*cit == '\t') {
629 if (!par.isFreeSpacing()) {
630 // tabs are like spaces here
631 par.insertChar(pos, ' ', font, params().trackChanges);
633 space_inserted = true;
635 const pos_type n = 8 - pos % 8;
636 for (pos_type i = 0; i < n; ++i) {
637 par.insertChar(pos, ' ', font, params().trackChanges);
640 space_inserted = true;
642 } else if (!isPrintable(*cit)) {
643 // Ignore unprintables
646 // just insert the character
647 par.insertChar(pos, *cit, font, params().trackChanges);
649 space_inserted = (*cit == ' ');
656 bool Buffer::readString(std::string const & s)
658 params().compressed = false;
660 // remove dummy empty par
661 paragraphs().clear();
663 std::istringstream is(s);
665 FileName const name(tempName());
666 switch (readFile(lex, name, true)) {
670 // We need to call lyx2lyx, so write the input to a file
671 std::ofstream os(name.toFilesystemEncoding().c_str());
674 return readFile(name);
684 bool Buffer::readFile(FileName const & filename)
686 FileName fname(filename);
687 // Check if the file is compressed.
688 string format = getFormatFromContents(filename);
689 if (format == "zip") {
690 // decompress to a temp directory
691 LYXERR(Debug::FILES) << filename << " is in zip format. Unzip to " << temppath() << endl;
692 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
694 FileName lyxfile(addName(temppath(), "content.lyx"));
695 // if both manifest.txt and file.lyx exist, this is am embedded file
696 if (fs::exists(lyxfile.toFilesystemEncoding())) {
697 params().embedded = true;
701 // The embedded lyx file can also be compressed, for backward compatibility
702 format = getFormatFromContents(fname);
703 if (format == "gzip" || format == "zip" || format == "compress") {
704 params().compressed = true;
707 // remove dummy empty par
708 paragraphs().clear();
711 if (readFile(lex, fname) != success)
718 bool Buffer::fully_loaded() const
720 return pimpl_->file_fully_loaded;
724 void Buffer::fully_loaded(bool const value)
726 pimpl_->file_fully_loaded = value;
730 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
733 BOOST_ASSERT(!filename.empty());
736 Alert::error(_("Document could not be read"),
737 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
742 string const token(lex.getString());
745 Alert::error(_("Document could not be read"),
746 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
750 // the first token _must_ be...
751 if (token != "\\lyxformat") {
752 lyxerr << "Token: " << token << endl;
754 Alert::error(_("Document format failure"),
755 bformat(_("%1$s is not a LyX document."),
756 from_utf8(filename.absFilename())));
761 string tmp_format = lex.getString();
762 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
763 // if present remove ".," from string.
764 string::size_type dot = tmp_format.find_first_of(".,");
765 //lyxerr << " dot found at " << dot << endl;
766 if (dot != string::npos)
767 tmp_format.erase(dot, 1);
768 int const file_format = convert<int>(tmp_format);
769 //lyxerr << "format: " << file_format << endl;
771 // save timestamp and checksum of the original disk file, making sure
772 // to not overwrite them with those of the file created in the tempdir
773 // when it has to be converted to the current format.
774 if (!pimpl_->checksum_) {
775 // Save the timestamp and checksum of disk file. If filename is an
776 // emergency file, save the timestamp and sum of the original lyx file
777 // because isExternallyModified will check for this file. (BUG4193)
778 string diskfile = filename.toFilesystemEncoding();
779 if (suffixIs(diskfile, ".emergency"))
780 diskfile = diskfile.substr(0, diskfile.size() - 10);
781 saveCheckSum(diskfile);
784 if (file_format != LYX_FORMAT) {
787 // lyx2lyx would fail
790 FileName const tmpfile(tempName());
791 if (tmpfile.empty()) {
792 Alert::error(_("Conversion failed"),
793 bformat(_("%1$s is from a different"
794 " version of LyX, but a temporary"
795 " file for converting it could"
797 from_utf8(filename.absFilename())));
800 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
801 if (lyx2lyx.empty()) {
802 Alert::error(_("Conversion script not found"),
803 bformat(_("%1$s is from a different"
804 " version of LyX, but the"
805 " conversion script lyx2lyx"
806 " could not be found."),
807 from_utf8(filename.absFilename())));
810 ostringstream command;
811 command << os::python()
812 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
813 << " -t " << convert<string>(LYX_FORMAT)
814 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
815 << ' ' << quoteName(filename.toFilesystemEncoding());
816 string const command_str = command.str();
818 LYXERR(Debug::INFO) << "Running '"
819 << command_str << '\''
822 cmd_ret const ret = runCommand(command_str);
823 if (ret.first != 0) {
824 Alert::error(_("Conversion script failed"),
825 bformat(_("%1$s is from a different version"
826 " of LyX, but the lyx2lyx script"
827 " failed to convert it."),
828 from_utf8(filename.absFilename())));
831 bool const ret = readFile(tmpfile);
832 // Do stuff with tmpfile name and buffer name here.
833 return ret ? success : failure;
838 if (readDocument(lex)) {
839 Alert::error(_("Document format failure"),
840 bformat(_("%1$s ended unexpectedly, which means"
841 " that it is probably corrupted."),
842 from_utf8(filename.absFilename())));
845 //lyxerr << "removing " << MacroTable::localMacros().size()
846 // << " temporary macro entries" << endl;
847 //MacroTable::localMacros().clear();
849 pimpl_->file_fully_loaded = true;
854 // Should probably be moved to somewhere else: BufferView? LyXView?
855 bool Buffer::save() const
857 // We don't need autosaves in the immediate future. (Asger)
858 resetAutosaveTimers();
860 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
863 bool madeBackup = false;
865 // make a backup if the file already exists
866 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
867 backupName = FileName(fileName() + '~');
868 if (!lyxrc.backupdir_path.empty())
869 backupName = FileName(addName(lyxrc.backupdir_path,
870 subst(os::internal_path(backupName.absFilename()), '/', '!')));
873 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
875 } catch (fs::filesystem_error const & fe) {
876 Alert::error(_("Backup failure"),
877 bformat(_("Cannot create backup file %1$s.\n"
878 "Please check whether the directory exists and is writeable."),
879 from_utf8(backupName.absFilename())));
880 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
884 // ask if the disk file has been externally modified (use checksum method)
885 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
886 docstring const file = makeDisplayPath(fileName(), 20);
887 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
888 "you want to overwrite this file?"), file);
889 int const ret = Alert::prompt(_("Overwrite modified file?"),
890 text, 1, 1, _("&Overwrite"), _("&Cancel"));
895 if (writeFile(pimpl_->filename)) {
897 removeAutosaveFile(fileName());
898 saveCheckSum(pimpl_->filename.toFilesystemEncoding());
901 // Saving failed, so backup is not backup
903 rename(backupName, pimpl_->filename);
909 bool Buffer::writeFile(FileName const & fname) const
911 if (pimpl_->read_only && fname == pimpl_->filename)
917 if (params().embedded)
918 // first write the .lyx file to the temporary directory
919 content = FileName(addName(temppath(), "content.lyx"));
923 if (params().compressed) {
924 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
930 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
937 if (retval && params().embedded) {
938 // write file.lyx and all the embedded files to the zip file fname
939 // if embedding is enabled
940 return pimpl_->embedded_files.writeFile(fname);
946 bool Buffer::write(ostream & ofs) const
949 // Use the standard "C" locale for file output.
950 ofs.imbue(std::locale::classic());
953 // The top of the file should not be written by params().
955 // write out a comment in the top of the file
956 ofs << "#LyX " << lyx_version
957 << " created this file. For more info see http://www.lyx.org/\n"
958 << "\\lyxformat " << LYX_FORMAT << "\n"
959 << "\\begin_document\n";
962 /// For each author, set 'used' to true if there is a change
963 /// by this author in the document; otherwise set it to 'false'.
964 AuthorList::Authors::const_iterator a_it = params().authors().begin();
965 AuthorList::Authors::const_iterator a_end = params().authors().end();
966 for (; a_it != a_end; ++a_it)
967 a_it->second.used(false);
969 ParIterator const end = par_iterator_end();
970 ParIterator it = par_iterator_begin();
971 for ( ; it != end; ++it)
972 it->checkAuthors(params().authors());
974 // now write out the buffer parameters.
975 ofs << "\\begin_header\n";
976 params().writeFile(ofs);
977 ofs << "\\end_header\n";
979 // write the manifest after header
980 ofs << "\n\\begin_manifest\n";
981 pimpl_->embedded_files.update();
982 embeddedFiles().writeManifest(ofs);
983 ofs << "\\end_manifest\n";
986 ofs << "\n\\begin_body\n";
987 text().write(*this, ofs);
988 ofs << "\n\\end_body\n";
990 // Write marker that shows file is complete
991 ofs << "\\end_document" << endl;
993 // Shouldn't really be needed....
996 // how to check if close went ok?
997 // Following is an attempt... (BE 20001011)
999 // good() returns false if any error occured, including some
1000 // formatting error.
1001 // bad() returns true if something bad happened in the buffer,
1002 // which should include file system full errors.
1007 lyxerr << "File was not closed properly." << endl;
1014 bool Buffer::makeLaTeXFile(FileName const & fname,
1015 string const & original_path,
1016 OutputParams const & runparams,
1017 bool output_preamble, bool output_body)
1019 string const encoding = runparams.encoding->iconvName();
1020 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
1021 << encoding << "..." << endl;
1023 odocfstream ofs(encoding);
1024 if (!openFileWrite(ofs, fname))
1027 //TexStream ts(ofs.rdbuf(), &texrow());
1029 bool failed_export = false;
1032 writeLaTeXSource(ofs, original_path,
1033 runparams, output_preamble, output_body);
1035 catch (iconv_codecvt_facet_exception & e) {
1036 lyxerr << "Caught iconv exception: " << e.what() << endl;
1037 failed_export = true;
1039 catch (std::exception const & e) {
1040 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1041 failed_export = true;
1044 lyxerr << "Caught some really weird exception..." << endl;
1045 LyX::cref().emergencyCleanup();
1051 failed_export = true;
1052 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1055 if (failed_export) {
1056 Alert::error(_("Encoding error"),
1057 _("Some characters of your document are probably not "
1058 "representable in the chosen encoding.\n"
1059 "Changing the document encoding to utf8 could help."));
1066 void Buffer::writeLaTeXSource(odocstream & os,
1067 string const & original_path,
1068 OutputParams const & runparams_in,
1069 bool const output_preamble, bool const output_body)
1071 OutputParams runparams = runparams_in;
1073 // validate the buffer.
1074 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
1075 LaTeXFeatures features(*this, params(), runparams);
1077 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
1079 // The starting paragraph of the coming rows is the
1080 // first paragraph of the document. (Asger)
1081 if (output_preamble && runparams.nice) {
1082 os << "%% LyX " << lyx_version << " created this file. "
1083 "For more info, see http://www.lyx.org/.\n"
1084 "%% Do not edit unless you really know what "
1089 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1090 // There are a few differences between nice LaTeX and usual files:
1091 // usual is \batchmode and has a
1092 // special input@path to allow the including of figures
1093 // with either \input or \includegraphics (what figinsets do).
1094 // input@path is set when the actual parameter
1095 // original_path is set. This is done for usual tex-file, but not
1096 // for nice-latex-file. (Matthias 250696)
1097 // Note that input@path is only needed for something the user does
1098 // in the preamble, included .tex files or ERT, files included by
1099 // LyX work without it.
1100 if (output_preamble) {
1101 if (!runparams.nice) {
1102 // code for usual, NOT nice-latex-file
1103 os << "\\batchmode\n"; // changed
1104 // from \nonstopmode
1107 if (!original_path.empty()) {
1109 // We don't know the encoding of inputpath
1110 docstring const inputpath = from_utf8(latex_path(original_path));
1111 os << "\\makeatletter\n"
1112 << "\\def\\input@path{{"
1113 << inputpath << "/}}\n"
1114 << "\\makeatother\n";
1120 // Write the preamble
1121 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1127 os << "\\begin{document}\n";
1129 } // output_preamble
1131 texrow().start(paragraphs().begin()->id(), 0);
1133 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1135 if (!lyxrc.language_auto_begin &&
1136 !params().language->babel().empty()) {
1138 os << from_utf8(subst(lyxrc.language_command_begin,
1140 params().language->babel()))
1145 Encoding const & encoding = params().encoding();
1146 if (encoding.package() == Encoding::CJK) {
1147 // Open a CJK environment, since in contrast to the encodings
1148 // handled by inputenc the document encoding is not set in
1149 // the preamble if it is handled by CJK.sty.
1150 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1155 // if we are doing a real file with body, even if this is the
1156 // child of some other buffer, let's cut the link here.
1157 // This happens for example if only a child document is printed.
1158 string save_parentname;
1159 if (output_preamble) {
1160 save_parentname = params().parentname;
1161 params().parentname.erase();
1164 loadChildDocuments(*this);
1167 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1169 // Restore the parenthood if needed
1170 if (output_preamble)
1171 params().parentname = save_parentname;
1173 // add this just in case after all the paragraphs
1177 if (encoding.package() == Encoding::CJK) {
1178 // Close the open CJK environment.
1179 // latexParagraphs will have opened one even if the last text
1181 os << "\\end{CJK}\n";
1185 if (!lyxrc.language_auto_end &&
1186 !params().language->babel().empty()) {
1187 os << from_utf8(subst(lyxrc.language_command_end,
1189 params().language->babel()))
1194 if (output_preamble) {
1195 os << "\\end{document}\n";
1198 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1200 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1203 runparams_in.encoding = runparams.encoding;
1205 // Just to be sure. (Asger)
1208 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1209 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1214 bool Buffer::isLatex() const
1216 return params().getTextClass().outputType() == LATEX;
1220 bool Buffer::isLiterate() const
1222 return params().getTextClass().outputType() == LITERATE;
1226 bool Buffer::isDocBook() const
1228 return params().getTextClass().outputType() == DOCBOOK;
1232 void Buffer::makeDocBookFile(FileName const & fname,
1233 OutputParams const & runparams,
1234 bool const body_only)
1236 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1240 if (!openFileWrite(ofs, fname))
1243 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1247 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1251 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1252 OutputParams const & runparams,
1253 bool const only_body)
1255 LaTeXFeatures features(*this, params(), runparams);
1260 TextClass const & tclass = params().getTextClass();
1261 string const top_element = tclass.latexname();
1264 if (runparams.flavor == OutputParams::XML)
1265 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1268 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1271 if (! tclass.class_header().empty())
1272 os << from_ascii(tclass.class_header());
1273 else if (runparams.flavor == OutputParams::XML)
1274 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1275 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1277 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1279 docstring preamble = from_utf8(params().preamble);
1280 if (runparams.flavor != OutputParams::XML ) {
1281 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1282 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1283 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1284 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1287 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1289 preamble += features.getIncludedFiles(name);
1290 preamble += features.getLyXSGMLEntities();
1292 if (!preamble.empty()) {
1293 os << "\n [ " << preamble << " ]";
1298 string top = top_element;
1300 if (runparams.flavor == OutputParams::XML)
1301 top += params().language->code();
1303 top += params().language->code().substr(0,2);
1306 if (!params().options.empty()) {
1308 top += params().options;
1311 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1312 << " file was created by LyX " << lyx_version
1313 << "\n See http://www.lyx.org/ for more information -->\n";
1315 params().getTextClass().counters().reset();
1317 loadChildDocuments(*this);
1319 sgml::openTag(os, top);
1321 docbookParagraphs(paragraphs(), *this, os, runparams);
1322 sgml::closeTag(os, top_element);
1326 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1327 // Other flags: -wall -v0 -x
1328 int Buffer::runChktex()
1332 // get LaTeX-Filename
1333 FileName const path(temppath());
1334 string const name = addName(path.absFilename(), getLatexName());
1335 string const org_path = filePath();
1337 support::Path p(path); // path to LaTeX file
1338 message(_("Running chktex..."));
1340 // Generate the LaTeX file if neccessary
1341 OutputParams runparams(¶ms().encoding());
1342 runparams.flavor = OutputParams::LATEX;
1343 runparams.nice = false;
1344 makeLaTeXFile(FileName(name), org_path, runparams);
1347 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1348 int const res = chktex.run(terr); // run chktex
1351 Alert::error(_("chktex failure"),
1352 _("Could not run chktex successfully."));
1353 } else if (res > 0) {
1354 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1355 // Clear out old errors
1357 // Fill-in the error list with the TeX errors
1358 bufferErrors(*this, terr, errorList);
1369 void Buffer::validate(LaTeXFeatures & features) const
1371 TextClass const & tclass = params().getTextClass();
1373 if (params().outputChanges) {
1374 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1375 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1376 LaTeXFeatures::isAvailable("xcolor");
1378 if (features.runparams().flavor == OutputParams::LATEX) {
1380 features.require("ct-dvipost");
1381 features.require("dvipost");
1382 } else if (xcolorsoul) {
1383 features.require("ct-xcolor-soul");
1384 features.require("soul");
1385 features.require("xcolor");
1387 features.require("ct-none");
1389 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1391 features.require("ct-xcolor-soul");
1392 features.require("soul");
1393 features.require("xcolor");
1394 features.require("pdfcolmk"); // improves color handling in PDF output
1396 features.require("ct-none");
1401 // AMS Style is at document level
1402 if (params().use_amsmath == BufferParams::package_on
1403 || tclass.provides("amsmath"))
1404 features.require("amsmath");
1405 if (params().use_esint == BufferParams::package_on)
1406 features.require("esint");
1408 loadChildDocuments(*this);
1410 for_each(paragraphs().begin(), paragraphs().end(),
1411 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1413 // the bullet shapes are buffer level not paragraph level
1414 // so they are tested here
1415 for (int i = 0; i < 4; ++i) {
1416 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1417 int const font = params().user_defined_bullet(i).getFont();
1419 int const c = params()
1420 .user_defined_bullet(i)
1427 features.require("latexsym");
1429 } else if (font == 1) {
1430 features.require("amssymb");
1431 } else if ((font >= 2 && font <= 5)) {
1432 features.require("pifont");
1437 if (lyxerr.debugging(Debug::LATEX)) {
1438 features.showStruct();
1443 void Buffer::getLabelList(vector<docstring> & list) const
1445 /// if this is a child document and the parent is already loaded
1446 /// Use the parent's list instead [ale990407]
1447 Buffer const * tmp = getMasterBuffer();
1449 lyxerr << "getMasterBuffer() failed!" << endl;
1453 tmp->getLabelList(list);
1457 loadChildDocuments(*this);
1459 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1460 it.nextInset()->getLabelList(*this, list);
1464 void Buffer::updateBibfilesCache()
1466 // if this is a child document and the parent is already loaded
1467 // update the parent's cache instead
1468 Buffer * tmp = getMasterBuffer();
1471 tmp->updateBibfilesCache();
1475 bibfilesCache_.clear();
1476 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1477 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1478 InsetBibtex const & inset =
1479 static_cast<InsetBibtex const &>(*it);
1480 vector<FileName> const bibfiles = inset.getFiles(*this);
1481 bibfilesCache_.insert(bibfilesCache_.end(),
1484 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1485 InsetInclude & inset =
1486 static_cast<InsetInclude &>(*it);
1487 inset.updateBibfilesCache(*this);
1488 vector<FileName> const & bibfiles =
1489 inset.getBibfilesCache(*this);
1490 bibfilesCache_.insert(bibfilesCache_.end(),
1498 vector<FileName> const & Buffer::getBibfilesCache() const
1500 // if this is a child document and the parent is already loaded
1501 // use the parent's cache instead
1502 Buffer const * tmp = getMasterBuffer();
1505 return tmp->getBibfilesCache();
1507 // We update the cache when first used instead of at loading time.
1508 if (bibfilesCache_.empty())
1509 const_cast<Buffer *>(this)->updateBibfilesCache();
1511 return bibfilesCache_;
1515 bool Buffer::isDepClean(string const & name) const
1517 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1518 if (it == pimpl_->dep_clean.end())
1524 void Buffer::markDepClean(string const & name)
1526 pimpl_->dep_clean[name] = true;
1530 bool Buffer::dispatch(string const & command, bool * result)
1532 return dispatch(lyxaction.lookupFunc(command), result);
1536 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1538 bool dispatched = true;
1540 switch (func.action) {
1541 case LFUN_BUFFER_EXPORT: {
1542 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1555 void Buffer::changeLanguage(Language const * from, Language const * to)
1560 for_each(par_iterator_begin(),
1562 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1566 bool Buffer::isMultiLingual() const
1568 ParConstIterator end = par_iterator_end();
1569 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1570 if (it->isMultiLingual(params()))
1577 ParIterator Buffer::getParFromID(int const id) const
1579 ParConstIterator it = par_iterator_begin();
1580 ParConstIterator const end = par_iterator_end();
1583 // John says this is called with id == -1 from undo
1584 lyxerr << "getParFromID(), id: " << id << endl;
1588 for (; it != end; ++it)
1596 bool Buffer::hasParWithID(int const id) const
1598 ParConstIterator const it = getParFromID(id);
1599 return it != par_iterator_end();
1603 ParIterator Buffer::par_iterator_begin()
1605 return lyx::par_iterator_begin(inset());
1609 ParIterator Buffer::par_iterator_end()
1611 return lyx::par_iterator_end(inset());
1615 ParConstIterator Buffer::par_iterator_begin() const
1617 return lyx::par_const_iterator_begin(inset());
1621 ParConstIterator Buffer::par_iterator_end() const
1623 return lyx::par_const_iterator_end(inset());
1627 Language const * Buffer::getLanguage() const
1629 return params().language;
1633 docstring const Buffer::B_(string const & l10n) const
1635 return params().B_(l10n);
1639 bool Buffer::isClean() const
1641 return pimpl_->lyx_clean;
1645 bool Buffer::isBakClean() const
1647 return pimpl_->bak_clean;
1651 bool Buffer::isExternallyModified(CheckMethod method) const
1653 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1654 // if method == timestamp, check timestamp before checksum
1655 return (method == checksum_method
1656 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1657 && pimpl_->checksum_ != sum(pimpl_->filename);
1661 void Buffer::saveCheckSum(string const & file) const
1663 if (fs::exists(file)) {
1664 pimpl_->timestamp_ = fs::last_write_time(file);
1665 pimpl_->checksum_ = sum(FileName(file));
1667 // in the case of save to a new file.
1668 pimpl_->timestamp_ = 0;
1669 pimpl_->checksum_ = 0;
1674 void Buffer::markClean() const
1676 if (!pimpl_->lyx_clean) {
1677 pimpl_->lyx_clean = true;
1680 // if the .lyx file has been saved, we don't need an
1682 pimpl_->bak_clean = true;
1686 void Buffer::markBakClean()
1688 pimpl_->bak_clean = true;
1692 void Buffer::setUnnamed(bool flag)
1694 pimpl_->unnamed = flag;
1698 bool Buffer::isUnnamed() const
1700 return pimpl_->unnamed;
1704 // FIXME: this function should be moved to buffer_pimpl.C
1705 void Buffer::markDirty()
1707 if (pimpl_->lyx_clean) {
1708 pimpl_->lyx_clean = false;
1711 pimpl_->bak_clean = false;
1713 DepClean::iterator it = pimpl_->dep_clean.begin();
1714 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1716 for (; it != end; ++it)
1721 string const Buffer::fileName() const
1723 return pimpl_->filename.absFilename();
1727 string const & Buffer::filePath() const
1729 return params().filepath;
1733 bool Buffer::isReadonly() const
1735 return pimpl_->read_only;
1739 void Buffer::setParentName(string const & name)
1741 if (name == pimpl_->filename.absFilename())
1742 // Avoids recursive include.
1743 params().parentname.clear();
1745 params().parentname = name;
1749 Buffer const * Buffer::getMasterBuffer() const
1751 if (!params().parentname.empty()
1752 && theBufferList().exists(params().parentname)) {
1753 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1754 //We need to check if the parent is us...
1755 //FIXME RECURSIVE INCLUDE
1756 //This is not sufficient, since recursive includes could be downstream.
1757 if (buf && buf != this)
1758 return buf->getMasterBuffer();
1765 Buffer * Buffer::getMasterBuffer()
1767 if (!params().parentname.empty()
1768 && theBufferList().exists(params().parentname)) {
1769 Buffer * buf = theBufferList().getBuffer(params().parentname);
1770 //We need to check if the parent is us...
1771 //FIXME RECURSIVE INCLUDE
1772 //This is not sufficient, since recursive includes could be downstream.
1773 if (buf && buf != this)
1774 return buf->getMasterBuffer();
1781 MacroData const & Buffer::getMacro(docstring const & name) const
1783 return pimpl_->macros.get(name);
1787 bool Buffer::hasMacro(docstring const & name) const
1789 return pimpl_->macros.has(name);
1793 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1795 MacroTable::globalMacros().insert(name, data);
1796 pimpl_->macros.insert(name, data);
1800 void Buffer::buildMacros()
1802 // Start with global table.
1803 pimpl_->macros = MacroTable::globalMacros();
1806 ParagraphList const & pars = text().paragraphs();
1807 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1808 //lyxerr << "searching main par " << i
1809 // << " for macro definitions" << std::endl;
1810 InsetList const & insets = pars[i].insetlist;
1811 InsetList::const_iterator it = insets.begin();
1812 InsetList::const_iterator end = insets.end();
1813 for ( ; it != end; ++it) {
1814 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1815 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1816 MathMacroTemplate const & mac
1817 = static_cast<MathMacroTemplate const &>(*it->inset);
1818 insertMacro(mac.name(), mac.asMacroData());
1825 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1828 //FIXME: This does not work for child documents yet.
1829 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1830 // Check if the label 'from' appears more than once
1831 vector<docstring> labels;
1833 if (code == Inset::CITE_CODE) {
1835 keys.fillWithBibKeys(this);
1836 BiblioInfo::const_iterator bit = keys.begin();
1837 BiblioInfo::const_iterator bend = keys.end();
1839 for (; bit != bend; ++bit)
1841 labels.push_back(bit->first);
1843 getLabelList(labels);
1845 if (std::count(labels.begin(), labels.end(), from) > 1)
1848 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1849 if (it->lyxCode() == code) {
1850 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1851 inset.replaceContents(to_utf8(from), to_utf8(to));
1857 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1858 pit_type par_end, bool full_source)
1860 OutputParams runparams(¶ms().encoding());
1861 runparams.nice = true;
1862 runparams.flavor = OutputParams::LATEX;
1863 runparams.linelen = lyxrc.plaintext_linelen;
1864 // No side effect of file copying and image conversion
1865 runparams.dryrun = true;
1869 os << "% " << _("Preview source code") << "\n\n";
1873 writeLaTeXSource(os, filePath(), runparams, true, true);
1875 writeDocBookSource(os, fileName(), runparams, false);
1878 runparams.par_begin = par_begin;
1879 runparams.par_end = par_end;
1880 if (par_begin + 1 == par_end)
1882 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1886 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1887 convert<docstring>(par_begin),
1888 convert<docstring>(par_end - 1))
1892 // output paragraphs
1894 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1897 docbookParagraphs(paragraphs(), *this, os, runparams);
1903 ErrorList const & Buffer::errorList(string const & type) const
1905 static ErrorList const emptyErrorList;
1906 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1907 if (I == pimpl_->errorLists.end())
1908 return emptyErrorList;
1914 ErrorList & Buffer::errorList(string const & type)
1916 return pimpl_->errorLists[type];