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"
58 #include "insets/InsetBibitem.h"
59 #include "insets/InsetBibtex.h"
60 #include "insets/InsetInclude.h"
61 #include "insets/InsetText.h"
63 #include "mathed/MathMacroTemplate.h"
64 #include "mathed/MacroTable.h"
65 #include "mathed/MathSupport.h"
67 #include "frontends/alert.h"
69 #include "graphics/Previews.h"
71 #include "support/types.h"
72 #include "support/lyxalgo.h"
73 #include "support/filetools.h"
74 #include "support/fs_extras.h"
75 #include "support/gzstream.h"
76 #include "support/lyxlib.h"
77 #include "support/os.h"
78 #include "support/Path.h"
79 #include "support/textutils.h"
80 #include "support/convert.h"
82 #include <boost/bind.hpp>
83 #include <boost/filesystem/exception.hpp>
84 #include <boost/filesystem/operations.hpp>
99 using std::ostringstream;
110 using support::addName;
111 using support::bformat;
112 using support::changeExtension;
113 using support::cmd_ret;
114 using support::createBufferTmpDir;
115 using support::destroyDir;
116 using support::FileName;
117 using support::getFormatFromContents;
118 using support::libFileSearch;
119 using support::latex_path;
120 using support::ltrim;
121 using support::makeAbsPath;
122 using support::makeDisplayPath;
123 using support::makeLatexName;
124 using support::onlyFilename;
125 using support::onlyPath;
126 using support::quoteName;
127 using support::removeAutosaveFile;
128 using support::rename;
129 using support::runCommand;
130 using support::split;
131 using support::subst;
132 using support::tempName;
136 namespace Alert = frontend::Alert;
137 namespace os = support::os;
138 namespace fs = boost::filesystem;
142 int const LYX_FORMAT = 281;
147 typedef std::map<string, bool> DepClean;
152 Impl(Buffer & parent, FileName const & file, bool readonly);
154 limited_stack<Undo> undostack;
155 limited_stack<Undo> redostack;
161 /// need to regenerate .tex?
165 mutable bool lyx_clean;
167 /// is autosave needed?
168 mutable bool bak_clean;
170 /// is this a unnamed file (New...)?
176 /// name of the file the buffer is associated with.
179 /** Set to true only when the file is fully loaded.
180 * Used to prevent the premature generation of previews
181 * and by the citation inset.
183 bool file_fully_loaded;
185 /// our Text that should be wrapped in an InsetText
192 TocBackend toc_backend;
194 /// Container for all sort of Buffer dependant errors.
195 map<string, ErrorList> errorLists;
197 /// timestamp and checksum used to test if the file has been externally
198 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200 unsigned long checksum_;
204 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
205 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
206 filename(file), file_fully_loaded(false), inset(params),
207 toc_backend(&parent), timestamp_(0), checksum_(0)
209 inset.setAutoBreakRows(true);
210 lyxvc.buffer(&parent);
211 temppath = createBufferTmpDir();
212 params.filepath = onlyPath(file.absFilename());
213 // FIXME: And now do something if temppath == string(), because we
214 // assume from now on that temppath points to a valid temp dir.
215 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
219 Buffer::Buffer(string const & file, bool readonly)
220 : pimpl_(new Impl(*this, FileName(file), readonly))
222 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
228 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
229 // here the buffer should take care that it is
230 // saved properly, before it goes into the void.
232 Buffer * master = getMasterBuffer();
233 if (master != this && use_gui)
234 // We are closing buf which was a child document so we
235 // must update the labels and section numbering of its master
237 updateLabels(*master);
239 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
240 Alert::warning(_("Could not remove temporary directory"),
241 bformat(_("Could not remove the temporary directory %1$s"),
242 from_utf8(temppath())));
245 // Remove any previewed LaTeX snippets associated with this buffer.
246 graphics::Previews::get().removeLoader(*this);
252 Text & Buffer::text() const
254 return const_cast<Text &>(pimpl_->inset.text_);
258 Inset & Buffer::inset() const
260 return const_cast<InsetText &>(pimpl_->inset);
264 limited_stack<Undo> & Buffer::undostack()
266 return pimpl_->undostack;
270 limited_stack<Undo> const & Buffer::undostack() const
272 return pimpl_->undostack;
276 limited_stack<Undo> & Buffer::redostack()
278 return pimpl_->redostack;
282 limited_stack<Undo> const & Buffer::redostack() const
284 return pimpl_->redostack;
288 BufferParams & Buffer::params()
290 return pimpl_->params;
294 BufferParams const & Buffer::params() const
296 return pimpl_->params;
300 ParagraphList & Buffer::paragraphs()
302 return text().paragraphs();
306 ParagraphList const & Buffer::paragraphs() const
308 return text().paragraphs();
312 LyXVC & Buffer::lyxvc()
314 return pimpl_->lyxvc;
318 LyXVC const & Buffer::lyxvc() const
320 return pimpl_->lyxvc;
324 string const & Buffer::temppath() const
326 return pimpl_->temppath;
330 TexRow & Buffer::texrow()
332 return pimpl_->texrow;
336 TexRow const & Buffer::texrow() const
338 return pimpl_->texrow;
342 TocBackend & Buffer::tocBackend()
344 return pimpl_->toc_backend;
348 TocBackend const & Buffer::tocBackend() const
350 return pimpl_->toc_backend;
354 string const Buffer::getLatexName(bool const no_path) const
356 string const name = changeExtension(makeLatexName(fileName()), ".tex");
357 return no_path ? onlyFilename(name) : name;
361 pair<Buffer::LogType, string> const Buffer::getLogName() const
363 string const filename = getLatexName(false);
365 if (filename.empty())
366 return make_pair(Buffer::latexlog, string());
368 string const path = temppath();
370 FileName const fname(addName(temppath(),
371 onlyFilename(changeExtension(filename,
373 FileName const bname(
374 addName(path, onlyFilename(
375 changeExtension(filename,
376 formats.extension("literate") + ".out"))));
378 // If no Latex log or Build log is newer, show Build log
380 if (fs::exists(bname.toFilesystemEncoding()) &&
381 (!fs::exists(fname.toFilesystemEncoding()) ||
382 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
383 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
384 return make_pair(Buffer::buildlog, bname.absFilename());
386 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
387 return make_pair(Buffer::latexlog, fname.absFilename());
391 void Buffer::setReadonly(bool const flag)
393 if (pimpl_->read_only != flag) {
394 pimpl_->read_only = flag;
400 void Buffer::setFileName(string const & newfile)
402 pimpl_->filename = makeAbsPath(newfile);
403 params().filepath = onlyPath(pimpl_->filename.absFilename());
404 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
409 // We'll remove this later. (Lgb)
412 void unknownClass(string const & unknown)
414 Alert::warning(_("Unknown document class"),
415 bformat(_("Using the default document class, because the "
416 "class %1$s is unknown."), from_utf8(unknown)));
422 int Buffer::readHeader(Lexer & lex)
424 int unknown_tokens = 0;
426 int begin_header_line = -1;
428 // Initialize parameters that may be/go lacking in header:
429 params().branchlist().clear();
430 params().preamble.erase();
431 params().options.erase();
432 params().float_placement.erase();
433 params().paperwidth.erase();
434 params().paperheight.erase();
435 params().leftmargin.erase();
436 params().rightmargin.erase();
437 params().topmargin.erase();
438 params().bottommargin.erase();
439 params().headheight.erase();
440 params().headsep.erase();
441 params().footskip.erase();
442 params().listings_params.clear();
443 params().clearLayoutModules();
445 for (int i = 0; i < 4; ++i) {
446 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
447 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
450 ErrorList & errorList = pimpl_->errorLists["Parse"];
454 string const token = lex.getString();
459 if (token == "\\end_header")
463 if (token == "\\begin_header") {
464 begin_header_line = line;
468 LYXERR(Debug::PARSER) << "Handling document header token: `"
469 << token << '\'' << endl;
471 string unknown = params().readToken(lex, token);
472 if (!unknown.empty()) {
473 if (unknown[0] != '\\' && token == "\\textclass") {
474 unknownClass(unknown);
477 docstring const s = bformat(_("Unknown token: "
481 errorList.push_back(ErrorItem(_("Document header error"),
486 if (begin_header_line) {
487 docstring const s = _("\\begin_header is missing");
488 errorList.push_back(ErrorItem(_("Document header error"),
492 return unknown_tokens;
497 // changed to be public and have one parameter
498 // Returns false if "\end_document" is not read (Asger)
499 bool Buffer::readDocument(Lexer & lex)
501 ErrorList & errorList = pimpl_->errorLists["Parse"];
505 string const token = lex.getString();
506 if (token != "\\begin_document") {
507 docstring const s = _("\\begin_document is missing");
508 errorList.push_back(ErrorItem(_("Document header error"),
512 // we are reading in a brand new document
513 BOOST_ASSERT(paragraphs().empty());
516 if (!params().getTextClass().load(filePath())) {
517 string theclass = params().getTextClass().name();
518 Alert::error(_("Can't load document class"), bformat(
519 _("Using the default document class, because the "
520 "class %1$s could not be loaded."), from_utf8(theclass)));
521 params().setBaseClass(defaultTextclass());
524 if (params().outputChanges) {
525 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
526 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
527 LaTeXFeatures::isAvailable("xcolor");
529 if (!dvipost && !xcolorsoul) {
530 Alert::warning(_("Changes not shown in LaTeX output"),
531 _("Changes will not be highlighted in LaTeX output, "
532 "because neither dvipost nor xcolor/soul are installed.\n"
533 "Please install these packages or redefine "
534 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
535 } else if (!xcolorsoul) {
536 Alert::warning(_("Changes not shown in LaTeX output"),
537 _("Changes will not be highlighted in LaTeX output "
538 "when using pdflatex, because xcolor and soul are not installed.\n"
539 "Please install both packages or redefine "
540 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
544 bool const res = text().read(*this, lex, errorList);
545 for_each(text().paragraphs().begin(),
546 text().paragraphs().end(),
547 bind(&Paragraph::setInsetOwner, _1, &inset()));
553 // needed to insert the selection
554 void Buffer::insertStringAsLines(ParagraphList & pars,
555 pit_type & pit, pos_type & pos,
556 Font const & fn, docstring const & str, bool autobreakrows)
560 // insert the string, don't insert doublespace
561 bool space_inserted = true;
562 for (docstring::const_iterator cit = str.begin();
563 cit != str.end(); ++cit) {
564 Paragraph & par = pars[pit];
566 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
567 breakParagraph(params(), pars, pit, pos,
568 par.layout()->isEnvironment());
571 space_inserted = true;
575 // do not insert consecutive spaces if !free_spacing
576 } else if ((*cit == ' ' || *cit == '\t') &&
577 space_inserted && !par.isFreeSpacing()) {
579 } else if (*cit == '\t') {
580 if (!par.isFreeSpacing()) {
581 // tabs are like spaces here
582 par.insertChar(pos, ' ', font, params().trackChanges);
584 space_inserted = true;
586 const pos_type n = 8 - pos % 8;
587 for (pos_type i = 0; i < n; ++i) {
588 par.insertChar(pos, ' ', font, params().trackChanges);
591 space_inserted = true;
593 } else if (!isPrintable(*cit)) {
594 // Ignore unprintables
597 // just insert the character
598 par.insertChar(pos, *cit, font, params().trackChanges);
600 space_inserted = (*cit == ' ');
607 bool Buffer::readString(std::string const & s)
609 params().compressed = false;
611 // remove dummy empty par
612 paragraphs().clear();
614 std::istringstream is(s);
616 FileName const name(tempName());
617 switch (readFile(lex, name, true)) {
621 // We need to call lyx2lyx, so write the input to a file
622 std::ofstream os(name.toFilesystemEncoding().c_str());
625 return readFile(name);
635 bool Buffer::readFile(FileName const & filename)
637 // Check if the file is compressed.
638 string const format = getFormatFromContents(filename);
639 if (format == "gzip" || format == "zip" || format == "compress") {
640 params().compressed = true;
643 // remove dummy empty par
644 paragraphs().clear();
646 lex.setFile(filename);
647 if (readFile(lex, filename) != success)
654 bool Buffer::fully_loaded() const
656 return pimpl_->file_fully_loaded;
660 void Buffer::fully_loaded(bool const value)
662 pimpl_->file_fully_loaded = value;
666 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
669 BOOST_ASSERT(!filename.empty());
672 Alert::error(_("Document could not be read"),
673 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
678 string const token(lex.getString());
681 Alert::error(_("Document could not be read"),
682 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
686 // the first token _must_ be...
687 if (token != "\\lyxformat") {
688 lyxerr << "Token: " << token << endl;
690 Alert::error(_("Document format failure"),
691 bformat(_("%1$s is not a LyX document."),
692 from_utf8(filename.absFilename())));
697 string tmp_format = lex.getString();
698 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
699 // if present remove ".," from string.
700 string::size_type dot = tmp_format.find_first_of(".,");
701 //lyxerr << " dot found at " << dot << endl;
702 if (dot != string::npos)
703 tmp_format.erase(dot, 1);
704 int const file_format = convert<int>(tmp_format);
705 //lyxerr << "format: " << file_format << endl;
707 // save timestamp and checksum of the original disk file, making sure
708 // to not overwrite them with those of the file created in the tempdir
709 // when it has to be converted to the current format.
710 if (!pimpl_->checksum_) {
711 pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
712 pimpl_->checksum_ = sum(filename);
715 if (file_format != LYX_FORMAT) {
718 // lyx2lyx would fail
721 FileName const tmpfile(tempName());
722 if (tmpfile.empty()) {
723 Alert::error(_("Conversion failed"),
724 bformat(_("%1$s is from a different"
725 " version of LyX, but a temporary"
726 " file for converting it could"
728 from_utf8(filename.absFilename())));
731 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
732 if (lyx2lyx.empty()) {
733 Alert::error(_("Conversion script not found"),
734 bformat(_("%1$s is from a different"
735 " version of LyX, but the"
736 " conversion script lyx2lyx"
737 " could not be found."),
738 from_utf8(filename.absFilename())));
741 ostringstream command;
742 command << os::python()
743 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
744 << " -t " << convert<string>(LYX_FORMAT)
745 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
746 << ' ' << quoteName(filename.toFilesystemEncoding());
747 string const command_str = command.str();
749 LYXERR(Debug::INFO) << "Running '"
750 << command_str << '\''
753 cmd_ret const ret = runCommand(command_str);
754 if (ret.first != 0) {
755 Alert::error(_("Conversion script failed"),
756 bformat(_("%1$s is from a different version"
757 " of LyX, but the lyx2lyx script"
758 " failed to convert it."),
759 from_utf8(filename.absFilename())));
762 bool const ret = readFile(tmpfile);
763 // Do stuff with tmpfile name and buffer name here.
764 return ret ? success : failure;
769 if (readDocument(lex)) {
770 Alert::error(_("Document format failure"),
771 bformat(_("%1$s ended unexpectedly, which means"
772 " that it is probably corrupted."),
773 from_utf8(filename.absFilename())));
776 //lyxerr << "removing " << MacroTable::localMacros().size()
777 // << " temporary macro entries" << endl;
778 //MacroTable::localMacros().clear();
780 pimpl_->file_fully_loaded = true;
785 // Should probably be moved to somewhere else: BufferView? LyXView?
786 bool Buffer::save() const
788 // We don't need autosaves in the immediate future. (Asger)
789 resetAutosaveTimers();
791 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
794 bool madeBackup = false;
796 // make a backup if the file already exists
797 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
798 backupName = FileName(fileName() + '~');
799 if (!lyxrc.backupdir_path.empty())
800 backupName = FileName(addName(lyxrc.backupdir_path,
801 subst(os::internal_path(backupName.absFilename()), '/', '!')));
804 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
806 } catch (fs::filesystem_error const & fe) {
807 Alert::error(_("Backup failure"),
808 bformat(_("Cannot create backup file %1$s.\n"
809 "Please check whether the directory exists and is writeable."),
810 from_utf8(backupName.absFilename())));
811 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
815 // ask if the disk file has been externally modified (use checksum method)
816 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
817 docstring const file = makeDisplayPath(fileName(), 20);
818 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
819 "you want to overwrite this file?"), file);
820 int const ret = Alert::prompt(_("Overwrite modified file?"),
821 text, 1, 1, _("&Overwrite"), _("&Cancel"));
826 if (writeFile(pimpl_->filename)) {
828 removeAutosaveFile(fileName());
829 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
830 pimpl_->checksum_ = sum(pimpl_->filename);
833 // Saving failed, so backup is not backup
835 rename(backupName, pimpl_->filename);
841 bool Buffer::writeFile(FileName const & fname) const
843 if (pimpl_->read_only && fname == pimpl_->filename)
848 if (params().compressed) {
849 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
855 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
866 bool Buffer::write(ostream & ofs) const
869 // Use the standard "C" locale for file output.
870 ofs.imbue(std::locale::classic());
873 // The top of the file should not be written by params().
875 // write out a comment in the top of the file
876 ofs << "#LyX " << lyx_version
877 << " created this file. For more info see http://www.lyx.org/\n"
878 << "\\lyxformat " << LYX_FORMAT << "\n"
879 << "\\begin_document\n";
882 /// For each author, set 'used' to true if there is a change
883 /// by this author in the document; otherwise set it to 'false'.
884 AuthorList::Authors::const_iterator a_it = params().authors().begin();
885 AuthorList::Authors::const_iterator a_end = params().authors().end();
886 for (; a_it != a_end; ++a_it)
887 a_it->second.used(false);
889 ParIterator const end = par_iterator_end();
890 ParIterator it = par_iterator_begin();
891 for ( ; it != end; ++it)
892 it->checkAuthors(params().authors());
894 // now write out the buffer parameters.
895 ofs << "\\begin_header\n";
896 params().writeFile(ofs);
897 ofs << "\\end_header\n";
900 ofs << "\n\\begin_body\n";
901 text().write(*this, ofs);
902 ofs << "\n\\end_body\n";
904 // Write marker that shows file is complete
905 ofs << "\\end_document" << endl;
907 // Shouldn't really be needed....
910 // how to check if close went ok?
911 // Following is an attempt... (BE 20001011)
913 // good() returns false if any error occured, including some
915 // bad() returns true if something bad happened in the buffer,
916 // which should include file system full errors.
921 lyxerr << "File was not closed properly." << endl;
928 bool Buffer::makeLaTeXFile(FileName const & fname,
929 string const & original_path,
930 OutputParams const & runparams,
931 bool output_preamble, bool output_body)
933 string const encoding = runparams.encoding->iconvName();
934 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
935 << encoding << "..." << endl;
937 odocfstream ofs(encoding);
938 if (!openFileWrite(ofs, fname))
941 //TexStream ts(ofs.rdbuf(), &texrow());
943 bool failed_export = false;
946 writeLaTeXSource(ofs, original_path,
947 runparams, output_preamble, output_body);
949 catch (iconv_codecvt_facet_exception & e) {
950 lyxerr << "Caught iconv exception: " << e.what() << endl;
951 failed_export = true;
953 catch (std::exception const & e) {
954 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
955 failed_export = true;
958 lyxerr << "Caught some really weird exception..." << endl;
959 LyX::cref().emergencyCleanup();
965 failed_export = true;
966 lyxerr << "File '" << fname << "' was not closed properly." << endl;
970 Alert::error(_("Encoding error"),
971 _("Some characters of your document are probably not "
972 "representable in the chosen encoding.\n"
973 "Changing the document encoding to utf8 could help."));
980 void Buffer::writeLaTeXSource(odocstream & os,
981 string const & original_path,
982 OutputParams const & runparams_in,
983 bool const output_preamble, bool const output_body)
985 OutputParams runparams = runparams_in;
987 // validate the buffer.
988 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
989 LaTeXFeatures features(*this, params(), runparams);
991 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
993 // The starting paragraph of the coming rows is the
994 // first paragraph of the document. (Asger)
995 if (output_preamble && runparams.nice) {
996 os << "%% LyX " << lyx_version << " created this file. "
997 "For more info, see http://www.lyx.org/.\n"
998 "%% Do not edit unless you really know what "
1003 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1004 // There are a few differences between nice LaTeX and usual files:
1005 // usual is \batchmode and has a
1006 // special input@path to allow the including of figures
1007 // with either \input or \includegraphics (what figinsets do).
1008 // input@path is set when the actual parameter
1009 // original_path is set. This is done for usual tex-file, but not
1010 // for nice-latex-file. (Matthias 250696)
1011 // Note that input@path is only needed for something the user does
1012 // in the preamble, included .tex files or ERT, files included by
1013 // LyX work without it.
1014 if (output_preamble) {
1015 if (!runparams.nice) {
1016 // code for usual, NOT nice-latex-file
1017 os << "\\batchmode\n"; // changed
1018 // from \nonstopmode
1021 if (!original_path.empty()) {
1023 // We don't know the encoding of inputpath
1024 docstring const inputpath = from_utf8(latex_path(original_path));
1025 os << "\\makeatletter\n"
1026 << "\\def\\input@path{{"
1027 << inputpath << "/}}\n"
1028 << "\\makeatother\n";
1034 // Write the preamble
1035 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1041 os << "\\begin{document}\n";
1043 } // output_preamble
1045 texrow().start(paragraphs().begin()->id(), 0);
1047 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1049 if (!lyxrc.language_auto_begin &&
1050 !params().language->babel().empty()) {
1052 os << from_utf8(subst(lyxrc.language_command_begin,
1054 params().language->babel()))
1059 Encoding const & encoding = params().encoding();
1060 if (encoding.package() == Encoding::CJK) {
1061 // Open a CJK environment, since in contrast to the encodings
1062 // handled by inputenc the document encoding is not set in
1063 // the preamble if it is handled by CJK.sty.
1064 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1069 // if we are doing a real file with body, even if this is the
1070 // child of some other buffer, let's cut the link here.
1071 // This happens for example if only a child document is printed.
1072 string save_parentname;
1073 if (output_preamble) {
1074 save_parentname = params().parentname;
1075 params().parentname.erase();
1078 loadChildDocuments(*this);
1081 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1083 // Restore the parenthood if needed
1084 if (output_preamble)
1085 params().parentname = save_parentname;
1087 // add this just in case after all the paragraphs
1091 if (encoding.package() == Encoding::CJK) {
1092 // Close the open CJK environment.
1093 // latexParagraphs will have opened one even if the last text
1095 os << "\\end{CJK}\n";
1099 if (!lyxrc.language_auto_end &&
1100 !params().language->babel().empty()) {
1101 os << from_utf8(subst(lyxrc.language_command_end,
1103 params().language->babel()))
1108 if (output_preamble) {
1109 os << "\\end{document}\n";
1112 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1114 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1117 runparams_in.encoding = runparams.encoding;
1119 // Just to be sure. (Asger)
1122 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1123 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1128 bool Buffer::isLatex() const
1130 return params().getTextClass().outputType() == LATEX;
1134 bool Buffer::isLiterate() const
1136 return params().getTextClass().outputType() == LITERATE;
1140 bool Buffer::isDocBook() const
1142 return params().getTextClass().outputType() == DOCBOOK;
1146 void Buffer::makeDocBookFile(FileName const & fname,
1147 OutputParams const & runparams,
1148 bool const body_only)
1150 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1154 if (!openFileWrite(ofs, fname))
1157 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1161 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1165 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1166 OutputParams const & runparams,
1167 bool const only_body)
1169 LaTeXFeatures features(*this, params(), runparams);
1174 TextClass const & tclass = params().getTextClass();
1175 string const top_element = tclass.latexname();
1178 if (runparams.flavor == OutputParams::XML)
1179 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1182 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1185 if (! tclass.class_header().empty())
1186 os << from_ascii(tclass.class_header());
1187 else if (runparams.flavor == OutputParams::XML)
1188 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1189 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1191 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1193 docstring preamble = from_utf8(params().preamble);
1194 if (runparams.flavor != OutputParams::XML ) {
1195 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1196 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1197 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1198 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1201 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1203 preamble += features.getIncludedFiles(name);
1204 preamble += features.getLyXSGMLEntities();
1206 if (!preamble.empty()) {
1207 os << "\n [ " << preamble << " ]";
1212 string top = top_element;
1214 if (runparams.flavor == OutputParams::XML)
1215 top += params().language->code();
1217 top += params().language->code().substr(0,2);
1220 if (!params().options.empty()) {
1222 top += params().options;
1225 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1226 << " file was created by LyX " << lyx_version
1227 << "\n See http://www.lyx.org/ for more information -->\n";
1229 params().getTextClass().counters().reset();
1231 loadChildDocuments(*this);
1233 sgml::openTag(os, top);
1235 docbookParagraphs(paragraphs(), *this, os, runparams);
1236 sgml::closeTag(os, top_element);
1240 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1241 // Other flags: -wall -v0 -x
1242 int Buffer::runChktex()
1246 // get LaTeX-Filename
1247 FileName const path(temppath());
1248 string const name = addName(path.absFilename(), getLatexName());
1249 string const org_path = filePath();
1251 support::Path p(path); // path to LaTeX file
1252 message(_("Running chktex..."));
1254 // Generate the LaTeX file if neccessary
1255 OutputParams runparams(¶ms().encoding());
1256 runparams.flavor = OutputParams::LATEX;
1257 runparams.nice = false;
1258 makeLaTeXFile(FileName(name), org_path, runparams);
1261 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1262 int const res = chktex.run(terr); // run chktex
1265 Alert::error(_("chktex failure"),
1266 _("Could not run chktex successfully."));
1267 } else if (res > 0) {
1268 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1269 // Clear out old errors
1271 // Fill-in the error list with the TeX errors
1272 bufferErrors(*this, terr, errorList);
1283 void Buffer::validate(LaTeXFeatures & features) const
1285 TextClass const & tclass = params().getTextClass();
1287 if (params().outputChanges) {
1288 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1289 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1290 LaTeXFeatures::isAvailable("xcolor");
1292 if (features.runparams().flavor == OutputParams::LATEX) {
1294 features.require("ct-dvipost");
1295 features.require("dvipost");
1296 } else if (xcolorsoul) {
1297 features.require("ct-xcolor-soul");
1298 features.require("soul");
1299 features.require("xcolor");
1301 features.require("ct-none");
1303 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1305 features.require("ct-xcolor-soul");
1306 features.require("soul");
1307 features.require("xcolor");
1308 features.require("pdfcolmk"); // improves color handling in PDF output
1310 features.require("ct-none");
1315 // AMS Style is at document level
1316 if (params().use_amsmath == BufferParams::package_on
1317 || tclass.provides("amsmath"))
1318 features.require("amsmath");
1319 if (params().use_esint == BufferParams::package_on)
1320 features.require("esint");
1322 loadChildDocuments(*this);
1324 for_each(paragraphs().begin(), paragraphs().end(),
1325 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1327 // the bullet shapes are buffer level not paragraph level
1328 // so they are tested here
1329 for (int i = 0; i < 4; ++i) {
1330 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1331 int const font = params().user_defined_bullet(i).getFont();
1333 int const c = params()
1334 .user_defined_bullet(i)
1341 features.require("latexsym");
1343 } else if (font == 1) {
1344 features.require("amssymb");
1345 } else if ((font >= 2 && font <= 5)) {
1346 features.require("pifont");
1351 if (lyxerr.debugging(Debug::LATEX)) {
1352 features.showStruct();
1357 void Buffer::getLabelList(vector<docstring> & list) const
1359 /// if this is a child document and the parent is already loaded
1360 /// Use the parent's list instead [ale990407]
1361 Buffer const * tmp = getMasterBuffer();
1363 lyxerr << "getMasterBuffer() failed!" << endl;
1367 tmp->getLabelList(list);
1371 loadChildDocuments(*this);
1373 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1374 it.nextInset()->getLabelList(*this, list);
1378 void Buffer::updateBibfilesCache()
1380 // if this is a child document and the parent is already loaded
1381 // update the parent's cache instead
1382 Buffer * tmp = getMasterBuffer();
1385 tmp->updateBibfilesCache();
1389 bibfilesCache_.clear();
1390 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1391 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1392 InsetBibtex const & inset =
1393 static_cast<InsetBibtex const &>(*it);
1394 vector<FileName> const bibfiles = inset.getFiles(*this);
1395 bibfilesCache_.insert(bibfilesCache_.end(),
1398 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1399 InsetInclude & inset =
1400 static_cast<InsetInclude &>(*it);
1401 inset.updateBibfilesCache(*this);
1402 vector<FileName> const & bibfiles =
1403 inset.getBibfilesCache(*this);
1404 bibfilesCache_.insert(bibfilesCache_.end(),
1412 vector<FileName> const & Buffer::getBibfilesCache() const
1414 // if this is a child document and the parent is already loaded
1415 // use the parent's cache instead
1416 Buffer const * tmp = getMasterBuffer();
1419 return tmp->getBibfilesCache();
1421 // We update the cache when first used instead of at loading time.
1422 if (bibfilesCache_.empty())
1423 const_cast<Buffer *>(this)->updateBibfilesCache();
1425 return bibfilesCache_;
1429 bool Buffer::isDepClean(string const & name) const
1431 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1432 if (it == pimpl_->dep_clean.end())
1438 void Buffer::markDepClean(string const & name)
1440 pimpl_->dep_clean[name] = true;
1444 bool Buffer::dispatch(string const & command, bool * result)
1446 return dispatch(lyxaction.lookupFunc(command), result);
1450 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1452 bool dispatched = true;
1454 switch (func.action) {
1455 case LFUN_BUFFER_EXPORT: {
1456 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1469 void Buffer::changeLanguage(Language const * from, Language const * to)
1474 for_each(par_iterator_begin(),
1476 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1478 text().current_font.setLanguage(to);
1479 text().real_current_font.setLanguage(to);
1483 bool Buffer::isMultiLingual() const
1485 ParConstIterator end = par_iterator_end();
1486 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1487 if (it->isMultiLingual(params()))
1494 ParIterator Buffer::getParFromID(int const id) const
1496 ParConstIterator it = par_iterator_begin();
1497 ParConstIterator const end = par_iterator_end();
1500 // John says this is called with id == -1 from undo
1501 lyxerr << "getParFromID(), id: " << id << endl;
1505 for (; it != end; ++it)
1513 bool Buffer::hasParWithID(int const id) const
1515 ParConstIterator const it = getParFromID(id);
1516 return it != par_iterator_end();
1520 ParIterator Buffer::par_iterator_begin()
1522 return lyx::par_iterator_begin(inset());
1526 ParIterator Buffer::par_iterator_end()
1528 return lyx::par_iterator_end(inset());
1532 ParConstIterator Buffer::par_iterator_begin() const
1534 return lyx::par_const_iterator_begin(inset());
1538 ParConstIterator Buffer::par_iterator_end() const
1540 return lyx::par_const_iterator_end(inset());
1544 Language const * Buffer::getLanguage() const
1546 return params().language;
1550 docstring const Buffer::B_(string const & l10n) const
1552 return params().B_(l10n);
1556 bool Buffer::isClean() const
1558 return pimpl_->lyx_clean;
1562 bool Buffer::isBakClean() const
1564 return pimpl_->bak_clean;
1568 bool Buffer::isExternallyModified(CheckMethod method) const
1570 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1571 // if method == timestamp, check timestamp before checksum
1572 return (method == checksum_method
1573 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1574 && pimpl_->checksum_ != sum(pimpl_->filename);
1578 void Buffer::markClean() const
1580 if (!pimpl_->lyx_clean) {
1581 pimpl_->lyx_clean = true;
1584 // if the .lyx file has been saved, we don't need an
1586 pimpl_->bak_clean = true;
1590 void Buffer::markBakClean()
1592 pimpl_->bak_clean = true;
1596 void Buffer::setUnnamed(bool flag)
1598 pimpl_->unnamed = flag;
1602 bool Buffer::isUnnamed() const
1604 return pimpl_->unnamed;
1608 // FIXME: this function should be moved to buffer_pimpl.C
1609 void Buffer::markDirty()
1611 if (pimpl_->lyx_clean) {
1612 pimpl_->lyx_clean = false;
1615 pimpl_->bak_clean = false;
1617 DepClean::iterator it = pimpl_->dep_clean.begin();
1618 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1620 for (; it != end; ++it)
1625 string const Buffer::fileName() const
1627 return pimpl_->filename.absFilename();
1631 string const & Buffer::filePath() const
1633 return params().filepath;
1637 bool Buffer::isReadonly() const
1639 return pimpl_->read_only;
1643 void Buffer::setParentName(string const & name)
1645 if (name == pimpl_->filename.absFilename())
1646 // Avoids recursive include.
1647 params().parentname.clear();
1649 params().parentname = name;
1653 Buffer const * Buffer::getMasterBuffer() const
1655 if (!params().parentname.empty()
1656 && theBufferList().exists(params().parentname)) {
1657 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1658 //We need to check if the parent is us...
1659 //FIXME RECURSIVE INCLUDE
1660 //This is not sufficient, since recursive includes could be downstream.
1661 if (buf && buf != this)
1662 return buf->getMasterBuffer();
1669 Buffer * Buffer::getMasterBuffer()
1671 if (!params().parentname.empty()
1672 && theBufferList().exists(params().parentname)) {
1673 Buffer * buf = theBufferList().getBuffer(params().parentname);
1675 return buf->getMasterBuffer();
1682 MacroData const & Buffer::getMacro(docstring const & name) const
1684 return pimpl_->macros.get(name);
1688 bool Buffer::hasMacro(docstring const & name) const
1690 return pimpl_->macros.has(name);
1694 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1696 MacroTable::globalMacros().insert(name, data);
1697 pimpl_->macros.insert(name, data);
1701 void Buffer::buildMacros()
1703 // Start with global table.
1704 pimpl_->macros = MacroTable::globalMacros();
1707 ParagraphList const & pars = text().paragraphs();
1708 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1709 //lyxerr << "searching main par " << i
1710 // << " for macro definitions" << std::endl;
1711 InsetList const & insets = pars[i].insetlist;
1712 InsetList::const_iterator it = insets.begin();
1713 InsetList::const_iterator end = insets.end();
1714 for ( ; it != end; ++it) {
1715 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1716 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1717 MathMacroTemplate const & mac
1718 = static_cast<MathMacroTemplate const &>(*it->inset);
1719 insertMacro(mac.name(), mac.asMacroData());
1726 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1729 //FIXME: This does not work for child documents yet.
1730 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1731 // Check if the label 'from' appears more than once
1732 vector<docstring> labels;
1734 if (code == Inset::CITE_CODE) {
1736 keys.fillWithBibKeys(this);
1737 BiblioInfo::const_iterator bit = keys.begin();
1738 BiblioInfo::const_iterator bend = keys.end();
1740 for (; bit != bend; ++bit)
1742 labels.push_back(bit->first);
1744 getLabelList(labels);
1746 if (std::count(labels.begin(), labels.end(), from) > 1)
1749 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1750 if (it->lyxCode() == code) {
1751 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1752 inset.replaceContents(to_utf8(from), to_utf8(to));
1758 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1759 pit_type par_end, bool full_source)
1761 OutputParams runparams(¶ms().encoding());
1762 runparams.nice = true;
1763 runparams.flavor = OutputParams::LATEX;
1764 runparams.linelen = lyxrc.plaintext_linelen;
1765 // No side effect of file copying and image conversion
1766 runparams.dryrun = true;
1770 os << "% " << _("Preview source code") << "\n\n";
1774 writeLaTeXSource(os, filePath(), runparams, true, true);
1776 writeDocBookSource(os, fileName(), runparams, false);
1779 runparams.par_begin = par_begin;
1780 runparams.par_end = par_end;
1781 if (par_begin + 1 == par_end)
1783 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1787 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1788 convert<docstring>(par_begin),
1789 convert<docstring>(par_end - 1))
1793 // output paragraphs
1795 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1798 docbookParagraphs(paragraphs(), *this, os, runparams);
1804 ErrorList const & Buffer::errorList(string const & type) const
1806 static ErrorList const emptyErrorList;
1807 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1808 if (I == pimpl_->errorLists.end())
1809 return emptyErrorList;
1815 ErrorList & Buffer::errorList(string const & type)
1817 return pimpl_->errorLists[type];