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 if (file_format != LYX_FORMAT) {
710 // lyx2lyx would fail
713 FileName const tmpfile(tempName());
714 if (tmpfile.empty()) {
715 Alert::error(_("Conversion failed"),
716 bformat(_("%1$s is from a different"
717 " version of LyX, but a temporary"
718 " file for converting it could"
720 from_utf8(filename.absFilename())));
723 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
724 if (lyx2lyx.empty()) {
725 Alert::error(_("Conversion script not found"),
726 bformat(_("%1$s is from a different"
727 " version of LyX, but the"
728 " conversion script lyx2lyx"
729 " could not be found."),
730 from_utf8(filename.absFilename())));
733 ostringstream command;
734 command << os::python()
735 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
736 << " -t " << convert<string>(LYX_FORMAT)
737 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
738 << ' ' << quoteName(filename.toFilesystemEncoding());
739 string const command_str = command.str();
741 LYXERR(Debug::INFO) << "Running '"
742 << command_str << '\''
745 cmd_ret const ret = runCommand(command_str);
746 if (ret.first != 0) {
747 Alert::error(_("Conversion script failed"),
748 bformat(_("%1$s is from a different version"
749 " of LyX, but the lyx2lyx script"
750 " failed to convert it."),
751 from_utf8(filename.absFilename())));
754 bool const ret = readFile(tmpfile);
755 // Do stuff with tmpfile name and buffer name here.
756 return ret ? success : failure;
761 if (readDocument(lex)) {
762 Alert::error(_("Document format failure"),
763 bformat(_("%1$s ended unexpectedly, which means"
764 " that it is probably corrupted."),
765 from_utf8(filename.absFilename())));
768 //lyxerr << "removing " << MacroTable::localMacros().size()
769 // << " temporary macro entries" << endl;
770 //MacroTable::localMacros().clear();
772 pimpl_->file_fully_loaded = true;
773 // save the timestamp and checksum of disk file
774 pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
775 pimpl_->checksum_ = sum(filename);
780 // Should probably be moved to somewhere else: BufferView? LyXView?
781 bool Buffer::save() const
783 // We don't need autosaves in the immediate future. (Asger)
784 resetAutosaveTimers();
786 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
789 bool madeBackup = false;
791 // make a backup if the file already exists
792 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
793 backupName = FileName(fileName() + '~');
794 if (!lyxrc.backupdir_path.empty())
795 backupName = FileName(addName(lyxrc.backupdir_path,
796 subst(os::internal_path(backupName.absFilename()), '/', '!')));
799 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
801 } catch (fs::filesystem_error const & fe) {
802 Alert::error(_("Backup failure"),
803 bformat(_("Cannot create backup file %1$s.\n"
804 "Please check whether the directory exists and is writeable."),
805 from_utf8(backupName.absFilename())));
806 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
810 // ask if the disk file has been externally modified (use checksum method)
811 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
812 docstring const file = makeDisplayPath(fileName(), 20);
813 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
814 "you want to overwrite this file?"), file);
815 int const ret = Alert::prompt(_("Overwrite modified file?"),
816 text, 1, 1, _("&Overwrite"), _("&Cancel"));
821 if (writeFile(pimpl_->filename)) {
823 removeAutosaveFile(fileName());
824 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
825 pimpl_->checksum_ = sum(pimpl_->filename);
828 // Saving failed, so backup is not backup
830 rename(backupName, pimpl_->filename);
836 bool Buffer::writeFile(FileName const & fname) const
838 if (pimpl_->read_only && fname == pimpl_->filename)
843 if (params().compressed) {
844 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
850 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
861 bool Buffer::write(ostream & ofs) const
864 // Use the standard "C" locale for file output.
865 ofs.imbue(std::locale::classic());
868 // The top of the file should not be written by params().
870 // write out a comment in the top of the file
871 ofs << "#LyX " << lyx_version
872 << " created this file. For more info see http://www.lyx.org/\n"
873 << "\\lyxformat " << LYX_FORMAT << "\n"
874 << "\\begin_document\n";
877 /// For each author, set 'used' to true if there is a change
878 /// by this author in the document; otherwise set it to 'false'.
879 AuthorList::Authors::const_iterator a_it = params().authors().begin();
880 AuthorList::Authors::const_iterator a_end = params().authors().end();
881 for (; a_it != a_end; ++a_it)
882 a_it->second.used(false);
884 ParIterator const end = par_iterator_end();
885 ParIterator it = par_iterator_begin();
886 for ( ; it != end; ++it)
887 it->checkAuthors(params().authors());
889 // now write out the buffer parameters.
890 ofs << "\\begin_header\n";
891 params().writeFile(ofs);
892 ofs << "\\end_header\n";
895 ofs << "\n\\begin_body\n";
896 text().write(*this, ofs);
897 ofs << "\n\\end_body\n";
899 // Write marker that shows file is complete
900 ofs << "\\end_document" << endl;
902 // Shouldn't really be needed....
905 // how to check if close went ok?
906 // Following is an attempt... (BE 20001011)
908 // good() returns false if any error occured, including some
910 // bad() returns true if something bad happened in the buffer,
911 // which should include file system full errors.
916 lyxerr << "File was not closed properly." << endl;
923 bool Buffer::makeLaTeXFile(FileName const & fname,
924 string const & original_path,
925 OutputParams const & runparams,
926 bool output_preamble, bool output_body)
928 string const encoding = runparams.encoding->iconvName();
929 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
930 << encoding << "..." << endl;
932 odocfstream ofs(encoding);
933 if (!openFileWrite(ofs, fname))
936 //TexStream ts(ofs.rdbuf(), &texrow());
938 bool failed_export = false;
941 writeLaTeXSource(ofs, original_path,
942 runparams, output_preamble, output_body);
944 catch (iconv_codecvt_facet_exception & e) {
945 lyxerr << "Caught iconv exception: " << e.what() << endl;
946 failed_export = true;
948 catch (std::exception const & e) {
949 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
950 failed_export = true;
953 lyxerr << "Caught some really weird exception..." << endl;
954 LyX::cref().emergencyCleanup();
960 failed_export = true;
961 lyxerr << "File '" << fname << "' was not closed properly." << endl;
965 Alert::error(_("Encoding error"),
966 _("Some characters of your document are probably not "
967 "representable in the chosen encoding.\n"
968 "Changing the document encoding to utf8 could help."));
975 void Buffer::writeLaTeXSource(odocstream & os,
976 string const & original_path,
977 OutputParams const & runparams_in,
978 bool const output_preamble, bool const output_body)
980 OutputParams runparams = runparams_in;
982 // validate the buffer.
983 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
984 LaTeXFeatures features(*this, params(), runparams);
986 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
988 // The starting paragraph of the coming rows is the
989 // first paragraph of the document. (Asger)
990 if (output_preamble && runparams.nice) {
991 os << "%% LyX " << lyx_version << " created this file. "
992 "For more info, see http://www.lyx.org/.\n"
993 "%% Do not edit unless you really know what "
998 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
999 // There are a few differences between nice LaTeX and usual files:
1000 // usual is \batchmode and has a
1001 // special input@path to allow the including of figures
1002 // with either \input or \includegraphics (what figinsets do).
1003 // input@path is set when the actual parameter
1004 // original_path is set. This is done for usual tex-file, but not
1005 // for nice-latex-file. (Matthias 250696)
1006 // Note that input@path is only needed for something the user does
1007 // in the preamble, included .tex files or ERT, files included by
1008 // LyX work without it.
1009 if (output_preamble) {
1010 if (!runparams.nice) {
1011 // code for usual, NOT nice-latex-file
1012 os << "\\batchmode\n"; // changed
1013 // from \nonstopmode
1016 if (!original_path.empty()) {
1018 // We don't know the encoding of inputpath
1019 docstring const inputpath = from_utf8(latex_path(original_path));
1020 os << "\\makeatletter\n"
1021 << "\\def\\input@path{{"
1022 << inputpath << "/}}\n"
1023 << "\\makeatother\n";
1029 // Write the preamble
1030 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1036 os << "\\begin{document}\n";
1038 } // output_preamble
1040 texrow().start(paragraphs().begin()->id(), 0);
1042 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1044 if (!lyxrc.language_auto_begin &&
1045 !params().language->babel().empty()) {
1047 os << from_utf8(subst(lyxrc.language_command_begin,
1049 params().language->babel()))
1054 Encoding const & encoding = params().encoding();
1055 if (encoding.package() == Encoding::CJK) {
1056 // Open a CJK environment, since in contrast to the encodings
1057 // handled by inputenc the document encoding is not set in
1058 // the preamble if it is handled by CJK.sty.
1059 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1064 // if we are doing a real file with body, even if this is the
1065 // child of some other buffer, let's cut the link here.
1066 // This happens for example if only a child document is printed.
1067 string save_parentname;
1068 if (output_preamble) {
1069 save_parentname = params().parentname;
1070 params().parentname.erase();
1073 loadChildDocuments(*this);
1076 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1078 // Restore the parenthood if needed
1079 if (output_preamble)
1080 params().parentname = save_parentname;
1082 // add this just in case after all the paragraphs
1086 if (encoding.package() == Encoding::CJK) {
1087 // Close the open CJK environment.
1088 // latexParagraphs will have opened one even if the last text
1090 os << "\\end{CJK}\n";
1094 if (!lyxrc.language_auto_end &&
1095 !params().language->babel().empty()) {
1096 os << from_utf8(subst(lyxrc.language_command_end,
1098 params().language->babel()))
1103 if (output_preamble) {
1104 os << "\\end{document}\n";
1107 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1109 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1112 runparams_in.encoding = runparams.encoding;
1114 // Just to be sure. (Asger)
1117 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1118 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1123 bool Buffer::isLatex() const
1125 return params().getTextClass().outputType() == LATEX;
1129 bool Buffer::isLiterate() const
1131 return params().getTextClass().outputType() == LITERATE;
1135 bool Buffer::isDocBook() const
1137 return params().getTextClass().outputType() == DOCBOOK;
1141 void Buffer::makeDocBookFile(FileName const & fname,
1142 OutputParams const & runparams,
1143 bool const body_only)
1145 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1149 if (!openFileWrite(ofs, fname))
1152 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1156 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1160 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1161 OutputParams const & runparams,
1162 bool const only_body)
1164 LaTeXFeatures features(*this, params(), runparams);
1169 TextClass const & tclass = params().getTextClass();
1170 string const top_element = tclass.latexname();
1173 if (runparams.flavor == OutputParams::XML)
1174 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1177 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1180 if (! tclass.class_header().empty())
1181 os << from_ascii(tclass.class_header());
1182 else if (runparams.flavor == OutputParams::XML)
1183 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1184 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1186 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1188 docstring preamble = from_utf8(params().preamble);
1189 if (runparams.flavor != OutputParams::XML ) {
1190 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1191 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1192 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1193 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1196 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1198 preamble += features.getIncludedFiles(name);
1199 preamble += features.getLyXSGMLEntities();
1201 if (!preamble.empty()) {
1202 os << "\n [ " << preamble << " ]";
1207 string top = top_element;
1209 if (runparams.flavor == OutputParams::XML)
1210 top += params().language->code();
1212 top += params().language->code().substr(0,2);
1215 if (!params().options.empty()) {
1217 top += params().options;
1220 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1221 << " file was created by LyX " << lyx_version
1222 << "\n See http://www.lyx.org/ for more information -->\n";
1224 params().getTextClass().counters().reset();
1226 loadChildDocuments(*this);
1228 sgml::openTag(os, top);
1230 docbookParagraphs(paragraphs(), *this, os, runparams);
1231 sgml::closeTag(os, top_element);
1235 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1236 // Other flags: -wall -v0 -x
1237 int Buffer::runChktex()
1241 // get LaTeX-Filename
1242 FileName const path(temppath());
1243 string const name = addName(path.absFilename(), getLatexName());
1244 string const org_path = filePath();
1246 support::Path p(path); // path to LaTeX file
1247 message(_("Running chktex..."));
1249 // Generate the LaTeX file if neccessary
1250 OutputParams runparams(¶ms().encoding());
1251 runparams.flavor = OutputParams::LATEX;
1252 runparams.nice = false;
1253 makeLaTeXFile(FileName(name), org_path, runparams);
1256 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1257 int const res = chktex.run(terr); // run chktex
1260 Alert::error(_("chktex failure"),
1261 _("Could not run chktex successfully."));
1262 } else if (res > 0) {
1263 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1264 // Clear out old errors
1266 // Fill-in the error list with the TeX errors
1267 bufferErrors(*this, terr, errorList);
1278 void Buffer::validate(LaTeXFeatures & features) const
1280 TextClass const & tclass = params().getTextClass();
1282 if (params().outputChanges) {
1283 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1284 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1285 LaTeXFeatures::isAvailable("xcolor");
1287 if (features.runparams().flavor == OutputParams::LATEX) {
1289 features.require("ct-dvipost");
1290 features.require("dvipost");
1291 } else if (xcolorsoul) {
1292 features.require("ct-xcolor-soul");
1293 features.require("soul");
1294 features.require("xcolor");
1296 features.require("ct-none");
1298 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1300 features.require("ct-xcolor-soul");
1301 features.require("soul");
1302 features.require("xcolor");
1303 features.require("pdfcolmk"); // improves color handling in PDF output
1305 features.require("ct-none");
1310 // AMS Style is at document level
1311 if (params().use_amsmath == BufferParams::package_on
1312 || tclass.provides("amsmath"))
1313 features.require("amsmath");
1314 if (params().use_esint == BufferParams::package_on)
1315 features.require("esint");
1317 loadChildDocuments(*this);
1319 for_each(paragraphs().begin(), paragraphs().end(),
1320 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1322 // the bullet shapes are buffer level not paragraph level
1323 // so they are tested here
1324 for (int i = 0; i < 4; ++i) {
1325 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1326 int const font = params().user_defined_bullet(i).getFont();
1328 int const c = params()
1329 .user_defined_bullet(i)
1336 features.require("latexsym");
1338 } else if (font == 1) {
1339 features.require("amssymb");
1340 } else if ((font >= 2 && font <= 5)) {
1341 features.require("pifont");
1346 if (lyxerr.debugging(Debug::LATEX)) {
1347 features.showStruct();
1352 void Buffer::getLabelList(vector<docstring> & list) const
1354 /// if this is a child document and the parent is already loaded
1355 /// Use the parent's list instead [ale990407]
1356 Buffer const * tmp = getMasterBuffer();
1358 lyxerr << "getMasterBuffer() failed!" << endl;
1362 tmp->getLabelList(list);
1366 loadChildDocuments(*this);
1368 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1369 it.nextInset()->getLabelList(*this, list);
1373 void Buffer::updateBibfilesCache()
1375 // if this is a child document and the parent is already loaded
1376 // update the parent's cache instead
1377 Buffer * tmp = getMasterBuffer();
1380 tmp->updateBibfilesCache();
1384 bibfilesCache_.clear();
1385 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1386 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1387 InsetBibtex const & inset =
1388 static_cast<InsetBibtex const &>(*it);
1389 vector<FileName> const bibfiles = inset.getFiles(*this);
1390 bibfilesCache_.insert(bibfilesCache_.end(),
1393 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1394 InsetInclude & inset =
1395 static_cast<InsetInclude &>(*it);
1396 inset.updateBibfilesCache(*this);
1397 vector<FileName> const & bibfiles =
1398 inset.getBibfilesCache(*this);
1399 bibfilesCache_.insert(bibfilesCache_.end(),
1407 vector<FileName> const & Buffer::getBibfilesCache() const
1409 // if this is a child document and the parent is already loaded
1410 // use the parent's cache instead
1411 Buffer const * tmp = getMasterBuffer();
1414 return tmp->getBibfilesCache();
1416 // We update the cache when first used instead of at loading time.
1417 if (bibfilesCache_.empty())
1418 const_cast<Buffer *>(this)->updateBibfilesCache();
1420 return bibfilesCache_;
1424 bool Buffer::isDepClean(string const & name) const
1426 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1427 if (it == pimpl_->dep_clean.end())
1433 void Buffer::markDepClean(string const & name)
1435 pimpl_->dep_clean[name] = true;
1439 bool Buffer::dispatch(string const & command, bool * result)
1441 return dispatch(lyxaction.lookupFunc(command), result);
1445 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1447 bool dispatched = true;
1449 switch (func.action) {
1450 case LFUN_BUFFER_EXPORT: {
1451 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1464 void Buffer::changeLanguage(Language const * from, Language const * to)
1469 for_each(par_iterator_begin(),
1471 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1473 text().current_font.setLanguage(to);
1474 text().real_current_font.setLanguage(to);
1478 bool Buffer::isMultiLingual() const
1480 ParConstIterator end = par_iterator_end();
1481 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1482 if (it->isMultiLingual(params()))
1489 ParIterator Buffer::getParFromID(int const id) const
1491 ParConstIterator it = par_iterator_begin();
1492 ParConstIterator const end = par_iterator_end();
1495 // John says this is called with id == -1 from undo
1496 lyxerr << "getParFromID(), id: " << id << endl;
1500 for (; it != end; ++it)
1508 bool Buffer::hasParWithID(int const id) const
1510 ParConstIterator const it = getParFromID(id);
1511 return it != par_iterator_end();
1515 ParIterator Buffer::par_iterator_begin()
1517 return lyx::par_iterator_begin(inset());
1521 ParIterator Buffer::par_iterator_end()
1523 return lyx::par_iterator_end(inset());
1527 ParConstIterator Buffer::par_iterator_begin() const
1529 return lyx::par_const_iterator_begin(inset());
1533 ParConstIterator Buffer::par_iterator_end() const
1535 return lyx::par_const_iterator_end(inset());
1539 Language const * Buffer::getLanguage() const
1541 return params().language;
1545 docstring const Buffer::B_(string const & l10n) const
1547 return params().B_(l10n);
1551 bool Buffer::isClean() const
1553 return pimpl_->lyx_clean;
1557 bool Buffer::isBakClean() const
1559 return pimpl_->bak_clean;
1563 bool Buffer::isExternallyModified(CheckMethod method) const
1565 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1566 // if method == timestamp, check timestamp before checksum
1567 return (method == checksum_method
1568 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1569 && pimpl_->checksum_ != sum(pimpl_->filename);
1573 void Buffer::markClean() const
1575 if (!pimpl_->lyx_clean) {
1576 pimpl_->lyx_clean = true;
1579 // if the .lyx file has been saved, we don't need an
1581 pimpl_->bak_clean = true;
1585 void Buffer::markBakClean()
1587 pimpl_->bak_clean = true;
1591 void Buffer::setUnnamed(bool flag)
1593 pimpl_->unnamed = flag;
1597 bool Buffer::isUnnamed() const
1599 return pimpl_->unnamed;
1603 // FIXME: this function should be moved to buffer_pimpl.C
1604 void Buffer::markDirty()
1606 if (pimpl_->lyx_clean) {
1607 pimpl_->lyx_clean = false;
1610 pimpl_->bak_clean = false;
1612 DepClean::iterator it = pimpl_->dep_clean.begin();
1613 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1615 for (; it != end; ++it)
1620 string const Buffer::fileName() const
1622 return pimpl_->filename.absFilename();
1626 string const & Buffer::filePath() const
1628 return params().filepath;
1632 bool Buffer::isReadonly() const
1634 return pimpl_->read_only;
1638 void Buffer::setParentName(string const & name)
1640 if (name == pimpl_->filename.absFilename())
1641 // Avoids recursive include.
1642 params().parentname.clear();
1644 params().parentname = name;
1648 Buffer const * Buffer::getMasterBuffer() const
1650 if (!params().parentname.empty()
1651 && theBufferList().exists(params().parentname)) {
1652 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1653 //We need to check if the parent is us...
1654 //FIXME RECURSIVE INCLUDE
1655 //This is not sufficient, since recursive includes could be downstream.
1656 if (buf && buf != this)
1657 return buf->getMasterBuffer();
1664 Buffer * Buffer::getMasterBuffer()
1666 if (!params().parentname.empty()
1667 && theBufferList().exists(params().parentname)) {
1668 Buffer * buf = theBufferList().getBuffer(params().parentname);
1670 return buf->getMasterBuffer();
1677 MacroData const & Buffer::getMacro(docstring const & name) const
1679 return pimpl_->macros.get(name);
1683 bool Buffer::hasMacro(docstring const & name) const
1685 return pimpl_->macros.has(name);
1689 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1691 MacroTable::globalMacros().insert(name, data);
1692 pimpl_->macros.insert(name, data);
1696 void Buffer::buildMacros()
1698 // Start with global table.
1699 pimpl_->macros = MacroTable::globalMacros();
1702 ParagraphList const & pars = text().paragraphs();
1703 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1704 //lyxerr << "searching main par " << i
1705 // << " for macro definitions" << std::endl;
1706 InsetList const & insets = pars[i].insetlist;
1707 InsetList::const_iterator it = insets.begin();
1708 InsetList::const_iterator end = insets.end();
1709 for ( ; it != end; ++it) {
1710 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1711 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1712 MathMacroTemplate const & mac
1713 = static_cast<MathMacroTemplate const &>(*it->inset);
1714 insertMacro(mac.name(), mac.asMacroData());
1721 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1724 //FIXME: This does not work for child documents yet.
1725 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1726 // Check if the label 'from' appears more than once
1727 vector<docstring> labels;
1729 if (code == Inset::CITE_CODE) {
1731 keys.fillWithBibKeys(this);
1732 BiblioInfo::const_iterator bit = keys.begin();
1733 BiblioInfo::const_iterator bend = keys.end();
1735 for (; bit != bend; ++bit)
1737 labels.push_back(bit->first);
1739 getLabelList(labels);
1741 if (std::count(labels.begin(), labels.end(), from) > 1)
1744 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1745 if (it->lyxCode() == code) {
1746 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1747 inset.replaceContents(to_utf8(from), to_utf8(to));
1753 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1754 pit_type par_end, bool full_source)
1756 OutputParams runparams(¶ms().encoding());
1757 runparams.nice = true;
1758 runparams.flavor = OutputParams::LATEX;
1759 runparams.linelen = lyxrc.plaintext_linelen;
1760 // No side effect of file copying and image conversion
1761 runparams.dryrun = true;
1765 os << "% " << _("Preview source code") << "\n\n";
1769 writeLaTeXSource(os, filePath(), runparams, true, true);
1771 writeDocBookSource(os, fileName(), runparams, false);
1774 runparams.par_begin = par_begin;
1775 runparams.par_end = par_end;
1776 if (par_begin + 1 == par_end)
1778 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1782 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1783 convert<docstring>(par_begin),
1784 convert<docstring>(par_end - 1))
1788 // output paragraphs
1790 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1793 docbookParagraphs(paragraphs(), *this, os, runparams);
1799 ErrorList const & Buffer::errorList(string const & type) const
1801 static ErrorList const emptyErrorList;
1802 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1803 if (I == pimpl_->errorLists.end())
1804 return emptyErrorList;
1810 ErrorList & Buffer::errorList(string const & type)
1812 return pimpl_->errorLists[type];