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"
36 #include "LyXAction.h"
44 #include "output_docbook.h"
45 #include "output_latex.h"
46 #include "Paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "ParIterator.h"
52 #include "TextClassList.h"
53 #include "TexStream.h"
54 #include "TocBackend.h"
57 #include "EmbeddedFiles.h"
59 #include "insets/InsetBibitem.h"
60 #include "insets/InsetBibtex.h"
61 #include "insets/InsetInclude.h"
62 #include "insets/InsetText.h"
64 #include "mathed/MathMacroTemplate.h"
65 #include "mathed/MacroTable.h"
66 #include "mathed/MathSupport.h"
68 #include "frontends/alert.h"
70 #include "graphics/Previews.h"
72 #include "support/types.h"
73 #include "support/lyxalgo.h"
74 #include "support/filetools.h"
75 #include "support/fs_extras.h"
76 #include "support/gzstream.h"
77 #include "support/lyxlib.h"
78 #include "support/os.h"
79 #include "support/Path.h"
80 #include "support/textutils.h"
81 #include "support/convert.h"
83 #include <boost/bind.hpp>
84 #include <boost/filesystem/exception.hpp>
85 #include <boost/filesystem/operations.hpp>
100 using std::ostringstream;
112 using support::addName;
113 using support::bformat;
114 using support::changeExtension;
115 using support::cmd_ret;
116 using support::createBufferTmpDir;
117 using support::destroyDir;
118 using support::FileName;
119 using support::getFormatFromContents;
120 using support::libFileSearch;
121 using support::latex_path;
122 using support::ltrim;
123 using support::makeAbsPath;
124 using support::makeDisplayPath;
125 using support::makeLatexName;
126 using support::onlyFilename;
127 using support::onlyPath;
128 using support::quoteName;
129 using support::removeAutosaveFile;
130 using support::rename;
131 using support::runCommand;
132 using support::split;
133 using support::subst;
134 using support::tempName;
137 using support::unzipToDir;
139 namespace Alert = frontend::Alert;
140 namespace os = support::os;
141 namespace fs = boost::filesystem;
145 int const LYX_FORMAT = 282;
150 typedef std::map<string, bool> DepClean;
155 Impl(Buffer & parent, FileName const & file, bool readonly);
157 limited_stack<Undo> undostack;
158 limited_stack<Undo> redostack;
164 /// need to regenerate .tex?
168 mutable bool lyx_clean;
170 /// is autosave needed?
171 mutable bool bak_clean;
173 /// is this a unnamed file (New...)?
179 /// name of the file the buffer is associated with.
182 /** Set to true only when the file is fully loaded.
183 * Used to prevent the premature generation of previews
184 * and by the citation inset.
186 bool file_fully_loaded;
188 /// our Text that should be wrapped in an InsetText
195 TocBackend toc_backend;
197 /// Container for all sort of Buffer dependant errors.
198 map<string, ErrorList> errorLists;
200 /// all embedded files of this buffer
201 EmbeddedFiles embedded_files;
203 /// timestamp and checksum used to test if the file has been externally
204 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
206 unsigned long checksum_;
210 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
211 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
212 filename(file), file_fully_loaded(false), inset(params),
213 toc_backend(&parent), embedded_files(&parent), timestamp_(0), checksum_(0)
215 inset.setAutoBreakRows(true);
216 lyxvc.buffer(&parent);
217 temppath = createBufferTmpDir();
218 params.filepath = onlyPath(file.absFilename());
219 // FIXME: And now do something if temppath == string(), because we
220 // assume from now on that temppath points to a valid temp dir.
221 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
225 Buffer::Buffer(string const & file, bool readonly)
226 : pimpl_(new Impl(*this, FileName(file), readonly))
228 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
234 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
235 // here the buffer should take care that it is
236 // saved properly, before it goes into the void.
238 Buffer * master = getMasterBuffer();
239 if (master != this && use_gui)
240 // We are closing buf which was a child document so we
241 // must update the labels and section numbering of its master
243 updateLabels(*master);
245 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
246 Alert::warning(_("Could not remove temporary directory"),
247 bformat(_("Could not remove the temporary directory %1$s"),
248 from_utf8(temppath())));
251 // Remove any previewed LaTeX snippets associated with this buffer.
252 graphics::Previews::get().removeLoader(*this);
258 Text & Buffer::text() const
260 return const_cast<Text &>(pimpl_->inset.text_);
264 Inset & Buffer::inset() const
266 return const_cast<InsetText &>(pimpl_->inset);
270 limited_stack<Undo> & Buffer::undostack()
272 return pimpl_->undostack;
276 limited_stack<Undo> const & Buffer::undostack() const
278 return pimpl_->undostack;
282 limited_stack<Undo> & Buffer::redostack()
284 return pimpl_->redostack;
288 limited_stack<Undo> const & Buffer::redostack() const
290 return pimpl_->redostack;
294 BufferParams & Buffer::params()
296 return pimpl_->params;
300 BufferParams const & Buffer::params() const
302 return pimpl_->params;
306 ParagraphList & Buffer::paragraphs()
308 return text().paragraphs();
312 ParagraphList const & Buffer::paragraphs() const
314 return text().paragraphs();
318 LyXVC & Buffer::lyxvc()
320 return pimpl_->lyxvc;
324 LyXVC const & Buffer::lyxvc() const
326 return pimpl_->lyxvc;
330 string const & Buffer::temppath() const
332 return pimpl_->temppath;
336 TexRow & Buffer::texrow()
338 return pimpl_->texrow;
342 TexRow const & Buffer::texrow() const
344 return pimpl_->texrow;
348 TocBackend & Buffer::tocBackend()
350 return pimpl_->toc_backend;
354 TocBackend const & Buffer::tocBackend() const
356 return pimpl_->toc_backend;
360 EmbeddedFiles & Buffer::embeddedFiles()
362 return pimpl_->embedded_files;
366 EmbeddedFiles const & Buffer::embeddedFiles() const
368 return pimpl_->embedded_files;
372 string const Buffer::getLatexName(bool const no_path) const
374 string const name = changeExtension(makeLatexName(fileName()), ".tex");
375 return no_path ? onlyFilename(name) : name;
379 pair<Buffer::LogType, string> const Buffer::getLogName() const
381 string const filename = getLatexName(false);
383 if (filename.empty())
384 return make_pair(Buffer::latexlog, string());
386 string const path = temppath();
388 FileName const fname(addName(temppath(),
389 onlyFilename(changeExtension(filename,
391 FileName const bname(
392 addName(path, onlyFilename(
393 changeExtension(filename,
394 formats.extension("literate") + ".out"))));
396 // If no Latex log or Build log is newer, show Build log
398 if (fs::exists(bname.toFilesystemEncoding()) &&
399 (!fs::exists(fname.toFilesystemEncoding()) ||
400 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
401 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
402 return make_pair(Buffer::buildlog, bname.absFilename());
404 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
405 return make_pair(Buffer::latexlog, fname.absFilename());
409 void Buffer::setReadonly(bool const flag)
411 if (pimpl_->read_only != flag) {
412 pimpl_->read_only = flag;
418 void Buffer::setFileName(string const & newfile)
420 pimpl_->filename = makeAbsPath(newfile);
421 params().filepath = onlyPath(pimpl_->filename.absFilename());
422 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
427 // We'll remove this later. (Lgb)
430 void unknownClass(string const & unknown)
432 Alert::warning(_("Unknown document class"),
433 bformat(_("Using the default document class, because the "
434 "class %1$s is unknown."), from_utf8(unknown)));
440 int Buffer::readHeader(Lexer & lex)
442 int unknown_tokens = 0;
444 int begin_header_line = -1;
446 // Initialize parameters that may be/go lacking in header:
447 params().branchlist().clear();
448 params().preamble.erase();
449 params().options.erase();
450 params().float_placement.erase();
451 params().paperwidth.erase();
452 params().paperheight.erase();
453 params().leftmargin.erase();
454 params().rightmargin.erase();
455 params().topmargin.erase();
456 params().bottommargin.erase();
457 params().headheight.erase();
458 params().headsep.erase();
459 params().footskip.erase();
460 params().listings_params.clear();
461 params().clearLayoutModules();
463 for (int i = 0; i < 4; ++i) {
464 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
465 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
468 ErrorList & errorList = pimpl_->errorLists["Parse"];
472 string const token = lex.getString();
477 if (token == "\\end_header")
481 if (token == "\\begin_header") {
482 begin_header_line = line;
486 LYXERR(Debug::PARSER) << "Handling document header token: `"
487 << token << '\'' << endl;
489 string unknown = params().readToken(lex, token);
490 if (!unknown.empty()) {
491 if (unknown[0] != '\\' && token == "\\textclass") {
492 unknownClass(unknown);
495 docstring const s = bformat(_("Unknown token: "
499 errorList.push_back(ErrorItem(_("Document header error"),
504 if (begin_header_line) {
505 docstring const s = _("\\begin_header is missing");
506 errorList.push_back(ErrorItem(_("Document header error"),
510 return unknown_tokens;
515 // changed to be public and have one parameter
516 // Returns false if "\end_document" is not read (Asger)
517 bool Buffer::readDocument(Lexer & lex)
519 ErrorList & errorList = pimpl_->errorLists["Parse"];
523 string const token = lex.getString();
524 if (token != "\\begin_document") {
525 docstring const s = _("\\begin_document is missing");
526 errorList.push_back(ErrorItem(_("Document header error"),
530 // we are reading in a brand new document
531 BOOST_ASSERT(paragraphs().empty());
534 if (!params().getTextClass().load(filePath())) {
535 string theclass = params().getTextClass().name();
536 Alert::error(_("Can't load document class"), bformat(
537 _("Using the default document class, because the "
538 "class %1$s could not be loaded."), from_utf8(theclass)));
539 params().setBaseClass(defaultTextclass());
542 if (params().outputChanges) {
543 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
544 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
545 LaTeXFeatures::isAvailable("xcolor");
547 if (!dvipost && !xcolorsoul) {
548 Alert::warning(_("Changes not shown in LaTeX output"),
549 _("Changes will not be highlighted in LaTeX output, "
550 "because neither dvipost nor xcolor/soul are installed.\n"
551 "Please install these packages or redefine "
552 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
553 } else if (!xcolorsoul) {
554 Alert::warning(_("Changes not shown in LaTeX output"),
555 _("Changes will not be highlighted in LaTeX output "
556 "when using pdflatex, because xcolor and soul are not installed.\n"
557 "Please install both packages or redefine "
558 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
562 bool const res = text().read(*this, lex, errorList);
563 for_each(text().paragraphs().begin(),
564 text().paragraphs().end(),
565 bind(&Paragraph::setInsetOwner, _1, &inset()));
571 // needed to insert the selection
572 void Buffer::insertStringAsLines(ParagraphList & pars,
573 pit_type & pit, pos_type & pos,
574 Font const & fn, docstring const & str, bool autobreakrows)
578 // insert the string, don't insert doublespace
579 bool space_inserted = true;
580 for (docstring::const_iterator cit = str.begin();
581 cit != str.end(); ++cit) {
582 Paragraph & par = pars[pit];
584 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
585 breakParagraph(params(), pars, pit, pos,
586 par.layout()->isEnvironment());
589 space_inserted = true;
593 // do not insert consecutive spaces if !free_spacing
594 } else if ((*cit == ' ' || *cit == '\t') &&
595 space_inserted && !par.isFreeSpacing()) {
597 } else if (*cit == '\t') {
598 if (!par.isFreeSpacing()) {
599 // tabs are like spaces here
600 par.insertChar(pos, ' ', font, params().trackChanges);
602 space_inserted = true;
604 const pos_type n = 8 - pos % 8;
605 for (pos_type i = 0; i < n; ++i) {
606 par.insertChar(pos, ' ', font, params().trackChanges);
609 space_inserted = true;
611 } else if (!isPrintable(*cit)) {
612 // Ignore unprintables
615 // just insert the character
616 par.insertChar(pos, *cit, font, params().trackChanges);
618 space_inserted = (*cit == ' ');
625 bool Buffer::readString(std::string const & s)
627 params().compressed = false;
629 // remove dummy empty par
630 paragraphs().clear();
632 std::istringstream is(s);
634 FileName const name(tempName());
635 switch (readFile(lex, name, true)) {
639 // We need to call lyx2lyx, so write the input to a file
640 std::ofstream os(name.toFilesystemEncoding().c_str());
643 return readFile(name);
653 bool Buffer::readFile(FileName const & filename)
655 FileName fname(filename);
656 // Check if the file is compressed.
657 string format = getFormatFromContents(filename);
658 if (format == "zip") {
659 // decompress to a temp directory
660 LYXERR(Debug::FILES) << filename << " is in zip format. Unzip to " << temppath() << endl;
661 unzipToDir(filename.toFilesystemEncoding(), temppath());
663 FileName manifest(addName(temppath(), "manifest.txt"));
664 FileName lyxfile(addName(temppath(),
665 onlyFilename(filename.toFilesystemEncoding())));
666 // if both manifest.txt and file.lyx exist, this is am embedded file
667 if (fs::exists(manifest.toFilesystemEncoding()) &&
668 fs::exists(lyxfile.toFilesystemEncoding())) {
669 params().embedded = true;
671 // read manifest file
672 ifstream is(manifest.toFilesystemEncoding().c_str());
673 is >> pimpl_->embedded_files;
675 LYXERR(Debug::FILES) << filename << " is a embedded file. Its manifest is:\n"
676 << pimpl_->embedded_files;
679 // The embedded lyx file can also be compressed, for backward compatibility
680 format = getFormatFromContents(fname);
681 if (format == "gzip" || format == "zip" || format == "compress") {
682 params().compressed = true;
685 // remove dummy empty par
686 paragraphs().clear();
689 if (readFile(lex, fname) != success)
696 bool Buffer::fully_loaded() const
698 return pimpl_->file_fully_loaded;
702 void Buffer::fully_loaded(bool const value)
704 pimpl_->file_fully_loaded = value;
708 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
711 BOOST_ASSERT(!filename.empty());
714 Alert::error(_("Document could not be read"),
715 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
720 string const token(lex.getString());
723 Alert::error(_("Document could not be read"),
724 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
728 // the first token _must_ be...
729 if (token != "\\lyxformat") {
730 lyxerr << "Token: " << token << endl;
732 Alert::error(_("Document format failure"),
733 bformat(_("%1$s is not a LyX document."),
734 from_utf8(filename.absFilename())));
739 string tmp_format = lex.getString();
740 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
741 // if present remove ".," from string.
742 string::size_type dot = tmp_format.find_first_of(".,");
743 //lyxerr << " dot found at " << dot << endl;
744 if (dot != string::npos)
745 tmp_format.erase(dot, 1);
746 int const file_format = convert<int>(tmp_format);
747 //lyxerr << "format: " << file_format << endl;
749 // save timestamp and checksum of the original disk file, making sure
750 // to not overwrite them with those of the file created in the tempdir
751 // when it has to be converted to the current format.
752 if (!pimpl_->checksum_) {
753 pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
754 pimpl_->checksum_ = sum(filename);
757 if (file_format != LYX_FORMAT) {
760 // lyx2lyx would fail
763 FileName const tmpfile(tempName());
764 if (tmpfile.empty()) {
765 Alert::error(_("Conversion failed"),
766 bformat(_("%1$s is from a different"
767 " version of LyX, but a temporary"
768 " file for converting it could"
770 from_utf8(filename.absFilename())));
773 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
774 if (lyx2lyx.empty()) {
775 Alert::error(_("Conversion script not found"),
776 bformat(_("%1$s is from a different"
777 " version of LyX, but the"
778 " conversion script lyx2lyx"
779 " could not be found."),
780 from_utf8(filename.absFilename())));
783 ostringstream command;
784 command << os::python()
785 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
786 << " -t " << convert<string>(LYX_FORMAT)
787 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
788 << ' ' << quoteName(filename.toFilesystemEncoding());
789 string const command_str = command.str();
791 LYXERR(Debug::INFO) << "Running '"
792 << command_str << '\''
795 cmd_ret const ret = runCommand(command_str);
796 if (ret.first != 0) {
797 Alert::error(_("Conversion script failed"),
798 bformat(_("%1$s is from a different version"
799 " of LyX, but the lyx2lyx script"
800 " failed to convert it."),
801 from_utf8(filename.absFilename())));
804 bool const ret = readFile(tmpfile);
805 // Do stuff with tmpfile name and buffer name here.
806 return ret ? success : failure;
811 if (readDocument(lex)) {
812 Alert::error(_("Document format failure"),
813 bformat(_("%1$s ended unexpectedly, which means"
814 " that it is probably corrupted."),
815 from_utf8(filename.absFilename())));
818 //lyxerr << "removing " << MacroTable::localMacros().size()
819 // << " temporary macro entries" << endl;
820 //MacroTable::localMacros().clear();
822 pimpl_->file_fully_loaded = true;
827 // Should probably be moved to somewhere else: BufferView? LyXView?
828 bool Buffer::save() const
830 // We don't need autosaves in the immediate future. (Asger)
831 resetAutosaveTimers();
833 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
836 bool madeBackup = false;
838 // make a backup if the file already exists
839 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
840 backupName = FileName(fileName() + '~');
841 if (!lyxrc.backupdir_path.empty())
842 backupName = FileName(addName(lyxrc.backupdir_path,
843 subst(os::internal_path(backupName.absFilename()), '/', '!')));
846 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
848 } catch (fs::filesystem_error const & fe) {
849 Alert::error(_("Backup failure"),
850 bformat(_("Cannot create backup file %1$s.\n"
851 "Please check whether the directory exists and is writeable."),
852 from_utf8(backupName.absFilename())));
853 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
857 // ask if the disk file has been externally modified (use checksum method)
858 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
859 docstring const file = makeDisplayPath(fileName(), 20);
860 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
861 "you want to overwrite this file?"), file);
862 int const ret = Alert::prompt(_("Overwrite modified file?"),
863 text, 1, 1, _("&Overwrite"), _("&Cancel"));
868 if (writeFile(pimpl_->filename)) {
870 removeAutosaveFile(fileName());
871 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
872 pimpl_->checksum_ = sum(pimpl_->filename);
875 // Saving failed, so backup is not backup
877 rename(backupName, pimpl_->filename);
883 bool Buffer::writeFile(FileName const & fname) const
885 if (pimpl_->read_only && fname == pimpl_->filename)
891 if (params().embedded)
892 // first write the .lyx file to the temporary directory
893 content = FileName(addName(temppath(),
894 onlyFilename(fname.toFilesystemEncoding())));
898 if (params().compressed) {
899 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
905 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
912 if (retval && params().embedded) {
913 // write file.lyx and all the embedded files to the zip file fname
914 // if embedding is enabled, and there is any embedded file
915 pimpl_->embedded_files.update();
916 return pimpl_->embedded_files.write(fname);
922 bool Buffer::write(ostream & ofs) const
925 // Use the standard "C" locale for file output.
926 ofs.imbue(std::locale::classic());
929 // The top of the file should not be written by params().
931 // write out a comment in the top of the file
932 ofs << "#LyX " << lyx_version
933 << " created this file. For more info see http://www.lyx.org/\n"
934 << "\\lyxformat " << LYX_FORMAT << "\n"
935 << "\\begin_document\n";
938 /// For each author, set 'used' to true if there is a change
939 /// by this author in the document; otherwise set it to 'false'.
940 AuthorList::Authors::const_iterator a_it = params().authors().begin();
941 AuthorList::Authors::const_iterator a_end = params().authors().end();
942 for (; a_it != a_end; ++a_it)
943 a_it->second.used(false);
945 ParIterator const end = par_iterator_end();
946 ParIterator it = par_iterator_begin();
947 for ( ; it != end; ++it)
948 it->checkAuthors(params().authors());
950 // now write out the buffer parameters.
951 ofs << "\\begin_header\n";
952 params().writeFile(ofs);
953 ofs << "\\end_header\n";
956 ofs << "\n\\begin_body\n";
957 text().write(*this, ofs);
958 ofs << "\n\\end_body\n";
960 // Write marker that shows file is complete
961 ofs << "\\end_document" << endl;
963 // Shouldn't really be needed....
966 // how to check if close went ok?
967 // Following is an attempt... (BE 20001011)
969 // good() returns false if any error occured, including some
971 // bad() returns true if something bad happened in the buffer,
972 // which should include file system full errors.
977 lyxerr << "File was not closed properly." << endl;
984 bool Buffer::makeLaTeXFile(FileName const & fname,
985 string const & original_path,
986 OutputParams const & runparams,
987 bool output_preamble, bool output_body)
989 string const encoding = runparams.encoding->iconvName();
990 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
991 << encoding << "..." << endl;
993 odocfstream ofs(encoding);
994 if (!openFileWrite(ofs, fname))
997 //TexStream ts(ofs.rdbuf(), &texrow());
999 bool failed_export = false;
1002 writeLaTeXSource(ofs, original_path,
1003 runparams, output_preamble, output_body);
1005 catch (iconv_codecvt_facet_exception & e) {
1006 lyxerr << "Caught iconv exception: " << e.what() << endl;
1007 failed_export = true;
1009 catch (std::exception const & e) {
1010 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1011 failed_export = true;
1014 lyxerr << "Caught some really weird exception..." << endl;
1015 LyX::cref().emergencyCleanup();
1021 failed_export = true;
1022 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1025 if (failed_export) {
1026 Alert::error(_("Encoding error"),
1027 _("Some characters of your document are probably not "
1028 "representable in the chosen encoding.\n"
1029 "Changing the document encoding to utf8 could help."));
1036 void Buffer::writeLaTeXSource(odocstream & os,
1037 string const & original_path,
1038 OutputParams const & runparams_in,
1039 bool const output_preamble, bool const output_body)
1041 OutputParams runparams = runparams_in;
1043 // validate the buffer.
1044 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
1045 LaTeXFeatures features(*this, params(), runparams);
1047 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
1049 // The starting paragraph of the coming rows is the
1050 // first paragraph of the document. (Asger)
1051 if (output_preamble && runparams.nice) {
1052 os << "%% LyX " << lyx_version << " created this file. "
1053 "For more info, see http://www.lyx.org/.\n"
1054 "%% Do not edit unless you really know what "
1059 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1060 // There are a few differences between nice LaTeX and usual files:
1061 // usual is \batchmode and has a
1062 // special input@path to allow the including of figures
1063 // with either \input or \includegraphics (what figinsets do).
1064 // input@path is set when the actual parameter
1065 // original_path is set. This is done for usual tex-file, but not
1066 // for nice-latex-file. (Matthias 250696)
1067 // Note that input@path is only needed for something the user does
1068 // in the preamble, included .tex files or ERT, files included by
1069 // LyX work without it.
1070 if (output_preamble) {
1071 if (!runparams.nice) {
1072 // code for usual, NOT nice-latex-file
1073 os << "\\batchmode\n"; // changed
1074 // from \nonstopmode
1077 if (!original_path.empty()) {
1079 // We don't know the encoding of inputpath
1080 docstring const inputpath = from_utf8(latex_path(original_path));
1081 os << "\\makeatletter\n"
1082 << "\\def\\input@path{{"
1083 << inputpath << "/}}\n"
1084 << "\\makeatother\n";
1090 // Write the preamble
1091 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1097 os << "\\begin{document}\n";
1099 } // output_preamble
1101 texrow().start(paragraphs().begin()->id(), 0);
1103 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1105 if (!lyxrc.language_auto_begin &&
1106 !params().language->babel().empty()) {
1108 os << from_utf8(subst(lyxrc.language_command_begin,
1110 params().language->babel()))
1115 Encoding const & encoding = params().encoding();
1116 if (encoding.package() == Encoding::CJK) {
1117 // Open a CJK environment, since in contrast to the encodings
1118 // handled by inputenc the document encoding is not set in
1119 // the preamble if it is handled by CJK.sty.
1120 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1125 // if we are doing a real file with body, even if this is the
1126 // child of some other buffer, let's cut the link here.
1127 // This happens for example if only a child document is printed.
1128 string save_parentname;
1129 if (output_preamble) {
1130 save_parentname = params().parentname;
1131 params().parentname.erase();
1134 loadChildDocuments(*this);
1137 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1139 // Restore the parenthood if needed
1140 if (output_preamble)
1141 params().parentname = save_parentname;
1143 // add this just in case after all the paragraphs
1147 if (encoding.package() == Encoding::CJK) {
1148 // Close the open CJK environment.
1149 // latexParagraphs will have opened one even if the last text
1151 os << "\\end{CJK}\n";
1155 if (!lyxrc.language_auto_end &&
1156 !params().language->babel().empty()) {
1157 os << from_utf8(subst(lyxrc.language_command_end,
1159 params().language->babel()))
1164 if (output_preamble) {
1165 os << "\\end{document}\n";
1168 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1170 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1173 runparams_in.encoding = runparams.encoding;
1175 // Just to be sure. (Asger)
1178 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1179 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1184 bool Buffer::isLatex() const
1186 return params().getTextClass().outputType() == LATEX;
1190 bool Buffer::isLiterate() const
1192 return params().getTextClass().outputType() == LITERATE;
1196 bool Buffer::isDocBook() const
1198 return params().getTextClass().outputType() == DOCBOOK;
1202 void Buffer::makeDocBookFile(FileName const & fname,
1203 OutputParams const & runparams,
1204 bool const body_only)
1206 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1210 if (!openFileWrite(ofs, fname))
1213 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1217 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1221 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1222 OutputParams const & runparams,
1223 bool const only_body)
1225 LaTeXFeatures features(*this, params(), runparams);
1230 TextClass const & tclass = params().getTextClass();
1231 string const top_element = tclass.latexname();
1234 if (runparams.flavor == OutputParams::XML)
1235 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1238 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1241 if (! tclass.class_header().empty())
1242 os << from_ascii(tclass.class_header());
1243 else if (runparams.flavor == OutputParams::XML)
1244 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1245 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1247 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1249 docstring preamble = from_utf8(params().preamble);
1250 if (runparams.flavor != OutputParams::XML ) {
1251 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1252 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1253 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1254 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1257 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1259 preamble += features.getIncludedFiles(name);
1260 preamble += features.getLyXSGMLEntities();
1262 if (!preamble.empty()) {
1263 os << "\n [ " << preamble << " ]";
1268 string top = top_element;
1270 if (runparams.flavor == OutputParams::XML)
1271 top += params().language->code();
1273 top += params().language->code().substr(0,2);
1276 if (!params().options.empty()) {
1278 top += params().options;
1281 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1282 << " file was created by LyX " << lyx_version
1283 << "\n See http://www.lyx.org/ for more information -->\n";
1285 params().getTextClass().counters().reset();
1287 loadChildDocuments(*this);
1289 sgml::openTag(os, top);
1291 docbookParagraphs(paragraphs(), *this, os, runparams);
1292 sgml::closeTag(os, top_element);
1296 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1297 // Other flags: -wall -v0 -x
1298 int Buffer::runChktex()
1302 // get LaTeX-Filename
1303 FileName const path(temppath());
1304 string const name = addName(path.absFilename(), getLatexName());
1305 string const org_path = filePath();
1307 support::Path p(path); // path to LaTeX file
1308 message(_("Running chktex..."));
1310 // Generate the LaTeX file if neccessary
1311 OutputParams runparams(¶ms().encoding());
1312 runparams.flavor = OutputParams::LATEX;
1313 runparams.nice = false;
1314 makeLaTeXFile(FileName(name), org_path, runparams);
1317 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1318 int const res = chktex.run(terr); // run chktex
1321 Alert::error(_("chktex failure"),
1322 _("Could not run chktex successfully."));
1323 } else if (res > 0) {
1324 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1325 // Clear out old errors
1327 // Fill-in the error list with the TeX errors
1328 bufferErrors(*this, terr, errorList);
1339 void Buffer::validate(LaTeXFeatures & features) const
1341 TextClass const & tclass = params().getTextClass();
1343 if (params().outputChanges) {
1344 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1345 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1346 LaTeXFeatures::isAvailable("xcolor");
1348 if (features.runparams().flavor == OutputParams::LATEX) {
1350 features.require("ct-dvipost");
1351 features.require("dvipost");
1352 } else if (xcolorsoul) {
1353 features.require("ct-xcolor-soul");
1354 features.require("soul");
1355 features.require("xcolor");
1357 features.require("ct-none");
1359 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1361 features.require("ct-xcolor-soul");
1362 features.require("soul");
1363 features.require("xcolor");
1364 features.require("pdfcolmk"); // improves color handling in PDF output
1366 features.require("ct-none");
1371 // AMS Style is at document level
1372 if (params().use_amsmath == BufferParams::package_on
1373 || tclass.provides("amsmath"))
1374 features.require("amsmath");
1375 if (params().use_esint == BufferParams::package_on)
1376 features.require("esint");
1378 loadChildDocuments(*this);
1380 for_each(paragraphs().begin(), paragraphs().end(),
1381 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1383 // the bullet shapes are buffer level not paragraph level
1384 // so they are tested here
1385 for (int i = 0; i < 4; ++i) {
1386 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1387 int const font = params().user_defined_bullet(i).getFont();
1389 int const c = params()
1390 .user_defined_bullet(i)
1397 features.require("latexsym");
1399 } else if (font == 1) {
1400 features.require("amssymb");
1401 } else if ((font >= 2 && font <= 5)) {
1402 features.require("pifont");
1407 if (lyxerr.debugging(Debug::LATEX)) {
1408 features.showStruct();
1413 void Buffer::getLabelList(vector<docstring> & list) const
1415 /// if this is a child document and the parent is already loaded
1416 /// Use the parent's list instead [ale990407]
1417 Buffer const * tmp = getMasterBuffer();
1419 lyxerr << "getMasterBuffer() failed!" << endl;
1423 tmp->getLabelList(list);
1427 loadChildDocuments(*this);
1429 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1430 it.nextInset()->getLabelList(*this, list);
1434 void Buffer::updateBibfilesCache()
1436 // if this is a child document and the parent is already loaded
1437 // update the parent's cache instead
1438 Buffer * tmp = getMasterBuffer();
1441 tmp->updateBibfilesCache();
1445 bibfilesCache_.clear();
1446 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1447 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1448 InsetBibtex const & inset =
1449 static_cast<InsetBibtex const &>(*it);
1450 vector<FileName> const bibfiles = inset.getFiles(*this);
1451 bibfilesCache_.insert(bibfilesCache_.end(),
1454 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1455 InsetInclude & inset =
1456 static_cast<InsetInclude &>(*it);
1457 inset.updateBibfilesCache(*this);
1458 vector<FileName> const & bibfiles =
1459 inset.getBibfilesCache(*this);
1460 bibfilesCache_.insert(bibfilesCache_.end(),
1468 vector<FileName> const & Buffer::getBibfilesCache() const
1470 // if this is a child document and the parent is already loaded
1471 // use the parent's cache instead
1472 Buffer const * tmp = getMasterBuffer();
1475 return tmp->getBibfilesCache();
1477 // We update the cache when first used instead of at loading time.
1478 if (bibfilesCache_.empty())
1479 const_cast<Buffer *>(this)->updateBibfilesCache();
1481 return bibfilesCache_;
1485 bool Buffer::isDepClean(string const & name) const
1487 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1488 if (it == pimpl_->dep_clean.end())
1494 void Buffer::markDepClean(string const & name)
1496 pimpl_->dep_clean[name] = true;
1500 bool Buffer::dispatch(string const & command, bool * result)
1502 return dispatch(lyxaction.lookupFunc(command), result);
1506 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1508 bool dispatched = true;
1510 switch (func.action) {
1511 case LFUN_BUFFER_EXPORT: {
1512 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1525 void Buffer::changeLanguage(Language const * from, Language const * to)
1530 for_each(par_iterator_begin(),
1532 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1534 text().current_font.setLanguage(to);
1535 text().real_current_font.setLanguage(to);
1539 bool Buffer::isMultiLingual() const
1541 ParConstIterator end = par_iterator_end();
1542 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1543 if (it->isMultiLingual(params()))
1550 ParIterator Buffer::getParFromID(int const id) const
1552 ParConstIterator it = par_iterator_begin();
1553 ParConstIterator const end = par_iterator_end();
1556 // John says this is called with id == -1 from undo
1557 lyxerr << "getParFromID(), id: " << id << endl;
1561 for (; it != end; ++it)
1569 bool Buffer::hasParWithID(int const id) const
1571 ParConstIterator const it = getParFromID(id);
1572 return it != par_iterator_end();
1576 ParIterator Buffer::par_iterator_begin()
1578 return lyx::par_iterator_begin(inset());
1582 ParIterator Buffer::par_iterator_end()
1584 return lyx::par_iterator_end(inset());
1588 ParConstIterator Buffer::par_iterator_begin() const
1590 return lyx::par_const_iterator_begin(inset());
1594 ParConstIterator Buffer::par_iterator_end() const
1596 return lyx::par_const_iterator_end(inset());
1600 Language const * Buffer::getLanguage() const
1602 return params().language;
1606 docstring const Buffer::B_(string const & l10n) const
1608 return params().B_(l10n);
1612 bool Buffer::isClean() const
1614 return pimpl_->lyx_clean;
1618 bool Buffer::isBakClean() const
1620 return pimpl_->bak_clean;
1624 bool Buffer::isExternallyModified(CheckMethod method) const
1626 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1627 // if method == timestamp, check timestamp before checksum
1628 return (method == checksum_method
1629 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1630 && pimpl_->checksum_ != sum(pimpl_->filename);
1634 void Buffer::markClean() const
1636 if (!pimpl_->lyx_clean) {
1637 pimpl_->lyx_clean = true;
1640 // if the .lyx file has been saved, we don't need an
1642 pimpl_->bak_clean = true;
1646 void Buffer::markBakClean()
1648 pimpl_->bak_clean = true;
1652 void Buffer::setUnnamed(bool flag)
1654 pimpl_->unnamed = flag;
1658 bool Buffer::isUnnamed() const
1660 return pimpl_->unnamed;
1664 // FIXME: this function should be moved to buffer_pimpl.C
1665 void Buffer::markDirty()
1667 if (pimpl_->lyx_clean) {
1668 pimpl_->lyx_clean = false;
1671 pimpl_->bak_clean = false;
1673 DepClean::iterator it = pimpl_->dep_clean.begin();
1674 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1676 for (; it != end; ++it)
1681 string const Buffer::fileName() const
1683 return pimpl_->filename.absFilename();
1687 string const & Buffer::filePath() const
1689 return params().filepath;
1693 bool Buffer::isReadonly() const
1695 return pimpl_->read_only;
1699 void Buffer::setParentName(string const & name)
1701 if (name == pimpl_->filename.absFilename())
1702 // Avoids recursive include.
1703 params().parentname.clear();
1705 params().parentname = name;
1709 Buffer const * Buffer::getMasterBuffer() const
1711 if (!params().parentname.empty()
1712 && theBufferList().exists(params().parentname)) {
1713 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1714 //We need to check if the parent is us...
1715 //FIXME RECURSIVE INCLUDE
1716 //This is not sufficient, since recursive includes could be downstream.
1717 if (buf && buf != this)
1718 return buf->getMasterBuffer();
1725 Buffer * Buffer::getMasterBuffer()
1727 if (!params().parentname.empty()
1728 && theBufferList().exists(params().parentname)) {
1729 Buffer * buf = theBufferList().getBuffer(params().parentname);
1731 return buf->getMasterBuffer();
1738 MacroData const & Buffer::getMacro(docstring const & name) const
1740 return pimpl_->macros.get(name);
1744 bool Buffer::hasMacro(docstring const & name) const
1746 return pimpl_->macros.has(name);
1750 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1752 MacroTable::globalMacros().insert(name, data);
1753 pimpl_->macros.insert(name, data);
1757 void Buffer::buildMacros()
1759 // Start with global table.
1760 pimpl_->macros = MacroTable::globalMacros();
1763 ParagraphList const & pars = text().paragraphs();
1764 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1765 //lyxerr << "searching main par " << i
1766 // << " for macro definitions" << std::endl;
1767 InsetList const & insets = pars[i].insetlist;
1768 InsetList::const_iterator it = insets.begin();
1769 InsetList::const_iterator end = insets.end();
1770 for ( ; it != end; ++it) {
1771 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1772 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1773 MathMacroTemplate const & mac
1774 = static_cast<MathMacroTemplate const &>(*it->inset);
1775 insertMacro(mac.name(), mac.asMacroData());
1782 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1785 //FIXME: This does not work for child documents yet.
1786 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1787 // Check if the label 'from' appears more than once
1788 vector<docstring> labels;
1790 if (code == Inset::CITE_CODE) {
1792 keys.fillWithBibKeys(this);
1793 BiblioInfo::const_iterator bit = keys.begin();
1794 BiblioInfo::const_iterator bend = keys.end();
1796 for (; bit != bend; ++bit)
1798 labels.push_back(bit->first);
1800 getLabelList(labels);
1802 if (std::count(labels.begin(), labels.end(), from) > 1)
1805 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1806 if (it->lyxCode() == code) {
1807 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1808 inset.replaceContents(to_utf8(from), to_utf8(to));
1814 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1815 pit_type par_end, bool full_source)
1817 OutputParams runparams(¶ms().encoding());
1818 runparams.nice = true;
1819 runparams.flavor = OutputParams::LATEX;
1820 runparams.linelen = lyxrc.plaintext_linelen;
1821 // No side effect of file copying and image conversion
1822 runparams.dryrun = true;
1826 os << "% " << _("Preview source code") << "\n\n";
1830 writeLaTeXSource(os, filePath(), runparams, true, true);
1832 writeDocBookSource(os, fileName(), runparams, false);
1835 runparams.par_begin = par_begin;
1836 runparams.par_end = par_end;
1837 if (par_begin + 1 == par_end)
1839 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1843 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1844 convert<docstring>(par_begin),
1845 convert<docstring>(par_end - 1))
1849 // output paragraphs
1851 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1854 docbookParagraphs(paragraphs(), *this, os, runparams);
1860 ErrorList const & Buffer::errorList(string const & type) const
1862 static ErrorList const emptyErrorList;
1863 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1864 if (I == pimpl_->errorLists.end())
1865 return emptyErrorList;
1871 ErrorList & Buffer::errorList(string const & type)
1873 return pimpl_->errorLists[type];