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 = 280;
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();
444 for (int i = 0; i < 4; ++i) {
445 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
446 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
449 ErrorList & errorList = pimpl_->errorLists["Parse"];
453 string const token = lex.getString();
458 if (token == "\\end_header")
462 if (token == "\\begin_header") {
463 begin_header_line = line;
467 LYXERR(Debug::PARSER) << "Handling document header token: `"
468 << token << '\'' << endl;
470 string unknown = params().readToken(lex, token);
471 if (!unknown.empty()) {
472 if (unknown[0] != '\\' && token == "\\textclass") {
473 unknownClass(unknown);
476 docstring const s = bformat(_("Unknown token: "
480 errorList.push_back(ErrorItem(_("Document header error"),
485 if (begin_header_line) {
486 docstring const s = _("\\begin_header is missing");
487 errorList.push_back(ErrorItem(_("Document header error"),
491 return unknown_tokens;
496 // changed to be public and have one parameter
497 // Returns false if "\end_document" is not read (Asger)
498 bool Buffer::readDocument(Lexer & lex)
500 ErrorList & errorList = pimpl_->errorLists["Parse"];
504 string const token = lex.getString();
505 if (token != "\\begin_document") {
506 docstring const s = _("\\begin_document is missing");
507 errorList.push_back(ErrorItem(_("Document header error"),
511 // we are reading in a brand new document
512 BOOST_ASSERT(paragraphs().empty());
515 if (!params().getTextClass().load(filePath())) {
516 string theclass = params().getTextClass().name();
517 Alert::error(_("Can't load document class"), bformat(
518 _("Using the default document class, because the "
519 "class %1$s could not be loaded."), from_utf8(theclass)));
520 params().setBaseClass(defaultTextclass());
523 if (params().outputChanges) {
524 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
525 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
526 LaTeXFeatures::isAvailable("xcolor");
528 if (!dvipost && !xcolorsoul) {
529 Alert::warning(_("Changes not shown in LaTeX output"),
530 _("Changes will not be highlighted in LaTeX output, "
531 "because neither dvipost nor xcolor/soul are installed.\n"
532 "Please install these packages or redefine "
533 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
534 } else if (!xcolorsoul) {
535 Alert::warning(_("Changes not shown in LaTeX output"),
536 _("Changes will not be highlighted in LaTeX output "
537 "when using pdflatex, because xcolor and soul are not installed.\n"
538 "Please install both packages or redefine "
539 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
543 bool const res = text().read(*this, lex, errorList);
544 for_each(text().paragraphs().begin(),
545 text().paragraphs().end(),
546 bind(&Paragraph::setInsetOwner, _1, &inset()));
552 // needed to insert the selection
553 void Buffer::insertStringAsLines(ParagraphList & pars,
554 pit_type & pit, pos_type & pos,
555 Font const & fn, docstring const & str, bool autobreakrows)
559 // insert the string, don't insert doublespace
560 bool space_inserted = true;
561 for (docstring::const_iterator cit = str.begin();
562 cit != str.end(); ++cit) {
563 Paragraph & par = pars[pit];
565 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
566 breakParagraph(params(), pars, pit, pos,
567 par.layout()->isEnvironment());
570 space_inserted = true;
574 // do not insert consecutive spaces if !free_spacing
575 } else if ((*cit == ' ' || *cit == '\t') &&
576 space_inserted && !par.isFreeSpacing()) {
578 } else if (*cit == '\t') {
579 if (!par.isFreeSpacing()) {
580 // tabs are like spaces here
581 par.insertChar(pos, ' ', font, params().trackChanges);
583 space_inserted = true;
585 const pos_type n = 8 - pos % 8;
586 for (pos_type i = 0; i < n; ++i) {
587 par.insertChar(pos, ' ', font, params().trackChanges);
590 space_inserted = true;
592 } else if (!isPrintable(*cit)) {
593 // Ignore unprintables
596 // just insert the character
597 par.insertChar(pos, *cit, font, params().trackChanges);
599 space_inserted = (*cit == ' ');
606 bool Buffer::readString(std::string const & s)
608 params().compressed = false;
610 // remove dummy empty par
611 paragraphs().clear();
613 std::istringstream is(s);
615 FileName const name(tempName());
616 switch (readFile(lex, name, true)) {
620 // We need to call lyx2lyx, so write the input to a file
621 std::ofstream os(name.toFilesystemEncoding().c_str());
624 return readFile(name);
634 bool Buffer::readFile(FileName const & filename)
636 // Check if the file is compressed.
637 string const format = getFormatFromContents(filename);
638 if (format == "gzip" || format == "zip" || format == "compress") {
639 params().compressed = true;
642 // remove dummy empty par
643 paragraphs().clear();
645 lex.setFile(filename);
646 if (readFile(lex, filename) != success)
653 bool Buffer::fully_loaded() const
655 return pimpl_->file_fully_loaded;
659 void Buffer::fully_loaded(bool const value)
661 pimpl_->file_fully_loaded = value;
665 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
668 BOOST_ASSERT(!filename.empty());
671 Alert::error(_("Document could not be read"),
672 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
677 string const token(lex.getString());
680 Alert::error(_("Document could not be read"),
681 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
685 // the first token _must_ be...
686 if (token != "\\lyxformat") {
687 lyxerr << "Token: " << token << endl;
689 Alert::error(_("Document format failure"),
690 bformat(_("%1$s is not a LyX document."),
691 from_utf8(filename.absFilename())));
696 string tmp_format = lex.getString();
697 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
698 // if present remove ".," from string.
699 string::size_type dot = tmp_format.find_first_of(".,");
700 //lyxerr << " dot found at " << dot << endl;
701 if (dot != string::npos)
702 tmp_format.erase(dot, 1);
703 int const file_format = convert<int>(tmp_format);
704 //lyxerr << "format: " << file_format << endl;
706 if (file_format != LYX_FORMAT) {
709 // lyx2lyx would fail
712 FileName const tmpfile(tempName());
713 if (tmpfile.empty()) {
714 Alert::error(_("Conversion failed"),
715 bformat(_("%1$s is from a different"
716 " version of LyX, but a temporary"
717 " file for converting it could"
719 from_utf8(filename.absFilename())));
722 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
723 if (lyx2lyx.empty()) {
724 Alert::error(_("Conversion script not found"),
725 bformat(_("%1$s is from a different"
726 " version of LyX, but the"
727 " conversion script lyx2lyx"
728 " could not be found."),
729 from_utf8(filename.absFilename())));
732 ostringstream command;
733 command << os::python()
734 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
735 << " -t " << convert<string>(LYX_FORMAT)
736 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
737 << ' ' << quoteName(filename.toFilesystemEncoding());
738 string const command_str = command.str();
740 LYXERR(Debug::INFO) << "Running '"
741 << command_str << '\''
744 cmd_ret const ret = runCommand(command_str);
745 if (ret.first != 0) {
746 Alert::error(_("Conversion script failed"),
747 bformat(_("%1$s is from a different version"
748 " of LyX, but the lyx2lyx script"
749 " failed to convert it."),
750 from_utf8(filename.absFilename())));
753 bool const ret = readFile(tmpfile);
754 // Do stuff with tmpfile name and buffer name here.
755 return ret ? success : failure;
760 if (readDocument(lex)) {
761 Alert::error(_("Document format failure"),
762 bformat(_("%1$s ended unexpectedly, which means"
763 " that it is probably corrupted."),
764 from_utf8(filename.absFilename())));
767 //lyxerr << "removing " << MacroTable::localMacros().size()
768 // << " temporary macro entries" << endl;
769 //MacroTable::localMacros().clear();
771 pimpl_->file_fully_loaded = true;
772 // save the timestamp and checksum of disk file
773 pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
774 pimpl_->checksum_ = sum(filename);
779 // Should probably be moved to somewhere else: BufferView? LyXView?
780 bool Buffer::save() const
782 // We don't need autosaves in the immediate future. (Asger)
783 resetAutosaveTimers();
785 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
788 bool madeBackup = false;
790 // make a backup if the file already exists
791 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
792 backupName = FileName(fileName() + '~');
793 if (!lyxrc.backupdir_path.empty())
794 backupName = FileName(addName(lyxrc.backupdir_path,
795 subst(os::internal_path(backupName.absFilename()), '/', '!')));
798 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
800 } catch (fs::filesystem_error const & fe) {
801 Alert::error(_("Backup failure"),
802 bformat(_("Cannot create backup file %1$s.\n"
803 "Please check whether the directory exists and is writeable."),
804 from_utf8(backupName.absFilename())));
805 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
809 // ask if the disk file has been externally modified (use checksum method)
810 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
811 docstring const file = makeDisplayPath(fileName(), 20);
812 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
813 "you want to overwrite this file?"), file);
814 int const ret = Alert::prompt(_("Overwrite modified file?"),
815 text, 1, 1, _("&Overwrite"), _("&Cancel"));
820 if (writeFile(pimpl_->filename)) {
822 removeAutosaveFile(fileName());
823 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
824 pimpl_->checksum_ = sum(pimpl_->filename);
827 // Saving failed, so backup is not backup
829 rename(backupName, pimpl_->filename);
835 bool Buffer::writeFile(FileName const & fname) const
837 if (pimpl_->read_only && fname == pimpl_->filename)
842 if (params().compressed) {
843 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
849 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
860 bool Buffer::write(ostream & ofs) const
863 // Use the standard "C" locale for file output.
864 ofs.imbue(std::locale::classic());
867 // The top of the file should not be written by params().
869 // write out a comment in the top of the file
870 ofs << "#LyX " << lyx_version
871 << " created this file. For more info see http://www.lyx.org/\n"
872 << "\\lyxformat " << LYX_FORMAT << "\n"
873 << "\\begin_document\n";
876 /// For each author, set 'used' to true if there is a change
877 /// by this author in the document; otherwise set it to 'false'.
878 AuthorList::Authors::const_iterator a_it = params().authors().begin();
879 AuthorList::Authors::const_iterator a_end = params().authors().end();
880 for (; a_it != a_end; ++a_it)
881 a_it->second.used(false);
883 ParIterator const end = par_iterator_end();
884 ParIterator it = par_iterator_begin();
885 for ( ; it != end; ++it)
886 it->checkAuthors(params().authors());
888 // now write out the buffer parameters.
889 ofs << "\\begin_header\n";
890 params().writeFile(ofs);
891 ofs << "\\end_header\n";
894 ofs << "\n\\begin_body\n";
895 text().write(*this, ofs);
896 ofs << "\n\\end_body\n";
898 // Write marker that shows file is complete
899 ofs << "\\end_document" << endl;
901 // Shouldn't really be needed....
904 // how to check if close went ok?
905 // Following is an attempt... (BE 20001011)
907 // good() returns false if any error occured, including some
909 // bad() returns true if something bad happened in the buffer,
910 // which should include file system full errors.
915 lyxerr << "File was not closed properly." << endl;
922 bool Buffer::makeLaTeXFile(FileName const & fname,
923 string const & original_path,
924 OutputParams const & runparams,
925 bool output_preamble, bool output_body)
927 string const encoding = runparams.encoding->iconvName();
928 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
929 << encoding << "..." << endl;
931 odocfstream ofs(encoding);
932 if (!openFileWrite(ofs, fname))
935 //TexStream ts(ofs.rdbuf(), &texrow());
937 bool failed_export = false;
940 writeLaTeXSource(ofs, original_path,
941 runparams, output_preamble, output_body);
943 catch (iconv_codecvt_facet_exception & e) {
944 lyxerr << "Caught iconv exception: " << e.what() << endl;
945 failed_export = true;
947 catch (std::exception const & e) {
948 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
949 failed_export = true;
952 lyxerr << "Caught some really weird exception..." << endl;
953 LyX::cref().emergencyCleanup();
959 failed_export = true;
960 lyxerr << "File '" << fname << "' was not closed properly." << endl;
964 Alert::error(_("Encoding error"),
965 _("Some characters of your document are probably not "
966 "representable in the chosen encoding.\n"
967 "Changing the document encoding to utf8 could help."));
974 void Buffer::writeLaTeXSource(odocstream & os,
975 string const & original_path,
976 OutputParams const & runparams_in,
977 bool const output_preamble, bool const output_body)
979 OutputParams runparams = runparams_in;
981 // validate the buffer.
982 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
983 LaTeXFeatures features(*this, params(), runparams);
985 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
987 // The starting paragraph of the coming rows is the
988 // first paragraph of the document. (Asger)
989 if (output_preamble && runparams.nice) {
990 os << "%% LyX " << lyx_version << " created this file. "
991 "For more info, see http://www.lyx.org/.\n"
992 "%% Do not edit unless you really know what "
997 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
998 // There are a few differences between nice LaTeX and usual files:
999 // usual is \batchmode and has a
1000 // special input@path to allow the including of figures
1001 // with either \input or \includegraphics (what figinsets do).
1002 // input@path is set when the actual parameter
1003 // original_path is set. This is done for usual tex-file, but not
1004 // for nice-latex-file. (Matthias 250696)
1005 // Note that input@path is only needed for something the user does
1006 // in the preamble, included .tex files or ERT, files included by
1007 // LyX work without it.
1008 if (output_preamble) {
1009 if (!runparams.nice) {
1010 // code for usual, NOT nice-latex-file
1011 os << "\\batchmode\n"; // changed
1012 // from \nonstopmode
1015 if (!original_path.empty()) {
1017 // We don't know the encoding of inputpath
1018 docstring const inputpath = from_utf8(latex_path(original_path));
1019 os << "\\makeatletter\n"
1020 << "\\def\\input@path{{"
1021 << inputpath << "/}}\n"
1022 << "\\makeatother\n";
1028 // Write the preamble
1029 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1035 os << "\\begin{document}\n";
1037 } // output_preamble
1039 texrow().start(paragraphs().begin()->id(), 0);
1041 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1043 if (!lyxrc.language_auto_begin &&
1044 !params().language->babel().empty()) {
1046 os << from_utf8(subst(lyxrc.language_command_begin,
1048 params().language->babel()))
1053 Encoding const & encoding = params().encoding();
1054 if (encoding.package() == Encoding::CJK) {
1055 // Open a CJK environment, since in contrast to the encodings
1056 // handled by inputenc the document encoding is not set in
1057 // the preamble if it is handled by CJK.sty.
1058 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1063 // if we are doing a real file with body, even if this is the
1064 // child of some other buffer, let's cut the link here.
1065 // This happens for example if only a child document is printed.
1066 string save_parentname;
1067 if (output_preamble) {
1068 save_parentname = params().parentname;
1069 params().parentname.erase();
1072 loadChildDocuments(*this);
1075 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1077 // Restore the parenthood if needed
1078 if (output_preamble)
1079 params().parentname = save_parentname;
1081 // add this just in case after all the paragraphs
1085 if (encoding.package() == Encoding::CJK) {
1086 // Close the open CJK environment.
1087 // latexParagraphs will have opened one even if the last text
1089 os << "\\end{CJK}\n";
1093 if (!lyxrc.language_auto_end &&
1094 !params().language->babel().empty()) {
1095 os << from_utf8(subst(lyxrc.language_command_end,
1097 params().language->babel()))
1102 if (output_preamble) {
1103 os << "\\end{document}\n";
1106 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1108 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1111 runparams_in.encoding = runparams.encoding;
1113 // Just to be sure. (Asger)
1116 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1117 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1122 bool Buffer::isLatex() const
1124 return params().getTextClass().outputType() == LATEX;
1128 bool Buffer::isLiterate() const
1130 return params().getTextClass().outputType() == LITERATE;
1134 bool Buffer::isDocBook() const
1136 return params().getTextClass().outputType() == DOCBOOK;
1140 void Buffer::makeDocBookFile(FileName const & fname,
1141 OutputParams const & runparams,
1142 bool const body_only)
1144 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1148 if (!openFileWrite(ofs, fname))
1151 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1155 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1159 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1160 OutputParams const & runparams,
1161 bool const only_body)
1163 LaTeXFeatures features(*this, params(), runparams);
1168 TextClass const & tclass = params().getTextClass();
1169 string const top_element = tclass.latexname();
1172 if (runparams.flavor == OutputParams::XML)
1173 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1176 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1179 if (! tclass.class_header().empty())
1180 os << from_ascii(tclass.class_header());
1181 else if (runparams.flavor == OutputParams::XML)
1182 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1183 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1185 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1187 docstring preamble = from_utf8(params().preamble);
1188 if (runparams.flavor != OutputParams::XML ) {
1189 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1190 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1191 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1192 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1195 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1197 preamble += features.getIncludedFiles(name);
1198 preamble += features.getLyXSGMLEntities();
1200 if (!preamble.empty()) {
1201 os << "\n [ " << preamble << " ]";
1206 string top = top_element;
1208 if (runparams.flavor == OutputParams::XML)
1209 top += params().language->code();
1211 top += params().language->code().substr(0,2);
1214 if (!params().options.empty()) {
1216 top += params().options;
1219 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1220 << " file was created by LyX " << lyx_version
1221 << "\n See http://www.lyx.org/ for more information -->\n";
1223 params().getTextClass().counters().reset();
1225 loadChildDocuments(*this);
1227 sgml::openTag(os, top);
1229 docbookParagraphs(paragraphs(), *this, os, runparams);
1230 sgml::closeTag(os, top_element);
1234 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1235 // Other flags: -wall -v0 -x
1236 int Buffer::runChktex()
1240 // get LaTeX-Filename
1241 FileName const path(temppath());
1242 string const name = addName(path.absFilename(), getLatexName());
1243 string const org_path = filePath();
1245 support::Path p(path); // path to LaTeX file
1246 message(_("Running chktex..."));
1248 // Generate the LaTeX file if neccessary
1249 OutputParams runparams(¶ms().encoding());
1250 runparams.flavor = OutputParams::LATEX;
1251 runparams.nice = false;
1252 makeLaTeXFile(FileName(name), org_path, runparams);
1255 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1256 int const res = chktex.run(terr); // run chktex
1259 Alert::error(_("chktex failure"),
1260 _("Could not run chktex successfully."));
1261 } else if (res > 0) {
1262 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1263 // Clear out old errors
1265 // Fill-in the error list with the TeX errors
1266 bufferErrors(*this, terr, errorList);
1277 void Buffer::validate(LaTeXFeatures & features) const
1279 TextClass const & tclass = params().getTextClass();
1281 if (params().outputChanges) {
1282 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1283 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1284 LaTeXFeatures::isAvailable("xcolor");
1286 if (features.runparams().flavor == OutputParams::LATEX) {
1288 features.require("ct-dvipost");
1289 features.require("dvipost");
1290 } else if (xcolorsoul) {
1291 features.require("ct-xcolor-soul");
1292 features.require("soul");
1293 features.require("xcolor");
1295 features.require("ct-none");
1297 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1299 features.require("ct-xcolor-soul");
1300 features.require("soul");
1301 features.require("xcolor");
1302 features.require("pdfcolmk"); // improves color handling in PDF output
1304 features.require("ct-none");
1309 // AMS Style is at document level
1310 if (params().use_amsmath == BufferParams::package_on
1311 || tclass.provides("amsmath"))
1312 features.require("amsmath");
1313 if (params().use_esint == BufferParams::package_on)
1314 features.require("esint");
1316 loadChildDocuments(*this);
1318 for_each(paragraphs().begin(), paragraphs().end(),
1319 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1321 // the bullet shapes are buffer level not paragraph level
1322 // so they are tested here
1323 for (int i = 0; i < 4; ++i) {
1324 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1325 int const font = params().user_defined_bullet(i).getFont();
1327 int const c = params()
1328 .user_defined_bullet(i)
1335 features.require("latexsym");
1337 } else if (font == 1) {
1338 features.require("amssymb");
1339 } else if ((font >= 2 && font <= 5)) {
1340 features.require("pifont");
1345 if (lyxerr.debugging(Debug::LATEX)) {
1346 features.showStruct();
1351 void Buffer::getLabelList(vector<docstring> & list) const
1353 /// if this is a child document and the parent is already loaded
1354 /// Use the parent's list instead [ale990407]
1355 Buffer const * tmp = getMasterBuffer();
1357 lyxerr << "getMasterBuffer() failed!" << endl;
1361 tmp->getLabelList(list);
1365 loadChildDocuments(*this);
1367 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1368 it.nextInset()->getLabelList(*this, list);
1372 void Buffer::updateBibfilesCache()
1374 // if this is a child document and the parent is already loaded
1375 // update the parent's cache instead
1376 Buffer * tmp = getMasterBuffer();
1379 tmp->updateBibfilesCache();
1383 bibfilesCache_.clear();
1384 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1385 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1386 InsetBibtex const & inset =
1387 static_cast<InsetBibtex const &>(*it);
1388 vector<FileName> const bibfiles = inset.getFiles(*this);
1389 bibfilesCache_.insert(bibfilesCache_.end(),
1392 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1393 InsetInclude & inset =
1394 static_cast<InsetInclude &>(*it);
1395 inset.updateBibfilesCache(*this);
1396 vector<FileName> const & bibfiles =
1397 inset.getBibfilesCache(*this);
1398 bibfilesCache_.insert(bibfilesCache_.end(),
1406 vector<FileName> const & Buffer::getBibfilesCache() const
1408 // if this is a child document and the parent is already loaded
1409 // use the parent's cache instead
1410 Buffer const * tmp = getMasterBuffer();
1413 return tmp->getBibfilesCache();
1415 // We update the cache when first used instead of at loading time.
1416 if (bibfilesCache_.empty())
1417 const_cast<Buffer *>(this)->updateBibfilesCache();
1419 return bibfilesCache_;
1423 bool Buffer::isDepClean(string const & name) const
1425 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1426 if (it == pimpl_->dep_clean.end())
1432 void Buffer::markDepClean(string const & name)
1434 pimpl_->dep_clean[name] = true;
1438 bool Buffer::dispatch(string const & command, bool * result)
1440 return dispatch(lyxaction.lookupFunc(command), result);
1444 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1446 bool dispatched = true;
1448 switch (func.action) {
1449 case LFUN_BUFFER_EXPORT: {
1450 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1463 void Buffer::changeLanguage(Language const * from, Language const * to)
1468 for_each(par_iterator_begin(),
1470 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1472 text().current_font.setLanguage(to);
1473 text().real_current_font.setLanguage(to);
1477 bool Buffer::isMultiLingual() const
1479 ParConstIterator end = par_iterator_end();
1480 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1481 if (it->isMultiLingual(params()))
1488 ParIterator Buffer::getParFromID(int const id) const
1490 ParConstIterator it = par_iterator_begin();
1491 ParConstIterator const end = par_iterator_end();
1494 // John says this is called with id == -1 from undo
1495 lyxerr << "getParFromID(), id: " << id << endl;
1499 for (; it != end; ++it)
1507 bool Buffer::hasParWithID(int const id) const
1509 ParConstIterator const it = getParFromID(id);
1510 return it != par_iterator_end();
1514 ParIterator Buffer::par_iterator_begin()
1516 return lyx::par_iterator_begin(inset());
1520 ParIterator Buffer::par_iterator_end()
1522 return lyx::par_iterator_end(inset());
1526 ParConstIterator Buffer::par_iterator_begin() const
1528 return lyx::par_const_iterator_begin(inset());
1532 ParConstIterator Buffer::par_iterator_end() const
1534 return lyx::par_const_iterator_end(inset());
1538 Language const * Buffer::getLanguage() const
1540 return params().language;
1544 docstring const Buffer::B_(string const & l10n) const
1546 return params().B_(l10n);
1550 bool Buffer::isClean() const
1552 return pimpl_->lyx_clean;
1556 bool Buffer::isBakClean() const
1558 return pimpl_->bak_clean;
1562 bool Buffer::isExternallyModified(CheckMethod method) const
1564 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1565 // if method == timestamp, check timestamp before checksum
1566 return (method == checksum_method
1567 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1568 && pimpl_->checksum_ != sum(pimpl_->filename);
1572 void Buffer::markClean() const
1574 if (!pimpl_->lyx_clean) {
1575 pimpl_->lyx_clean = true;
1578 // if the .lyx file has been saved, we don't need an
1580 pimpl_->bak_clean = true;
1584 void Buffer::markBakClean()
1586 pimpl_->bak_clean = true;
1590 void Buffer::setUnnamed(bool flag)
1592 pimpl_->unnamed = flag;
1596 bool Buffer::isUnnamed() const
1598 return pimpl_->unnamed;
1602 // FIXME: this function should be moved to buffer_pimpl.C
1603 void Buffer::markDirty()
1605 if (pimpl_->lyx_clean) {
1606 pimpl_->lyx_clean = false;
1609 pimpl_->bak_clean = false;
1611 DepClean::iterator it = pimpl_->dep_clean.begin();
1612 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1614 for (; it != end; ++it)
1619 string const Buffer::fileName() const
1621 return pimpl_->filename.absFilename();
1625 string const & Buffer::filePath() const
1627 return params().filepath;
1631 bool Buffer::isReadonly() const
1633 return pimpl_->read_only;
1637 void Buffer::setParentName(string const & name)
1639 if (name == pimpl_->filename.absFilename())
1640 // Avoids recursive include.
1641 params().parentname.clear();
1643 params().parentname = name;
1647 Buffer const * Buffer::getMasterBuffer() const
1649 if (!params().parentname.empty()
1650 && theBufferList().exists(params().parentname)) {
1651 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1652 //We need to check if the parent is us...
1653 //FIXME RECURSIVE INCLUDE
1654 //This is not sufficient, since recursive includes could be downstream.
1655 if (buf && buf != this)
1656 return buf->getMasterBuffer();
1663 Buffer * Buffer::getMasterBuffer()
1665 if (!params().parentname.empty()
1666 && theBufferList().exists(params().parentname)) {
1667 Buffer * buf = theBufferList().getBuffer(params().parentname);
1669 return buf->getMasterBuffer();
1676 MacroData const & Buffer::getMacro(docstring const & name) const
1678 return pimpl_->macros.get(name);
1682 bool Buffer::hasMacro(docstring const & name) const
1684 return pimpl_->macros.has(name);
1688 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1690 MacroTable::globalMacros().insert(name, data);
1691 pimpl_->macros.insert(name, data);
1695 void Buffer::buildMacros()
1697 // Start with global table.
1698 pimpl_->macros = MacroTable::globalMacros();
1701 ParagraphList const & pars = text().paragraphs();
1702 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1703 //lyxerr << "searching main par " << i
1704 // << " for macro definitions" << std::endl;
1705 InsetList const & insets = pars[i].insetlist;
1706 InsetList::const_iterator it = insets.begin();
1707 InsetList::const_iterator end = insets.end();
1708 for ( ; it != end; ++it) {
1709 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1710 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1711 MathMacroTemplate const & mac
1712 = static_cast<MathMacroTemplate const &>(*it->inset);
1713 insertMacro(mac.name(), mac.asMacroData());
1720 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1723 //FIXME: This does not work for child documents yet.
1724 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1725 // Check if the label 'from' appears more than once
1726 vector<docstring> labels;
1728 if (code == Inset::CITE_CODE) {
1730 keys.fillWithBibKeys(this);
1731 BiblioInfo::const_iterator bit = keys.begin();
1732 BiblioInfo::const_iterator bend = keys.end();
1734 for (; bit != bend; ++bit)
1736 labels.push_back(bit->first);
1738 getLabelList(labels);
1740 if (std::count(labels.begin(), labels.end(), from) > 1)
1743 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1744 if (it->lyxCode() == code) {
1745 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1746 inset.replaceContents(to_utf8(from), to_utf8(to));
1752 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1753 pit_type par_end, bool full_source)
1755 OutputParams runparams(¶ms().encoding());
1756 runparams.nice = true;
1757 runparams.flavor = OutputParams::LATEX;
1758 runparams.linelen = lyxrc.plaintext_linelen;
1759 // No side effect of file copying and image conversion
1760 runparams.dryrun = true;
1764 os << "% " << _("Preview source code") << "\n\n";
1768 writeLaTeXSource(os, filePath(), runparams, true, true);
1770 writeDocBookSource(os, fileName(), runparams, false);
1773 runparams.par_begin = par_begin;
1774 runparams.par_end = par_end;
1775 if (par_begin + 1 == par_end)
1777 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1781 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1782 convert<docstring>(par_begin),
1783 convert<docstring>(par_end - 1))
1787 // output paragraphs
1789 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1792 docbookParagraphs(paragraphs(), *this, os, runparams);
1798 ErrorList const & Buffer::errorList(string const & type) const
1800 static ErrorList const emptyErrorList;
1801 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1802 if (I == pimpl_->errorLists.end())
1803 return emptyErrorList;
1809 ErrorList & Buffer::errorList(string const & type)
1811 return pimpl_->errorLists[type];