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 "BranchList.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
25 #include "ErrorList.h"
28 #include "FuncRequest.h"
30 #include "InsetIterator.h"
33 #include "LaTeXFeatures.h"
34 #include "LyXAction.h"
42 #include "output_docbook.h"
43 #include "output_latex.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
50 #include "TocBackend.h"
54 #include "insets/InsetBibitem.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetInclude.h"
57 #include "insets/InsetText.h"
59 #include "mathed/MathMacroTemplate.h"
60 #include "mathed/MacroTable.h"
61 #include "mathed/MathSupport.h"
63 #include "frontends/alert.h"
65 #include "graphics/Previews.h"
67 #include "support/types.h"
68 #include "support/lyxalgo.h"
69 #include "support/filetools.h"
70 #include "support/fs_extras.h"
71 #include "support/lyxlib.h"
72 #include "support/os.h"
73 #include "support/Path.h"
74 #include "support/textutils.h"
75 #include "support/convert.h"
77 #include <boost/iostreams/filtering_stream.hpp>
78 #include <boost/iostreams/filter/gzip.hpp>
79 #include <boost/iostreams/device/file.hpp>
80 #include <boost/bind.hpp>
81 #include <boost/filesystem/exception.hpp>
82 #include <boost/filesystem/operations.hpp>
84 #if defined (HAVE_UTIME_H)
86 #elif defined (HAVE_SYS_UTIME_H)
87 #include <sys/utime.h>
98 using support::addName;
99 using support::bformat;
100 using support::changeExtension;
101 using support::cmd_ret;
102 using support::createBufferTmpDir;
103 using support::destroyDir;
104 using support::FileName;
105 using support::getFormatFromContents;
106 using support::libFileSearch;
107 using support::latex_path;
108 using support::ltrim;
109 using support::makeAbsPath;
110 using support::makeDisplayPath;
111 using support::makeLatexName;
112 using support::onlyFilename;
113 using support::onlyPath;
114 using support::quoteName;
115 using support::removeAutosaveFile;
116 using support::rename;
117 using support::runCommand;
118 using support::split;
119 using support::subst;
120 using support::tempName;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
125 namespace fs = boost::filesystem;
126 namespace io = boost::iostreams;
130 using std::make_pair;
135 using std::ostringstream;
145 int const LYX_FORMAT = 276;
150 typedef std::map<string, bool> DepClean;
155 Impl(Buffer & parent, FileName const & file, bool readonly);
157 limited_stack<Undo> undostack;
158 limited_stack<Undo> redostack;
164 /// need to regenerate .tex?
168 mutable bool lyx_clean;
170 /// is autosave needed?
171 mutable bool bak_clean;
173 /// is this a unnamed file (New...)?
179 /// name of the file the buffer is associated with.
182 /** Set to true only when the file is fully loaded.
183 * Used to prevent the premature generation of previews
184 * and by the citation inset.
186 bool file_fully_loaded;
188 /// our Text that should be wrapped in an InsetText
195 TocBackend toc_backend;
197 /// Container for all sort of Buffer dependant errors.
198 map<string, ErrorList> errorLists;
202 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
203 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
204 filename(file), file_fully_loaded(false), inset(params),
207 inset.setAutoBreakRows(true);
208 lyxvc.buffer(&parent);
209 temppath = createBufferTmpDir();
210 params.filepath = onlyPath(file.absFilename());
211 // FIXME: And now do something if temppath == string(), because we
212 // assume from now on that temppath points to a valid temp dir.
213 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
217 Buffer::Buffer(string const & file, bool readonly)
218 : pimpl_(new Impl(*this, FileName(file), readonly))
220 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
226 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
227 // here the buffer should take care that it is
228 // saved properly, before it goes into the void.
232 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
233 Alert::warning(_("Could not remove temporary directory"),
234 bformat(_("Could not remove the temporary directory %1$s"),
235 from_utf8(temppath())));
238 // Remove any previewed LaTeX snippets associated with this buffer.
239 graphics::Previews::get().removeLoader(*this);
243 Text & Buffer::text() const
245 return const_cast<Text &>(pimpl_->inset.text_);
249 Inset & Buffer::inset() const
251 return const_cast<InsetText &>(pimpl_->inset);
255 limited_stack<Undo> & Buffer::undostack()
257 return pimpl_->undostack;
261 limited_stack<Undo> const & Buffer::undostack() const
263 return pimpl_->undostack;
267 limited_stack<Undo> & Buffer::redostack()
269 return pimpl_->redostack;
273 limited_stack<Undo> const & Buffer::redostack() const
275 return pimpl_->redostack;
279 BufferParams & Buffer::params()
281 return pimpl_->params;
285 BufferParams const & Buffer::params() const
287 return pimpl_->params;
291 ParagraphList & Buffer::paragraphs()
293 return text().paragraphs();
297 ParagraphList const & Buffer::paragraphs() const
299 return text().paragraphs();
303 LyXVC & Buffer::lyxvc()
305 return pimpl_->lyxvc;
309 LyXVC const & Buffer::lyxvc() const
311 return pimpl_->lyxvc;
315 string const & Buffer::temppath() const
317 return pimpl_->temppath;
321 TexRow & Buffer::texrow()
323 return pimpl_->texrow;
327 TexRow const & Buffer::texrow() const
329 return pimpl_->texrow;
333 TocBackend & Buffer::tocBackend()
335 return pimpl_->toc_backend;
339 TocBackend const & Buffer::tocBackend() const
341 return pimpl_->toc_backend;
345 string const Buffer::getLatexName(bool const no_path) const
347 string const name = changeExtension(makeLatexName(fileName()), ".tex");
348 return no_path ? onlyFilename(name) : name;
352 pair<Buffer::LogType, string> const Buffer::getLogName() const
354 string const filename = getLatexName(false);
356 if (filename.empty())
357 return make_pair(Buffer::latexlog, string());
359 string const path = temppath();
361 FileName const fname(addName(temppath(),
362 onlyFilename(changeExtension(filename,
364 FileName const bname(
365 addName(path, onlyFilename(
366 changeExtension(filename,
367 formats.extension("literate") + ".out"))));
369 // If no Latex log or Build log is newer, show Build log
371 if (fs::exists(bname.toFilesystemEncoding()) &&
372 (!fs::exists(fname.toFilesystemEncoding()) ||
373 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
374 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
375 return make_pair(Buffer::buildlog, bname.absFilename());
377 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
378 return make_pair(Buffer::latexlog, fname.absFilename());
382 void Buffer::setReadonly(bool const flag)
384 if (pimpl_->read_only != flag) {
385 pimpl_->read_only = flag;
391 void Buffer::setFileName(string const & newfile)
393 pimpl_->filename = makeAbsPath(newfile);
394 params().filepath = onlyPath(pimpl_->filename.absFilename());
395 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
400 // We'll remove this later. (Lgb)
403 void unknownClass(string const & unknown)
405 Alert::warning(_("Unknown document class"),
406 bformat(_("Using the default document class, because the "
407 "class %1$s is unknown."), from_utf8(unknown)));
413 int Buffer::readHeader(Lexer & lex)
415 int unknown_tokens = 0;
417 int begin_header_line = -1;
419 // Initialize parameters that may be/go lacking in header:
420 params().branchlist().clear();
421 params().preamble.erase();
422 params().options.erase();
423 params().float_placement.erase();
424 params().paperwidth.erase();
425 params().paperheight.erase();
426 params().leftmargin.erase();
427 params().rightmargin.erase();
428 params().topmargin.erase();
429 params().bottommargin.erase();
430 params().headheight.erase();
431 params().headsep.erase();
432 params().footskip.erase();
433 params().listings_params.clear();
434 for (int i = 0; i < 4; ++i) {
435 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
436 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
439 ErrorList & errorList = pimpl_->errorLists["Parse"];
443 string const token = lex.getString();
448 if (token == "\\end_header")
452 if (token == "\\begin_header") {
453 begin_header_line = line;
457 LYXERR(Debug::PARSER) << "Handling document header token: `"
458 << token << '\'' << endl;
460 string unknown = params().readToken(lex, token);
461 if (!unknown.empty()) {
462 if (unknown[0] != '\\' && token == "\\textclass") {
463 unknownClass(unknown);
466 docstring const s = bformat(_("Unknown token: "
470 errorList.push_back(ErrorItem(_("Document header error"),
475 if (begin_header_line) {
476 docstring const s = _("\\begin_header is missing");
477 errorList.push_back(ErrorItem(_("Document header error"),
481 return unknown_tokens;
486 // changed to be public and have one parameter
487 // Returns false if "\end_document" is not read (Asger)
488 bool Buffer::readDocument(Lexer & lex)
490 ErrorList & errorList = pimpl_->errorLists["Parse"];
494 string const token = lex.getString();
495 if (token != "\\begin_document") {
496 docstring const s = _("\\begin_document is missing");
497 errorList.push_back(ErrorItem(_("Document header error"),
501 // we are reading in a brand new document
502 BOOST_ASSERT(paragraphs().empty());
505 if (!params().getTextClass().load(filePath())) {
506 string theclass = params().getTextClass().name();
507 Alert::error(_("Can't load document class"), bformat(
508 _("Using the default document class, because the "
509 "class %1$s could not be loaded."), from_utf8(theclass)));
510 params().textclass = 0;
513 if (params().outputChanges) {
514 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
515 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
516 LaTeXFeatures::isAvailable("xcolor");
518 if (!dvipost && !xcolorsoul) {
519 Alert::warning(_("Changes not shown in LaTeX output"),
520 _("Changes will not be highlighted in LaTeX output, "
521 "because neither dvipost nor xcolor/soul are installed.\n"
522 "Please install these packages or redefine "
523 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
524 } else if (!xcolorsoul) {
525 Alert::warning(_("Changes not shown in LaTeX output"),
526 _("Changes will not be highlighted in LaTeX output "
527 "when using pdflatex, because xcolor and soul are not installed.\n"
528 "Please install both packages or redefine "
529 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
533 bool const res = text().read(*this, lex, errorList);
534 for_each(text().paragraphs().begin(),
535 text().paragraphs().end(),
536 bind(&Paragraph::setInsetOwner, _1, &inset()));
542 // needed to insert the selection
543 void Buffer::insertStringAsLines(ParagraphList & pars,
544 pit_type & pit, pos_type & pos,
545 Font const & fn, docstring const & str, bool autobreakrows)
549 // insert the string, don't insert doublespace
550 bool space_inserted = true;
551 for (docstring::const_iterator cit = str.begin();
552 cit != str.end(); ++cit) {
553 Paragraph & par = pars[pit];
555 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
556 breakParagraph(params(), pars, pit, pos,
557 par.layout()->isEnvironment());
560 space_inserted = true;
564 // do not insert consecutive spaces if !free_spacing
565 } else if ((*cit == ' ' || *cit == '\t') &&
566 space_inserted && !par.isFreeSpacing()) {
568 } else if (*cit == '\t') {
569 if (!par.isFreeSpacing()) {
570 // tabs are like spaces here
571 par.insertChar(pos, ' ', font, params().trackChanges);
573 space_inserted = true;
575 const pos_type n = 8 - pos % 8;
576 for (pos_type i = 0; i < n; ++i) {
577 par.insertChar(pos, ' ', font, params().trackChanges);
580 space_inserted = true;
582 } else if (!isPrintable(*cit)) {
583 // Ignore unprintables
586 // just insert the character
587 par.insertChar(pos, *cit, font, params().trackChanges);
589 space_inserted = (*cit == ' ');
596 bool Buffer::readString(std::string const & s)
598 params().compressed = false;
600 // remove dummy empty par
601 paragraphs().clear();
603 std::istringstream is(s);
605 FileName const name(tempName());
606 switch (readFile(lex, name, true)) {
610 // We need to call lyx2lyx, so write the input to a file
611 std::ofstream os(name.toFilesystemEncoding().c_str());
614 return readFile(name);
624 bool Buffer::readFile(FileName const & filename)
626 // Check if the file is compressed.
627 string const format = getFormatFromContents(filename);
628 if (format == "gzip" || format == "zip" || format == "compress") {
629 params().compressed = true;
632 // remove dummy empty par
633 paragraphs().clear();
635 lex.setFile(filename);
636 if (readFile(lex, filename) != success)
643 bool Buffer::fully_loaded() const
645 return pimpl_->file_fully_loaded;
649 void Buffer::fully_loaded(bool const value)
651 pimpl_->file_fully_loaded = value;
655 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
658 BOOST_ASSERT(!filename.empty());
661 Alert::error(_("Document could not be read"),
662 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
667 string const token(lex.getString());
670 Alert::error(_("Document could not be read"),
671 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
675 // the first token _must_ be...
676 if (token != "\\lyxformat") {
677 lyxerr << "Token: " << token << endl;
679 Alert::error(_("Document format failure"),
680 bformat(_("%1$s is not a LyX document."),
681 from_utf8(filename.absFilename())));
686 string tmp_format = lex.getString();
687 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
688 // if present remove ".," from string.
689 string::size_type dot = tmp_format.find_first_of(".,");
690 //lyxerr << " dot found at " << dot << endl;
691 if (dot != string::npos)
692 tmp_format.erase(dot, 1);
693 int const file_format = convert<int>(tmp_format);
694 //lyxerr << "format: " << file_format << endl;
696 if (file_format != LYX_FORMAT) {
699 // lyx2lyx would fail
702 FileName const tmpfile(tempName());
703 if (tmpfile.empty()) {
704 Alert::error(_("Conversion failed"),
705 bformat(_("%1$s is from a different"
706 " version of LyX, but a temporary"
707 " file for converting it could"
709 from_utf8(filename.absFilename())));
712 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
713 if (lyx2lyx.empty()) {
714 Alert::error(_("Conversion script not found"),
715 bformat(_("%1$s is from a different"
716 " version of LyX, but the"
717 " conversion script lyx2lyx"
718 " could not be found."),
719 from_utf8(filename.absFilename())));
722 ostringstream command;
723 command << os::python()
724 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
725 << " -t " << convert<string>(LYX_FORMAT)
726 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
727 << ' ' << quoteName(filename.toFilesystemEncoding());
728 string const command_str = command.str();
730 LYXERR(Debug::INFO) << "Running '"
731 << command_str << '\''
734 cmd_ret const ret = runCommand(command_str);
735 if (ret.first != 0) {
736 Alert::error(_("Conversion script failed"),
737 bformat(_("%1$s is from a different version"
738 " of LyX, but the lyx2lyx script"
739 " failed to convert it."),
740 from_utf8(filename.absFilename())));
743 bool const ret = readFile(tmpfile);
744 // Do stuff with tmpfile name and buffer name here.
745 return ret ? success : failure;
750 if (readDocument(lex)) {
751 Alert::error(_("Document format failure"),
752 bformat(_("%1$s ended unexpectedly, which means"
753 " that it is probably corrupted."),
754 from_utf8(filename.absFilename())));
757 //lyxerr << "removing " << MacroTable::localMacros().size()
758 // << " temporary macro entries" << endl;
759 //MacroTable::localMacros().clear();
761 pimpl_->file_fully_loaded = true;
766 // Should probably be moved to somewhere else: BufferView? LyXView?
767 bool Buffer::save() const
769 // We don't need autosaves in the immediate future. (Asger)
770 resetAutosaveTimers();
772 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
775 bool madeBackup = false;
777 // make a backup if the file already exists
778 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
779 backupName = FileName(fileName() + '~');
780 if (!lyxrc.backupdir_path.empty())
781 backupName = FileName(addName(lyxrc.backupdir_path,
782 subst(os::internal_path(backupName.absFilename()), '/', '!')));
785 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
787 } catch (fs::filesystem_error const & fe) {
788 Alert::error(_("Backup failure"),
789 bformat(_("Cannot create backup file %1$s.\n"
790 "Please check whether the directory exists and is writeable."),
791 from_utf8(backupName.absFilename())));
792 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
796 if (writeFile(pimpl_->filename)) {
798 removeAutosaveFile(fileName());
801 // Saving failed, so backup is not backup
803 rename(backupName, pimpl_->filename);
809 bool Buffer::writeFile(FileName const & fname) const
811 if (pimpl_->read_only && fname == pimpl_->filename)
816 if (params().compressed) {
817 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
823 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
834 bool Buffer::write(ostream & ofs) const
837 // Use the standard "C" locale for file output.
838 ofs.imbue(std::locale::classic());
841 // The top of the file should not be written by params().
843 // write out a comment in the top of the file
844 ofs << "#LyX " << lyx_version
845 << " created this file. For more info see http://www.lyx.org/\n"
846 << "\\lyxformat " << LYX_FORMAT << "\n"
847 << "\\begin_document\n";
850 /// For each author, set 'used' to true if there is a change
851 /// by this author in the document; otherwise set it to 'false'.
852 AuthorList::Authors::const_iterator a_it = params().authors().begin();
853 AuthorList::Authors::const_iterator a_end = params().authors().end();
854 for (; a_it != a_end; ++a_it)
855 a_it->second.used(false);
857 ParIterator const end = par_iterator_end();
858 ParIterator it = par_iterator_begin();
859 for ( ; it != end; ++it)
860 it->checkAuthors(params().authors());
862 // now write out the buffer parameters.
863 ofs << "\\begin_header\n";
864 params().writeFile(ofs);
865 ofs << "\\end_header\n";
868 ofs << "\n\\begin_body\n";
869 text().write(*this, ofs);
870 ofs << "\n\\end_body\n";
872 // Write marker that shows file is complete
873 ofs << "\\end_document" << endl;
875 // Shouldn't really be needed....
878 // how to check if close went ok?
879 // Following is an attempt... (BE 20001011)
881 // good() returns false if any error occured, including some
883 // bad() returns true if something bad happened in the buffer,
884 // which should include file system full errors.
889 lyxerr << "File was not closed properly." << endl;
896 bool Buffer::makeLaTeXFile(FileName const & fname,
897 string const & original_path,
898 OutputParams const & runparams,
899 bool output_preamble, bool output_body)
901 string const encoding = runparams.encoding->iconvName();
902 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
903 << encoding << "..." << endl;
905 odocfstream ofs(encoding);
906 if (!openFileWrite(ofs, fname))
909 bool failed_export = false;
911 writeLaTeXSource(ofs, original_path,
912 runparams, output_preamble, output_body);
914 catch (iconv_codecvt_facet_exception & e) {
915 lyxerr << "Caught iconv exception: " << e.what() << endl;
916 failed_export = true;
918 catch (std::exception const & e) {
919 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
920 failed_export = true;
923 lyxerr << "Caught some really weird exception..." << endl;
924 LyX::cref().emergencyCleanup();
930 failed_export = true;
931 lyxerr << "File '" << fname << "' was not closed properly." << endl;
935 Alert::error(_("Encoding error"),
936 _("Some characters of your document are probably not "
937 "representable in the chosen encoding.\n"
938 "Changing the document encoding to utf8 could help."));
945 void Buffer::writeLaTeXSource(odocstream & os,
946 string const & original_path,
947 OutputParams const & runparams_in,
948 bool const output_preamble, bool const output_body)
950 OutputParams runparams = runparams_in;
952 // validate the buffer.
953 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
954 LaTeXFeatures features(*this, params(), runparams);
956 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
960 // The starting paragraph of the coming rows is the
961 // first paragraph of the document. (Asger)
962 texrow().start(paragraphs().begin()->id(), 0);
964 if (output_preamble && runparams.nice) {
965 os << "%% LyX " << lyx_version << " created this file. "
966 "For more info, see http://www.lyx.org/.\n"
967 "%% Do not edit unless you really know what "
972 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
973 // There are a few differences between nice LaTeX and usual files:
974 // usual is \batchmode and has a
975 // special input@path to allow the including of figures
976 // with either \input or \includegraphics (what figinsets do).
977 // input@path is set when the actual parameter
978 // original_path is set. This is done for usual tex-file, but not
979 // for nice-latex-file. (Matthias 250696)
980 // Note that input@path is only needed for something the user does
981 // in the preamble, included .tex files or ERT, files included by
982 // LyX work without it.
983 if (output_preamble) {
984 if (!runparams.nice) {
985 // code for usual, NOT nice-latex-file
986 os << "\\batchmode\n"; // changed
990 if (!original_path.empty()) {
992 // We don't know the encoding of inputpath
993 docstring const inputpath = from_utf8(latex_path(original_path));
994 os << "\\makeatletter\n"
995 << "\\def\\input@path{{"
996 << inputpath << "/}}\n"
997 << "\\makeatother\n";
1003 // Write the preamble
1004 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1010 os << "\\begin{document}\n";
1012 } // output_preamble
1013 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1015 if (!lyxrc.language_auto_begin &&
1016 !params().language->babel().empty()) {
1018 os << from_utf8(subst(lyxrc.language_command_begin,
1020 params().language->babel()))
1025 Encoding const & encoding = params().encoding();
1026 if (encoding.package() == Encoding::CJK) {
1027 // Open a CJK environment, since in contrast to the encodings
1028 // handled by inputenc the document encoding is not set in
1029 // the preamble if it is handled by CJK.sty.
1030 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1035 // if we are doing a real file with body, even if this is the
1036 // child of some other buffer, let's cut the link here.
1037 // This happens for example if only a child document is printed.
1038 string save_parentname;
1039 if (output_preamble) {
1040 save_parentname = params().parentname;
1041 params().parentname.erase();
1045 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1047 // Restore the parenthood if needed
1048 if (output_preamble)
1049 params().parentname = save_parentname;
1051 // add this just in case after all the paragraphs
1055 if (encoding.package() == Encoding::CJK) {
1056 // Close the open CJK environment.
1057 // latexParagraphs will have opened one even if the last text
1059 os << "\\end{CJK}\n";
1063 if (!lyxrc.language_auto_end &&
1064 !params().language->babel().empty()) {
1065 os << from_utf8(subst(lyxrc.language_command_end,
1067 params().language->babel()))
1072 if (output_preamble) {
1073 os << "\\end{document}\n";
1076 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1078 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1081 runparams_in.encoding = runparams.encoding;
1083 // Just to be sure. (Asger)
1086 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1087 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1092 bool Buffer::isLatex() const
1094 return params().getTextClass().outputType() == LATEX;
1098 bool Buffer::isLiterate() const
1100 return params().getTextClass().outputType() == LITERATE;
1104 bool Buffer::isDocBook() const
1106 return params().getTextClass().outputType() == DOCBOOK;
1110 void Buffer::makeDocBookFile(FileName const & fname,
1111 OutputParams const & runparams,
1112 bool const body_only)
1114 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1118 if (!openFileWrite(ofs, fname))
1121 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1125 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1129 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1130 OutputParams const & runparams,
1131 bool const only_body)
1133 LaTeXFeatures features(*this, params(), runparams);
1138 TextClass const & tclass = params().getTextClass();
1139 string const top_element = tclass.latexname();
1142 if (runparams.flavor == OutputParams::XML)
1143 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1146 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1149 if (! tclass.class_header().empty())
1150 os << from_ascii(tclass.class_header());
1151 else if (runparams.flavor == OutputParams::XML)
1152 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1153 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1155 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1157 docstring preamble = from_utf8(params().preamble);
1158 if (runparams.flavor != OutputParams::XML ) {
1159 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1160 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1161 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1162 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1165 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1167 preamble += features.getIncludedFiles(name);
1168 preamble += features.getLyXSGMLEntities();
1170 if (!preamble.empty()) {
1171 os << "\n [ " << preamble << " ]";
1176 string top = top_element;
1178 if (runparams.flavor == OutputParams::XML)
1179 top += params().language->code();
1181 top += params().language->code().substr(0,2);
1184 if (!params().options.empty()) {
1186 top += params().options;
1189 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1190 << " file was created by LyX " << lyx_version
1191 << "\n See http://www.lyx.org/ for more information -->\n";
1193 params().getTextClass().counters().reset();
1195 sgml::openTag(os, top);
1197 docbookParagraphs(paragraphs(), *this, os, runparams);
1198 sgml::closeTag(os, top_element);
1202 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1203 // Other flags: -wall -v0 -x
1204 int Buffer::runChktex()
1208 // get LaTeX-Filename
1209 FileName const path(temppath());
1210 string const name = addName(path.absFilename(), getLatexName());
1211 string const org_path = filePath();
1213 support::Path p(path); // path to LaTeX file
1214 message(_("Running chktex..."));
1216 // Generate the LaTeX file if neccessary
1217 OutputParams runparams(¶ms().encoding());
1218 runparams.flavor = OutputParams::LATEX;
1219 runparams.nice = false;
1220 makeLaTeXFile(FileName(name), org_path, runparams);
1223 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1224 int const res = chktex.run(terr); // run chktex
1227 Alert::error(_("chktex failure"),
1228 _("Could not run chktex successfully."));
1229 } else if (res > 0) {
1230 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1231 // Clear out old errors
1233 // Fill-in the error list with the TeX errors
1234 bufferErrors(*this, terr, errorList);
1245 void Buffer::validate(LaTeXFeatures & features) const
1247 TextClass const & tclass = params().getTextClass();
1249 if (params().outputChanges) {
1250 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1251 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1252 LaTeXFeatures::isAvailable("xcolor");
1254 if (features.runparams().flavor == OutputParams::LATEX) {
1256 features.require("ct-dvipost");
1257 features.require("dvipost");
1258 } else if (xcolorsoul) {
1259 features.require("ct-xcolor-soul");
1260 features.require("soul");
1261 features.require("xcolor");
1263 features.require("ct-none");
1265 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1267 features.require("ct-xcolor-soul");
1268 features.require("soul");
1269 features.require("xcolor");
1270 features.require("pdfcolmk"); // improves color handling in PDF output
1272 features.require("ct-none");
1277 // AMS Style is at document level
1278 if (params().use_amsmath == BufferParams::package_on
1279 || tclass.provides("amsmath"))
1280 features.require("amsmath");
1281 if (params().use_esint == BufferParams::package_on)
1282 features.require("esint");
1284 for_each(paragraphs().begin(), paragraphs().end(),
1285 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1287 // the bullet shapes are buffer level not paragraph level
1288 // so they are tested here
1289 for (int i = 0; i < 4; ++i) {
1290 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1291 int const font = params().user_defined_bullet(i).getFont();
1293 int const c = params()
1294 .user_defined_bullet(i)
1301 features.require("latexsym");
1303 } else if (font == 1) {
1304 features.require("amssymb");
1305 } else if ((font >= 2 && font <= 5)) {
1306 features.require("pifont");
1311 if (lyxerr.debugging(Debug::LATEX)) {
1312 features.showStruct();
1317 void Buffer::getLabelList(vector<docstring> & list) const
1319 /// if this is a child document and the parent is already loaded
1320 /// Use the parent's list instead [ale990407]
1321 Buffer const * tmp = getMasterBuffer();
1323 lyxerr << "getMasterBuffer() failed!" << endl;
1327 tmp->getLabelList(list);
1331 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1332 it.nextInset()->getLabelList(*this, list);
1336 // This is also a buffer property (ale)
1337 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1340 /// if this is a child document and the parent is already loaded
1341 /// use the parent's list instead [ale990412]
1342 Buffer const * tmp = getMasterBuffer();
1345 tmp->fillWithBibKeys(keys);
1349 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1350 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1351 InsetBibtex const & inset =
1352 static_cast<InsetBibtex const &>(*it);
1353 inset.fillWithBibKeys(*this, keys);
1354 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1355 InsetInclude const & inset =
1356 static_cast<InsetInclude const &>(*it);
1357 inset.fillWithBibKeys(*this, keys);
1358 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1359 InsetBibitem const & inset =
1360 static_cast<InsetBibitem const &>(*it);
1362 string const key = to_utf8(inset.getParam("key"));
1363 docstring const label = inset.getParam("label");
1364 DocIterator doc_it(it); doc_it.forwardPos();
1365 docstring const ref = doc_it.paragraph().asString(*this, false);
1366 docstring const info = label + "TheBibliographyRef" + ref;
1367 keys.push_back(pair<string, docstring>(key, info));
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 void Buffer::markClean() const
1565 if (!pimpl_->lyx_clean) {
1566 pimpl_->lyx_clean = true;
1569 // if the .lyx file has been saved, we don't need an
1571 pimpl_->bak_clean = true;
1575 void Buffer::markBakClean()
1577 pimpl_->bak_clean = true;
1581 void Buffer::setUnnamed(bool flag)
1583 pimpl_->unnamed = flag;
1587 bool Buffer::isUnnamed() const
1589 return pimpl_->unnamed;
1593 #ifdef WITH_WARNINGS
1594 #warning this function should be moved to buffer_pimpl.C
1596 void Buffer::markDirty()
1598 if (pimpl_->lyx_clean) {
1599 pimpl_->lyx_clean = false;
1602 pimpl_->bak_clean = false;
1604 DepClean::iterator it = pimpl_->dep_clean.begin();
1605 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1607 for (; it != end; ++it)
1612 string const Buffer::fileName() const
1614 return pimpl_->filename.absFilename();
1618 string const & Buffer::filePath() const
1620 return params().filepath;
1624 bool Buffer::isReadonly() const
1626 return pimpl_->read_only;
1630 void Buffer::setParentName(string const & name)
1632 if (name == pimpl_->filename.absFilename())
1633 // Avoids recursive include.
1634 params().parentname.clear();
1636 params().parentname = name;
1640 Buffer const * Buffer::getMasterBuffer() const
1642 if (!params().parentname.empty()
1643 && theBufferList().exists(params().parentname)) {
1644 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1645 //We need to check if the parent is us...
1646 //FIXME RECURSIVE INCLUDE
1647 //This is not sufficient, since recursive includes could be downstream.
1648 if (buf && buf != this)
1649 return buf->getMasterBuffer();
1656 Buffer * Buffer::getMasterBuffer()
1658 if (!params().parentname.empty()
1659 && theBufferList().exists(params().parentname)) {
1660 Buffer * buf = theBufferList().getBuffer(params().parentname);
1662 return buf->getMasterBuffer();
1669 MacroData const & Buffer::getMacro(docstring const & name) const
1671 return pimpl_->macros.get(name);
1675 bool Buffer::hasMacro(docstring const & name) const
1677 return pimpl_->macros.has(name);
1681 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1683 MacroTable::globalMacros().insert(name, data);
1684 pimpl_->macros.insert(name, data);
1688 void Buffer::buildMacros()
1690 // Start with global table.
1691 pimpl_->macros = MacroTable::globalMacros();
1694 ParagraphList const & pars = text().paragraphs();
1695 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1696 //lyxerr << "searching main par " << i
1697 // << " for macro definitions" << std::endl;
1698 InsetList const & insets = pars[i].insetlist;
1699 InsetList::const_iterator it = insets.begin();
1700 InsetList::const_iterator end = insets.end();
1701 for ( ; it != end; ++it) {
1702 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1703 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1704 MathMacroTemplate const & mac
1705 = static_cast<MathMacroTemplate const &>(*it->inset);
1706 insertMacro(mac.name(), mac.asMacroData());
1713 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
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) {
1729 vector<pair<string, docstring> > keys;
1730 fillWithBibKeys(keys);
1731 vector<pair<string, docstring> >::const_iterator bit = keys.begin();
1732 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1734 for (; bit != bend; ++bit)
1736 labels.push_back(from_utf8(bit->first));
1738 getLabelList(labels);
1740 if (lyx::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;
1763 os << "% " << _("Preview source code") << "\n\n";
1765 writeLaTeXSource(os, filePath(), runparams, true, true);
1767 writeDocBookSource(os, fileName(), runparams, false);
1770 runparams.par_begin = par_begin;
1771 runparams.par_end = par_end;
1772 if (par_begin + 1 == par_end)
1774 << bformat(_("Preview source code for paragraph %1$s"), par_begin)
1778 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1779 convert<docstring>(par_begin),
1780 convert<docstring>(par_end - 1))
1782 // output paragraphs
1785 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1788 docbookParagraphs(paragraphs(), *this, os, runparams);
1794 ErrorList const & Buffer::errorList(string const & type) const
1796 static ErrorList const emptyErrorList;
1797 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1798 if (I == pimpl_->errorLists.end())
1799 return emptyErrorList;
1805 ErrorList & Buffer::errorList(string const & type)
1807 return pimpl_->errorLists[type];