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.
17 #include "BranchList.h"
18 #include "buffer_funcs.h"
19 #include "BufferList.h"
20 #include "BufferParams.h"
26 #include "ErrorList.h"
29 #include "FuncRequest.h"
31 #include "InsetIterator.h"
34 #include "LaTeXFeatures.h"
35 #include "LyXAction.h"
43 #include "output_docbook.h"
44 #include "output_latex.h"
45 #include "Paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
51 #include "TexStream.h"
52 #include "TocBackend.h"
56 #include "insets/InsetBibitem.h"
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetInclude.h"
59 #include "insets/InsetText.h"
61 #include "mathed/MathMacroTemplate.h"
62 #include "mathed/MacroTable.h"
63 #include "mathed/MathSupport.h"
65 #include "frontends/alert.h"
67 #include "graphics/Previews.h"
69 #include "support/types.h"
70 #include "support/lyxalgo.h"
71 #include "support/filetools.h"
72 #include "support/fs_extras.h"
73 #include "support/gzstream.h"
74 #include "support/lyxlib.h"
75 #include "support/os.h"
76 #include "support/Path.h"
77 #include "support/textutils.h"
78 #include "support/convert.h"
80 #include <boost/bind.hpp>
81 #include <boost/filesystem/exception.hpp>
82 #include <boost/filesystem/operations.hpp>
97 using std::ostringstream;
108 using support::addName;
109 using support::bformat;
110 using support::changeExtension;
111 using support::cmd_ret;
112 using support::createBufferTmpDir;
113 using support::destroyDir;
114 using support::FileName;
115 using support::getFormatFromContents;
116 using support::libFileSearch;
117 using support::latex_path;
118 using support::ltrim;
119 using support::makeAbsPath;
120 using support::makeDisplayPath;
121 using support::makeLatexName;
122 using support::onlyFilename;
123 using support::onlyPath;
124 using support::quoteName;
125 using support::removeAutosaveFile;
126 using support::rename;
127 using support::runCommand;
128 using support::split;
129 using support::subst;
130 using support::tempName;
134 namespace Alert = frontend::Alert;
135 namespace os = support::os;
136 namespace fs = boost::filesystem;
140 int const LYX_FORMAT = 278;
145 typedef std::map<string, bool> DepClean;
150 Impl(Buffer & parent, FileName const & file, bool readonly);
152 limited_stack<Undo> undostack;
153 limited_stack<Undo> redostack;
159 /// need to regenerate .tex?
163 mutable bool lyx_clean;
165 /// is autosave needed?
166 mutable bool bak_clean;
168 /// is this a unnamed file (New...)?
174 /// name of the file the buffer is associated with.
177 /** Set to true only when the file is fully loaded.
178 * Used to prevent the premature generation of previews
179 * and by the citation inset.
181 bool file_fully_loaded;
183 /// our Text that should be wrapped in an InsetText
190 TocBackend toc_backend;
192 /// Container for all sort of Buffer dependant errors.
193 map<string, ErrorList> errorLists;
195 /// timestamp and checksum used to test if the file has been externally
196 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
198 unsigned long checksum_;
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),
205 toc_backend(&parent), timestamp_(0), checksum_(0)
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;
762 // save the timestamp and checksum of disk file
763 pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
764 pimpl_->checksum_ = sum(filename);
769 // Should probably be moved to somewhere else: BufferView? LyXView?
770 bool Buffer::save() const
772 // We don't need autosaves in the immediate future. (Asger)
773 resetAutosaveTimers();
775 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
778 bool madeBackup = false;
780 // make a backup if the file already exists
781 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
782 backupName = FileName(fileName() + '~');
783 if (!lyxrc.backupdir_path.empty())
784 backupName = FileName(addName(lyxrc.backupdir_path,
785 subst(os::internal_path(backupName.absFilename()), '/', '!')));
788 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
790 } catch (fs::filesystem_error const & fe) {
791 Alert::error(_("Backup failure"),
792 bformat(_("Cannot create backup file %1$s.\n"
793 "Please check whether the directory exists and is writeable."),
794 from_utf8(backupName.absFilename())));
795 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
799 // ask if the disk file has been externally modified (use checksum method)
800 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
801 docstring const file = makeDisplayPath(fileName(), 20);
802 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
803 "you want to overwrite this file?"), file);
804 int const ret = Alert::prompt(_("Overwrite modified file?"),
805 text, 1, 1, _("&Overwrite"), _("&Cancel"));
810 if (writeFile(pimpl_->filename)) {
812 removeAutosaveFile(fileName());
813 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
814 pimpl_->checksum_ = sum(pimpl_->filename);
817 // Saving failed, so backup is not backup
819 rename(backupName, pimpl_->filename);
825 bool Buffer::writeFile(FileName const & fname) const
827 if (pimpl_->read_only && fname == pimpl_->filename)
832 if (params().compressed) {
833 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
839 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
850 bool Buffer::write(ostream & ofs) const
853 // Use the standard "C" locale for file output.
854 ofs.imbue(std::locale::classic());
857 // The top of the file should not be written by params().
859 // write out a comment in the top of the file
860 ofs << "#LyX " << lyx_version
861 << " created this file. For more info see http://www.lyx.org/\n"
862 << "\\lyxformat " << LYX_FORMAT << "\n"
863 << "\\begin_document\n";
866 /// For each author, set 'used' to true if there is a change
867 /// by this author in the document; otherwise set it to 'false'.
868 AuthorList::Authors::const_iterator a_it = params().authors().begin();
869 AuthorList::Authors::const_iterator a_end = params().authors().end();
870 for (; a_it != a_end; ++a_it)
871 a_it->second.used(false);
873 ParIterator const end = par_iterator_end();
874 ParIterator it = par_iterator_begin();
875 for ( ; it != end; ++it)
876 it->checkAuthors(params().authors());
878 // now write out the buffer parameters.
879 ofs << "\\begin_header\n";
880 params().writeFile(ofs);
881 ofs << "\\end_header\n";
884 ofs << "\n\\begin_body\n";
885 text().write(*this, ofs);
886 ofs << "\n\\end_body\n";
888 // Write marker that shows file is complete
889 ofs << "\\end_document" << endl;
891 // Shouldn't really be needed....
894 // how to check if close went ok?
895 // Following is an attempt... (BE 20001011)
897 // good() returns false if any error occured, including some
899 // bad() returns true if something bad happened in the buffer,
900 // which should include file system full errors.
905 lyxerr << "File was not closed properly." << endl;
912 bool Buffer::makeLaTeXFile(FileName const & fname,
913 string const & original_path,
914 OutputParams const & runparams,
915 bool output_preamble, bool output_body)
917 string const encoding = runparams.encoding->iconvName();
918 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
919 << encoding << "..." << endl;
921 odocfstream ofs(encoding);
922 if (!openFileWrite(ofs, fname))
925 //TexStream ts(ofs.rdbuf(), &texrow());
927 bool failed_export = false;
930 writeLaTeXSource(ofs, original_path,
931 runparams, output_preamble, output_body);
933 catch (iconv_codecvt_facet_exception & e) {
934 lyxerr << "Caught iconv exception: " << e.what() << endl;
935 failed_export = true;
937 catch (std::exception const & e) {
938 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
939 failed_export = true;
942 lyxerr << "Caught some really weird exception..." << endl;
943 LyX::cref().emergencyCleanup();
949 failed_export = true;
950 lyxerr << "File '" << fname << "' was not closed properly." << endl;
954 Alert::error(_("Encoding error"),
955 _("Some characters of your document are probably not "
956 "representable in the chosen encoding.\n"
957 "Changing the document encoding to utf8 could help."));
964 void Buffer::writeLaTeXSource(odocstream & os,
965 string const & original_path,
966 OutputParams const & runparams_in,
967 bool const output_preamble, bool const output_body)
969 OutputParams runparams = runparams_in;
971 // validate the buffer.
972 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
973 LaTeXFeatures features(*this, params(), runparams);
975 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
977 // The starting paragraph of the coming rows is the
978 // first paragraph of the document. (Asger)
979 if (output_preamble && runparams.nice) {
980 os << "%% LyX " << lyx_version << " created this file. "
981 "For more info, see http://www.lyx.org/.\n"
982 "%% Do not edit unless you really know what "
987 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
988 // There are a few differences between nice LaTeX and usual files:
989 // usual is \batchmode and has a
990 // special input@path to allow the including of figures
991 // with either \input or \includegraphics (what figinsets do).
992 // input@path is set when the actual parameter
993 // original_path is set. This is done for usual tex-file, but not
994 // for nice-latex-file. (Matthias 250696)
995 // Note that input@path is only needed for something the user does
996 // in the preamble, included .tex files or ERT, files included by
997 // LyX work without it.
998 if (output_preamble) {
999 if (!runparams.nice) {
1000 // code for usual, NOT nice-latex-file
1001 os << "\\batchmode\n"; // changed
1002 // from \nonstopmode
1005 if (!original_path.empty()) {
1007 // We don't know the encoding of inputpath
1008 docstring const inputpath = from_utf8(latex_path(original_path));
1009 os << "\\makeatletter\n"
1010 << "\\def\\input@path{{"
1011 << inputpath << "/}}\n"
1012 << "\\makeatother\n";
1018 // Write the preamble
1019 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1025 os << "\\begin{document}\n";
1027 } // output_preamble
1029 texrow().start(paragraphs().begin()->id(), 0);
1031 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1033 if (!lyxrc.language_auto_begin &&
1034 !params().language->babel().empty()) {
1036 os << from_utf8(subst(lyxrc.language_command_begin,
1038 params().language->babel()))
1043 Encoding const & encoding = params().encoding();
1044 if (encoding.package() == Encoding::CJK) {
1045 // Open a CJK environment, since in contrast to the encodings
1046 // handled by inputenc the document encoding is not set in
1047 // the preamble if it is handled by CJK.sty.
1048 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1053 // if we are doing a real file with body, even if this is the
1054 // child of some other buffer, let's cut the link here.
1055 // This happens for example if only a child document is printed.
1056 string save_parentname;
1057 if (output_preamble) {
1058 save_parentname = params().parentname;
1059 params().parentname.erase();
1062 loadChildDocuments(*this);
1065 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1067 // Restore the parenthood if needed
1068 if (output_preamble)
1069 params().parentname = save_parentname;
1071 // add this just in case after all the paragraphs
1075 if (encoding.package() == Encoding::CJK) {
1076 // Close the open CJK environment.
1077 // latexParagraphs will have opened one even if the last text
1079 os << "\\end{CJK}\n";
1083 if (!lyxrc.language_auto_end &&
1084 !params().language->babel().empty()) {
1085 os << from_utf8(subst(lyxrc.language_command_end,
1087 params().language->babel()))
1092 if (output_preamble) {
1093 os << "\\end{document}\n";
1096 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1098 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1101 runparams_in.encoding = runparams.encoding;
1103 // Just to be sure. (Asger)
1106 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1107 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1112 bool Buffer::isLatex() const
1114 return params().getTextClass().outputType() == LATEX;
1118 bool Buffer::isLiterate() const
1120 return params().getTextClass().outputType() == LITERATE;
1124 bool Buffer::isDocBook() const
1126 return params().getTextClass().outputType() == DOCBOOK;
1130 void Buffer::makeDocBookFile(FileName const & fname,
1131 OutputParams const & runparams,
1132 bool const body_only)
1134 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1138 if (!openFileWrite(ofs, fname))
1141 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1145 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1149 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1150 OutputParams const & runparams,
1151 bool const only_body)
1153 LaTeXFeatures features(*this, params(), runparams);
1158 TextClass const & tclass = params().getTextClass();
1159 string const top_element = tclass.latexname();
1162 if (runparams.flavor == OutputParams::XML)
1163 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1166 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1169 if (! tclass.class_header().empty())
1170 os << from_ascii(tclass.class_header());
1171 else if (runparams.flavor == OutputParams::XML)
1172 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1173 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1175 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1177 docstring preamble = from_utf8(params().preamble);
1178 if (runparams.flavor != OutputParams::XML ) {
1179 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1180 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1181 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1182 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1185 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1187 preamble += features.getIncludedFiles(name);
1188 preamble += features.getLyXSGMLEntities();
1190 if (!preamble.empty()) {
1191 os << "\n [ " << preamble << " ]";
1196 string top = top_element;
1198 if (runparams.flavor == OutputParams::XML)
1199 top += params().language->code();
1201 top += params().language->code().substr(0,2);
1204 if (!params().options.empty()) {
1206 top += params().options;
1209 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1210 << " file was created by LyX " << lyx_version
1211 << "\n See http://www.lyx.org/ for more information -->\n";
1213 params().getTextClass().counters().reset();
1215 loadChildDocuments(*this);
1217 sgml::openTag(os, top);
1219 docbookParagraphs(paragraphs(), *this, os, runparams);
1220 sgml::closeTag(os, top_element);
1224 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1225 // Other flags: -wall -v0 -x
1226 int Buffer::runChktex()
1230 // get LaTeX-Filename
1231 FileName const path(temppath());
1232 string const name = addName(path.absFilename(), getLatexName());
1233 string const org_path = filePath();
1235 support::Path p(path); // path to LaTeX file
1236 message(_("Running chktex..."));
1238 // Generate the LaTeX file if neccessary
1239 OutputParams runparams(¶ms().encoding());
1240 runparams.flavor = OutputParams::LATEX;
1241 runparams.nice = false;
1242 makeLaTeXFile(FileName(name), org_path, runparams);
1245 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1246 int const res = chktex.run(terr); // run chktex
1249 Alert::error(_("chktex failure"),
1250 _("Could not run chktex successfully."));
1251 } else if (res > 0) {
1252 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1253 // Clear out old errors
1255 // Fill-in the error list with the TeX errors
1256 bufferErrors(*this, terr, errorList);
1267 void Buffer::validate(LaTeXFeatures & features) const
1269 TextClass const & tclass = params().getTextClass();
1271 if (params().outputChanges) {
1272 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1273 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1274 LaTeXFeatures::isAvailable("xcolor");
1276 if (features.runparams().flavor == OutputParams::LATEX) {
1278 features.require("ct-dvipost");
1279 features.require("dvipost");
1280 } else if (xcolorsoul) {
1281 features.require("ct-xcolor-soul");
1282 features.require("soul");
1283 features.require("xcolor");
1285 features.require("ct-none");
1287 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1289 features.require("ct-xcolor-soul");
1290 features.require("soul");
1291 features.require("xcolor");
1292 features.require("pdfcolmk"); // improves color handling in PDF output
1294 features.require("ct-none");
1299 // AMS Style is at document level
1300 if (params().use_amsmath == BufferParams::package_on
1301 || tclass.provides("amsmath"))
1302 features.require("amsmath");
1303 if (params().use_esint == BufferParams::package_on)
1304 features.require("esint");
1306 loadChildDocuments(*this);
1308 for_each(paragraphs().begin(), paragraphs().end(),
1309 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1311 // the bullet shapes are buffer level not paragraph level
1312 // so they are tested here
1313 for (int i = 0; i < 4; ++i) {
1314 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1315 int const font = params().user_defined_bullet(i).getFont();
1317 int const c = params()
1318 .user_defined_bullet(i)
1325 features.require("latexsym");
1327 } else if (font == 1) {
1328 features.require("amssymb");
1329 } else if ((font >= 2 && font <= 5)) {
1330 features.require("pifont");
1335 if (lyxerr.debugging(Debug::LATEX)) {
1336 features.showStruct();
1341 void Buffer::getLabelList(vector<docstring> & list) const
1343 /// if this is a child document and the parent is already loaded
1344 /// Use the parent's list instead [ale990407]
1345 Buffer const * tmp = getMasterBuffer();
1347 lyxerr << "getMasterBuffer() failed!" << endl;
1351 tmp->getLabelList(list);
1355 loadChildDocuments(*this);
1357 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1358 it.nextInset()->getLabelList(*this, list);
1362 // This is also a buffer property (ale)
1363 void Buffer::fillWithBibKeys(biblio::BibKeyList & keys)
1366 biblio::fillWithBibKeys(this, keys);
1370 void Buffer::updateBibfilesCache()
1372 // if this is a child document and the parent is already loaded
1373 // update the parent's cache instead
1374 Buffer * tmp = getMasterBuffer();
1377 tmp->updateBibfilesCache();
1381 bibfilesCache_.clear();
1382 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1383 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1384 InsetBibtex const & inset =
1385 static_cast<InsetBibtex const &>(*it);
1386 vector<FileName> const bibfiles = inset.getFiles(*this);
1387 bibfilesCache_.insert(bibfilesCache_.end(),
1390 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1391 InsetInclude & inset =
1392 static_cast<InsetInclude &>(*it);
1393 inset.updateBibfilesCache(*this);
1394 vector<FileName> const & bibfiles =
1395 inset.getBibfilesCache(*this);
1396 bibfilesCache_.insert(bibfilesCache_.end(),
1404 vector<FileName> const & Buffer::getBibfilesCache() const
1406 // if this is a child document and the parent is already loaded
1407 // use the parent's cache instead
1408 Buffer const * tmp = getMasterBuffer();
1411 return tmp->getBibfilesCache();
1413 // We update the cache when first used instead of at loading time.
1414 if (bibfilesCache_.empty())
1415 const_cast<Buffer *>(this)->updateBibfilesCache();
1417 return bibfilesCache_;
1421 bool Buffer::isDepClean(string const & name) const
1423 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1424 if (it == pimpl_->dep_clean.end())
1430 void Buffer::markDepClean(string const & name)
1432 pimpl_->dep_clean[name] = true;
1436 bool Buffer::dispatch(string const & command, bool * result)
1438 return dispatch(lyxaction.lookupFunc(command), result);
1442 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1444 bool dispatched = true;
1446 switch (func.action) {
1447 case LFUN_BUFFER_EXPORT: {
1448 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1461 void Buffer::changeLanguage(Language const * from, Language const * to)
1466 for_each(par_iterator_begin(),
1468 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1470 text().current_font.setLanguage(to);
1471 text().real_current_font.setLanguage(to);
1475 bool Buffer::isMultiLingual() const
1477 ParConstIterator end = par_iterator_end();
1478 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1479 if (it->isMultiLingual(params()))
1486 ParIterator Buffer::getParFromID(int const id) const
1488 ParConstIterator it = par_iterator_begin();
1489 ParConstIterator const end = par_iterator_end();
1492 // John says this is called with id == -1 from undo
1493 lyxerr << "getParFromID(), id: " << id << endl;
1497 for (; it != end; ++it)
1505 bool Buffer::hasParWithID(int const id) const
1507 ParConstIterator const it = getParFromID(id);
1508 return it != par_iterator_end();
1512 ParIterator Buffer::par_iterator_begin()
1514 return lyx::par_iterator_begin(inset());
1518 ParIterator Buffer::par_iterator_end()
1520 return lyx::par_iterator_end(inset());
1524 ParConstIterator Buffer::par_iterator_begin() const
1526 return lyx::par_const_iterator_begin(inset());
1530 ParConstIterator Buffer::par_iterator_end() const
1532 return lyx::par_const_iterator_end(inset());
1536 Language const * Buffer::getLanguage() const
1538 return params().language;
1542 docstring const Buffer::B_(string const & l10n) const
1544 return params().B_(l10n);
1548 bool Buffer::isClean() const
1550 return pimpl_->lyx_clean;
1554 bool Buffer::isBakClean() const
1556 return pimpl_->bak_clean;
1560 bool Buffer::isExternallyModified(CheckMethod method) const
1562 BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1563 // if method == timestamp, check timestamp before checksum
1564 return (method == checksum_method
1565 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1566 && pimpl_->checksum_ != sum(pimpl_->filename);
1570 void Buffer::markClean() const
1572 if (!pimpl_->lyx_clean) {
1573 pimpl_->lyx_clean = true;
1576 // if the .lyx file has been saved, we don't need an
1578 pimpl_->bak_clean = true;
1582 void Buffer::markBakClean()
1584 pimpl_->bak_clean = true;
1588 void Buffer::setUnnamed(bool flag)
1590 pimpl_->unnamed = flag;
1594 bool Buffer::isUnnamed() const
1596 return pimpl_->unnamed;
1600 // FIXME: this function should be moved to buffer_pimpl.C
1601 void Buffer::markDirty()
1603 if (pimpl_->lyx_clean) {
1604 pimpl_->lyx_clean = false;
1607 pimpl_->bak_clean = false;
1609 DepClean::iterator it = pimpl_->dep_clean.begin();
1610 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1612 for (; it != end; ++it)
1617 string const Buffer::fileName() const
1619 return pimpl_->filename.absFilename();
1623 string const & Buffer::filePath() const
1625 return params().filepath;
1629 bool Buffer::isReadonly() const
1631 return pimpl_->read_only;
1635 void Buffer::setParentName(string const & name)
1637 if (name == pimpl_->filename.absFilename())
1638 // Avoids recursive include.
1639 params().parentname.clear();
1641 params().parentname = name;
1645 Buffer const * Buffer::getMasterBuffer() const
1647 if (!params().parentname.empty()
1648 && theBufferList().exists(params().parentname)) {
1649 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1650 //We need to check if the parent is us...
1651 //FIXME RECURSIVE INCLUDE
1652 //This is not sufficient, since recursive includes could be downstream.
1653 if (buf && buf != this)
1654 return buf->getMasterBuffer();
1661 Buffer * Buffer::getMasterBuffer()
1663 if (!params().parentname.empty()
1664 && theBufferList().exists(params().parentname)) {
1665 Buffer * buf = theBufferList().getBuffer(params().parentname);
1667 return buf->getMasterBuffer();
1674 MacroData const & Buffer::getMacro(docstring const & name) const
1676 return pimpl_->macros.get(name);
1680 bool Buffer::hasMacro(docstring const & name) const
1682 return pimpl_->macros.has(name);
1686 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1688 MacroTable::globalMacros().insert(name, data);
1689 pimpl_->macros.insert(name, data);
1693 void Buffer::buildMacros()
1695 // Start with global table.
1696 pimpl_->macros = MacroTable::globalMacros();
1699 ParagraphList const & pars = text().paragraphs();
1700 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1701 //lyxerr << "searching main par " << i
1702 // << " for macro definitions" << std::endl;
1703 InsetList const & insets = pars[i].insetlist;
1704 InsetList::const_iterator it = insets.begin();
1705 InsetList::const_iterator end = insets.end();
1706 for ( ; it != end; ++it) {
1707 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1708 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1709 MathMacroTemplate const & mac
1710 = static_cast<MathMacroTemplate const &>(*it->inset);
1711 insertMacro(mac.name(), mac.asMacroData());
1718 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1725 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1728 //FIXME: This does not work for child documents yet.
1729 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1730 // Check if the label 'from' appears more than once
1731 vector<docstring> labels;
1733 if (code == Inset::CITE_CODE) {
1734 biblio::BibKeyList keys;
1735 fillWithBibKeys(keys);
1736 biblio::BibKeyList::const_iterator bit = keys.begin();
1737 biblio::BibKeyList::const_iterator bend = keys.end();
1739 for (; bit != bend; ++bit)
1741 labels.push_back(from_utf8(bit->first));
1743 getLabelList(labels);
1745 if (std::count(labels.begin(), labels.end(), from) > 1)
1748 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1749 if (it->lyxCode() == code) {
1750 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1751 inset.replaceContents(to_utf8(from), to_utf8(to));
1757 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1758 pit_type par_end, bool full_source)
1760 OutputParams runparams(¶ms().encoding());
1761 runparams.nice = true;
1762 runparams.flavor = OutputParams::LATEX;
1763 runparams.linelen = lyxrc.plaintext_linelen;
1764 // No side effect of file copying and image conversion
1765 runparams.dryrun = true;
1769 os << "% " << _("Preview source code") << "\n\n";
1773 writeLaTeXSource(os, filePath(), runparams, true, true);
1775 writeDocBookSource(os, fileName(), runparams, false);
1778 runparams.par_begin = par_begin;
1779 runparams.par_end = par_end;
1780 if (par_begin + 1 == par_end)
1782 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1786 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1787 convert<docstring>(par_begin),
1788 convert<docstring>(par_end - 1))
1792 // output paragraphs
1794 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1797 docbookParagraphs(paragraphs(), *this, os, runparams);
1803 ErrorList const & Buffer::errorList(string const & type) const
1805 static ErrorList const emptyErrorList;
1806 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1807 if (I == pimpl_->errorLists.end())
1808 return emptyErrorList;
1814 ErrorList & Buffer::errorList(string const & type)
1816 return pimpl_->errorLists[type];