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"
41 #include "output_docbook.h"
42 #include "output_latex.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "TocBackend.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetBibtex.h"
55 #include "insets/InsetInclude.h"
56 #include "insets/InsetText.h"
58 #include "mathed/MathMacroTemplate.h"
59 #include "mathed/MacroTable.h"
60 #include "mathed/MathSupport.h"
62 #include "frontends/alert.h"
64 #include "graphics/Previews.h"
66 #include "support/types.h"
67 #include "support/lyxalgo.h"
68 #include "support/filetools.h"
69 #include "support/fs_extras.h"
70 #include "support/lyxlib.h"
71 #include "support/os.h"
72 #include "support/Path.h"
73 #include "support/textutils.h"
74 #include "support/convert.h"
76 #include <boost/iostreams/filtering_stream.hpp>
77 #include <boost/iostreams/filter/gzip.hpp>
78 #include <boost/iostreams/device/file.hpp>
79 #include <boost/bind.hpp>
80 #include <boost/filesystem/exception.hpp>
81 #include <boost/filesystem/operations.hpp>
83 #if defined (HAVE_UTIME_H)
85 #elif defined (HAVE_SYS_UTIME_H)
86 #include <sys/utime.h>
97 using support::addName;
98 using support::bformat;
99 using support::changeExtension;
100 using support::cmd_ret;
101 using support::createBufferTmpDir;
102 using support::destroyDir;
103 using support::FileName;
104 using support::getFormatFromContents;
105 using support::libFileSearch;
106 using support::latex_path;
107 using support::ltrim;
108 using support::makeAbsPath;
109 using support::makeDisplayPath;
110 using support::makeLatexName;
111 using support::onlyFilename;
112 using support::onlyPath;
113 using support::quoteName;
114 using support::removeAutosaveFile;
115 using support::rename;
116 using support::runCommand;
117 using support::split;
118 using support::subst;
119 using support::tempName;
122 namespace Alert = frontend::Alert;
123 namespace os = support::os;
124 namespace fs = boost::filesystem;
125 namespace io = boost::iostreams;
129 using std::make_pair;
134 using std::ostringstream;
144 int const LYX_FORMAT = 270;
149 typedef std::map<string, bool> DepClean;
154 Impl(Buffer & parent, FileName const & file, bool readonly);
156 limited_stack<Undo> undostack;
157 limited_stack<Undo> redostack;
163 /// need to regenerate .tex?
167 mutable bool lyx_clean;
169 /// is autosave needed?
170 mutable bool bak_clean;
172 /// is this a unnamed file (New...)?
178 /// name of the file the buffer is associated with.
181 /** Set to true only when the file is fully loaded.
182 * Used to prevent the premature generation of previews
183 * and by the citation inset.
185 bool file_fully_loaded;
187 /// our Text that should be wrapped in an InsetText
194 TocBackend toc_backend;
198 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
199 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
200 filename(file), file_fully_loaded(false), inset(params),
203 inset.setAutoBreakRows(true);
204 lyxvc.buffer(&parent);
205 temppath = createBufferTmpDir();
206 params.filepath = onlyPath(file.absFilename());
207 // FIXME: And now do something if temppath == string(), because we
208 // assume from now on that temppath points to a valid temp dir.
209 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
213 Buffer::Buffer(string const & file, bool readonly)
214 : pimpl_(new Impl(*this, FileName(file), readonly))
216 LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
222 LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
223 // here the buffer should take care that it is
224 // saved properly, before it goes into the void.
228 if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
229 Alert::warning(_("Could not remove temporary directory"),
230 bformat(_("Could not remove the temporary directory %1$s"),
231 from_utf8(temppath())));
234 // Remove any previewed LaTeX snippets associated with this buffer.
235 graphics::Previews::get().removeLoader(*this);
239 Text & Buffer::text() const
241 return const_cast<Text &>(pimpl_->inset.text_);
245 Inset & Buffer::inset() const
247 return const_cast<InsetText &>(pimpl_->inset);
251 limited_stack<Undo> & Buffer::undostack()
253 return pimpl_->undostack;
257 limited_stack<Undo> const & Buffer::undostack() const
259 return pimpl_->undostack;
263 limited_stack<Undo> & Buffer::redostack()
265 return pimpl_->redostack;
269 limited_stack<Undo> const & Buffer::redostack() const
271 return pimpl_->redostack;
275 BufferParams & Buffer::params()
277 return pimpl_->params;
281 BufferParams const & Buffer::params() const
283 return pimpl_->params;
287 ParagraphList & Buffer::paragraphs()
289 return text().paragraphs();
293 ParagraphList const & Buffer::paragraphs() const
295 return text().paragraphs();
299 LyXVC & Buffer::lyxvc()
301 return pimpl_->lyxvc;
305 LyXVC const & Buffer::lyxvc() const
307 return pimpl_->lyxvc;
311 string const & Buffer::temppath() const
313 return pimpl_->temppath;
317 TexRow & Buffer::texrow()
319 return pimpl_->texrow;
323 TexRow const & Buffer::texrow() const
325 return pimpl_->texrow;
329 TocBackend & Buffer::tocBackend()
331 return pimpl_->toc_backend;
335 TocBackend const & Buffer::tocBackend() const
337 return pimpl_->toc_backend;
341 string const Buffer::getLatexName(bool const no_path) const
343 string const name = changeExtension(makeLatexName(fileName()), ".tex");
344 return no_path ? onlyFilename(name) : name;
348 pair<Buffer::LogType, string> const Buffer::getLogName() const
350 string const filename = getLatexName(false);
352 if (filename.empty())
353 return make_pair(Buffer::latexlog, string());
355 string const path = temppath();
357 FileName const fname(addName(temppath(),
358 onlyFilename(changeExtension(filename,
360 FileName const bname(
361 addName(path, onlyFilename(
362 changeExtension(filename,
363 formats.extension("literate") + ".out"))));
365 // If no Latex log or Build log is newer, show Build log
367 if (fs::exists(bname.toFilesystemEncoding()) &&
368 (!fs::exists(fname.toFilesystemEncoding()) ||
369 fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
370 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
371 return make_pair(Buffer::buildlog, bname.absFilename());
373 LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
374 return make_pair(Buffer::latexlog, fname.absFilename());
378 void Buffer::setReadonly(bool const flag)
380 if (pimpl_->read_only != flag) {
381 pimpl_->read_only = flag;
387 void Buffer::setFileName(string const & newfile)
389 pimpl_->filename = makeAbsPath(newfile);
390 params().filepath = onlyPath(pimpl_->filename.absFilename());
391 setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
396 // We'll remove this later. (Lgb)
399 void unknownClass(string const & unknown)
401 Alert::warning(_("Unknown document class"),
402 bformat(_("Using the default document class, because the "
403 "class %1$s is unknown."), from_utf8(unknown)));
409 int Buffer::readHeader(Lexer & lex)
411 int unknown_tokens = 0;
413 int begin_header_line = -1;
415 // Initialize parameters that may be/go lacking in header:
416 params().branchlist().clear();
417 params().preamble.erase();
418 params().options.erase();
419 params().float_placement.erase();
420 params().paperwidth.erase();
421 params().paperheight.erase();
422 params().leftmargin.erase();
423 params().rightmargin.erase();
424 params().topmargin.erase();
425 params().bottommargin.erase();
426 params().headheight.erase();
427 params().headsep.erase();
428 params().footskip.erase();
429 for (int i = 0; i < 4; ++i) {
430 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
431 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
434 ErrorList & errorList = errorLists_["Parse"];
438 string const token = lex.getString();
443 if (token == "\\end_header")
447 if (token == "\\begin_header") {
448 begin_header_line = line;
452 LYXERR(Debug::PARSER) << "Handling document header token: `"
453 << token << '\'' << endl;
455 string unknown = params().readToken(lex, token);
456 if (!unknown.empty()) {
457 if (unknown[0] != '\\' && token == "\\textclass") {
458 unknownClass(unknown);
461 docstring const s = bformat(_("Unknown token: "
465 errorList.push_back(ErrorItem(_("Document header error"),
470 if (begin_header_line) {
471 docstring const s = _("\\begin_header is missing");
472 errorList.push_back(ErrorItem(_("Document header error"),
476 return unknown_tokens;
481 // changed to be public and have one parameter
482 // Returns false if "\end_document" is not read (Asger)
483 bool Buffer::readDocument(Lexer & lex)
485 ErrorList & errorList = errorLists_["Parse"];
489 string const token = lex.getString();
490 if (token != "\\begin_document") {
491 docstring const s = _("\\begin_document is missing");
492 errorList.push_back(ErrorItem(_("Document header error"),
496 // we are reading in a brand new document
497 BOOST_ASSERT(paragraphs().empty());
500 if (!params().getTextClass().load(filePath())) {
501 string theclass = params().getTextClass().name();
502 Alert::error(_("Can't load document class"), bformat(
503 _("Using the default document class, because the "
504 "class %1$s could not be loaded."), from_utf8(theclass)));
505 params().textclass = 0;
508 if (params().outputChanges) {
509 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
510 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
511 LaTeXFeatures::isAvailable("xcolor");
513 if (!dvipost && !xcolorsoul) {
514 Alert::warning(_("Changes not shown in LaTeX output"),
515 _("Changes will not be highlighted in LaTeX output, "
516 "because neither dvipost nor xcolor/soul are installed.\n"
517 "Please install these packages or redefine "
518 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
519 } else if (!xcolorsoul) {
520 Alert::warning(_("Changes not shown in LaTeX output"),
521 _("Changes will not be highlighted in LaTeX output "
522 "when using pdflatex, because xcolor and soul are not installed.\n"
523 "Please install both packages or redefine "
524 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
528 bool const res = text().read(*this, lex, errorList);
529 for_each(text().paragraphs().begin(),
530 text().paragraphs().end(),
531 bind(&Paragraph::setInsetOwner, _1, &inset()));
537 // needed to insert the selection
538 void Buffer::insertStringAsLines(ParagraphList & pars,
539 pit_type & pit, pos_type & pos,
540 Font const & fn, docstring const & str, bool autobreakrows)
544 // insert the string, don't insert doublespace
545 bool space_inserted = true;
546 for (docstring::const_iterator cit = str.begin();
547 cit != str.end(); ++cit) {
548 Paragraph & par = pars[pit];
550 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
551 breakParagraph(params(), pars, pit, pos,
552 par.layout()->isEnvironment());
555 space_inserted = true;
559 // do not insert consecutive spaces if !free_spacing
560 } else if ((*cit == ' ' || *cit == '\t') &&
561 space_inserted && !par.isFreeSpacing()) {
563 } else if (*cit == '\t') {
564 if (!par.isFreeSpacing()) {
565 // tabs are like spaces here
566 par.insertChar(pos, ' ', font, params().trackChanges);
568 space_inserted = true;
570 const pos_type n = 8 - pos % 8;
571 for (pos_type i = 0; i < n; ++i) {
572 par.insertChar(pos, ' ', font, params().trackChanges);
575 space_inserted = true;
577 } else if (!isPrintable(*cit)) {
578 // Ignore unprintables
581 // just insert the character
582 par.insertChar(pos, *cit, font, params().trackChanges);
584 space_inserted = (*cit == ' ');
591 bool Buffer::readString(std::string const & s)
593 params().compressed = false;
595 // remove dummy empty par
596 paragraphs().clear();
598 std::istringstream is(s);
600 FileName const name(tempName());
601 switch (readFile(lex, name, true)) {
605 // We need to call lyx2lyx, so write the input to a file
606 std::ofstream os(name.toFilesystemEncoding().c_str());
609 return readFile(name);
619 bool Buffer::readFile(FileName const & filename)
621 // Check if the file is compressed.
622 string const format = getFormatFromContents(filename);
623 if (format == "gzip" || format == "zip" || format == "compress") {
624 params().compressed = true;
627 // remove dummy empty par
628 paragraphs().clear();
630 lex.setFile(filename);
631 if (readFile(lex, filename) != success)
638 bool Buffer::fully_loaded() const
640 return pimpl_->file_fully_loaded;
644 void Buffer::fully_loaded(bool const value)
646 pimpl_->file_fully_loaded = value;
650 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
653 BOOST_ASSERT(!filename.empty());
656 Alert::error(_("Document could not be read"),
657 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
662 string const token(lex.getString());
665 Alert::error(_("Document could not be read"),
666 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
670 // the first token _must_ be...
671 if (token != "\\lyxformat") {
672 lyxerr << "Token: " << token << endl;
674 Alert::error(_("Document format failure"),
675 bformat(_("%1$s is not a LyX document."),
676 from_utf8(filename.absFilename())));
681 string tmp_format = lex.getString();
682 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
683 // if present remove ".," from string.
684 string::size_type dot = tmp_format.find_first_of(".,");
685 //lyxerr << " dot found at " << dot << endl;
686 if (dot != string::npos)
687 tmp_format.erase(dot, 1);
688 int const file_format = convert<int>(tmp_format);
689 //lyxerr << "format: " << file_format << endl;
691 if (file_format != LYX_FORMAT) {
694 // lyx2lyx would fail
697 FileName const tmpfile(tempName());
698 if (tmpfile.empty()) {
699 Alert::error(_("Conversion failed"),
700 bformat(_("%1$s is from a different"
701 " version of LyX, but a temporary"
702 " file for converting it could"
704 from_utf8(filename.absFilename())));
707 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
708 if (lyx2lyx.empty()) {
709 Alert::error(_("Conversion script not found"),
710 bformat(_("%1$s is from a different"
711 " version of LyX, but the"
712 " conversion script lyx2lyx"
713 " could not be found."),
714 from_utf8(filename.absFilename())));
717 ostringstream command;
718 command << os::python()
719 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
720 << " -t " << convert<string>(LYX_FORMAT)
721 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
722 << ' ' << quoteName(filename.toFilesystemEncoding());
723 string const command_str = command.str();
725 LYXERR(Debug::INFO) << "Running '"
726 << command_str << '\''
729 cmd_ret const ret = runCommand(command_str);
730 if (ret.first != 0) {
731 Alert::error(_("Conversion script failed"),
732 bformat(_("%1$s is from a different version"
733 " of LyX, but the lyx2lyx script"
734 " failed to convert it."),
735 from_utf8(filename.absFilename())));
738 bool const ret = readFile(tmpfile);
739 // Do stuff with tmpfile name and buffer name here.
740 return ret ? success : failure;
745 if (readDocument(lex)) {
746 Alert::error(_("Document format failure"),
747 bformat(_("%1$s ended unexpectedly, which means"
748 " that it is probably corrupted."),
749 from_utf8(filename.absFilename())));
752 //lyxerr << "removing " << MacroTable::localMacros().size()
753 // << " temporary macro entries" << endl;
754 //MacroTable::localMacros().clear();
756 pimpl_->file_fully_loaded = true;
761 // Should probably be moved to somewhere else: BufferView? LyXView?
762 bool Buffer::save() const
764 // We don't need autosaves in the immediate future. (Asger)
765 resetAutosaveTimers();
767 string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
770 bool madeBackup = false;
772 // make a backup if the file already exists
773 if (lyxrc.make_backup && fs::exists(encodedFilename)) {
774 backupName = FileName(fileName() + '~');
775 if (!lyxrc.backupdir_path.empty())
776 backupName = FileName(addName(lyxrc.backupdir_path,
777 subst(os::internal_path(backupName.absFilename()), '/', '!')));
780 fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
782 } catch (fs::filesystem_error const & fe) {
783 Alert::error(_("Backup failure"),
784 bformat(_("Cannot create backup file %1$s.\n"
785 "Please check whether the directory exists and is writeable."),
786 from_utf8(backupName.absFilename())));
787 LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
791 if (writeFile(pimpl_->filename)) {
793 removeAutosaveFile(fileName());
796 // Saving failed, so backup is not backup
798 rename(backupName, pimpl_->filename);
804 bool Buffer::writeFile(FileName const & fname) const
806 if (pimpl_->read_only && fname == pimpl_->filename)
811 if (params().compressed) {
812 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
818 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
829 bool Buffer::write(ostream & ofs) const
832 // Use the standard "C" locale for file output.
833 ofs.imbue(std::locale::classic());
836 // The top of the file should not be written by params().
838 // write out a comment in the top of the file
839 ofs << "#LyX " << lyx_version
840 << " created this file. For more info see http://www.lyx.org/\n"
841 << "\\lyxformat " << LYX_FORMAT << "\n"
842 << "\\begin_document\n";
844 // now write out the buffer parameters.
845 ofs << "\\begin_header\n";
846 params().writeFile(ofs);
847 ofs << "\\end_header\n";
850 ofs << "\n\\begin_body\n";
851 text().write(*this, ofs);
852 ofs << "\n\\end_body\n";
854 // Write marker that shows file is complete
855 ofs << "\\end_document" << endl;
857 // Shouldn't really be needed....
860 // how to check if close went ok?
861 // Following is an attempt... (BE 20001011)
863 // good() returns false if any error occured, including some
865 // bad() returns true if something bad happened in the buffer,
866 // which should include file system full errors.
871 lyxerr << "File was not closed properly." << endl;
878 bool Buffer::makeLaTeXFile(FileName const & fname,
879 string const & original_path,
880 OutputParams const & runparams,
881 bool output_preamble, bool output_body)
883 string const encoding = runparams.encoding->iconvName();
884 LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
885 << encoding << "..." << endl;
887 odocfstream ofs(encoding);
888 if (!openFileWrite(ofs, fname))
892 writeLaTeXSource(ofs, original_path,
893 runparams, output_preamble, output_body);
895 catch (iconv_codecvt_facet_exception &) {
896 Alert::error(_("Encoding error"),
897 _("Some characters of your document are not "
898 "representable in the chosen encoding.\n"
899 "Changing the document encoding to utf8 could help."));
905 lyxerr << "File '" << fname << "' was not closed properly." << endl;
906 Alert::error(_("Error closing file"),
907 _("The output file could not be closed properly.\n"
908 " Probably some characters of your document are not "
909 "representable in the chosen encoding.\n"
910 "Changing the document encoding to utf8 could help."));
917 void Buffer::writeLaTeXSource(odocstream & os,
918 string const & original_path,
919 OutputParams const & runparams_in,
920 bool const output_preamble, bool const output_body)
922 OutputParams runparams = runparams_in;
924 // validate the buffer.
925 LYXERR(Debug::LATEX) << " Validating buffer..." << endl;
926 LaTeXFeatures features(*this, params(), runparams);
928 LYXERR(Debug::LATEX) << " Buffer validation done." << endl;
932 // The starting paragraph of the coming rows is the
933 // first paragraph of the document. (Asger)
934 texrow().start(paragraphs().begin()->id(), 0);
936 if (output_preamble && runparams.nice) {
937 os << "%% LyX " << lyx_version << " created this file. "
938 "For more info, see http://www.lyx.org/.\n"
939 "%% Do not edit unless you really know what "
944 LYXERR(Debug::INFO) << "lyx document header finished" << endl;
945 // There are a few differences between nice LaTeX and usual files:
946 // usual is \batchmode and has a
947 // special input@path to allow the including of figures
948 // with either \input or \includegraphics (what figinsets do).
949 // input@path is set when the actual parameter
950 // original_path is set. This is done for usual tex-file, but not
951 // for nice-latex-file. (Matthias 250696)
952 // Note that input@path is only needed for something the user does
953 // in the preamble, included .tex files or ERT, files included by
954 // LyX work without it.
955 if (output_preamble) {
956 if (!runparams.nice) {
957 // code for usual, NOT nice-latex-file
958 os << "\\batchmode\n"; // changed
962 if (!original_path.empty()) {
964 // We don't know the encoding of inputpath
965 docstring const inputpath = from_utf8(latex_path(original_path));
966 os << "\\makeatletter\n"
967 << "\\def\\input@path{{"
968 << inputpath << "/}}\n"
969 << "\\makeatother\n";
975 // Write the preamble
976 runparams.use_babel = params().writeLaTeX(os, features, texrow());
982 os << "\\begin{document}\n";
985 LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
987 if (!lyxrc.language_auto_begin &&
988 !params().language->babel().empty()) {
990 os << from_utf8(subst(lyxrc.language_command_begin,
992 params().language->babel()))
997 Encoding const & encoding = params().encoding();
998 if (encoding.package() == Encoding::CJK) {
999 // Open a CJK environment, since in contrast to the encodings
1000 // handled by inputenc the document encoding is not set in
1001 // the preamble if it is handled by CJK.sty.
1002 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1007 // if we are doing a real file with body, even if this is the
1008 // child of some other buffer, let's cut the link here.
1009 // This happens for example if only a child document is printed.
1010 string save_parentname;
1011 if (output_preamble) {
1012 save_parentname = params().parentname;
1013 params().parentname.erase();
1017 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1019 // Restore the parenthood if needed
1020 if (output_preamble)
1021 params().parentname = save_parentname;
1023 // add this just in case after all the paragraphs
1027 if (encoding.package() == Encoding::CJK) {
1028 // Close the open CJK environment.
1029 // latexParagraphs will have opened one even if the last text
1031 os << "\\end{CJK}\n";
1035 if (!lyxrc.language_auto_end &&
1036 !params().language->babel().empty()) {
1037 os << from_utf8(subst(lyxrc.language_command_end,
1039 params().language->babel()))
1044 if (output_preamble) {
1045 os << "\\end{document}\n";
1048 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1050 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1053 runparams_in.encoding = runparams.encoding;
1055 // Just to be sure. (Asger)
1058 LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1059 LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1064 bool Buffer::isLatex() const
1066 return params().getTextClass().outputType() == LATEX;
1070 bool Buffer::isLiterate() const
1072 return params().getTextClass().outputType() == LITERATE;
1076 bool Buffer::isDocBook() const
1078 return params().getTextClass().outputType() == DOCBOOK;
1082 void Buffer::makeDocBookFile(FileName const & fname,
1083 OutputParams const & runparams,
1084 bool const body_only)
1086 LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1090 if (!openFileWrite(ofs, fname))
1093 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1097 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1101 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1102 OutputParams const & runparams,
1103 bool const only_body)
1105 LaTeXFeatures features(*this, params(), runparams);
1110 TextClass const & tclass = params().getTextClass();
1111 string const top_element = tclass.latexname();
1114 if (runparams.flavor == OutputParams::XML)
1115 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1118 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1121 if (! tclass.class_header().empty())
1122 os << from_ascii(tclass.class_header());
1123 else if (runparams.flavor == OutputParams::XML)
1124 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1125 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1127 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1129 docstring preamble = from_utf8(params().preamble);
1130 if (runparams.flavor != OutputParams::XML ) {
1131 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1132 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1133 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1134 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1137 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1139 preamble += features.getIncludedFiles(name);
1140 preamble += features.getLyXSGMLEntities();
1142 if (!preamble.empty()) {
1143 os << "\n [ " << preamble << " ]";
1148 string top = top_element;
1150 if (runparams.flavor == OutputParams::XML)
1151 top += params().language->code();
1153 top += params().language->code().substr(0,2);
1156 if (!params().options.empty()) {
1158 top += params().options;
1161 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1162 << " file was created by LyX " << lyx_version
1163 << "\n See http://www.lyx.org/ for more information -->\n";
1165 params().getTextClass().counters().reset();
1167 sgml::openTag(os, top);
1169 docbookParagraphs(paragraphs(), *this, os, runparams);
1170 sgml::closeTag(os, top_element);
1174 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1175 // Other flags: -wall -v0 -x
1176 int Buffer::runChktex()
1180 // get LaTeX-Filename
1181 FileName const path(temppath());
1182 string const name = addName(path.absFilename(), getLatexName());
1183 string const org_path = filePath();
1185 support::Path p(path); // path to LaTeX file
1186 message(_("Running chktex..."));
1188 // Generate the LaTeX file if neccessary
1189 OutputParams runparams(¶ms().encoding());
1190 runparams.flavor = OutputParams::LATEX;
1191 runparams.nice = false;
1192 makeLaTeXFile(FileName(name), org_path, runparams);
1195 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1196 int const res = chktex.run(terr); // run chktex
1199 Alert::error(_("chktex failure"),
1200 _("Could not run chktex successfully."));
1201 } else if (res > 0) {
1202 ErrorList & errorList = errorLists_["ChkTeX"];
1203 // Clear out old errors
1205 // Fill-in the error list with the TeX errors
1206 bufferErrors(*this, terr, errorList);
1217 void Buffer::validate(LaTeXFeatures & features) const
1219 TextClass const & tclass = params().getTextClass();
1221 if (params().outputChanges) {
1222 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1223 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1224 LaTeXFeatures::isAvailable("xcolor");
1226 if (features.runparams().flavor == OutputParams::LATEX) {
1228 features.require("ct-dvipost");
1229 features.require("dvipost");
1230 } else if (xcolorsoul) {
1231 features.require("ct-xcolor-soul");
1232 features.require("soul");
1233 features.require("xcolor");
1235 features.require("ct-none");
1237 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1239 features.require("ct-xcolor-soul");
1240 features.require("soul");
1241 features.require("xcolor");
1242 features.require("pdfcolmk"); // improves color handling in PDF output
1244 features.require("ct-none");
1249 // AMS Style is at document level
1250 if (params().use_amsmath == BufferParams::package_on
1251 || tclass.provides("amsmath"))
1252 features.require("amsmath");
1253 if (params().use_esint == BufferParams::package_on)
1254 features.require("esint");
1256 for_each(paragraphs().begin(), paragraphs().end(),
1257 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1259 // the bullet shapes are buffer level not paragraph level
1260 // so they are tested here
1261 for (int i = 0; i < 4; ++i) {
1262 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1263 int const font = params().user_defined_bullet(i).getFont();
1265 int const c = params()
1266 .user_defined_bullet(i)
1273 features.require("latexsym");
1275 } else if (font == 1) {
1276 features.require("amssymb");
1277 } else if ((font >= 2 && font <= 5)) {
1278 features.require("pifont");
1283 if (lyxerr.debugging(Debug::LATEX)) {
1284 features.showStruct();
1289 void Buffer::getLabelList(vector<docstring> & list) const
1291 /// if this is a child document and the parent is already loaded
1292 /// Use the parent's list instead [ale990407]
1293 Buffer const * tmp = getMasterBuffer();
1295 lyxerr << "getMasterBuffer() failed!" << endl;
1299 tmp->getLabelList(list);
1303 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1304 it.nextInset()->getLabelList(*this, list);
1308 // This is also a buffer property (ale)
1309 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1312 /// if this is a child document and the parent is already loaded
1313 /// use the parent's list instead [ale990412]
1314 Buffer const * tmp = getMasterBuffer();
1317 tmp->fillWithBibKeys(keys);
1321 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1322 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1323 InsetBibtex const & inset =
1324 static_cast<InsetBibtex const &>(*it);
1325 inset.fillWithBibKeys(*this, keys);
1326 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1327 InsetInclude const & inset =
1328 static_cast<InsetInclude const &>(*it);
1329 inset.fillWithBibKeys(*this, keys);
1330 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1331 InsetBibitem const & inset =
1332 static_cast<InsetBibitem const &>(*it);
1334 string const key = to_utf8(inset.getParam("key"));
1335 docstring const label = inset.getParam("label");
1336 DocIterator doc_it(it); doc_it.forwardPos();
1337 docstring const ref = doc_it.paragraph().asString(*this, false);
1338 docstring const info = label + "TheBibliographyRef" + ref;
1339 keys.push_back(pair<string, docstring>(key, info));
1345 void Buffer::updateBibfilesCache()
1347 // if this is a child document and the parent is already loaded
1348 // update the parent's cache instead
1349 Buffer * tmp = getMasterBuffer();
1352 tmp->updateBibfilesCache();
1356 bibfilesCache_.clear();
1357 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1358 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1359 InsetBibtex const & inset =
1360 static_cast<InsetBibtex const &>(*it);
1361 vector<FileName> const bibfiles = inset.getFiles(*this);
1362 bibfilesCache_.insert(bibfilesCache_.end(),
1365 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1366 InsetInclude & inset =
1367 static_cast<InsetInclude &>(*it);
1368 inset.updateBibfilesCache(*this);
1369 vector<FileName> const & bibfiles =
1370 inset.getBibfilesCache(*this);
1371 bibfilesCache_.insert(bibfilesCache_.end(),
1379 vector<FileName> const & Buffer::getBibfilesCache() const
1381 // if this is a child document and the parent is already loaded
1382 // use the parent's cache instead
1383 Buffer const * tmp = getMasterBuffer();
1386 return tmp->getBibfilesCache();
1388 // We update the cache when first used instead of at loading time.
1389 if (bibfilesCache_.empty())
1390 const_cast<Buffer *>(this)->updateBibfilesCache();
1392 return bibfilesCache_;
1396 bool Buffer::isDepClean(string const & name) const
1398 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1399 if (it == pimpl_->dep_clean.end())
1405 void Buffer::markDepClean(string const & name)
1407 pimpl_->dep_clean[name] = true;
1411 bool Buffer::dispatch(string const & command, bool * result)
1413 return dispatch(lyxaction.lookupFunc(command), result);
1417 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1419 bool dispatched = true;
1421 switch (func.action) {
1422 case LFUN_BUFFER_EXPORT: {
1423 bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1436 void Buffer::changeLanguage(Language const * from, Language const * to)
1441 for_each(par_iterator_begin(),
1443 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1445 text().current_font.setLanguage(to);
1446 text().real_current_font.setLanguage(to);
1450 bool Buffer::isMultiLingual() const
1452 ParConstIterator end = par_iterator_end();
1453 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1454 if (it->isMultiLingual(params()))
1461 ParIterator Buffer::getParFromID(int const id) const
1463 ParConstIterator it = par_iterator_begin();
1464 ParConstIterator const end = par_iterator_end();
1467 // John says this is called with id == -1 from undo
1468 lyxerr << "getParFromID(), id: " << id << endl;
1472 for (; it != end; ++it)
1480 bool Buffer::hasParWithID(int const id) const
1482 ParConstIterator const it = getParFromID(id);
1483 return it != par_iterator_end();
1487 ParIterator Buffer::par_iterator_begin()
1489 return lyx::par_iterator_begin(inset());
1493 ParIterator Buffer::par_iterator_end()
1495 return lyx::par_iterator_end(inset());
1499 ParConstIterator Buffer::par_iterator_begin() const
1501 return lyx::par_const_iterator_begin(inset());
1505 ParConstIterator Buffer::par_iterator_end() const
1507 return lyx::par_const_iterator_end(inset());
1511 Language const * Buffer::getLanguage() const
1513 return params().language;
1517 docstring const Buffer::B_(string const & l10n) const
1519 return params().B_(l10n);
1523 bool Buffer::isClean() const
1525 return pimpl_->lyx_clean;
1529 bool Buffer::isBakClean() const
1531 return pimpl_->bak_clean;
1535 void Buffer::markClean() const
1537 if (!pimpl_->lyx_clean) {
1538 pimpl_->lyx_clean = true;
1541 // if the .lyx file has been saved, we don't need an
1543 pimpl_->bak_clean = true;
1547 void Buffer::markBakClean()
1549 pimpl_->bak_clean = true;
1553 void Buffer::setUnnamed(bool flag)
1555 pimpl_->unnamed = flag;
1559 bool Buffer::isUnnamed() const
1561 return pimpl_->unnamed;
1565 #ifdef WITH_WARNINGS
1566 #warning this function should be moved to buffer_pimpl.C
1568 void Buffer::markDirty()
1570 if (pimpl_->lyx_clean) {
1571 pimpl_->lyx_clean = false;
1574 pimpl_->bak_clean = false;
1576 DepClean::iterator it = pimpl_->dep_clean.begin();
1577 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1579 for (; it != end; ++it)
1584 string const Buffer::fileName() const
1586 return pimpl_->filename.absFilename();
1590 string const & Buffer::filePath() const
1592 return params().filepath;
1596 bool Buffer::isReadonly() const
1598 return pimpl_->read_only;
1602 void Buffer::setParentName(string const & name)
1604 params().parentname = name;
1608 Buffer const * Buffer::getMasterBuffer() const
1610 if (!params().parentname.empty()
1611 && theBufferList().exists(params().parentname)) {
1612 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1614 return buf->getMasterBuffer();
1621 Buffer * Buffer::getMasterBuffer()
1623 if (!params().parentname.empty()
1624 && theBufferList().exists(params().parentname)) {
1625 Buffer * buf = theBufferList().getBuffer(params().parentname);
1627 return buf->getMasterBuffer();
1634 MacroData const & Buffer::getMacro(docstring const & name) const
1636 return pimpl_->macros.get(name);
1640 bool Buffer::hasMacro(docstring const & name) const
1642 return pimpl_->macros.has(name);
1646 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1648 MacroTable::globalMacros().insert(name, data);
1649 pimpl_->macros.insert(name, data);
1653 void Buffer::buildMacros()
1655 // Start with global table.
1656 pimpl_->macros = MacroTable::globalMacros();
1659 ParagraphList const & pars = text().paragraphs();
1660 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1661 //lyxerr << "searching main par " << i
1662 // << " for macro definitions" << std::endl;
1663 InsetList const & insets = pars[i].insetlist;
1664 InsetList::const_iterator it = insets.begin();
1665 InsetList::const_iterator end = insets.end();
1666 for ( ; it != end; ++it) {
1667 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1668 if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1669 MathMacroTemplate const & mac
1670 = static_cast<MathMacroTemplate const &>(*it->inset);
1671 insertMacro(mac.name(), mac.asMacroData());
1678 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1685 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1688 //FIXME: This does not work for child documents yet.
1689 BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1690 // Check if the label 'from' appears more than once
1691 vector<docstring> labels;
1693 if (code == Inset::CITE_CODE) {
1694 vector<pair<string, docstring> > keys;
1695 fillWithBibKeys(keys);
1696 vector<pair<string, docstring> >::const_iterator bit = keys.begin();
1697 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1699 for (; bit != bend; ++bit)
1701 labels.push_back(from_utf8(bit->first));
1703 getLabelList(labels);
1705 if (lyx::count(labels.begin(), labels.end(), from) > 1)
1708 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1709 if (it->lyxCode() == code) {
1710 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1711 inset.replaceContents(to_utf8(from), to_utf8(to));
1717 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1718 pit_type par_end, bool full_source)
1720 OutputParams runparams(¶ms().encoding());
1721 runparams.nice = true;
1722 runparams.flavor = OutputParams::LATEX;
1723 runparams.linelen = lyxrc.plaintext_linelen;
1724 // No side effect of file copying and image conversion
1725 runparams.dryrun = true;
1728 os << "% Preview source code\n\n";
1730 writeLaTeXSource(os, filePath(), runparams, true, true);
1732 writeDocBookSource(os, fileName(), runparams, false);
1735 runparams.par_begin = par_begin;
1736 runparams.par_end = par_end;
1737 if (par_begin + 1 == par_end)
1738 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1740 os << "% Preview source code from paragraph " << par_begin
1741 << " to " << par_end - 1 << "\n\n";
1742 // output paragraphs
1745 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1748 docbookParagraphs(paragraphs(), *this, os, runparams);
1754 ErrorList const & Buffer::errorList(string const & type) const
1756 static ErrorList const emptyErrorList;
1757 std::map<string, ErrorList>::const_iterator I = errorLists_.find(type);
1758 if (I == errorLists_.end())
1759 return emptyErrorList;
1765 ErrorList & Buffer::errorList(string const & type)
1767 return errorLists_[type];