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 "TexStream.h"
53 #include "TocBackend.h"
57 #include "insets/InsetBibitem.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetInclude.h"
60 #include "insets/InsetText.h"
62 #include "mathed/MathMacroTemplate.h"
63 #include "mathed/MacroTable.h"
64 #include "mathed/MathSupport.h"
66 #include "frontends/alert.h"
68 #include "graphics/Previews.h"
70 #include "support/types.h"
71 #include "support/lyxalgo.h"
72 #include "support/filetools.h"
73 #include "support/fs_extras.h"
74 #include "support/gzstream.h"
75 #include "support/lyxlib.h"
76 #include "support/os.h"
77 #include "support/Path.h"
78 #include "support/textutils.h"
79 #include "support/convert.h"
81 #include <boost/bind.hpp>
82 #include <boost/filesystem/exception.hpp>
83 #include <boost/filesystem/operations.hpp>
98 using std::ostringstream;
109 using support::addName;
110 using support::bformat;
111 using support::changeExtension;
112 using support::cmd_ret;
113 using support::createBufferTmpDir;
114 using support::destroyDir;
115 using support::FileName;
116 using support::getFormatFromContents;
117 using support::libFileSearch;
118 using support::latex_path;
119 using support::ltrim;
120 using support::makeAbsPath;
121 using support::makeDisplayPath;
122 using support::makeLatexName;
123 using support::onlyFilename;
124 using support::onlyPath;
125 using support::quoteName;
126 using support::removeAutosaveFile;
127 using support::rename;
128 using support::runCommand;
129 using support::split;
130 using support::subst;
131 using support::tempName;
135 namespace Alert = frontend::Alert;
136 namespace os = support::os;
137 namespace fs = boost::filesystem;
141 int const LYX_FORMAT = 280;
146 typedef std::map<string, bool> DepClean;
151 Impl(Buffer & parent, FileName const & file, bool readonly);
153 limited_stack<Undo> undostack;
154 limited_stack<Undo> redostack;
160 /// need to regenerate .tex?
164 mutable bool lyx_clean;
166 /// is autosave needed?
167 mutable bool bak_clean;
169 /// is this a unnamed file (New...)?
175 /// name of the file the buffer is associated with.
178 /** Set to true only when the file is fully loaded.
179 * Used to prevent the premature generation of previews
180 * and by the citation inset.
182 bool file_fully_loaded;
184 /// our Text that should be wrapped in an InsetText
191 TocBackend toc_backend;
193 /// Container for all sort of Buffer dependant errors.
194 map<string, ErrorList> errorLists;
196 /// timestamp and checksum used to test if the file has been externally
197 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
199 unsigned long checksum_;
203 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
204 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
205 filename(file), file_fully_loaded(false), inset(params),
206 toc_backend(&parent), timestamp_(0), checksum_(0)
208 inset.setAutoBreakRows(true);
209 lyxvc.buffer(&parent);
210 temppath = createBufferTmpDir();
211 params.filepath = onlyPath(file.absFilename());
212 // FIXME: And now do something if temppath == string(), because we
213 // assume from now on that temppath points to a valid temp dir.
214 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
218 Buffer::Buffer(string const & file, bool readonly)
219 : pimpl_(new Impl(*this, FileName(file), readonly))
221 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
227 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
228 // here the buffer should take care that it is
229 // saved properly, before it goes into the void.
231 Buffer * master = getMasterBuffer();
232 if (master != this && use_gui)
233 // We are closing buf which was a child document so we
234 // must update the labels and section numbering of its master
236 updateLabels(*master);
238 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
239 Alert::warning(_("Could not remove temporary directory"),
240 bformat(_("Could not remove the temporary directory %1$s"),
241 from_utf8(temppath())));
244 // Remove any previewed LaTeX snippets associated with this buffer.
245 graphics::Previews::get().removeLoader(*this);
251 Text & Buffer::text() const
253 return const_cast<Text &>(pimpl_->inset.text_);
257 Inset & Buffer::inset() const
259 return const_cast<InsetText &>(pimpl_->inset);
263 limited_stack<Undo> & Buffer::undostack()
265 return pimpl_->undostack;
269 limited_stack<Undo> const & Buffer::undostack() const
271 return pimpl_->undostack;
275 limited_stack<Undo> & Buffer::redostack()
277 return pimpl_->redostack;
281 limited_stack<Undo> const & Buffer::redostack() const
283 return pimpl_->redostack;
287 BufferParams & Buffer::params()
289 return pimpl_->params;
293 BufferParams const & Buffer::params() const
295 return pimpl_->params;
299 ParagraphList & Buffer::paragraphs()
301 return text().paragraphs();
305 ParagraphList const & Buffer::paragraphs() const
307 return text().paragraphs();
311 LyXVC & Buffer::lyxvc()
313 return pimpl_->lyxvc;
317 LyXVC const & Buffer::lyxvc() const
319 return pimpl_->lyxvc;
323 string const & Buffer::temppath() const
325 return pimpl_->temppath;
329 TexRow & Buffer::texrow()
331 return pimpl_->texrow;
335 TexRow const & Buffer::texrow() const
337 return pimpl_->texrow;
341 TocBackend & Buffer::tocBackend()
343 return pimpl_->toc_backend;
347 TocBackend const & Buffer::tocBackend() const
349 return pimpl_->toc_backend;
353 string const Buffer::getLatexName(bool const no_path) const
355 string const name = changeExtension(makeLatexName(fileName()), ".tex");
356 return no_path ? onlyFilename(name) : name;
360 pair<Buffer::LogType, string> const Buffer::getLogName() const
362 string const filename = getLatexName(false);
364 if (filename.empty())
365 return make_pair(Buffer::latexlog, string());
367 string const path = temppath();
369 FileName const fname(addName(temppath(),
370 onlyFilename(changeExtension(filename,
372 FileName const bname(
373 addName(path, onlyFilename(
374 changeExtension(filename,
375 formats.extension("literate") + ".out"))));
377 // If no Latex log or Build log is newer, show Build log
379 if (fs::exists(bname.toFilesystemEncoding()) &&
380 (!fs::exists(fname.toFilesystemEncoding()) ||
381 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
382 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
383 return make_pair(Buffer::buildlog, bname.absFilename());
385 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
386 return make_pair(Buffer::latexlog, fname.absFilename());
390 void Buffer::setReadonly(bool const flag)
392 if (pimpl_->read_only != flag) {
393 pimpl_->read_only = flag;
399 void Buffer::setFileName(string const & newfile)
401 pimpl_->filename = makeAbsPath(newfile);
402 params().filepath = onlyPath(pimpl_->filename.absFilename());
403 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
408 // We'll remove this later. (Lgb)
411 void unknownClass(string const & unknown)
413 Alert::warning(_("Unknown document class"),
414 bformat(_("Using the default document class, because the "
415 "class %1$s is unknown."), from_utf8(unknown)));
421 int Buffer::readHeader(Lexer & lex)
423 int unknown_tokens = 0;
425 int begin_header_line = -1;
427 // Initialize parameters that may be/go lacking in header:
428 params().branchlist().clear();
429 params().preamble.erase();
430 params().options.erase();
431 params().float_placement.erase();
432 params().paperwidth.erase();
433 params().paperheight.erase();
434 params().leftmargin.erase();
435 params().rightmargin.erase();
436 params().topmargin.erase();
437 params().bottommargin.erase();
438 params().headheight.erase();
439 params().headsep.erase();
440 params().footskip.erase();
441 params().listings_params.clear();
442 for (int i = 0; i < 4; ++i) {
443 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
444 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
447 ErrorList & errorList = pimpl_->errorLists["Parse"];
451 string const token = lex.getString();
456 if (token == "\\end_header")
460 if (token == "\\begin_header") {
461 begin_header_line = line;
465 LYXERR(Debug::PARSER) << "Handling document header token: `"
466 << token << '\'' << endl;
468 string unknown = params().readToken(lex, token);
469 if (!unknown.empty()) {
470 if (unknown[0] != '\\' && token == "\\textclass") {
471 unknownClass(unknown);
474 docstring const s = bformat(_("Unknown token: "
478 errorList.push_back(ErrorItem(_("Document header error"),
483 if (begin_header_line) {
484 docstring const s = _("\\begin_header is missing");
485 errorList.push_back(ErrorItem(_("Document header error"),
489 return unknown_tokens;
494 // changed to be public and have one parameter
495 // Returns false if "\end_document" is not read (Asger)
496 bool Buffer::readDocument(Lexer & lex)
498 ErrorList & errorList = pimpl_->errorLists["Parse"];
502 string const token = lex.getString();
503 if (token != "\\begin_document") {
504 docstring const s = _("\\begin_document is missing");
505 errorList.push_back(ErrorItem(_("Document header error"),
509 // we are reading in a brand new document
510 BOOST_ASSERT(paragraphs().empty());
513 if (!params().getTextClass().load(filePath())) {
514 string theclass = params().getTextClass().name();
515 Alert::error(_("Can't load document class"), bformat(
516 _("Using the default document class, because the "
517 "class %1$s could not be loaded."), from_utf8(theclass)));
518 params().textclass = 0;
521 if (params().outputChanges) {
522 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
523 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
524 LaTeXFeatures::isAvailable("xcolor");
526 if (!dvipost && !xcolorsoul) {
527 Alert::warning(_("Changes not shown in LaTeX output"),
528 _("Changes will not be highlighted in LaTeX output, "
529 "because neither dvipost nor xcolor/soul are installed.\n"
530 "Please install these packages or redefine "
531 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
532 } else if (!xcolorsoul) {
533 Alert::warning(_("Changes not shown in LaTeX output"),
534 _("Changes will not be highlighted in LaTeX output "
535 "when using pdflatex, because xcolor and soul are not installed.\n"
536 "Please install both packages or redefine "
537 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
541 bool const res = text().read(*this, lex, errorList);
542 for_each(text().paragraphs().begin(),
543 text().paragraphs().end(),
544 bind(&Paragraph::setInsetOwner, _1, &inset()));
550 // needed to insert the selection
551 void Buffer::insertStringAsLines(ParagraphList & pars,
552 pit_type & pit, pos_type & pos,
553 Font const & fn, docstring const & str, bool autobreakrows)
557 // insert the string, don't insert doublespace
558 bool space_inserted = true;
559 for (docstring::const_iterator cit = str.begin();
560 cit != str.end(); ++cit) {
561 Paragraph & par = pars[pit];
563 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
564 breakParagraph(params(), pars, pit, pos,
565 par.layout()->isEnvironment());
568 space_inserted = true;
572 // do not insert consecutive spaces if !free_spacing
573 } else if ((*cit == ' ' || *cit == '\t') &&
574 space_inserted && !par.isFreeSpacing()) {
576 } else if (*cit == '\t') {
577 if (!par.isFreeSpacing()) {
578 // tabs are like spaces here
579 par.insertChar(pos, ' ', font, params().trackChanges);
581 space_inserted = true;
583 const pos_type n = 8 - pos % 8;
584 for (pos_type i = 0; i < n; ++i) {
585 par.insertChar(pos, ' ', font, params().trackChanges);
588 space_inserted = true;
590 } else if (!isPrintable(*cit)) {
591 // Ignore unprintables
594 // just insert the character
595 par.insertChar(pos, *cit, font, params().trackChanges);
597 space_inserted = (*cit == ' ');
604 bool Buffer::readString(std::string const & s)
606 params().compressed = false;
608 // remove dummy empty par
609 paragraphs().clear();
611 std::istringstream is(s);
613 FileName const name(tempName());
614 switch (readFile(lex, name, true)) {
618 // We need to call lyx2lyx, so write the input to a file
619 std::ofstream os(name.toFilesystemEncoding().c_str());
622 return readFile(name);
632 bool Buffer::readFile(FileName const & filename)
634 // Check if the file is compressed.
635 string const format = getFormatFromContents(filename);
636 if (format == "gzip" || format == "zip" || format == "compress") {
637 params().compressed = true;
640 // remove dummy empty par
641 paragraphs().clear();
643 lex.setFile(filename);
644 if (readFile(lex, filename) != success)
651 bool Buffer::fully_loaded() const
653 return pimpl_->file_fully_loaded;
657 void Buffer::fully_loaded(bool const value)
659 pimpl_->file_fully_loaded = value;
663 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
666 BOOST_ASSERT(!filename.empty());
669 Alert::error(_("Document could not be read"),
670 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
675 string const token(lex.getString());
678 Alert::error(_("Document could not be read"),
679 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
683 // the first token _must_ be...
684 if (token != "\\lyxformat") {
685 lyxerr << "Token: " << token << endl;
687 Alert::error(_("Document format failure"),
688 bformat(_("%1$s is not a LyX document."),
689 from_utf8(filename.absFilename())));
694 string tmp_format = lex.getString();
695 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
696 // if present remove ".," from string.
697 string::size_type dot = tmp_format.find_first_of(".,");
698 //lyxerr << " dot found at " << dot << endl;
699 if (dot != string::npos)
700 tmp_format.erase(dot, 1);
701 int const file_format = convert<int>(tmp_format);
702 //lyxerr << "format: " << file_format << endl;
704 if (file_format != LYX_FORMAT) {
707 // lyx2lyx would fail
710 FileName const tmpfile(tempName());
711 if (tmpfile.empty()) {
712 Alert::error(_("Conversion failed"),
713 bformat(_("%1$s is from a different"
714 " version of LyX, but a temporary"
715 " file for converting it could"
717 from_utf8(filename.absFilename())));
720 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
721 if (lyx2lyx.empty()) {
722 Alert::error(_("Conversion script not found"),
723 bformat(_("%1$s is from a different"
724 " version of LyX, but the"
725 " conversion script lyx2lyx"
726 " could not be found."),
727 from_utf8(filename.absFilename())));
730 ostringstream command;
731 command << os::python()
732 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
733 << " -t " << convert<string>(LYX_FORMAT)
734 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
735 << ' ' << quoteName(filename.toFilesystemEncoding());
736 string const command_str = command.str();
738 LYXERR(Debug::INFO) << "Running '"
739 << command_str << '\''
742 cmd_ret const ret = runCommand(command_str);
743 if (ret.first != 0) {
744 Alert::error(_("Conversion script failed"),
745 bformat(_("%1$s is from a different version"
746 " of LyX, but the lyx2lyx script"
747 " failed to convert it."),
748 from_utf8(filename.absFilename())));
751 bool const ret = readFile(tmpfile);
752 // Do stuff with tmpfile name and buffer name here.
753 return ret ? success : failure;
758 if (readDocument(lex)) {
759 Alert::error(_("Document format failure"),
760 bformat(_("%1$s ended unexpectedly, which means"
761 " that it is probably corrupted."),
762 from_utf8(filename.absFilename())));
765 //lyxerr << "removing " << MacroTable::localMacros().size()
766 // << " temporary macro entries" << endl;
767 //MacroTable::localMacros().clear();
769 pimpl_->file_fully_loaded = true;
770 // save the timestamp and checksum of disk file
771 pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
772 pimpl_->checksum_ = sum(filename);
777 // Should probably be moved to somewhere else: BufferView? LyXView?
778 bool Buffer::save() const
780 // We don't need autosaves in the immediate future. (Asger)
781 resetAutosaveTimers();
783 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
786 bool madeBackup = false;
788 // make a backup if the file already exists
789 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
790 backupName = FileName(fileName() + '~');
791 if (!lyxrc.backupdir_path.empty())
792 backupName = FileName(addName(lyxrc.backupdir_path,
793 subst(os::internal_path(backupName.absFilename()), '/', '!')));
796 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
798 } catch (fs::filesystem_error const & fe) {
799 Alert::error(_("Backup failure"),
800 bformat(_("Cannot create backup file %1$s.\n"
801 "Please check whether the directory exists and is writeable."),
802 from_utf8(backupName.absFilename())));
803 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
807 // ask if the disk file has been externally modified (use checksum method)
808 if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
809 docstring const file = makeDisplayPath(fileName(), 20);
810 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
811 "you want to overwrite this file?"), file);
812 int const ret = Alert::prompt(_("Overwrite modified file?"),
813 text, 1, 1, _("&Overwrite"), _("&Cancel"));
818 if (writeFile(pimpl_->filename)) {
820 removeAutosaveFile(fileName());
821 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
822 pimpl_->checksum_ = sum(pimpl_->filename);
825 // Saving failed, so backup is not backup
827 rename(backupName, pimpl_->filename);
833 bool Buffer::writeFile(FileName const & fname) const
835 if (pimpl_->read_only && fname == pimpl_->filename)
840 if (params().compressed) {
841 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
847 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
858 bool Buffer::write(ostream & ofs) const
861 // Use the standard "C" locale for file output.
862 ofs.imbue(std::locale::classic());
865 // The top of the file should not be written by params().
867 // write out a comment in the top of the file
868 ofs << "#LyX " << lyx_version
869 << " created this file. For more info see http://www.lyx.org/\n"
870 << "\\lyxformat " << LYX_FORMAT << "\n"
871 << "\\begin_document\n";
874 /// For each author, set 'used' to true if there is a change
875 /// by this author in the document; otherwise set it to 'false'.
876 AuthorList::Authors::const_iterator a_it = params().authors().begin();
877 AuthorList::Authors::const_iterator a_end = params().authors().end();
878 for (; a_it != a_end; ++a_it)
879 a_it->second.used(false);
881 ParIterator const end = par_iterator_end();
882 ParIterator it = par_iterator_begin();
883 for ( ; it != end; ++it)
884 it->checkAuthors(params().authors());
886 // now write out the buffer parameters.
887 ofs << "\\begin_header\n";
888 params().writeFile(ofs);
889 ofs << "\\end_header\n";
892 ofs << "\n\\begin_body\n";
893 text().write(*this, ofs);
894 ofs << "\n\\end_body\n";
896 // Write marker that shows file is complete
897 ofs << "\\end_document" << endl;
899 // Shouldn't really be needed....
902 // how to check if close went ok?
903 // Following is an attempt... (BE 20001011)
905 // good() returns false if any error occured, including some
907 // bad() returns true if something bad happened in the buffer,
908 // which should include file system full errors.
913 lyxerr << "File was not closed properly." << endl;
920 bool Buffer::makeLaTeXFile(FileName const & fname,
921 string const & original_path,
922 OutputParams const & runparams,
923 bool output_preamble, bool output_body)
925 string const encoding = runparams.encoding->iconvName();
926 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
927 << encoding << "..." << endl;
929 odocfstream ofs(encoding);
930 if (!openFileWrite(ofs, fname))
933 //TexStream ts(ofs.rdbuf(), &texrow());
935 bool failed_export = false;
938 writeLaTeXSource(ofs, original_path,
939 runparams, output_preamble, output_body);
941 catch (iconv_codecvt_facet_exception & e) {
942 lyxerr << "Caught iconv exception: " << e.what() << endl;
943 failed_export = true;
945 catch (std::exception const & e) {
946 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
947 failed_export = true;
950 lyxerr << "Caught some really weird exception..." << endl;
951 LyX::cref().emergencyCleanup();
957 failed_export = true;
958 lyxerr << "File '" << fname << "' was not closed properly." << endl;
962 Alert::error(_("Encoding error"),
963 _("Some characters of your document are probably not "
964 "representable in the chosen encoding.\n"
965 "Changing the document encoding to utf8 could help."));
972 void Buffer::writeLaTeXSource(odocstream & os,
973 string const & original_path,
974 OutputParams const & runparams_in,
975 bool const output_preamble, bool const output_body)
977 OutputParams runparams = runparams_in;
979 // validate the buffer.
980 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
981 LaTeXFeatures features(*this, params(), runparams);
983 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
985 // The starting paragraph of the coming rows is the
986 // first paragraph of the document. (Asger)
987 if (output_preamble && runparams.nice) {
988 os << "%% LyX " << lyx_version << " created this file. "
989 "For more info, see http://www.lyx.org/.\n"
990 "%% Do not edit unless you really know what "
995 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
996 // There are a few differences between nice LaTeX and usual files:
997 // usual is \batchmode and has a
998 // special input@path to allow the including of figures
999 // with either \input or \includegraphics (what figinsets do).
1000 // input@path is set when the actual parameter
1001 // original_path is set. This is done for usual tex-file, but not
1002 // for nice-latex-file. (Matthias 250696)
1003 // Note that input@path is only needed for something the user does
1004 // in the preamble, included .tex files or ERT, files included by
1005 // LyX work without it.
1006 if (output_preamble) {
1007 if (!runparams.nice) {
1008 // code for usual, NOT nice-latex-file
1009 os << "\\batchmode\n"; // changed
1010 // from \nonstopmode
1013 if (!original_path.empty()) {
1015 // We don't know the encoding of inputpath
1016 docstring const inputpath = from_utf8(latex_path(original_path));
1017 os << "\\makeatletter\n"
1018 << "\\def\\input@path{{"
1019 << inputpath << "/}}\n"
1020 << "\\makeatother\n";
1026 // Write the preamble
1027 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1033 os << "\\begin{document}\n";
1035 } // output_preamble
1037 texrow().start(paragraphs().begin()->id(), 0);
1039 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1041 if (!lyxrc.language_auto_begin &&
1042 !params().language->babel().empty()) {
1044 os << from_utf8(subst(lyxrc.language_command_begin,
1046 params().language->babel()))
1051 Encoding const & encoding = params().encoding();
1052 if (encoding.package() == Encoding::CJK) {
1053 // Open a CJK environment, since in contrast to the encodings
1054 // handled by inputenc the document encoding is not set in
1055 // the preamble if it is handled by CJK.sty.
1056 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1061 // if we are doing a real file with body, even if this is the
1062 // child of some other buffer, let's cut the link here.
1063 // This happens for example if only a child document is printed.
1064 string save_parentname;
1065 if (output_preamble) {
1066 save_parentname = params().parentname;
1067 params().parentname.erase();
1070 loadChildDocuments(*this);
1073 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1075 // Restore the parenthood if needed
1076 if (output_preamble)
1077 params().parentname = save_parentname;
1079 // add this just in case after all the paragraphs
1083 if (encoding.package() == Encoding::CJK) {
1084 // Close the open CJK environment.
1085 // latexParagraphs will have opened one even if the last text
1087 os << "\\end{CJK}\n";
1091 if (!lyxrc.language_auto_end &&
1092 !params().language->babel().empty()) {
1093 os << from_utf8(subst(lyxrc.language_command_end,
1095 params().language->babel()))
1100 if (output_preamble) {
1101 os << "\\end{document}\n";
1104 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1106 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1109 runparams_in.encoding = runparams.encoding;
1111 // Just to be sure. (Asger)
1114 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1115 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1120 bool Buffer::isLatex() const
1122 return params().getTextClass().outputType() == LATEX;
1126 bool Buffer::isLiterate() const
1128 return params().getTextClass().outputType() == LITERATE;
1132 bool Buffer::isDocBook() const
1134 return params().getTextClass().outputType() == DOCBOOK;
1138 void Buffer::makeDocBookFile(FileName const & fname,
1139 OutputParams const & runparams,
1140 bool const body_only)
1142 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1146 if (!openFileWrite(ofs, fname))
1149 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1153 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1157 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1158 OutputParams const & runparams,
1159 bool const only_body)
1161 LaTeXFeatures features(*this, params(), runparams);
1166 TextClass const & tclass = params().getTextClass();
1167 string const top_element = tclass.latexname();
1170 if (runparams.flavor == OutputParams::XML)
1171 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1174 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1177 if (! tclass.class_header().empty())
1178 os << from_ascii(tclass.class_header());
1179 else if (runparams.flavor == OutputParams::XML)
1180 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1181 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1183 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1185 docstring preamble = from_utf8(params().preamble);
1186 if (runparams.flavor != OutputParams::XML ) {
1187 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1188 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1189 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1190 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1193 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1195 preamble += features.getIncludedFiles(name);
1196 preamble += features.getLyXSGMLEntities();
1198 if (!preamble.empty()) {
1199 os << "\n [ " << preamble << " ]";
1204 string top = top_element;
1206 if (runparams.flavor == OutputParams::XML)
1207 top += params().language->code();
1209 top += params().language->code().substr(0,2);
1212 if (!params().options.empty()) {
1214 top += params().options;
1217 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1218 << " file was created by LyX " << lyx_version
1219 << "\n See http://www.lyx.org/ for more information -->\n";
1221 params().getTextClass().counters().reset();
1223 loadChildDocuments(*this);
1225 sgml::openTag(os, top);
1227 docbookParagraphs(paragraphs(), *this, os, runparams);
1228 sgml::closeTag(os, top_element);
1232 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1233 // Other flags: -wall -v0 -x
1234 int Buffer::runChktex()
1238 // get LaTeX-Filename
1239 FileName const path(temppath());
1240 string const name = addName(path.absFilename(), getLatexName());
1241 string const org_path = filePath();
1243 support::Path p(path); // path to LaTeX file
1244 message(_("Running chktex..."));
1246 // Generate the LaTeX file if neccessary
1247 OutputParams runparams(¶ms().encoding());
1248 runparams.flavor = OutputParams::LATEX;
1249 runparams.nice = false;
1250 makeLaTeXFile(FileName(name), org_path, runparams);
1253 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1254 int const res = chktex.run(terr); // run chktex
1257 Alert::error(_("chktex failure"),
1258 _("Could not run chktex successfully."));
1259 } else if (res > 0) {
1260 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1261 // Clear out old errors
1263 // Fill-in the error list with the TeX errors
1264 bufferErrors(*this, terr, errorList);
1275 void Buffer::validate(LaTeXFeatures & features) const
1277 TextClass const & tclass = params().getTextClass();
1279 if (params().outputChanges) {
1280 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1281 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1282 LaTeXFeatures::isAvailable("xcolor");
1284 if (features.runparams().flavor == OutputParams::LATEX) {
1286 features.require("ct-dvipost");
1287 features.require("dvipost");
1288 } else if (xcolorsoul) {
1289 features.require("ct-xcolor-soul");
1290 features.require("soul");
1291 features.require("xcolor");
1293 features.require("ct-none");
1295 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1297 features.require("ct-xcolor-soul");
1298 features.require("soul");
1299 features.require("xcolor");
1300 features.require("pdfcolmk"); // improves color handling in PDF output
1302 features.require("ct-none");
1307 // AMS Style is at document level
1308 if (params().use_amsmath == BufferParams::package_on
1309 || tclass.provides("amsmath"))
1310 features.require("amsmath");
1311 if (params().use_esint == BufferParams::package_on)
1312 features.require("esint");
1314 loadChildDocuments(*this);
1316 for_each(paragraphs().begin(), paragraphs().end(),
1317 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1319 // the bullet shapes are buffer level not paragraph level
1320 // so they are tested here
1321 for (int i = 0; i < 4; ++i) {
1322 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1323 int const font = params().user_defined_bullet(i).getFont();
1325 int const c = params()
1326 .user_defined_bullet(i)
1333 features.require("latexsym");
1335 } else if (font == 1) {
1336 features.require("amssymb");
1337 } else if ((font >= 2 && font <= 5)) {
1338 features.require("pifont");
1343 if (lyxerr.debugging(Debug::LATEX)) {
1344 features.showStruct();
1349 void Buffer::getLabelList(vector<docstring> & list) const
1351 /// if this is a child document and the parent is already loaded
1352 /// Use the parent's list instead [ale990407]
1353 Buffer const * tmp = getMasterBuffer();
1355 lyxerr << "getMasterBuffer() failed!" << endl;
1359 tmp->getLabelList(list);
1363 loadChildDocuments(*this);
1365 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1366 it.nextInset()->getLabelList(*this, list);
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::changeRefsIfUnique(docstring const & from, docstring const & to,
1721 //FIXME: This does not work for child documents yet.
1722 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1723 // Check if the label 'from' appears more than once
1724 vector<docstring> labels;
1726 if (code == Inset::CITE_CODE) {
1728 keys.fillWithBibKeys(this);
1729 BiblioInfo::const_iterator bit = keys.begin();
1730 BiblioInfo::const_iterator bend = keys.end();
1732 for (; bit != bend; ++bit)
1734 labels.push_back(bit->first);
1736 getLabelList(labels);
1738 if (std::count(labels.begin(), labels.end(), from) > 1)
1741 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1742 if (it->lyxCode() == code) {
1743 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1744 inset.replaceContents(to_utf8(from), to_utf8(to));
1750 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1751 pit_type par_end, bool full_source)
1753 OutputParams runparams(¶ms().encoding());
1754 runparams.nice = true;
1755 runparams.flavor = OutputParams::LATEX;
1756 runparams.linelen = lyxrc.plaintext_linelen;
1757 // No side effect of file copying and image conversion
1758 runparams.dryrun = true;
1762 os << "% " << _("Preview source code") << "\n\n";
1766 writeLaTeXSource(os, filePath(), runparams, true, true);
1768 writeDocBookSource(os, fileName(), runparams, false);
1771 runparams.par_begin = par_begin;
1772 runparams.par_end = par_end;
1773 if (par_begin + 1 == par_end)
1775 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1779 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1780 convert<docstring>(par_begin),
1781 convert<docstring>(par_end - 1))
1785 // output paragraphs
1787 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1790 docbookParagraphs(paragraphs(), *this, os, runparams);
1796 ErrorList const & Buffer::errorList(string const & type) const
1798 static ErrorList const emptyErrorList;
1799 std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1800 if (I == pimpl_->errorLists.end())
1801 return emptyErrorList;
1807 ErrorList & Buffer::errorList(string const & type)
1809 return pimpl_->errorLists[type];