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
281 BOOST_ASSERT(pimpl_->wa_);
286 Text & Buffer::text() const
288 return const_cast<Text &>(pimpl_->inset.text_);
292 Inset & Buffer::inset() const
294 return const_cast<InsetText &>(pimpl_->inset);
298 limited_stack<Undo> & Buffer::undostack()
300 return pimpl_->undostack;
304 limited_stack<Undo> const & Buffer::undostack() const
306 return pimpl_->undostack;
310 limited_stack<Undo> & Buffer::redostack()
312 return pimpl_->redostack;
316 limited_stack<Undo> const & Buffer::redostack() const
318 return pimpl_->redostack;
322 BufferParams & Buffer::params()
324 return pimpl_->params;
328 BufferParams const & Buffer::params() const
330 return pimpl_->params;
334 ParagraphList & Buffer::paragraphs()
336 return text().paragraphs();
340 ParagraphList const & Buffer::paragraphs() const
342 return text().paragraphs();
346 LyXVC & Buffer::lyxvc()
348 return pimpl_->lyxvc;
352 LyXVC const & Buffer::lyxvc() const
354 return pimpl_->lyxvc;
358 string const & Buffer::temppath() const
360 return pimpl_->temppath;
364 TexRow & Buffer::texrow()
366 return pimpl_->texrow;
370 TexRow const & Buffer::texrow() const
372 return pimpl_->texrow;
376 TocBackend & Buffer::tocBackend()
378 return pimpl_->toc_backend;
382 TocBackend const & Buffer::tocBackend() const
384 return pimpl_->toc_backend;
388 EmbeddedFiles & Buffer::embeddedFiles()
390 return pimpl_->embedded_files;
394 EmbeddedFiles const & Buffer::embeddedFiles() const
396 return pimpl_->embedded_files;
400 string const Buffer::getLatexName(bool const no_path) const
402 string const name = changeExtension(makeLatexName(fileName()), ".tex");
403 return no_path ? onlyFilename(name) : name;
407 pair<Buffer::LogType, string> const Buffer::getLogName() const
409 string const filename = getLatexName(false);
411 if (filename.empty())
412 return make_pair(Buffer::latexlog, string());
414 string const path = temppath();
416 FileName const fname(addName(temppath(),
417 onlyFilename(changeExtension(filename,
419 FileName const bname(
420 addName(path, onlyFilename(
421 changeExtension(filename,
422 formats.extension("literate") + ".out"))));
424 // If no Latex log or Build log is newer, show Build log
426 if (fs::exists(bname.toFilesystemEncoding()) &&
427 (!fs::exists(fname.toFilesystemEncoding()) ||
428 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
429 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
430 return make_pair(Buffer::buildlog, bname.absFilename());
432 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
433 return make_pair(Buffer::latexlog, fname.absFilename());
437 void Buffer::setReadonly(bool const flag)
439 if (pimpl_->read_only != flag) {
440 pimpl_->read_only = flag;
446 void Buffer::setFileName(string const & newfile)
448 pimpl_->filename = makeAbsPath(newfile);
449 params().filepath = onlyPath(pimpl_->filename.absFilename());
450 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
455 // We'll remove this later. (Lgb)
458 void unknownClass(string const & unknown)
460 Alert::warning(_("Unknown document class"),
461 bformat(_("Using the default document class, because the "
462 "class %1$s is unknown."), from_utf8(unknown)));
468 int Buffer::readHeader(Lexer & lex)
470 int unknown_tokens = 0;
472 int begin_header_line = -1;
474 // Initialize parameters that may be/go lacking in header:
475 params().branchlist().clear();
476 params().preamble.erase();
477 params().options.erase();
478 params().float_placement.erase();
479 params().paperwidth.erase();
480 params().paperheight.erase();
481 params().leftmargin.erase();
482 params().rightmargin.erase();
483 params().topmargin.erase();
484 params().bottommargin.erase();
485 params().headheight.erase();
486 params().headsep.erase();
487 params().footskip.erase();
488 params().listings_params.clear();
489 params().clearLayoutModules();
490 params().pdfoptions().clear();
492 for (int i = 0; i < 4; ++i) {
493 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
494 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
497 ErrorList & errorList = pimpl_->errorLists["Parse"];
501 string const token = lex.getString();
506 if (token == "\\end_header")
510 if (token == "\\begin_header") {
511 begin_header_line = line;
515 LYXERR(Debug::PARSER) << "Handling document header token: `"
516 << token << '\'' << endl;
518 string unknown = params().readToken(lex, token);
519 if (!unknown.empty()) {
520 if (unknown[0] != '\\' && token == "\\textclass") {
521 unknownClass(unknown);
524 docstring const s = bformat(_("Unknown token: "
528 errorList.push_back(ErrorItem(_("Document header error"),
533 if (begin_header_line) {
534 docstring const s = _("\\begin_header is missing");
535 errorList.push_back(ErrorItem(_("Document header error"),
539 return unknown_tokens;
544 // changed to be public and have one parameter
545 // Returns false if "\end_document" is not read (Asger)
546 bool Buffer::readDocument(Lexer & lex)
548 ErrorList & errorList = pimpl_->errorLists["Parse"];
552 string const token = lex.getString();
553 if (token != "\\begin_document") {
554 docstring const s = _("\\begin_document is missing");
555 errorList.push_back(ErrorItem(_("Document header error"),
559 // we are reading in a brand new document
560 BOOST_ASSERT(paragraphs().empty());
563 TextClass const & baseClass = textclasslist[params().getBaseClass()];
564 if (!baseClass.load(filePath())) {
565 string theclass = baseClass.name();
566 Alert::error(_("Can't load document class"), bformat(
567 _("Using the default document class, because the "
568 "class %1$s could not be loaded."), from_utf8(theclass)));
569 params().setBaseClass(defaultTextclass());
572 if (params().outputChanges) {
573 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
574 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
575 LaTeXFeatures::isAvailable("xcolor");
577 if (!dvipost && !xcolorsoul) {
578 Alert::warning(_("Changes not shown in LaTeX output"),
579 _("Changes will not be highlighted in LaTeX output, "
580 "because neither dvipost nor xcolor/soul are installed.\n"
581 "Please install these packages or redefine "
582 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
583 } else if (!xcolorsoul) {
584 Alert::warning(_("Changes not shown in LaTeX output"),
585 _("Changes will not be highlighted in LaTeX output "
586 "when using pdflatex, because xcolor and soul are not installed.\n"
587 "Please install both packages or redefine "
588 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
591 // read manifest after header
592 embeddedFiles().readManifest(lex, errorList);
595 bool const res = text().read(*this, lex, errorList);
596 for_each(text().paragraphs().begin(),
597 text().paragraphs().end(),
598 bind(&Paragraph::setInsetOwner, _1, &inset()));
604 // needed to insert the selection
605 void Buffer::insertStringAsLines(ParagraphList & pars,
606 pit_type & pit, pos_type & pos,
607 Font const & fn, docstring const & str, bool autobreakrows)
611 // insert the string, don't insert doublespace
612 bool space_inserted = true;
613 for (docstring::const_iterator cit = str.begin();
614 cit != str.end(); ++cit) {
615 Paragraph & par = pars[pit];
617 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
618 breakParagraph(params(), pars, pit, pos,
619 par.layout()->isEnvironment());
622 space_inserted = true;
626 // do not insert consecutive spaces if !free_spacing
627 } else if ((*cit == ' ' || *cit == '\t') &&
628 space_inserted && !par.isFreeSpacing()) {
630 } else if (*cit == '\t') {
631 if (!par.isFreeSpacing()) {
632 // tabs are like spaces here
633 par.insertChar(pos, ' ', font, params().trackChanges);
635 space_inserted = true;
637 const pos_type n = 8 - pos % 8;
638 for (pos_type i = 0; i < n; ++i) {
639 par.insertChar(pos, ' ', font, params().trackChanges);
642 space_inserted = true;
644 } else if (!isPrintable(*cit)) {
645 // Ignore unprintables
648 // just insert the character
649 par.insertChar(pos, *cit, font, params().trackChanges);
651 space_inserted = (*cit == ' ');
658 bool Buffer::readString(std::string const & s)
660 params().compressed = false;
662 // remove dummy empty par
663 paragraphs().clear();
665 std::istringstream is(s);
667 FileName const name(tempName());
668 switch (readFile(lex, name, true)) {
672 // We need to call lyx2lyx, so write the input to a file
673 std::ofstream os(name.toFilesystemEncoding().c_str());
676 return readFile(name);
686 bool Buffer::readFile(FileName const & filename)
688 FileName fname(filename);
689 // Check if the file is compressed.
690 string format = getFormatFromContents(filename);
691 if (format == "zip") {
692 // decompress to a temp directory
693 LYXERR(Debug::FILES) << filename << " is in zip format. Unzip to " << temppath() << endl;
694 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
696 FileName lyxfile(addName(temppath(), "content.lyx"));
697 // if both manifest.txt and file.lyx exist, this is am embedded file
698 if (fs::exists(lyxfile.toFilesystemEncoding())) {
699 params().embedded = true;
703 // The embedded lyx file can also be compressed, for backward compatibility
704 format = getFormatFromContents(fname);
705 if (format == "gzip" || format == "zip" || format == "compress") {
706 params().compressed = true;
709 // remove dummy empty par
710 paragraphs().clear();
713 if (readFile(lex, fname) != success)
720 bool Buffer::fully_loaded() const
722 return pimpl_->file_fully_loaded;
726 void Buffer::fully_loaded(bool const value)
728 pimpl_->file_fully_loaded = value;
732 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
735 BOOST_ASSERT(!filename.empty());
738 Alert::error(_("Document could not be read"),
739 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
744 string const token(lex.getString());
747 Alert::error(_("Document could not be read"),
748 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
752 // the first token _must_ be...
753 if (token != "\\lyxformat") {
754 lyxerr << "Token: " << token << endl;
756 Alert::error(_("Document format failure"),
757 bformat(_("%1$s is not a LyX document."),
758 from_utf8(filename.absFilename())));
763 string tmp_format = lex.getString();
764 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
765 // if present remove ".," from string.
766 string::size_type dot = tmp_format.find_first_of(".,");
767 //lyxerr << " dot found at " << dot << endl;
768 if (dot != string::npos)
769 tmp_format.erase(dot, 1);
770 int const file_format = convert<int>(tmp_format);
771 //lyxerr << "format: " << file_format << endl;
773 // save timestamp and checksum of the original disk file, making sure
774 // to not overwrite them with those of the file created in the tempdir
775 // when it has to be converted to the current format.
776 if (!pimpl_->checksum_) {
777 // Save the timestamp and checksum of disk file. If filename is an
778 // emergency file, save the timestamp and sum of the original lyx file
779 // because isExternallyModified will check for this file. (BUG4193)
780 string diskfile = filename.toFilesystemEncoding();
781 if (suffixIs(diskfile, ".emergency"))
782 diskfile = diskfile.substr(0, diskfile.size() - 10);
783 saveCheckSum(diskfile);
786 if (file_format != LYX_FORMAT) {
789 // lyx2lyx would fail
792 FileName const tmpfile(tempName());
793 if (tmpfile.empty()) {
794 Alert::error(_("Conversion failed"),
795 bformat(_("%1$s is from a different"
796 " version of LyX, but a temporary"
797 " file for converting it could"
799 from_utf8(filename.absFilename())));
802 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
803 if (lyx2lyx.empty()) {
804 Alert::error(_("Conversion script not found"),
805 bformat(_("%1$s is from a different"
806 " version of LyX, but the"
807 " conversion script lyx2lyx"
808 " could not be found."),
809 from_utf8(filename.absFilename())));
812 ostringstream command;
813 command << os::python()
814 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
815 << " -t " << convert<string>(LYX_FORMAT)
816 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
817 << ' ' << quoteName(filename.toFilesystemEncoding());
818 string const command_str = command.str();
820 LYXERR(Debug::INFO) << "Running '"
821 << command_str << '\''
824 cmd_ret const ret = runCommand(command_str);
825 if (ret.first != 0) {
826 Alert::error(_("Conversion script failed"),
827 bformat(_("%1$s is from a different version"
828 " of LyX, but the lyx2lyx script"
829 " failed to convert it."),
830 from_utf8(filename.absFilename())));
833 bool const ret = readFile(tmpfile);
834 // Do stuff with tmpfile name and buffer name here.
835 return ret ? success : failure;
840 if (readDocument(lex)) {
841 Alert::error(_("Document format failure"),
842 bformat(_("%1$s ended unexpectedly, which means"
843 " that it is probably corrupted."),
844 from_utf8(filename.absFilename())));
847 //lyxerr << "removing " << MacroTable::localMacros().size()
848 // << " temporary macro entries" << endl;
849 //MacroTable::localMacros().clear();
851 pimpl_->file_fully_loaded = true;
856 // Should probably be moved to somewhere else: BufferView? LyXView?
857 bool Buffer::save() const
859 // We don't need autosaves in the immediate future. (Asger)
860 resetAutosaveTimers();
862 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
865 bool madeBackup = false;
867 // make a backup if the file already exists
868 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
869 backupName = FileName(fileName() + '~');
870 if (!lyxrc.backupdir_path.empty())
871 backupName = FileName(addName(lyxrc.backupdir_path,
872 subst(os::internal_path(backupName.absFilename()), '/', '!')));
875 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
877 } catch (fs::filesystem_error const & fe) {
878 Alert::error(_("Backup failure"),
879 bformat(_("Cannot create backup file %1$s.\n"
880 "Please check whether the directory exists and is writeable."),
881 from_utf8(backupName.absFilename())));
882 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
886 // ask if the disk file has been externally modified (use checksum method)
887 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
888 docstring const file = makeDisplayPath(fileName(), 20);
889 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
890 "you want to overwrite this file?"), file);
891 int const ret = Alert::prompt(_("Overwrite modified file?"),
892 text, 1, 1, _("&Overwrite"), _("&Cancel"));
897 if (writeFile(pimpl_->filename)) {
899 removeAutosaveFile(fileName());
900 saveCheckSum(pimpl_->filename.toFilesystemEncoding());
903 // Saving failed, so backup is not backup
905 rename(backupName, pimpl_->filename);
911 bool Buffer::writeFile(FileName const & fname) const
913 if (pimpl_->read_only && fname == pimpl_->filename)
919 if (params().embedded)
920 // first write the .lyx file to the temporary directory
921 content = FileName(addName(temppath(), "content.lyx"));
925 if (params().compressed) {
926 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
932 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
939 if (retval && params().embedded) {
940 // write file.lyx and all the embedded files to the zip file fname
941 // if embedding is enabled
942 return pimpl_->embedded_files.writeFile(fname);
948 bool Buffer::write(ostream & ofs) const
951 // Use the standard "C" locale for file output.
952 ofs.imbue(std::locale::classic());
955 // The top of the file should not be written by params().
957 // write out a comment in the top of the file
958 ofs << "#LyX " << lyx_version
959 << " created this file. For more info see http://www.lyx.org/\n"
960 << "\\lyxformat " << LYX_FORMAT << "\n"
961 << "\\begin_document\n";
964 /// For each author, set 'used' to true if there is a change
965 /// by this author in the document; otherwise set it to 'false'.
966 AuthorList::Authors::const_iterator a_it = params().authors().begin();
967 AuthorList::Authors::const_iterator a_end = params().authors().end();
968 for (; a_it != a_end; ++a_it)
969 a_it->second.used(false);
971 ParIterator const end = par_iterator_end();
972 ParIterator it = par_iterator_begin();
973 for ( ; it != end; ++it)
974 it->checkAuthors(params().authors());
976 // now write out the buffer parameters.
977 ofs << "\\begin_header\n";
978 params().writeFile(ofs);
979 ofs << "\\end_header\n";
981 // write the manifest after header
982 ofs << "\n\\begin_manifest\n";
983 pimpl_->embedded_files.update();
984 embeddedFiles().writeManifest(ofs);
985 ofs << "\\end_manifest\n";
988 ofs << "\n\\begin_body\n";
989 text().write(*this, ofs);
990 ofs << "\n\\end_body\n";
992 // Write marker that shows file is complete
993 ofs << "\\end_document" << endl;
995 // Shouldn't really be needed....
998 // how to check if close went ok?
999 // Following is an attempt... (BE 20001011)
1001 // good() returns false if any error occured, including some
1002 // formatting error.
1003 // bad() returns true if something bad happened in the buffer,
1004 // which should include file system full errors.
1009 lyxerr << "File was not closed properly." << endl;
1016 bool Buffer::makeLaTeXFile(FileName const & fname,
1017 string const & original_path,
1018 OutputParams const & runparams,
1019 bool output_preamble, bool output_body)
1021 string const encoding = runparams.encoding->iconvName();
1022 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
1023 << encoding << "..." << endl;
1025 odocfstream ofs(encoding);
1026 if (!openFileWrite(ofs, fname))
1029 //TexStream ts(ofs.rdbuf(), &texrow());
1031 bool failed_export = false;
1034 writeLaTeXSource(ofs, original_path,
1035 runparams, output_preamble, output_body);
1037 catch (iconv_codecvt_facet_exception & e) {
1038 lyxerr << "Caught iconv exception: " << e.what() << endl;
1039 failed_export = true;
1041 catch (std::exception const & e) {
1042 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1043 failed_export = true;
1046 lyxerr << "Caught some really weird exception..." << endl;
1047 LyX::cref().emergencyCleanup();
1053 failed_export = true;
1054 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1057 if (failed_export) {
1058 Alert::error(_("Encoding error"),
1059 _("Some characters of your document are probably not "
1060 "representable in the chosen encoding.\n"
1061 "Changing the document encoding to utf8 could help."));
1068 void Buffer::writeLaTeXSource(odocstream & os,
1069 string const & original_path,
1070 OutputParams const & runparams_in,
1071 bool const output_preamble, bool const output_body)
1073 OutputParams runparams = runparams_in;
1075 // validate the buffer.
1076 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
1077 LaTeXFeatures features(*this, params(), runparams);
1079 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
1081 // The starting paragraph of the coming rows is the
1082 // first paragraph of the document. (Asger)
1083 if (output_preamble && runparams.nice) {
1084 os << "%% LyX " << lyx_version << " created this file. "
1085 "For more info, see http://www.lyx.org/.\n"
1086 "%% Do not edit unless you really know what "
1091 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1092 // There are a few differences between nice LaTeX and usual files:
1093 // usual is \batchmode and has a
1094 // special input@path to allow the including of figures
1095 // with either \input or \includegraphics (what figinsets do).
1096 // input@path is set when the actual parameter
1097 // original_path is set. This is done for usual tex-file, but not
1098 // for nice-latex-file. (Matthias 250696)
1099 // Note that input@path is only needed for something the user does
1100 // in the preamble, included .tex files or ERT, files included by
1101 // LyX work without it.
1102 if (output_preamble) {
1103 if (!runparams.nice) {
1104 // code for usual, NOT nice-latex-file
1105 os << "\\batchmode\n"; // changed
1106 // from \nonstopmode
1109 if (!original_path.empty()) {
1111 // We don't know the encoding of inputpath
1112 docstring const inputpath = from_utf8(latex_path(original_path));
1113 os << "\\makeatletter\n"
1114 << "\\def\\input@path{{"
1115 << inputpath << "/}}\n"
1116 << "\\makeatother\n";
1122 // Write the preamble
1123 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1129 os << "\\begin{document}\n";
1131 } // output_preamble
1133 texrow().start(paragraphs().begin()->id(), 0);
1135 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1137 if (!lyxrc.language_auto_begin &&
1138 !params().language->babel().empty()) {
1140 os << from_utf8(subst(lyxrc.language_command_begin,
1142 params().language->babel()))
1147 Encoding const & encoding = params().encoding();
1148 if (encoding.package() == Encoding::CJK) {
1149 // Open a CJK environment, since in contrast to the encodings
1150 // handled by inputenc the document encoding is not set in
1151 // the preamble if it is handled by CJK.sty.
1152 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1157 // if we are doing a real file with body, even if this is the
1158 // child of some other buffer, let's cut the link here.
1159 // This happens for example if only a child document is printed.
1160 string save_parentname;
1161 if (output_preamble) {
1162 save_parentname = params().parentname;
1163 params().parentname.erase();
1166 loadChildDocuments(*this);
1169 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1171 // Restore the parenthood if needed
1172 if (output_preamble)
1173 params().parentname = save_parentname;
1175 // add this just in case after all the paragraphs
1179 if (encoding.package() == Encoding::CJK) {
1180 // Close the open CJK environment.
1181 // latexParagraphs will have opened one even if the last text
1183 os << "\\end{CJK}\n";
1187 if (!lyxrc.language_auto_end &&
1188 !params().language->babel().empty()) {
1189 os << from_utf8(subst(lyxrc.language_command_end,
1191 params().language->babel()))
1196 if (output_preamble) {
1197 os << "\\end{document}\n";
1200 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1202 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1205 runparams_in.encoding = runparams.encoding;
1207 // Just to be sure. (Asger)
1210 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1211 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1216 bool Buffer::isLatex() const
1218 return params().getTextClass().outputType() == LATEX;
1222 bool Buffer::isLiterate() const
1224 return params().getTextClass().outputType() == LITERATE;
1228 bool Buffer::isDocBook() const
1230 return params().getTextClass().outputType() == DOCBOOK;
1234 void Buffer::makeDocBookFile(FileName const & fname,
1235 OutputParams const & runparams,
1236 bool const body_only)
1238 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1242 if (!openFileWrite(ofs, fname))
1245 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1249 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1253 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1254 OutputParams const & runparams,
1255 bool const only_body)
1257 LaTeXFeatures features(*this, params(), runparams);
1262 TextClass const & tclass = params().getTextClass();
1263 string const top_element = tclass.latexname();
1266 if (runparams.flavor == OutputParams::XML)
1267 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1270 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1273 if (! tclass.class_header().empty())
1274 os << from_ascii(tclass.class_header());
1275 else if (runparams.flavor == OutputParams::XML)
1276 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1277 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1279 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1281 docstring preamble = from_utf8(params().preamble);
1282 if (runparams.flavor != OutputParams::XML ) {
1283 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1284 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1285 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1286 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1289 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1291 preamble += features.getIncludedFiles(name);
1292 preamble += features.getLyXSGMLEntities();
1294 if (!preamble.empty()) {
1295 os << "\n [ " << preamble << " ]";
1300 string top = top_element;
1302 if (runparams.flavor == OutputParams::XML)
1303 top += params().language->code();
1305 top += params().language->code().substr(0,2);
1308 if (!params().options.empty()) {
1310 top += params().options;
1313 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1314 << " file was created by LyX " << lyx_version
1315 << "\n See http://www.lyx.org/ for more information -->\n";
1317 params().getTextClass().counters().reset();
1319 loadChildDocuments(*this);
1321 sgml::openTag(os, top);
1323 docbookParagraphs(paragraphs(), *this, os, runparams);
1324 sgml::closeTag(os, top_element);
1328 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1329 // Other flags: -wall -v0 -x
1330 int Buffer::runChktex()
1334 // get LaTeX-Filename
1335 FileName const path(temppath());
1336 string const name = addName(path.absFilename(), getLatexName());
1337 string const org_path = filePath();
1339 support::Path p(path); // path to LaTeX file
1340 message(_("Running chktex..."));
1342 // Generate the LaTeX file if neccessary
1343 OutputParams runparams(¶ms().encoding());
1344 runparams.flavor = OutputParams::LATEX;
1345 runparams.nice = false;
1346 makeLaTeXFile(FileName(name), org_path, runparams);
1349 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1350 int const res = chktex.run(terr); // run chktex
1353 Alert::error(_("chktex failure"),
1354 _("Could not run chktex successfully."));
1355 } else if (res > 0) {
1356 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1357 // Clear out old errors
1359 // Fill-in the error list with the TeX errors
1360 bufferErrors(*this, terr, errorList);
1371 void Buffer::validate(LaTeXFeatures & features) const
1373 TextClass const & tclass = params().getTextClass();
1375 if (params().outputChanges) {
1376 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1377 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1378 LaTeXFeatures::isAvailable("xcolor");
1380 if (features.runparams().flavor == OutputParams::LATEX) {
1382 features.require("ct-dvipost");
1383 features.require("dvipost");
1384 } else if (xcolorsoul) {
1385 features.require("ct-xcolor-soul");
1386 features.require("soul");
1387 features.require("xcolor");
1389 features.require("ct-none");
1391 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1393 features.require("ct-xcolor-soul");
1394 features.require("soul");
1395 features.require("xcolor");
1396 features.require("pdfcolmk"); // improves color handling in PDF output
1398 features.require("ct-none");
1403 // AMS Style is at document level
1404 if (params().use_amsmath == BufferParams::package_on
1405 || tclass.provides("amsmath"))
1406 features.require("amsmath");
1407 if (params().use_esint == BufferParams::package_on)
1408 features.require("esint");
1410 loadChildDocuments(*this);
1412 for_each(paragraphs().begin(), paragraphs().end(),
1413 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1415 // the bullet shapes are buffer level not paragraph level
1416 // so they are tested here
1417 for (int i = 0; i < 4; ++i) {
1418 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1419 int const font = params().user_defined_bullet(i).getFont();
1421 int const c = params()
1422 .user_defined_bullet(i)
1429 features.require("latexsym");
1431 } else if (font == 1) {
1432 features.require("amssymb");
1433 } else if ((font >= 2 && font <= 5)) {
1434 features.require("pifont");
1439 if (lyxerr.debugging(Debug::LATEX)) {
1440 features.showStruct();
1445 void Buffer::getLabelList(vector<docstring> & list) const
1447 /// if this is a child document and the parent is already loaded
1448 /// Use the parent's list instead [ale990407]
1449 Buffer const * tmp = getMasterBuffer();
1451 lyxerr << "getMasterBuffer() failed!" << endl;
1455 tmp->getLabelList(list);
1459 loadChildDocuments(*this);
1461 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1462 it.nextInset()->getLabelList(*this, list);
1466 void Buffer::updateBibfilesCache()
1468 // if this is a child document and the parent is already loaded
1469 // update the parent's cache instead
1470 Buffer * tmp = getMasterBuffer();
1473 tmp->updateBibfilesCache();
1477 bibfilesCache_.clear();
1478 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1479 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1480 InsetBibtex const & inset =
1481 static_cast<InsetBibtex const &>(*it);
1482 vector<FileName> const bibfiles = inset.getFiles(*this);
1483 bibfilesCache_.insert(bibfilesCache_.end(),
1486 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1487 InsetInclude & inset =
1488 static_cast<InsetInclude &>(*it);
1489 inset.updateBibfilesCache(*this);
1490 vector<FileName> const & bibfiles =
1491 inset.getBibfilesCache(*this);
1492 bibfilesCache_.insert(bibfilesCache_.end(),
1500 vector<FileName> const & Buffer::getBibfilesCache() const
1502 // if this is a child document and the parent is already loaded
1503 // use the parent's cache instead
1504 Buffer const * tmp = getMasterBuffer();
1507 return tmp->getBibfilesCache();
1509 // We update the cache when first used instead of at loading time.
1510 if (bibfilesCache_.empty())
1511 const_cast<Buffer *>(this)->updateBibfilesCache();
1513 return bibfilesCache_;
1517 bool Buffer::isDepClean(string const & name) const
1519 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1520 if (it == pimpl_->dep_clean.end())
1526 void Buffer::markDepClean(string const & name)
1528 pimpl_->dep_clean[name] = true;
1532 bool Buffer::dispatch(string const & command, bool * result)
1534 return dispatch(lyxaction.lookupFunc(command), result);
1538 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1540 bool dispatched = true;
1542 switch (func.action) {
1543 case LFUN_BUFFER_EXPORT: {
1544 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1557 void Buffer::changeLanguage(Language const * from, Language const * to)
1562 for_each(par_iterator_begin(),
1564 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1568 bool Buffer::isMultiLingual() const
1570 ParConstIterator end = par_iterator_end();
1571 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1572 if (it->isMultiLingual(params()))
1579 ParIterator Buffer::getParFromID(int const id) const
1581 ParConstIterator it = par_iterator_begin();
1582 ParConstIterator const end = par_iterator_end();
1585 // John says this is called with id == -1 from undo
1586 lyxerr << "getParFromID(), id: " << id << endl;
1590 for (; it != end; ++it)
1598 bool Buffer::hasParWithID(int const id) const
1600 ParConstIterator const it = getParFromID(id);
1601 return it != par_iterator_end();
1605 ParIterator Buffer::par_iterator_begin()
1607 return lyx::par_iterator_begin(inset());
1611 ParIterator Buffer::par_iterator_end()
1613 return lyx::par_iterator_end(inset());
1617 ParConstIterator Buffer::par_iterator_begin() const
1619 return lyx::par_const_iterator_begin(inset());
1623 ParConstIterator Buffer::par_iterator_end() const
1625 return lyx::par_const_iterator_end(inset());
1629 Language const * Buffer::getLanguage() const
1631 return params().language;
1635 docstring const Buffer::B_(string const & l10n) const
1637 return params().B_(l10n);
1641 bool Buffer::isClean() const
1643 return pimpl_->lyx_clean;
1647 bool Buffer::isBakClean() const
1649 return pimpl_->bak_clean;
1653 bool Buffer::isExternallyModified(CheckMethod method) const
1655 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1656 // if method == timestamp, check timestamp before checksum
1657 return (method == checksum_method
1658 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1659 && pimpl_->checksum_ != sum(pimpl_->filename);
1663 void Buffer::saveCheckSum(string const & file) const
1665 if (fs::exists(file)) {
1666 pimpl_->timestamp_ = fs::last_write_time(file);
1667 pimpl_->checksum_ = sum(FileName(file));
1669 // in the case of save to a new file.
1670 pimpl_->timestamp_ = 0;
1671 pimpl_->checksum_ = 0;
1676 void Buffer::markClean() const
1678 if (!pimpl_->lyx_clean) {
1679 pimpl_->lyx_clean = true;
1682 // if the .lyx file has been saved, we don't need an
1684 pimpl_->bak_clean = true;
1688 void Buffer::markBakClean()
1690 pimpl_->bak_clean = true;
1694 void Buffer::setUnnamed(bool flag)
1696 pimpl_->unnamed = flag;
1700 bool Buffer::isUnnamed() const
1702 return pimpl_->unnamed;
1706 // FIXME: this function should be moved to buffer_pimpl.C
1707 void Buffer::markDirty()
1709 if (pimpl_->lyx_clean) {
1710 pimpl_->lyx_clean = false;
1713 pimpl_->bak_clean = false;
1715 DepClean::iterator it = pimpl_->dep_clean.begin();
1716 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1718 for (; it != end; ++it)
1723 string const Buffer::fileName() const
1725 return pimpl_->filename.absFilename();
1729 string const & Buffer::filePath() const
1731 return params().filepath;
1735 bool Buffer::isReadonly() const
1737 return pimpl_->read_only;
1741 void Buffer::setParentName(string const & name)
1743 if (name == pimpl_->filename.absFilename())
1744 // Avoids recursive include.
1745 params().parentname.clear();
1747 params().parentname = name;
1751 Buffer const * Buffer::getMasterBuffer() const
1753 if (!params().parentname.empty()
1754 && theBufferList().exists(params().parentname)) {
1755 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1756 //We need to check if the parent is us...
1757 //FIXME RECURSIVE INCLUDE
1758 //This is not sufficient, since recursive includes could be downstream.
1759 if (buf && buf != this)
1760 return buf->getMasterBuffer();
1767 Buffer * Buffer::getMasterBuffer()
1769 if (!params().parentname.empty()
1770 && theBufferList().exists(params().parentname)) {
1771 Buffer * buf = theBufferList().getBuffer(params().parentname);
1772 //We need to check if the parent is us...
1773 //FIXME RECURSIVE INCLUDE
1774 //This is not sufficient, since recursive includes could be downstream.
1775 if (buf && buf != this)
1776 return buf->getMasterBuffer();
1783 MacroData const & Buffer::getMacro(docstring const & name) const
1785 return pimpl_->macros.get(name);
1789 bool Buffer::hasMacro(docstring const & name) const
1791 return pimpl_->macros.has(name);
1795 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1797 MacroTable::globalMacros().insert(name, data);
1798 pimpl_->macros.insert(name, data);
1802 void Buffer::buildMacros()
1804 // Start with global table.
1805 pimpl_->macros = MacroTable::globalMacros();
1808 ParagraphList const & pars = text().paragraphs();
1809 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1810 //lyxerr << "searching main par " << i
1811 // << " for macro definitions" << std::endl;
1812 InsetList const & insets = pars[i].insetlist;
1813 InsetList::const_iterator it = insets.begin();
1814 InsetList::const_iterator end = insets.end();
1815 for ( ; it != end; ++it) {
1816 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1817 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1818 MathMacroTemplate const & mac
1819 = static_cast<MathMacroTemplate const &>(*it->inset);
1820 insertMacro(mac.name(), mac.asMacroData());
1827 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1830 //FIXME: This does not work for child documents yet.
1831 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1832 // Check if the label 'from' appears more than once
1833 vector<docstring> labels;
1835 if (code == Inset::CITE_CODE) {
1837 keys.fillWithBibKeys(this);
1838 BiblioInfo::const_iterator bit = keys.begin();
1839 BiblioInfo::const_iterator bend = keys.end();
1841 for (; bit != bend; ++bit)
1843 labels.push_back(bit->first);
1845 getLabelList(labels);
1847 if (std::count(labels.begin(), labels.end(), from) > 1)
1850 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1851 if (it->lyxCode() == code) {
1852 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1853 inset.replaceContents(to_utf8(from), to_utf8(to));
1859 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1860 pit_type par_end, bool full_source)
1862 OutputParams runparams(¶ms().encoding());
1863 runparams.nice = true;
1864 runparams.flavor = OutputParams::LATEX;
1865 runparams.linelen = lyxrc.plaintext_linelen;
1866 // No side effect of file copying and image conversion
1867 runparams.dryrun = true;
1871 os << "% " << _("Preview source code") << "\n\n";
1875 writeLaTeXSource(os, filePath(), runparams, true, true);
1877 writeDocBookSource(os, fileName(), runparams, false);
1880 runparams.par_begin = par_begin;
1881 runparams.par_end = par_end;
1882 if (par_begin + 1 == par_end)
1884 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1888 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1889 convert<docstring>(par_begin),
1890 convert<docstring>(par_end - 1))
1894 // output paragraphs
1896 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1899 docbookParagraphs(paragraphs(), *this, os, runparams);
1905 ErrorList const & Buffer::errorList(string const & type) const
1907 static ErrorList const emptyErrorList;
1908 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1909 if (I == pimpl_->errorLists.end())
1910 return emptyErrorList;
1916 ErrorList & Buffer::errorList(string const & type)
1918 return pimpl_->errorLists[type];