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/Delegates.h"
72 #include "frontends/WorkAreaManager.h"
74 #include "graphics/Previews.h"
76 #include "support/types.h"
77 #include "support/lyxalgo.h"
78 #include "support/filetools.h"
79 #include "support/fs_extras.h"
80 #include "support/gzstream.h"
81 #include "support/lyxlib.h"
82 #include "support/os.h"
83 #include "support/Path.h"
84 #include "support/textutils.h"
85 #include "support/convert.h"
87 #include <boost/bind.hpp>
88 #include <boost/filesystem/exception.hpp>
89 #include <boost/filesystem/operations.hpp>
104 using std::ostringstream;
116 using support::addName;
117 using support::bformat;
118 using support::changeExtension;
119 using support::cmd_ret;
120 using support::createBufferTmpDir;
121 using support::destroyDir;
122 using support::FileName;
123 using support::getFormatFromContents;
124 using support::libFileSearch;
125 using support::latex_path;
126 using support::ltrim;
127 using support::makeAbsPath;
128 using support::makeDisplayPath;
129 using support::makeLatexName;
130 using support::onlyFilename;
131 using support::onlyPath;
132 using support::quoteName;
133 using support::removeAutosaveFile;
134 using support::rename;
135 using support::runCommand;
136 using support::split;
137 using support::subst;
138 using support::tempName;
141 using support::suffixIs;
143 namespace Alert = frontend::Alert;
144 namespace os = support::os;
145 namespace fs = boost::filesystem;
149 int const LYX_FORMAT = 288; //RGH, command insets
154 typedef std::map<string, bool> DepClean;
159 Impl(Buffer & parent, FileName const & file, bool readonly);
161 limited_stack<Undo> undostack;
162 limited_stack<Undo> redostack;
168 /// need to regenerate .tex?
172 mutable bool lyx_clean;
174 /// is autosave needed?
175 mutable bool bak_clean;
177 /// is this a unnamed file (New...)?
183 /// name of the file the buffer is associated with.
186 /** Set to true only when the file is fully loaded.
187 * Used to prevent the premature generation of previews
188 * and by the citation inset.
190 bool file_fully_loaded;
192 /// our Text that should be wrapped in an InsetText
199 TocBackend toc_backend;
201 /// Container for all sort of Buffer dependant errors.
202 map<string, ErrorList> errorLists;
204 /// all embedded files of this buffer
205 EmbeddedFiles embedded_files;
207 /// timestamp and checksum used to test if the file has been externally
208 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
210 unsigned long checksum_;
213 frontend::WorkAreaManager * wa_;
217 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
218 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
219 filename(file), file_fully_loaded(false), inset(params),
220 toc_backend(&parent), embedded_files(&parent), timestamp_(0),
223 inset.setAutoBreakRows(true);
224 lyxvc.buffer(&parent);
225 temppath = createBufferTmpDir();
226 params.filepath = onlyPath(file.absFilename());
227 // FIXME: And now do something if temppath == string(), because we
228 // assume from now on that temppath points to a valid temp dir.
229 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
232 wa_ = new frontend::WorkAreaManager;
236 Buffer::Buffer(string const & file, bool readonly)
237 : pimpl_(new Impl(*this, FileName(file), readonly)), gui_(0)
239 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
245 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
246 // here the buffer should take care that it is
247 // saved properly, before it goes into the void.
249 Buffer * master = getMasterBuffer();
250 if (master != this && use_gui)
251 // We are closing buf which was a child document so we
252 // must update the labels and section numbering of its master
254 updateLabels(*master);
256 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
257 Alert::warning(_("Could not remove temporary directory"),
258 bformat(_("Could not remove the temporary directory %1$s"),
259 from_utf8(temppath())));
262 // Remove any previewed LaTeX snippets associated with this buffer.
263 graphics::Previews::get().removeLoader(*this);
266 pimpl_->wa_->closeAll();
273 void Buffer::changed() const
276 pimpl_->wa_->redrawAll();
280 frontend::WorkAreaManager & Buffer::workAreaManager() const
282 BOOST_ASSERT(pimpl_->wa_);
287 Text & Buffer::text() const
289 return const_cast<Text &>(pimpl_->inset.text_);
293 Inset & Buffer::inset() const
295 return const_cast<InsetText &>(pimpl_->inset);
299 limited_stack<Undo> & Buffer::undostack()
301 return pimpl_->undostack;
305 limited_stack<Undo> const & Buffer::undostack() const
307 return pimpl_->undostack;
311 limited_stack<Undo> & Buffer::redostack()
313 return pimpl_->redostack;
317 limited_stack<Undo> const & Buffer::redostack() const
319 return pimpl_->redostack;
323 BufferParams & Buffer::params()
325 return pimpl_->params;
329 BufferParams const & Buffer::params() const
331 return pimpl_->params;
335 ParagraphList & Buffer::paragraphs()
337 return text().paragraphs();
341 ParagraphList const & Buffer::paragraphs() const
343 return text().paragraphs();
347 LyXVC & Buffer::lyxvc()
349 return pimpl_->lyxvc;
353 LyXVC const & Buffer::lyxvc() const
355 return pimpl_->lyxvc;
359 string const & Buffer::temppath() const
361 return pimpl_->temppath;
365 TexRow & Buffer::texrow()
367 return pimpl_->texrow;
371 TexRow const & Buffer::texrow() const
373 return pimpl_->texrow;
377 TocBackend & Buffer::tocBackend()
379 return pimpl_->toc_backend;
383 TocBackend const & Buffer::tocBackend() const
385 return pimpl_->toc_backend;
389 EmbeddedFiles & Buffer::embeddedFiles()
391 return pimpl_->embedded_files;
395 EmbeddedFiles const & Buffer::embeddedFiles() const
397 return pimpl_->embedded_files;
401 string const Buffer::getLatexName(bool const no_path) const
403 string const name = changeExtension(makeLatexName(fileName()), ".tex");
404 return no_path ? onlyFilename(name) : name;
408 pair<Buffer::LogType, string> const Buffer::getLogName() const
410 string const filename = getLatexName(false);
412 if (filename.empty())
413 return make_pair(Buffer::latexlog, string());
415 string const path = temppath();
417 FileName const fname(addName(temppath(),
418 onlyFilename(changeExtension(filename,
420 FileName const bname(
421 addName(path, onlyFilename(
422 changeExtension(filename,
423 formats.extension("literate") + ".out"))));
425 // If no Latex log or Build log is newer, show Build log
427 if (fs::exists(bname.toFilesystemEncoding()) &&
428 (!fs::exists(fname.toFilesystemEncoding()) ||
429 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
430 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
431 return make_pair(Buffer::buildlog, bname.absFilename());
433 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
434 return make_pair(Buffer::latexlog, fname.absFilename());
438 void Buffer::setReadonly(bool const flag)
440 if (pimpl_->read_only != flag) {
441 pimpl_->read_only = flag;
447 void Buffer::setFileName(string const & newfile)
449 pimpl_->filename = makeAbsPath(newfile);
450 params().filepath = onlyPath(pimpl_->filename.absFilename());
451 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
456 // We'll remove this later. (Lgb)
459 void unknownClass(string const & unknown)
461 Alert::warning(_("Unknown document class"),
462 bformat(_("Using the default document class, because the "
463 "class %1$s is unknown."), from_utf8(unknown)));
469 int Buffer::readHeader(Lexer & lex)
471 int unknown_tokens = 0;
473 int begin_header_line = -1;
475 // Initialize parameters that may be/go lacking in header:
476 params().branchlist().clear();
477 params().preamble.erase();
478 params().options.erase();
479 params().float_placement.erase();
480 params().paperwidth.erase();
481 params().paperheight.erase();
482 params().leftmargin.erase();
483 params().rightmargin.erase();
484 params().topmargin.erase();
485 params().bottommargin.erase();
486 params().headheight.erase();
487 params().headsep.erase();
488 params().footskip.erase();
489 params().listings_params.clear();
490 params().clearLayoutModules();
491 params().pdfoptions().clear();
493 for (int i = 0; i < 4; ++i) {
494 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
495 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
498 ErrorList & errorList = pimpl_->errorLists["Parse"];
502 string const token = lex.getString();
507 if (token == "\\end_header")
511 if (token == "\\begin_header") {
512 begin_header_line = line;
516 LYXERR(Debug::PARSER) << "Handling document header token: `"
517 << token << '\'' << endl;
519 string unknown = params().readToken(lex, token);
520 if (!unknown.empty()) {
521 if (unknown[0] != '\\' && token == "\\textclass") {
522 unknownClass(unknown);
525 docstring const s = bformat(_("Unknown token: "
529 errorList.push_back(ErrorItem(_("Document header error"),
534 if (begin_header_line) {
535 docstring const s = _("\\begin_header is missing");
536 errorList.push_back(ErrorItem(_("Document header error"),
540 return unknown_tokens;
545 // changed to be public and have one parameter
546 // Returns false if "\end_document" is not read (Asger)
547 bool Buffer::readDocument(Lexer & lex)
549 ErrorList & errorList = pimpl_->errorLists["Parse"];
553 string const token = lex.getString();
554 if (token != "\\begin_document") {
555 docstring const s = _("\\begin_document is missing");
556 errorList.push_back(ErrorItem(_("Document header error"),
560 // we are reading in a brand new document
561 BOOST_ASSERT(paragraphs().empty());
564 TextClass const & baseClass = textclasslist[params().getBaseClass()];
565 if (!baseClass.load(filePath())) {
566 string theclass = baseClass.name();
567 Alert::error(_("Can't load document class"), bformat(
568 _("Using the default document class, because the "
569 "class %1$s could not be loaded."), from_utf8(theclass)));
570 params().setBaseClass(defaultTextclass());
573 if (params().outputChanges) {
574 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
575 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
576 LaTeXFeatures::isAvailable("xcolor");
578 if (!dvipost && !xcolorsoul) {
579 Alert::warning(_("Changes not shown in LaTeX output"),
580 _("Changes will not be highlighted in LaTeX output, "
581 "because neither dvipost nor xcolor/soul are installed.\n"
582 "Please install these packages or redefine "
583 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
584 } else if (!xcolorsoul) {
585 Alert::warning(_("Changes not shown in LaTeX output"),
586 _("Changes will not be highlighted in LaTeX output "
587 "when using pdflatex, because xcolor and soul are not installed.\n"
588 "Please install both packages or redefine "
589 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
592 // read manifest after header
593 embeddedFiles().readManifest(lex, errorList);
596 bool const res = text().read(*this, lex, errorList);
597 for_each(text().paragraphs().begin(),
598 text().paragraphs().end(),
599 bind(&Paragraph::setInsetOwner, _1, &inset()));
605 // needed to insert the selection
606 void Buffer::insertStringAsLines(ParagraphList & pars,
607 pit_type & pit, pos_type & pos,
608 Font const & fn, docstring const & str, bool autobreakrows)
612 // insert the string, don't insert doublespace
613 bool space_inserted = true;
614 for (docstring::const_iterator cit = str.begin();
615 cit != str.end(); ++cit) {
616 Paragraph & par = pars[pit];
618 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
619 breakParagraph(params(), pars, pit, pos,
620 par.layout()->isEnvironment());
623 space_inserted = true;
627 // do not insert consecutive spaces if !free_spacing
628 } else if ((*cit == ' ' || *cit == '\t') &&
629 space_inserted && !par.isFreeSpacing()) {
631 } else if (*cit == '\t') {
632 if (!par.isFreeSpacing()) {
633 // tabs are like spaces here
634 par.insertChar(pos, ' ', font, params().trackChanges);
636 space_inserted = true;
638 const pos_type n = 8 - pos % 8;
639 for (pos_type i = 0; i < n; ++i) {
640 par.insertChar(pos, ' ', font, params().trackChanges);
643 space_inserted = true;
645 } else if (!isPrintable(*cit)) {
646 // Ignore unprintables
649 // just insert the character
650 par.insertChar(pos, *cit, font, params().trackChanges);
652 space_inserted = (*cit == ' ');
659 bool Buffer::readString(std::string const & s)
661 params().compressed = false;
663 // remove dummy empty par
664 paragraphs().clear();
666 std::istringstream is(s);
668 FileName const name(tempName());
669 switch (readFile(lex, name, true)) {
673 // We need to call lyx2lyx, so write the input to a file
674 std::ofstream os(name.toFilesystemEncoding().c_str());
677 return readFile(name);
687 bool Buffer::readFile(FileName const & filename)
689 FileName fname(filename);
690 // Check if the file is compressed.
691 string format = getFormatFromContents(filename);
692 if (format == "zip") {
693 // decompress to a temp directory
694 LYXERR(Debug::FILES) << filename << " is in zip format. Unzip to " << temppath() << endl;
695 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
697 FileName lyxfile(addName(temppath(), "content.lyx"));
698 // if both manifest.txt and file.lyx exist, this is am embedded file
699 if (fs::exists(lyxfile.toFilesystemEncoding())) {
700 params().embedded = true;
704 // The embedded lyx file can also be compressed, for backward compatibility
705 format = getFormatFromContents(fname);
706 if (format == "gzip" || format == "zip" || format == "compress") {
707 params().compressed = true;
710 // remove dummy empty par
711 paragraphs().clear();
714 if (readFile(lex, fname) != success)
721 bool Buffer::fully_loaded() const
723 return pimpl_->file_fully_loaded;
727 void Buffer::fully_loaded(bool const value)
729 pimpl_->file_fully_loaded = value;
733 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
736 BOOST_ASSERT(!filename.empty());
739 Alert::error(_("Document could not be read"),
740 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
745 string const token(lex.getString());
748 Alert::error(_("Document could not be read"),
749 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
753 // the first token _must_ be...
754 if (token != "\\lyxformat") {
755 lyxerr << "Token: " << token << endl;
757 Alert::error(_("Document format failure"),
758 bformat(_("%1$s is not a LyX document."),
759 from_utf8(filename.absFilename())));
764 string tmp_format = lex.getString();
765 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
766 // if present remove ".," from string.
767 string::size_type dot = tmp_format.find_first_of(".,");
768 //lyxerr << " dot found at " << dot << endl;
769 if (dot != string::npos)
770 tmp_format.erase(dot, 1);
771 int const file_format = convert<int>(tmp_format);
772 //lyxerr << "format: " << file_format << endl;
774 // save timestamp and checksum of the original disk file, making sure
775 // to not overwrite them with those of the file created in the tempdir
776 // when it has to be converted to the current format.
777 if (!pimpl_->checksum_) {
778 // Save the timestamp and checksum of disk file. If filename is an
779 // emergency file, save the timestamp and sum of the original lyx file
780 // because isExternallyModified will check for this file. (BUG4193)
781 string diskfile = filename.toFilesystemEncoding();
782 if (suffixIs(diskfile, ".emergency"))
783 diskfile = diskfile.substr(0, diskfile.size() - 10);
784 saveCheckSum(diskfile);
787 if (file_format != LYX_FORMAT) {
790 // lyx2lyx would fail
793 FileName const tmpfile(tempName());
794 if (tmpfile.empty()) {
795 Alert::error(_("Conversion failed"),
796 bformat(_("%1$s is from a different"
797 " version of LyX, but a temporary"
798 " file for converting it could"
800 from_utf8(filename.absFilename())));
803 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
804 if (lyx2lyx.empty()) {
805 Alert::error(_("Conversion script not found"),
806 bformat(_("%1$s is from a different"
807 " version of LyX, but the"
808 " conversion script lyx2lyx"
809 " could not be found."),
810 from_utf8(filename.absFilename())));
813 ostringstream command;
814 command << os::python()
815 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
816 << " -t " << convert<string>(LYX_FORMAT)
817 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
818 << ' ' << quoteName(filename.toFilesystemEncoding());
819 string const command_str = command.str();
821 LYXERR(Debug::INFO) << "Running '"
822 << command_str << '\''
825 cmd_ret const ret = runCommand(command_str);
826 if (ret.first != 0) {
827 Alert::error(_("Conversion script failed"),
828 bformat(_("%1$s is from a different version"
829 " of LyX, but the lyx2lyx script"
830 " failed to convert it."),
831 from_utf8(filename.absFilename())));
834 bool const ret = readFile(tmpfile);
835 // Do stuff with tmpfile name and buffer name here.
836 return ret ? success : failure;
841 if (readDocument(lex)) {
842 Alert::error(_("Document format failure"),
843 bformat(_("%1$s ended unexpectedly, which means"
844 " that it is probably corrupted."),
845 from_utf8(filename.absFilename())));
848 //lyxerr << "removing " << MacroTable::localMacros().size()
849 // << " temporary macro entries" << endl;
850 //MacroTable::localMacros().clear();
852 pimpl_->file_fully_loaded = true;
857 // Should probably be moved to somewhere else: BufferView? LyXView?
858 bool Buffer::save() const
860 // We don't need autosaves in the immediate future. (Asger)
861 resetAutosaveTimers();
863 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
866 bool madeBackup = false;
868 // make a backup if the file already exists
869 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
870 backupName = FileName(fileName() + '~');
871 if (!lyxrc.backupdir_path.empty())
872 backupName = FileName(addName(lyxrc.backupdir_path,
873 subst(os::internal_path(backupName.absFilename()), '/', '!')));
876 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
878 } catch (fs::filesystem_error const & fe) {
879 Alert::error(_("Backup failure"),
880 bformat(_("Cannot create backup file %1$s.\n"
881 "Please check whether the directory exists and is writeable."),
882 from_utf8(backupName.absFilename())));
883 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
887 // ask if the disk file has been externally modified (use checksum method)
888 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
889 docstring const file = makeDisplayPath(fileName(), 20);
890 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
891 "you want to overwrite this file?"), file);
892 int const ret = Alert::prompt(_("Overwrite modified file?"),
893 text, 1, 1, _("&Overwrite"), _("&Cancel"));
898 if (writeFile(pimpl_->filename)) {
900 removeAutosaveFile(fileName());
901 saveCheckSum(pimpl_->filename.toFilesystemEncoding());
904 // Saving failed, so backup is not backup
906 rename(backupName, pimpl_->filename);
912 bool Buffer::writeFile(FileName const & fname) const
914 if (pimpl_->read_only && fname == pimpl_->filename)
920 if (params().embedded)
921 // first write the .lyx file to the temporary directory
922 content = FileName(addName(temppath(), "content.lyx"));
926 if (params().compressed) {
927 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
933 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
940 if (retval && params().embedded) {
941 // write file.lyx and all the embedded files to the zip file fname
942 // if embedding is enabled
943 return pimpl_->embedded_files.writeFile(fname);
949 bool Buffer::write(ostream & ofs) const
952 // Use the standard "C" locale for file output.
953 ofs.imbue(std::locale::classic());
956 // The top of the file should not be written by params().
958 // write out a comment in the top of the file
959 ofs << "#LyX " << lyx_version
960 << " created this file. For more info see http://www.lyx.org/\n"
961 << "\\lyxformat " << LYX_FORMAT << "\n"
962 << "\\begin_document\n";
965 /// For each author, set 'used' to true if there is a change
966 /// by this author in the document; otherwise set it to 'false'.
967 AuthorList::Authors::const_iterator a_it = params().authors().begin();
968 AuthorList::Authors::const_iterator a_end = params().authors().end();
969 for (; a_it != a_end; ++a_it)
970 a_it->second.used(false);
972 ParIterator const end = par_iterator_end();
973 ParIterator it = par_iterator_begin();
974 for ( ; it != end; ++it)
975 it->checkAuthors(params().authors());
977 // now write out the buffer parameters.
978 ofs << "\\begin_header\n";
979 params().writeFile(ofs);
980 ofs << "\\end_header\n";
982 // write the manifest after header
983 ofs << "\n\\begin_manifest\n";
984 pimpl_->embedded_files.update();
985 embeddedFiles().writeManifest(ofs);
986 ofs << "\\end_manifest\n";
989 ofs << "\n\\begin_body\n";
990 text().write(*this, ofs);
991 ofs << "\n\\end_body\n";
993 // Write marker that shows file is complete
994 ofs << "\\end_document" << endl;
996 // Shouldn't really be needed....
999 // how to check if close went ok?
1000 // Following is an attempt... (BE 20001011)
1002 // good() returns false if any error occured, including some
1003 // formatting error.
1004 // bad() returns true if something bad happened in the buffer,
1005 // which should include file system full errors.
1010 lyxerr << "File was not closed properly." << endl;
1017 bool Buffer::makeLaTeXFile(FileName const & fname,
1018 string const & original_path,
1019 OutputParams const & runparams,
1020 bool output_preamble, bool output_body)
1022 string const encoding = runparams.encoding->iconvName();
1023 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
1024 << encoding << "..." << endl;
1026 odocfstream ofs(encoding);
1027 if (!openFileWrite(ofs, fname))
1030 //TexStream ts(ofs.rdbuf(), &texrow());
1032 bool failed_export = false;
1035 writeLaTeXSource(ofs, original_path,
1036 runparams, output_preamble, output_body);
1038 catch (iconv_codecvt_facet_exception & e) {
1039 lyxerr << "Caught iconv exception: " << e.what() << endl;
1040 failed_export = true;
1042 catch (std::exception const & e) {
1043 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1044 failed_export = true;
1047 lyxerr << "Caught some really weird exception..." << endl;
1048 LyX::cref().emergencyCleanup();
1054 failed_export = true;
1055 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1058 if (failed_export) {
1059 Alert::error(_("Encoding error"),
1060 _("Some characters of your document are probably not "
1061 "representable in the chosen encoding.\n"
1062 "Changing the document encoding to utf8 could help."));
1069 void Buffer::writeLaTeXSource(odocstream & os,
1070 string const & original_path,
1071 OutputParams const & runparams_in,
1072 bool const output_preamble, bool const output_body)
1074 OutputParams runparams = runparams_in;
1076 // validate the buffer.
1077 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
1078 LaTeXFeatures features(*this, params(), runparams);
1080 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
1082 // The starting paragraph of the coming rows is the
1083 // first paragraph of the document. (Asger)
1084 if (output_preamble && runparams.nice) {
1085 os << "%% LyX " << lyx_version << " created this file. "
1086 "For more info, see http://www.lyx.org/.\n"
1087 "%% Do not edit unless you really know what "
1092 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1093 // There are a few differences between nice LaTeX and usual files:
1094 // usual is \batchmode and has a
1095 // special input@path to allow the including of figures
1096 // with either \input or \includegraphics (what figinsets do).
1097 // input@path is set when the actual parameter
1098 // original_path is set. This is done for usual tex-file, but not
1099 // for nice-latex-file. (Matthias 250696)
1100 // Note that input@path is only needed for something the user does
1101 // in the preamble, included .tex files or ERT, files included by
1102 // LyX work without it.
1103 if (output_preamble) {
1104 if (!runparams.nice) {
1105 // code for usual, NOT nice-latex-file
1106 os << "\\batchmode\n"; // changed
1107 // from \nonstopmode
1110 if (!original_path.empty()) {
1112 // We don't know the encoding of inputpath
1113 docstring const inputpath = from_utf8(latex_path(original_path));
1114 os << "\\makeatletter\n"
1115 << "\\def\\input@path{{"
1116 << inputpath << "/}}\n"
1117 << "\\makeatother\n";
1123 // Write the preamble
1124 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1130 os << "\\begin{document}\n";
1132 } // output_preamble
1134 texrow().start(paragraphs().begin()->id(), 0);
1136 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1138 if (!lyxrc.language_auto_begin &&
1139 !params().language->babel().empty()) {
1141 os << from_utf8(subst(lyxrc.language_command_begin,
1143 params().language->babel()))
1148 Encoding const & encoding = params().encoding();
1149 if (encoding.package() == Encoding::CJK) {
1150 // Open a CJK environment, since in contrast to the encodings
1151 // handled by inputenc the document encoding is not set in
1152 // the preamble if it is handled by CJK.sty.
1153 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1158 // if we are doing a real file with body, even if this is the
1159 // child of some other buffer, let's cut the link here.
1160 // This happens for example if only a child document is printed.
1161 string save_parentname;
1162 if (output_preamble) {
1163 save_parentname = params().parentname;
1164 params().parentname.erase();
1167 loadChildDocuments(*this);
1170 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1172 // Restore the parenthood if needed
1173 if (output_preamble)
1174 params().parentname = save_parentname;
1176 // add this just in case after all the paragraphs
1180 if (encoding.package() == Encoding::CJK) {
1181 // Close the open CJK environment.
1182 // latexParagraphs will have opened one even if the last text
1184 os << "\\end{CJK}\n";
1188 if (!lyxrc.language_auto_end &&
1189 !params().language->babel().empty()) {
1190 os << from_utf8(subst(lyxrc.language_command_end,
1192 params().language->babel()))
1197 if (output_preamble) {
1198 os << "\\end{document}\n";
1201 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1203 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1206 runparams_in.encoding = runparams.encoding;
1208 // Just to be sure. (Asger)
1211 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1212 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1217 bool Buffer::isLatex() const
1219 return params().getTextClass().outputType() == LATEX;
1223 bool Buffer::isLiterate() const
1225 return params().getTextClass().outputType() == LITERATE;
1229 bool Buffer::isDocBook() const
1231 return params().getTextClass().outputType() == DOCBOOK;
1235 void Buffer::makeDocBookFile(FileName const & fname,
1236 OutputParams const & runparams,
1237 bool const body_only)
1239 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1243 if (!openFileWrite(ofs, fname))
1246 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1250 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1254 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1255 OutputParams const & runparams,
1256 bool const only_body)
1258 LaTeXFeatures features(*this, params(), runparams);
1263 TextClass const & tclass = params().getTextClass();
1264 string const top_element = tclass.latexname();
1267 if (runparams.flavor == OutputParams::XML)
1268 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1271 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1274 if (! tclass.class_header().empty())
1275 os << from_ascii(tclass.class_header());
1276 else if (runparams.flavor == OutputParams::XML)
1277 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1278 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1280 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1282 docstring preamble = from_utf8(params().preamble);
1283 if (runparams.flavor != OutputParams::XML ) {
1284 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1285 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1286 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1287 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1290 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1292 preamble += features.getIncludedFiles(name);
1293 preamble += features.getLyXSGMLEntities();
1295 if (!preamble.empty()) {
1296 os << "\n [ " << preamble << " ]";
1301 string top = top_element;
1303 if (runparams.flavor == OutputParams::XML)
1304 top += params().language->code();
1306 top += params().language->code().substr(0,2);
1309 if (!params().options.empty()) {
1311 top += params().options;
1314 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1315 << " file was created by LyX " << lyx_version
1316 << "\n See http://www.lyx.org/ for more information -->\n";
1318 params().getTextClass().counters().reset();
1320 loadChildDocuments(*this);
1322 sgml::openTag(os, top);
1324 docbookParagraphs(paragraphs(), *this, os, runparams);
1325 sgml::closeTag(os, top_element);
1329 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1330 // Other flags: -wall -v0 -x
1331 int Buffer::runChktex()
1335 // get LaTeX-Filename
1336 FileName const path(temppath());
1337 string const name = addName(path.absFilename(), getLatexName());
1338 string const org_path = filePath();
1340 support::Path p(path); // path to LaTeX file
1341 message(_("Running chktex..."));
1343 // Generate the LaTeX file if neccessary
1344 OutputParams runparams(¶ms().encoding());
1345 runparams.flavor = OutputParams::LATEX;
1346 runparams.nice = false;
1347 makeLaTeXFile(FileName(name), org_path, runparams);
1350 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1351 int const res = chktex.run(terr); // run chktex
1354 Alert::error(_("chktex failure"),
1355 _("Could not run chktex successfully."));
1356 } else if (res > 0) {
1357 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1358 // Clear out old errors
1360 // Fill-in the error list with the TeX errors
1361 bufferErrors(*this, terr, errorList);
1372 void Buffer::validate(LaTeXFeatures & features) const
1374 TextClass const & tclass = params().getTextClass();
1376 if (params().outputChanges) {
1377 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1378 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1379 LaTeXFeatures::isAvailable("xcolor");
1381 if (features.runparams().flavor == OutputParams::LATEX) {
1383 features.require("ct-dvipost");
1384 features.require("dvipost");
1385 } else if (xcolorsoul) {
1386 features.require("ct-xcolor-soul");
1387 features.require("soul");
1388 features.require("xcolor");
1390 features.require("ct-none");
1392 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1394 features.require("ct-xcolor-soul");
1395 features.require("soul");
1396 features.require("xcolor");
1397 features.require("pdfcolmk"); // improves color handling in PDF output
1399 features.require("ct-none");
1404 // AMS Style is at document level
1405 if (params().use_amsmath == BufferParams::package_on
1406 || tclass.provides("amsmath"))
1407 features.require("amsmath");
1408 if (params().use_esint == BufferParams::package_on)
1409 features.require("esint");
1411 loadChildDocuments(*this);
1413 for_each(paragraphs().begin(), paragraphs().end(),
1414 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1416 // the bullet shapes are buffer level not paragraph level
1417 // so they are tested here
1418 for (int i = 0; i < 4; ++i) {
1419 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1420 int const font = params().user_defined_bullet(i).getFont();
1422 int const c = params()
1423 .user_defined_bullet(i)
1430 features.require("latexsym");
1432 } else if (font == 1) {
1433 features.require("amssymb");
1434 } else if ((font >= 2 && font <= 5)) {
1435 features.require("pifont");
1440 if (lyxerr.debugging(Debug::LATEX)) {
1441 features.showStruct();
1446 void Buffer::getLabelList(vector<docstring> & list) const
1448 /// if this is a child document and the parent is already loaded
1449 /// Use the parent's list instead [ale990407]
1450 Buffer const * tmp = getMasterBuffer();
1452 lyxerr << "getMasterBuffer() failed!" << endl;
1456 tmp->getLabelList(list);
1460 loadChildDocuments(*this);
1462 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1463 it.nextInset()->getLabelList(*this, list);
1467 void Buffer::updateBibfilesCache()
1469 // if this is a child document and the parent is already loaded
1470 // update the parent's cache instead
1471 Buffer * tmp = getMasterBuffer();
1474 tmp->updateBibfilesCache();
1478 bibfilesCache_.clear();
1479 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1480 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1481 InsetBibtex const & inset =
1482 static_cast<InsetBibtex const &>(*it);
1483 vector<FileName> const bibfiles = inset.getFiles(*this);
1484 bibfilesCache_.insert(bibfilesCache_.end(),
1487 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1488 InsetInclude & inset =
1489 static_cast<InsetInclude &>(*it);
1490 inset.updateBibfilesCache(*this);
1491 vector<FileName> const & bibfiles =
1492 inset.getBibfilesCache(*this);
1493 bibfilesCache_.insert(bibfilesCache_.end(),
1501 vector<FileName> const & Buffer::getBibfilesCache() const
1503 // if this is a child document and the parent is already loaded
1504 // use the parent's cache instead
1505 Buffer const * tmp = getMasterBuffer();
1508 return tmp->getBibfilesCache();
1510 // We update the cache when first used instead of at loading time.
1511 if (bibfilesCache_.empty())
1512 const_cast<Buffer *>(this)->updateBibfilesCache();
1514 return bibfilesCache_;
1518 bool Buffer::isDepClean(string const & name) const
1520 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1521 if (it == pimpl_->dep_clean.end())
1527 void Buffer::markDepClean(string const & name)
1529 pimpl_->dep_clean[name] = true;
1533 bool Buffer::dispatch(string const & command, bool * result)
1535 return dispatch(lyxaction.lookupFunc(command), result);
1539 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1541 bool dispatched = true;
1543 switch (func.action) {
1544 case LFUN_BUFFER_EXPORT: {
1545 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1558 void Buffer::changeLanguage(Language const * from, Language const * to)
1563 for_each(par_iterator_begin(),
1565 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1569 bool Buffer::isMultiLingual() const
1571 ParConstIterator end = par_iterator_end();
1572 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1573 if (it->isMultiLingual(params()))
1580 ParIterator Buffer::getParFromID(int const id) const
1582 ParConstIterator it = par_iterator_begin();
1583 ParConstIterator const end = par_iterator_end();
1586 // John says this is called with id == -1 from undo
1587 lyxerr << "getParFromID(), id: " << id << endl;
1591 for (; it != end; ++it)
1599 bool Buffer::hasParWithID(int const id) const
1601 ParConstIterator const it = getParFromID(id);
1602 return it != par_iterator_end();
1606 ParIterator Buffer::par_iterator_begin()
1608 return lyx::par_iterator_begin(inset());
1612 ParIterator Buffer::par_iterator_end()
1614 return lyx::par_iterator_end(inset());
1618 ParConstIterator Buffer::par_iterator_begin() const
1620 return lyx::par_const_iterator_begin(inset());
1624 ParConstIterator Buffer::par_iterator_end() const
1626 return lyx::par_const_iterator_end(inset());
1630 Language const * Buffer::getLanguage() const
1632 return params().language;
1636 docstring const Buffer::B_(string const & l10n) const
1638 return params().B_(l10n);
1642 bool Buffer::isClean() const
1644 return pimpl_->lyx_clean;
1648 bool Buffer::isBakClean() const
1650 return pimpl_->bak_clean;
1654 bool Buffer::isExternallyModified(CheckMethod method) const
1656 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1657 // if method == timestamp, check timestamp before checksum
1658 return (method == checksum_method
1659 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1660 && pimpl_->checksum_ != sum(pimpl_->filename);
1664 void Buffer::saveCheckSum(string const & file) const
1666 if (fs::exists(file)) {
1667 pimpl_->timestamp_ = fs::last_write_time(file);
1668 pimpl_->checksum_ = sum(FileName(file));
1670 // in the case of save to a new file.
1671 pimpl_->timestamp_ = 0;
1672 pimpl_->checksum_ = 0;
1677 void Buffer::markClean() const
1679 if (!pimpl_->lyx_clean) {
1680 pimpl_->lyx_clean = true;
1683 // if the .lyx file has been saved, we don't need an
1685 pimpl_->bak_clean = true;
1689 void Buffer::markBakClean()
1691 pimpl_->bak_clean = true;
1695 void Buffer::setUnnamed(bool flag)
1697 pimpl_->unnamed = flag;
1701 bool Buffer::isUnnamed() const
1703 return pimpl_->unnamed;
1707 // FIXME: this function should be moved to buffer_pimpl.C
1708 void Buffer::markDirty()
1710 if (pimpl_->lyx_clean) {
1711 pimpl_->lyx_clean = false;
1714 pimpl_->bak_clean = false;
1716 DepClean::iterator it = pimpl_->dep_clean.begin();
1717 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1719 for (; it != end; ++it)
1724 string const Buffer::fileName() const
1726 return pimpl_->filename.absFilename();
1730 string const & Buffer::filePath() const
1732 return params().filepath;
1736 bool Buffer::isReadonly() const
1738 return pimpl_->read_only;
1742 void Buffer::setParentName(string const & name)
1744 if (name == pimpl_->filename.absFilename())
1745 // Avoids recursive include.
1746 params().parentname.clear();
1748 params().parentname = name;
1752 Buffer const * Buffer::getMasterBuffer() const
1754 if (!params().parentname.empty()
1755 && theBufferList().exists(params().parentname)) {
1756 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1757 //We need to check if the parent is us...
1758 //FIXME RECURSIVE INCLUDE
1759 //This is not sufficient, since recursive includes could be downstream.
1760 if (buf && buf != this)
1761 return buf->getMasterBuffer();
1768 Buffer * Buffer::getMasterBuffer()
1770 if (!params().parentname.empty()
1771 && theBufferList().exists(params().parentname)) {
1772 Buffer * buf = theBufferList().getBuffer(params().parentname);
1773 //We need to check if the parent is us...
1774 //FIXME RECURSIVE INCLUDE
1775 //This is not sufficient, since recursive includes could be downstream.
1776 if (buf && buf != this)
1777 return buf->getMasterBuffer();
1784 MacroData const & Buffer::getMacro(docstring const & name) const
1786 return pimpl_->macros.get(name);
1790 bool Buffer::hasMacro(docstring const & name) const
1792 return pimpl_->macros.has(name);
1796 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1798 MacroTable::globalMacros().insert(name, data);
1799 pimpl_->macros.insert(name, data);
1803 void Buffer::buildMacros()
1805 // Start with global table.
1806 pimpl_->macros = MacroTable::globalMacros();
1809 ParagraphList const & pars = text().paragraphs();
1810 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1811 //lyxerr << "searching main par " << i
1812 // << " for macro definitions" << std::endl;
1813 InsetList const & insets = pars[i].insetlist;
1814 InsetList::const_iterator it = insets.begin();
1815 InsetList::const_iterator end = insets.end();
1816 for ( ; it != end; ++it) {
1817 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1818 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1819 MathMacroTemplate const & mac
1820 = static_cast<MathMacroTemplate const &>(*it->inset);
1821 insertMacro(mac.name(), mac.asMacroData());
1828 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1831 //FIXME: This does not work for child documents yet.
1832 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1833 // Check if the label 'from' appears more than once
1834 vector<docstring> labels;
1836 if (code == Inset::CITE_CODE) {
1838 keys.fillWithBibKeys(this);
1839 BiblioInfo::const_iterator bit = keys.begin();
1840 BiblioInfo::const_iterator bend = keys.end();
1842 for (; bit != bend; ++bit)
1844 labels.push_back(bit->first);
1846 getLabelList(labels);
1848 if (std::count(labels.begin(), labels.end(), from) > 1)
1851 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1852 if (it->lyxCode() == code) {
1853 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1854 inset.replaceContents(to_utf8(from), to_utf8(to));
1860 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1861 pit_type par_end, bool full_source)
1863 OutputParams runparams(¶ms().encoding());
1864 runparams.nice = true;
1865 runparams.flavor = OutputParams::LATEX;
1866 runparams.linelen = lyxrc.plaintext_linelen;
1867 // No side effect of file copying and image conversion
1868 runparams.dryrun = true;
1872 os << "% " << _("Preview source code") << "\n\n";
1876 writeLaTeXSource(os, filePath(), runparams, true, true);
1878 writeDocBookSource(os, fileName(), runparams, false);
1881 runparams.par_begin = par_begin;
1882 runparams.par_end = par_end;
1883 if (par_begin + 1 == par_end)
1885 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1889 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1890 convert<docstring>(par_begin),
1891 convert<docstring>(par_end - 1))
1895 // output paragraphs
1897 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1900 docbookParagraphs(paragraphs(), *this, os, runparams);
1906 ErrorList const & Buffer::errorList(string const & type) const
1908 static ErrorList const emptyErrorList;
1909 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1910 if (I == pimpl_->errorLists.end())
1911 return emptyErrorList;
1917 ErrorList & Buffer::errorList(string const & type)
1919 return pimpl_->errorLists[type];
1923 void Buffer::structureChanged() const
1926 gui_->structureChanged();
1930 void Buffer::embeddingChanged() const
1933 gui_->embeddingChanged();
1937 void Buffer::errors(std::string const & err) const
1944 void Buffer::message(docstring const & msg) const
1951 void Buffer::busy(bool on) const
1958 void Buffer::readonly(bool on) const
1965 void Buffer::updateTitles() const
1968 gui_->updateTitles();
1972 void Buffer::resetAutosaveTimers() const
1975 gui_->resetAutosaveTimers();
1979 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)