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
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
55 #include "TexStream.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
60 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/assert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
109 using namespace lyx::support;
113 namespace Alert = frontend::Alert;
114 namespace os = support::os;
118 int const LYX_FORMAT = 329;
120 typedef map<string, bool> DepClean;
121 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 Impl(Buffer & parent, FileName const & file, bool readonly);
141 mutable TexRow texrow;
142 Buffer const * parent_buffer;
144 /// need to regenerate .tex?
148 mutable bool lyx_clean;
150 /// is autosave needed?
151 mutable bool bak_clean;
153 /// is this a unnamed file (New...)?
159 /// name of the file the buffer is associated with.
162 /** Set to true only when the file is fully loaded.
163 * Used to prevent the premature generation of previews
164 * and by the citation inset.
166 bool file_fully_loaded;
169 mutable TocBackend toc_backend;
172 typedef pair<DocIterator, MacroData> ScopeMacro;
173 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
174 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
175 /// map from the macro name to the position map,
176 /// which maps the macro definition position to the scope and the MacroData.
177 NamePositionScopeMacroMap macros;
180 /// positions of child buffers in the buffer
181 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
182 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
183 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
184 /// position of children buffers in this buffer
185 BufferPositionMap children_positions;
186 /// map from children inclusion positions to their scope and their buffer
187 PositionScopeBufferMap position_to_children;
189 /// Container for all sort of Buffer dependant errors.
190 map<string, ErrorList> errorLists;
192 /// timestamp and checksum used to test if the file has been externally
193 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
195 unsigned long checksum_;
198 frontend::WorkAreaManager * wa_;
203 /// A cache for the bibfiles (including bibfiles of loaded child
204 /// documents), needed for appropriate update of natbib labels.
205 mutable support::FileNameList bibfilesCache_;
207 /// A cache for bibliography info
208 mutable BiblioInfo bibinfo_;
210 mutable RefCache ref_cache_;
212 /// our Text that should be wrapped in an InsetText
217 /// Creates the per buffer temporary directory
218 static FileName createBufferTmpDir()
221 // We are in our own directory. Why bother to mangle name?
222 // In fact I wrote this code to circumvent a problematic behaviour
223 // (bug?) of EMX mkstemp().
224 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
225 convert<string>(count++));
227 if (!tmpfl.createDirectory(0777)) {
228 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
229 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
230 from_utf8(tmpfl.absFilename())));
236 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
237 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
238 read_only(readonly_), filename(file), file_fully_loaded(false),
239 toc_backend(&parent), macro_lock(false), timestamp_(0),
240 checksum_(0), wa_(0), undo_(parent)
242 temppath = createBufferTmpDir();
243 lyxvc.setBuffer(&parent);
245 wa_ = new frontend::WorkAreaManager;
249 Buffer::Buffer(string const & file, bool readonly)
250 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
252 LYXERR(Debug::INFO, "Buffer::Buffer()");
254 d->inset.setBuffer(*this);
255 d->inset.initParagraphs(*this);
256 d->inset.setAutoBreakRows(true);
257 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
263 LYXERR(Debug::INFO, "Buffer::~Buffer()");
264 // here the buffer should take care that it is
265 // saved properly, before it goes into the void.
267 // GuiView already destroyed
270 // clear references to children in macro tables
271 d->children_positions.clear();
272 d->position_to_children.clear();
274 if (!d->temppath.destroyDirectory()) {
275 Alert::warning(_("Could not remove temporary directory"),
276 bformat(_("Could not remove the temporary directory %1$s"),
277 from_utf8(d->temppath.absFilename())));
280 // Remove any previewed LaTeX snippets associated with this buffer.
281 graphics::Previews::get().removeLoader(*this);
287 void Buffer::changed() const
294 frontend::WorkAreaManager & Buffer::workAreaManager() const
296 LASSERT(d->wa_, /**/);
301 Text & Buffer::text() const
303 return const_cast<Text &>(d->inset.text_);
307 Inset & Buffer::inset() const
309 return const_cast<InsetText &>(d->inset);
313 BufferParams & Buffer::params()
319 BufferParams const & Buffer::params() const
325 ParagraphList & Buffer::paragraphs()
327 return text().paragraphs();
331 ParagraphList const & Buffer::paragraphs() const
333 return text().paragraphs();
337 LyXVC & Buffer::lyxvc()
343 LyXVC const & Buffer::lyxvc() const
349 string const Buffer::temppath() const
351 return d->temppath.absFilename();
355 TexRow const & Buffer::texrow() const
361 TocBackend & Buffer::tocBackend() const
363 return d->toc_backend;
367 Undo & Buffer::undo()
373 string Buffer::latexName(bool const no_path) const
375 FileName latex_name = makeLatexName(d->filename);
376 return no_path ? latex_name.onlyFileName()
377 : latex_name.absFilename();
381 string Buffer::logName(LogType * type) const
383 string const filename = latexName(false);
385 if (filename.empty()) {
391 string const path = temppath();
393 FileName const fname(addName(temppath(),
394 onlyFilename(changeExtension(filename,
396 FileName const bname(
397 addName(path, onlyFilename(
398 changeExtension(filename,
399 formats.extension("literate") + ".out"))));
401 // If no Latex log or Build log is newer, show Build log
403 if (bname.exists() &&
404 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
405 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
408 return bname.absFilename();
410 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
413 return fname.absFilename();
417 void Buffer::setReadonly(bool const flag)
419 if (d->read_only != flag) {
426 void Buffer::setFileName(string const & newfile)
428 d->filename = makeAbsPath(newfile);
429 setReadonly(d->filename.isReadOnly());
434 int Buffer::readHeader(Lexer & lex)
436 int unknown_tokens = 0;
438 int begin_header_line = -1;
440 // Initialize parameters that may be/go lacking in header:
441 params().branchlist().clear();
442 params().preamble.erase();
443 params().options.erase();
444 params().master.erase();
445 params().float_placement.erase();
446 params().paperwidth.erase();
447 params().paperheight.erase();
448 params().leftmargin.erase();
449 params().rightmargin.erase();
450 params().topmargin.erase();
451 params().bottommargin.erase();
452 params().headheight.erase();
453 params().headsep.erase();
454 params().footskip.erase();
455 params().columnsep.erase();
456 params().listings_params.clear();
457 params().clearLayoutModules();
458 params().pdfoptions().clear();
460 for (int i = 0; i < 4; ++i) {
461 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
462 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
465 ErrorList & errorList = d->errorLists["Parse"];
474 if (token == "\\end_header")
478 if (token == "\\begin_header") {
479 begin_header_line = line;
483 LYXERR(Debug::PARSER, "Handling document header token: `"
486 string unknown = params().readToken(lex, token, d->filename.onlyPath());
487 if (!unknown.empty()) {
488 if (unknown[0] != '\\' && token == "\\textclass") {
489 Alert::warning(_("Unknown document class"),
490 bformat(_("Using the default document class, because the "
491 "class %1$s is unknown."), from_utf8(unknown)));
494 docstring const s = bformat(_("Unknown token: "
498 errorList.push_back(ErrorItem(_("Document header error"),
503 if (begin_header_line) {
504 docstring const s = _("\\begin_header is missing");
505 errorList.push_back(ErrorItem(_("Document header error"),
509 params().makeDocumentClass();
511 return unknown_tokens;
516 // changed to be public and have one parameter
517 // Returns false if "\end_document" is not read (Asger)
518 bool Buffer::readDocument(Lexer & lex)
520 ErrorList & errorList = d->errorLists["Parse"];
523 if (!lex.checkFor("\\begin_document")) {
524 docstring const s = _("\\begin_document is missing");
525 errorList.push_back(ErrorItem(_("Document header error"),
529 // we are reading in a brand new document
530 LASSERT(paragraphs().empty(), /**/);
534 if (params().outputChanges) {
535 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
536 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
537 LaTeXFeatures::isAvailable("xcolor");
539 if (!dvipost && !xcolorsoul) {
540 Alert::warning(_("Changes not shown in LaTeX output"),
541 _("Changes will not be highlighted in LaTeX output, "
542 "because neither dvipost nor xcolor/soul are installed.\n"
543 "Please install these packages or redefine "
544 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
545 } else if (!xcolorsoul) {
546 Alert::warning(_("Changes not shown in LaTeX output"),
547 _("Changes will not be highlighted in LaTeX output "
548 "when using pdflatex, because xcolor and soul are not installed.\n"
549 "Please install both packages or redefine "
550 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
554 if (!params().master.empty()) {
555 FileName const master_file = makeAbsPath(params().master,
556 onlyPath(absFileName()));
557 if (isLyXFilename(master_file.absFilename())) {
558 Buffer * master = checkAndLoadLyXFile(master_file);
559 d->parent_buffer = master;
564 bool const res = text().read(*this, lex, errorList, &(d->inset));
567 updateMacroInstances();
572 // needed to insert the selection
573 void Buffer::insertStringAsLines(ParagraphList & pars,
574 pit_type & pit, pos_type & pos,
575 Font const & fn, docstring const & str, bool autobreakrows)
579 // insert the string, don't insert doublespace
580 bool space_inserted = true;
581 for (docstring::const_iterator cit = str.begin();
582 cit != str.end(); ++cit) {
583 Paragraph & par = pars[pit];
585 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
586 breakParagraph(params(), pars, pit, pos,
587 par.layout().isEnvironment());
590 space_inserted = true;
594 // do not insert consecutive spaces if !free_spacing
595 } else if ((*cit == ' ' || *cit == '\t') &&
596 space_inserted && !par.isFreeSpacing()) {
598 } else if (*cit == '\t') {
599 if (!par.isFreeSpacing()) {
600 // tabs are like spaces here
601 par.insertChar(pos, ' ', font, params().trackChanges);
603 space_inserted = true;
605 const pos_type n = 8 - pos % 8;
606 for (pos_type i = 0; i < n; ++i) {
607 par.insertChar(pos, ' ', font, params().trackChanges);
610 space_inserted = true;
612 } else if (!isPrintable(*cit)) {
613 // Ignore unprintables
616 // just insert the character
617 par.insertChar(pos, *cit, font, params().trackChanges);
619 space_inserted = (*cit == ' ');
626 bool Buffer::readString(string const & s)
628 params().compressed = false;
630 // remove dummy empty par
631 paragraphs().clear();
635 FileName const name = FileName::tempName();
636 switch (readFile(lex, name, true)) {
640 // We need to call lyx2lyx, so write the input to a file
641 ofstream os(name.toFilesystemEncoding().c_str());
644 return readFile(name);
654 bool Buffer::readFile(FileName const & filename)
656 FileName fname(filename);
658 // remove dummy empty par
659 paragraphs().clear();
662 if (readFile(lex, fname) != success)
669 bool Buffer::isFullyLoaded() const
671 return d->file_fully_loaded;
675 void Buffer::setFullyLoaded(bool value)
677 d->file_fully_loaded = value;
681 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
684 LASSERT(!filename.empty(), /**/);
686 // the first (non-comment) token _must_ be...
687 if (!lex.checkFor("\\lyxformat")) {
688 Alert::error(_("Document format failure"),
689 bformat(_("%1$s is not a readable LyX document."),
690 from_utf8(filename.absFilename())));
696 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
697 // if present remove ".," from string.
698 size_t dot = tmp_format.find_first_of(".,");
699 //lyxerr << " dot found at " << dot << endl;
700 if (dot != string::npos)
701 tmp_format.erase(dot, 1);
702 int const file_format = convert<int>(tmp_format);
703 //lyxerr << "format: " << file_format << endl;
705 // save timestamp and checksum of the original disk file, making sure
706 // to not overwrite them with those of the file created in the tempdir
707 // when it has to be converted to the current format.
709 // Save the timestamp and checksum of disk file. If filename is an
710 // emergency file, save the timestamp and checksum of the original lyx file
711 // because isExternallyModified will check for this file. (BUG4193)
712 string diskfile = filename.absFilename();
713 if (suffixIs(diskfile, ".emergency"))
714 diskfile = diskfile.substr(0, diskfile.size() - 10);
715 saveCheckSum(FileName(diskfile));
718 if (file_format != LYX_FORMAT) {
721 // lyx2lyx would fail
724 FileName const tmpfile = FileName::tempName();
725 if (tmpfile.empty()) {
726 Alert::error(_("Conversion failed"),
727 bformat(_("%1$s is from a different"
728 " version of LyX, but a temporary"
729 " file for converting it could"
731 from_utf8(filename.absFilename())));
734 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
735 if (lyx2lyx.empty()) {
736 Alert::error(_("Conversion script not found"),
737 bformat(_("%1$s is from a different"
738 " version of LyX, but the"
739 " conversion script lyx2lyx"
740 " could not be found."),
741 from_utf8(filename.absFilename())));
744 ostringstream command;
745 command << os::python()
746 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
747 << " -t " << convert<string>(LYX_FORMAT)
748 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
749 << ' ' << quoteName(filename.toFilesystemEncoding());
750 string const command_str = command.str();
752 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
754 cmd_ret const ret = runCommand(command_str);
755 if (ret.first != 0) {
756 Alert::error(_("Conversion script failed"),
757 bformat(_("%1$s is from a different version"
758 " of LyX, but the lyx2lyx script"
759 " failed to convert it."),
760 from_utf8(filename.absFilename())));
763 bool const ret = readFile(tmpfile);
764 // Do stuff with tmpfile name and buffer name here.
765 return ret ? success : failure;
770 if (readDocument(lex)) {
771 Alert::error(_("Document format failure"),
772 bformat(_("%1$s ended unexpectedly, which means"
773 " that it is probably corrupted."),
774 from_utf8(filename.absFilename())));
777 d->file_fully_loaded = true;
782 // Should probably be moved to somewhere else: BufferView? LyXView?
783 bool Buffer::save() const
785 // We don't need autosaves in the immediate future. (Asger)
786 resetAutosaveTimers();
788 string const encodedFilename = d->filename.toFilesystemEncoding();
791 bool madeBackup = false;
793 // make a backup if the file already exists
794 if (lyxrc.make_backup && fileName().exists()) {
795 backupName = FileName(absFileName() + '~');
796 if (!lyxrc.backupdir_path.empty()) {
797 string const mangledName =
798 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
799 backupName = FileName(addName(lyxrc.backupdir_path,
802 if (fileName().copyTo(backupName)) {
805 Alert::error(_("Backup failure"),
806 bformat(_("Cannot create backup file %1$s.\n"
807 "Please check whether the directory exists and is writeable."),
808 from_utf8(backupName.absFilename())));
809 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
813 // ask if the disk file has been externally modified (use checksum method)
814 if (fileName().exists() && isExternallyModified(checksum_method)) {
815 docstring const file = makeDisplayPath(absFileName(), 20);
816 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
817 "you want to overwrite this file?"), file);
818 int const ret = Alert::prompt(_("Overwrite modified file?"),
819 text, 1, 1, _("&Overwrite"), _("&Cancel"));
824 if (writeFile(d->filename)) {
828 // Saving failed, so backup is not backup
830 backupName.moveTo(d->filename);
836 bool Buffer::writeFile(FileName const & fname) const
838 if (d->read_only && fname == d->filename)
843 docstring const str = bformat(_("Saving document %1$s..."),
844 makeDisplayPath(fname.absFilename()));
847 if (params().compressed) {
848 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
849 retval = ofs && write(ofs);
851 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
852 retval = ofs && write(ofs);
856 message(str + _(" could not write file!"));
860 removeAutosaveFile(d->filename.absFilename());
862 saveCheckSum(d->filename);
863 message(str + _(" done."));
869 bool Buffer::write(ostream & ofs) const
872 // Use the standard "C" locale for file output.
873 ofs.imbue(locale::classic());
876 // The top of the file should not be written by params().
878 // write out a comment in the top of the file
879 ofs << "#LyX " << lyx_version
880 << " created this file. For more info see http://www.lyx.org/\n"
881 << "\\lyxformat " << LYX_FORMAT << "\n"
882 << "\\begin_document\n";
884 /// For each author, set 'used' to true if there is a change
885 /// by this author in the document; otherwise set it to 'false'.
886 AuthorList::Authors::const_iterator a_it = params().authors().begin();
887 AuthorList::Authors::const_iterator a_end = params().authors().end();
888 for (; a_it != a_end; ++a_it)
889 a_it->second.setUsed(false);
891 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
892 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
893 for ( ; it != end; ++it)
894 it->checkAuthors(params().authors());
896 // now write out the buffer parameters.
897 ofs << "\\begin_header\n";
898 params().writeFile(ofs);
899 ofs << "\\end_header\n";
902 ofs << "\n\\begin_body\n";
903 text().write(*this, ofs);
904 ofs << "\n\\end_body\n";
906 // Write marker that shows file is complete
907 ofs << "\\end_document" << endl;
909 // Shouldn't really be needed....
912 // how to check if close went ok?
913 // Following is an attempt... (BE 20001011)
915 // good() returns false if any error occured, including some
917 // bad() returns true if something bad happened in the buffer,
918 // which should include file system full errors.
923 lyxerr << "File was not closed properly." << endl;
930 bool Buffer::makeLaTeXFile(FileName const & fname,
931 string const & original_path,
932 OutputParams const & runparams,
933 bool output_preamble, bool output_body) const
935 string const encoding = runparams.encoding->iconvName();
936 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
939 try { ofs.reset(encoding); }
940 catch (iconv_codecvt_facet_exception & e) {
941 lyxerr << "Caught iconv exception: " << e.what() << endl;
942 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
943 "verify that the support software for your encoding (%1$s) is "
944 "properly installed"), from_ascii(encoding)));
947 if (!openFileWrite(ofs, fname))
950 //TexStream ts(ofs.rdbuf(), &texrow());
951 ErrorList & errorList = d->errorLists["Export"];
953 bool failed_export = false;
956 writeLaTeXSource(ofs, original_path,
957 runparams, output_preamble, output_body);
959 catch (EncodingException & e) {
960 odocstringstream ods;
961 ods.put(e.failed_char);
963 oss << "0x" << hex << e.failed_char << dec;
964 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
965 " (code point %2$s)"),
966 ods.str(), from_utf8(oss.str()));
967 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
968 "representable in the chosen encoding.\n"
969 "Changing the document encoding to utf8 could help."),
970 e.par_id, e.pos, e.pos + 1));
971 failed_export = true;
973 catch (iconv_codecvt_facet_exception & e) {
974 errorList.push_back(ErrorItem(_("iconv conversion failed"),
975 _(e.what()), -1, 0, 0));
976 failed_export = true;
978 catch (exception const & e) {
979 errorList.push_back(ErrorItem(_("conversion failed"),
980 _(e.what()), -1, 0, 0));
981 failed_export = true;
984 lyxerr << "Caught some really weird exception..." << endl;
990 failed_export = true;
991 lyxerr << "File '" << fname << "' was not closed properly." << endl;
995 return !failed_export;
999 void Buffer::writeLaTeXSource(odocstream & os,
1000 string const & original_path,
1001 OutputParams const & runparams_in,
1002 bool const output_preamble, bool const output_body) const
1004 // The child documents, if any, shall be already loaded at this point.
1006 OutputParams runparams = runparams_in;
1008 // validate the buffer.
1009 LYXERR(Debug::LATEX, " Validating buffer...");
1010 LaTeXFeatures features(*this, params(), runparams);
1012 LYXERR(Debug::LATEX, " Buffer validation done.");
1014 // The starting paragraph of the coming rows is the
1015 // first paragraph of the document. (Asger)
1016 if (output_preamble && runparams.nice) {
1017 os << "%% LyX " << lyx_version << " created this file. "
1018 "For more info, see http://www.lyx.org/.\n"
1019 "%% Do not edit unless you really know what "
1021 d->texrow.newline();
1022 d->texrow.newline();
1024 LYXERR(Debug::INFO, "lyx document header finished");
1026 // Don't move this behind the parent_buffer=0 code below,
1027 // because then the macros will not get the right "redefinition"
1028 // flag as they don't see the parent macros which are output before.
1031 // fold macros if possible, still with parent buffer as the
1032 // macros will be put in the prefix anyway.
1033 updateMacroInstances();
1035 // There are a few differences between nice LaTeX and usual files:
1036 // usual is \batchmode and has a
1037 // special input@path to allow the including of figures
1038 // with either \input or \includegraphics (what figinsets do).
1039 // input@path is set when the actual parameter
1040 // original_path is set. This is done for usual tex-file, but not
1041 // for nice-latex-file. (Matthias 250696)
1042 // Note that input@path is only needed for something the user does
1043 // in the preamble, included .tex files or ERT, files included by
1044 // LyX work without it.
1045 if (output_preamble) {
1046 if (!runparams.nice) {
1047 // code for usual, NOT nice-latex-file
1048 os << "\\batchmode\n"; // changed
1049 // from \nonstopmode
1050 d->texrow.newline();
1052 if (!original_path.empty()) {
1054 // We don't know the encoding of inputpath
1055 docstring const inputpath = from_utf8(latex_path(original_path));
1056 os << "\\makeatletter\n"
1057 << "\\def\\input@path{{"
1058 << inputpath << "/}}\n"
1059 << "\\makeatother\n";
1060 d->texrow.newline();
1061 d->texrow.newline();
1062 d->texrow.newline();
1065 // get parent macros (if this buffer has a parent) which will be
1066 // written at the document begin further down.
1067 MacroSet parentMacros;
1068 listParentMacros(parentMacros, features);
1070 // Write the preamble
1071 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1077 os << "\\begin{document}\n";
1078 d->texrow.newline();
1080 // output the parent macros
1081 MacroSet::iterator it = parentMacros.begin();
1082 MacroSet::iterator end = parentMacros.end();
1083 for (; it != end; ++it)
1084 (*it)->write(os, true);
1085 } // output_preamble
1087 d->texrow.start(paragraphs().begin()->id(), 0);
1089 LYXERR(Debug::INFO, "preamble finished, now the body.");
1091 // if we are doing a real file with body, even if this is the
1092 // child of some other buffer, let's cut the link here.
1093 // This happens for example if only a child document is printed.
1094 Buffer const * save_parent = 0;
1095 if (output_preamble) {
1096 save_parent = d->parent_buffer;
1097 d->parent_buffer = 0;
1101 latexParagraphs(*this, text(), os, d->texrow, runparams);
1103 // Restore the parenthood if needed
1104 if (output_preamble)
1105 d->parent_buffer = save_parent;
1107 // add this just in case after all the paragraphs
1109 d->texrow.newline();
1111 if (output_preamble) {
1112 os << "\\end{document}\n";
1113 d->texrow.newline();
1114 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1116 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1118 runparams_in.encoding = runparams.encoding;
1120 // Just to be sure. (Asger)
1121 d->texrow.newline();
1123 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1124 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1128 bool Buffer::isLatex() const
1130 return params().documentClass().outputType() == LATEX;
1134 bool Buffer::isLiterate() const
1136 return params().documentClass().outputType() == LITERATE;
1140 bool Buffer::isDocBook() const
1142 return params().documentClass().outputType() == DOCBOOK;
1146 void Buffer::makeDocBookFile(FileName const & fname,
1147 OutputParams const & runparams,
1148 bool const body_only) const
1150 LYXERR(Debug::LATEX, "makeDocBookFile...");
1153 if (!openFileWrite(ofs, fname))
1156 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1160 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1164 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1165 OutputParams const & runparams,
1166 bool const only_body) const
1168 LaTeXFeatures features(*this, params(), runparams);
1173 DocumentClass const & tclass = params().documentClass();
1174 string const top_element = tclass.latexname();
1177 if (runparams.flavor == OutputParams::XML)
1178 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1181 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1184 if (! tclass.class_header().empty())
1185 os << from_ascii(tclass.class_header());
1186 else if (runparams.flavor == OutputParams::XML)
1187 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1188 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1190 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1192 docstring preamble = from_utf8(params().preamble);
1193 if (runparams.flavor != OutputParams::XML ) {
1194 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1195 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1196 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1197 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1200 string const name = runparams.nice
1201 ? changeExtension(absFileName(), ".sgml") : fname;
1202 preamble += features.getIncludedFiles(name);
1203 preamble += features.getLyXSGMLEntities();
1205 if (!preamble.empty()) {
1206 os << "\n [ " << preamble << " ]";
1211 string top = top_element;
1213 if (runparams.flavor == OutputParams::XML)
1214 top += params().language->code();
1216 top += params().language->code().substr(0,2);
1219 if (!params().options.empty()) {
1221 top += params().options;
1224 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1225 << " file was created by LyX " << lyx_version
1226 << "\n See http://www.lyx.org/ for more information -->\n";
1228 params().documentClass().counters().reset();
1232 sgml::openTag(os, top);
1234 docbookParagraphs(paragraphs(), *this, os, runparams);
1235 sgml::closeTag(os, top_element);
1239 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1240 // Other flags: -wall -v0 -x
1241 int Buffer::runChktex()
1245 // get LaTeX-Filename
1246 FileName const path(temppath());
1247 string const name = addName(path.absFilename(), latexName());
1248 string const org_path = filePath();
1250 PathChanger p(path); // path to LaTeX file
1251 message(_("Running chktex..."));
1253 // Generate the LaTeX file if neccessary
1254 OutputParams runparams(¶ms().encoding());
1255 runparams.flavor = OutputParams::LATEX;
1256 runparams.nice = false;
1257 makeLaTeXFile(FileName(name), org_path, runparams);
1260 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1261 int const res = chktex.run(terr); // run chktex
1264 Alert::error(_("chktex failure"),
1265 _("Could not run chktex successfully."));
1266 } else if (res > 0) {
1267 ErrorList & errlist = d->errorLists["ChkTeX"];
1269 bufferErrors(terr, errlist);
1280 void Buffer::validate(LaTeXFeatures & features) const
1282 params().validate(features);
1286 for_each(paragraphs().begin(), paragraphs().end(),
1287 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1289 if (lyxerr.debugging(Debug::LATEX)) {
1290 features.showStruct();
1295 void Buffer::getLabelList(vector<docstring> & list) const
1297 // If this is a child document, use the parent's list instead.
1298 if (d->parent_buffer) {
1299 d->parent_buffer->getLabelList(list);
1304 Toc & toc = d->toc_backend.toc("label");
1305 TocIterator toc_it = toc.begin();
1306 TocIterator end = toc.end();
1307 for (; toc_it != end; ++toc_it) {
1308 if (toc_it->depth() == 0)
1309 list.push_back(toc_it->str());
1314 void Buffer::updateBibfilesCache() const
1316 // If this is a child document, use the parent's cache instead.
1317 if (d->parent_buffer) {
1318 d->parent_buffer->updateBibfilesCache();
1322 d->bibfilesCache_.clear();
1323 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1324 if (it->lyxCode() == BIBTEX_CODE) {
1325 InsetBibtex const & inset =
1326 static_cast<InsetBibtex const &>(*it);
1327 support::FileNameList const bibfiles = inset.getBibFiles();
1328 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1331 } else if (it->lyxCode() == INCLUDE_CODE) {
1332 InsetInclude & inset =
1333 static_cast<InsetInclude &>(*it);
1334 inset.updateBibfilesCache();
1335 support::FileNameList const & bibfiles =
1336 inset.getBibfilesCache(*this);
1337 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1345 support::FileNameList const & Buffer::getBibfilesCache() const
1347 // If this is a child document, use the parent's cache instead.
1348 if (d->parent_buffer)
1349 return d->parent_buffer->getBibfilesCache();
1351 // We update the cache when first used instead of at loading time.
1352 if (d->bibfilesCache_.empty())
1353 const_cast<Buffer *>(this)->updateBibfilesCache();
1355 return d->bibfilesCache_;
1359 BiblioInfo const & Buffer::masterBibInfo() const
1361 // if this is a child document and the parent is already loaded
1362 // use the parent's list instead [ale990412]
1363 Buffer const * const tmp = masterBuffer();
1366 return tmp->masterBibInfo();
1367 return localBibInfo();
1371 BiblioInfo const & Buffer::localBibInfo() const
1373 // cache the timestamp of the bibliography files.
1374 static map<FileName, time_t> bibfileStatus;
1376 support::FileNameList const & bibfilesCache = getBibfilesCache();
1377 // compare the cached timestamps with the actual ones.
1378 bool changed = false;
1379 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1380 support::FileNameList::const_iterator en = bibfilesCache.end();
1381 for (; ei != en; ++ ei) {
1382 time_t lastw = ei->lastModified();
1383 if (lastw != bibfileStatus[*ei]) {
1385 bibfileStatus[*ei] = lastw;
1391 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1392 it->fillWithBibKeys(d->bibinfo_, it);
1398 bool Buffer::isDepClean(string const & name) const
1400 DepClean::const_iterator const it = d->dep_clean.find(name);
1401 if (it == d->dep_clean.end())
1407 void Buffer::markDepClean(string const & name)
1409 d->dep_clean[name] = true;
1413 bool Buffer::dispatch(string const & command, bool * result)
1415 return dispatch(lyxaction.lookupFunc(command), result);
1419 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1421 bool dispatched = true;
1423 switch (func.action) {
1424 case LFUN_BUFFER_EXPORT: {
1425 bool const tmp = doExport(to_utf8(func.argument()), false);
1438 void Buffer::changeLanguage(Language const * from, Language const * to)
1440 LASSERT(from, /**/);
1443 for_each(par_iterator_begin(),
1445 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1449 bool Buffer::isMultiLingual() const
1451 ParConstIterator end = par_iterator_end();
1452 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1453 if (it->isMultiLingual(params()))
1460 DocIterator Buffer::getParFromID(int const id) const
1463 // John says this is called with id == -1 from undo
1464 lyxerr << "getParFromID(), id: " << id << endl;
1465 return doc_iterator_end(inset());
1468 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1469 if (it.paragraph().id() == id)
1472 return doc_iterator_end(inset());
1476 bool Buffer::hasParWithID(int const id) const
1478 return !getParFromID(id).atEnd();
1482 ParIterator Buffer::par_iterator_begin()
1484 return ParIterator(doc_iterator_begin(inset()));
1488 ParIterator Buffer::par_iterator_end()
1490 return ParIterator(doc_iterator_end(inset()));
1494 ParConstIterator Buffer::par_iterator_begin() const
1496 return lyx::par_const_iterator_begin(inset());
1500 ParConstIterator Buffer::par_iterator_end() const
1502 return lyx::par_const_iterator_end(inset());
1506 Language const * Buffer::language() const
1508 return params().language;
1512 docstring const Buffer::B_(string const & l10n) const
1514 return params().B_(l10n);
1518 bool Buffer::isClean() const
1520 return d->lyx_clean;
1524 bool Buffer::isBakClean() const
1526 return d->bak_clean;
1530 bool Buffer::isExternallyModified(CheckMethod method) const
1532 LASSERT(d->filename.exists(), /**/);
1533 // if method == timestamp, check timestamp before checksum
1534 return (method == checksum_method
1535 || d->timestamp_ != d->filename.lastModified())
1536 && d->checksum_ != d->filename.checksum();
1540 void Buffer::saveCheckSum(FileName const & file) const
1542 if (file.exists()) {
1543 d->timestamp_ = file.lastModified();
1544 d->checksum_ = file.checksum();
1546 // in the case of save to a new file.
1553 void Buffer::markClean() const
1555 if (!d->lyx_clean) {
1556 d->lyx_clean = true;
1559 // if the .lyx file has been saved, we don't need an
1561 d->bak_clean = true;
1565 void Buffer::markBakClean() const
1567 d->bak_clean = true;
1571 void Buffer::setUnnamed(bool flag)
1577 bool Buffer::isUnnamed() const
1583 // FIXME: this function should be moved to buffer_pimpl.C
1584 void Buffer::markDirty()
1587 d->lyx_clean = false;
1590 d->bak_clean = false;
1592 DepClean::iterator it = d->dep_clean.begin();
1593 DepClean::const_iterator const end = d->dep_clean.end();
1595 for (; it != end; ++it)
1600 FileName Buffer::fileName() const
1606 string Buffer::absFileName() const
1608 return d->filename.absFilename();
1612 string Buffer::filePath() const
1614 return d->filename.onlyPath().absFilename() + "/";
1618 bool Buffer::isReadonly() const
1620 return d->read_only;
1624 void Buffer::setParent(Buffer const * buffer)
1626 // Avoids recursive include.
1627 d->parent_buffer = buffer == this ? 0 : buffer;
1632 Buffer const * Buffer::parent()
1634 return d->parent_buffer;
1638 Buffer const * Buffer::masterBuffer() const
1640 if (!d->parent_buffer)
1643 return d->parent_buffer->masterBuffer();
1647 template<typename M>
1648 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1653 typename M::iterator it = m.lower_bound(x);
1654 if (it == m.begin())
1662 MacroData const * Buffer::getBufferMacro(docstring const & name,
1663 DocIterator const & pos) const
1665 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1667 // if paragraphs have no macro context set, pos will be empty
1671 // we haven't found anything yet
1672 DocIterator bestPos = par_iterator_begin();
1673 MacroData const * bestData = 0;
1675 // find macro definitions for name
1676 Impl::NamePositionScopeMacroMap::iterator nameIt
1677 = d->macros.find(name);
1678 if (nameIt != d->macros.end()) {
1679 // find last definition in front of pos or at pos itself
1680 Impl::PositionScopeMacroMap::const_iterator it
1681 = greatest_below(nameIt->second, pos);
1682 if (it != nameIt->second.end()) {
1684 // scope ends behind pos?
1685 if (pos < it->second.first) {
1686 // Looks good, remember this. If there
1687 // is no external macro behind this,
1688 // we found the right one already.
1689 bestPos = it->first;
1690 bestData = &it->second.second;
1694 // try previous macro if there is one
1695 if (it == nameIt->second.begin())
1702 // find macros in included files
1703 Impl::PositionScopeBufferMap::const_iterator it
1704 = greatest_below(d->position_to_children, pos);
1705 if (it == d->position_to_children.end())
1706 // no children before
1710 // do we know something better (i.e. later) already?
1711 if (it->first < bestPos )
1714 // scope ends behind pos?
1715 if (pos < it->second.first) {
1716 // look for macro in external file
1717 d->macro_lock = true;
1718 MacroData const * data
1719 = it->second.second->getMacro(name, false);
1720 d->macro_lock = false;
1722 bestPos = it->first;
1728 // try previous file if there is one
1729 if (it == d->position_to_children.begin())
1734 // return the best macro we have found
1739 MacroData const * Buffer::getMacro(docstring const & name,
1740 DocIterator const & pos, bool global) const
1745 // query buffer macros
1746 MacroData const * data = getBufferMacro(name, pos);
1750 // If there is a master buffer, query that
1751 if (d->parent_buffer) {
1752 d->macro_lock = true;
1753 MacroData const * macro = d->parent_buffer->getMacro(
1754 name, *this, false);
1755 d->macro_lock = false;
1761 data = MacroTable::globalMacros().get(name);
1770 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1772 // set scope end behind the last paragraph
1773 DocIterator scope = par_iterator_begin();
1774 scope.pit() = scope.lastpit() + 1;
1776 return getMacro(name, scope, global);
1780 MacroData const * Buffer::getMacro(docstring const & name,
1781 Buffer const & child, bool global) const
1783 // look where the child buffer is included first
1784 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1785 if (it == d->children_positions.end())
1788 // check for macros at the inclusion position
1789 return getMacro(name, it->second, global);
1793 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1795 pit_type lastpit = it.lastpit();
1797 // look for macros in each paragraph
1798 while (it.pit() <= lastpit) {
1799 Paragraph & par = it.paragraph();
1801 // iterate over the insets of the current paragraph
1802 InsetList const & insets = par.insetList();
1803 InsetList::const_iterator iit = insets.begin();
1804 InsetList::const_iterator end = insets.end();
1805 for (; iit != end; ++iit) {
1806 it.pos() = iit->pos;
1808 // is it a nested text inset?
1809 if (iit->inset->asInsetText()) {
1810 // Inset needs its own scope?
1811 InsetText const * itext
1812 = iit->inset->asInsetText();
1813 bool newScope = itext->isMacroScope();
1815 // scope which ends just behind the inset
1816 DocIterator insetScope = it;
1819 // collect macros in inset
1820 it.push_back(CursorSlice(*iit->inset));
1821 updateMacros(it, newScope ? insetScope : scope);
1826 // is it an external file?
1827 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1828 // get buffer of external file
1829 InsetCommand const & inset
1830 = static_cast<InsetCommand const &>(*iit->inset);
1831 InsetCommandParams const & ip = inset.params();
1832 d->macro_lock = true;
1833 Buffer * child = loadIfNeeded(*this, ip);
1834 d->macro_lock = false;
1838 // register its position, but only when it is
1839 // included first in the buffer
1840 if (d->children_positions.find(child)
1841 == d->children_positions.end())
1842 d->children_positions[child] = it;
1844 // register child with its scope
1845 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1849 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1853 MathMacroTemplate & macroTemplate
1854 = static_cast<MathMacroTemplate &>(*iit->inset);
1855 MacroContext mc(*this, it);
1856 macroTemplate.updateToContext(mc);
1859 bool valid = macroTemplate.validMacro();
1860 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1861 // then the BufferView's cursor will be invalid in
1862 // some cases which leads to crashes.
1867 d->macros[macroTemplate.name()][it] =
1868 Impl::ScopeMacro(scope, MacroData(*this, it));
1878 void Buffer::updateMacros() const
1883 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1885 // start with empty table
1887 d->children_positions.clear();
1888 d->position_to_children.clear();
1890 // Iterate over buffer, starting with first paragraph
1891 // The scope must be bigger than any lookup DocIterator
1892 // later. For the global lookup, lastpit+1 is used, hence
1893 // we use lastpit+2 here.
1894 DocIterator it = par_iterator_begin();
1895 DocIterator outerScope = it;
1896 outerScope.pit() = outerScope.lastpit() + 2;
1897 updateMacros(it, outerScope);
1901 void Buffer::updateMacroInstances() const
1903 LYXERR(Debug::MACROS, "updateMacroInstances for "
1904 << d->filename.onlyFileName());
1905 DocIterator it = doc_iterator_begin(inset());
1906 DocIterator end = doc_iterator_end(inset());
1907 for (; it != end; it.forwardPos()) {
1908 // look for MathData cells in InsetMathNest insets
1909 Inset * inset = it.nextInset();
1913 InsetMath * minset = inset->asInsetMath();
1917 // update macro in all cells of the InsetMathNest
1918 DocIterator::idx_type n = minset->nargs();
1919 MacroContext mc = MacroContext(*this, it);
1920 for (DocIterator::idx_type i = 0; i < n; ++i) {
1921 MathData & data = minset->cell(i);
1922 data.updateMacros(0, mc);
1928 void Buffer::listMacroNames(MacroNameSet & macros) const
1933 d->macro_lock = true;
1935 // loop over macro names
1936 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1937 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1938 for (; nameIt != nameEnd; ++nameIt)
1939 macros.insert(nameIt->first);
1941 // loop over children
1942 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1943 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1944 for (; it != end; ++it)
1945 it->first->listMacroNames(macros);
1948 if (d->parent_buffer)
1949 d->parent_buffer->listMacroNames(macros);
1951 d->macro_lock = false;
1955 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1957 if (!d->parent_buffer)
1961 d->parent_buffer->listMacroNames(names);
1964 MacroNameSet::iterator it = names.begin();
1965 MacroNameSet::iterator end = names.end();
1966 for (; it != end; ++it) {
1968 MacroData const * data =
1969 d->parent_buffer->getMacro(*it, *this, false);
1971 macros.insert(data);
1973 // we cannot access the original MathMacroTemplate anymore
1974 // here to calls validate method. So we do its work here manually.
1975 // FIXME: somehow make the template accessible here.
1976 if (data->optionals() > 0)
1977 features.require("xargs");
1983 Buffer::References & Buffer::references(docstring const & label)
1985 if (d->parent_buffer)
1986 return const_cast<Buffer *>(masterBuffer())->references(label);
1988 RefCache::iterator it = d->ref_cache_.find(label);
1989 if (it != d->ref_cache_.end())
1990 return it->second.second;
1992 static InsetLabel const * dummy_il = 0;
1993 static References const dummy_refs;
1994 it = d->ref_cache_.insert(
1995 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
1996 return it->second.second;
2000 Buffer::References const & Buffer::references(docstring const & label) const
2002 return const_cast<Buffer *>(this)->references(label);
2006 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2008 masterBuffer()->d->ref_cache_[label].first = il;
2012 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2014 return masterBuffer()->d->ref_cache_[label].first;
2018 void Buffer::clearReferenceCache() const
2020 if (!d->parent_buffer)
2021 d->ref_cache_.clear();
2025 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2028 //FIXME: This does not work for child documents yet.
2029 LASSERT(code == CITE_CODE, /**/);
2030 // Check if the label 'from' appears more than once
2031 vector<docstring> labels;
2033 BiblioInfo const & keys = masterBibInfo();
2034 BiblioInfo::const_iterator bit = keys.begin();
2035 BiblioInfo::const_iterator bend = keys.end();
2037 for (; bit != bend; ++bit)
2039 labels.push_back(bit->first);
2042 if (count(labels.begin(), labels.end(), from) > 1)
2045 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2046 if (it->lyxCode() == code) {
2047 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2048 docstring const oldValue = inset.getParam(paramName);
2049 if (oldValue == from)
2050 inset.setParam(paramName, to);
2056 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2057 pit_type par_end, bool full_source)
2059 OutputParams runparams(¶ms().encoding());
2060 runparams.nice = true;
2061 runparams.flavor = OutputParams::LATEX;
2062 runparams.linelen = lyxrc.plaintext_linelen;
2063 // No side effect of file copying and image conversion
2064 runparams.dryrun = true;
2068 os << "% " << _("Preview source code") << "\n\n";
2069 d->texrow.newline();
2070 d->texrow.newline();
2072 writeLaTeXSource(os, filePath(), runparams, true, true);
2074 writeDocBookSource(os, absFileName(), runparams, false);
2076 runparams.par_begin = par_begin;
2077 runparams.par_end = par_end;
2078 if (par_begin + 1 == par_end) {
2080 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2084 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2085 convert<docstring>(par_begin),
2086 convert<docstring>(par_end - 1))
2089 d->texrow.newline();
2090 d->texrow.newline();
2091 // output paragraphs
2093 latexParagraphs(*this, text(), os, d->texrow, runparams);
2096 docbookParagraphs(paragraphs(), *this, os, runparams);
2101 ErrorList & Buffer::errorList(string const & type) const
2103 static ErrorList emptyErrorList;
2104 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2105 if (I == d->errorLists.end())
2106 return emptyErrorList;
2112 void Buffer::structureChanged() const
2115 gui_->structureChanged();
2119 void Buffer::errors(string const & err) const
2126 void Buffer::message(docstring const & msg) const
2133 void Buffer::setBusy(bool on) const
2140 void Buffer::setReadOnly(bool on) const
2143 d->wa_->setReadOnly(on);
2147 void Buffer::updateTitles() const
2150 d->wa_->updateTitles();
2154 void Buffer::resetAutosaveTimers() const
2157 gui_->resetAutosaveTimers();
2161 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2170 class AutoSaveBuffer : public ForkedProcess {
2173 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2174 : buffer_(buffer), fname_(fname) {}
2176 virtual boost::shared_ptr<ForkedProcess> clone() const
2178 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2183 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2184 from_utf8(fname_.absFilename())));
2185 return run(DontWait);
2189 virtual int generateChild();
2191 Buffer const & buffer_;
2196 int AutoSaveBuffer::generateChild()
2198 // tmp_ret will be located (usually) in /tmp
2199 // will that be a problem?
2200 // Note that this calls ForkedCalls::fork(), so it's
2201 // ok cross-platform.
2202 pid_t const pid = fork();
2203 // If you want to debug the autosave
2204 // you should set pid to -1, and comment out the fork.
2205 if (pid != 0 && pid != -1)
2208 // pid = -1 signifies that lyx was unable
2209 // to fork. But we will do the save
2211 bool failed = false;
2212 FileName const tmp_ret = FileName::tempName("lyxauto");
2213 if (!tmp_ret.empty()) {
2214 buffer_.writeFile(tmp_ret);
2215 // assume successful write of tmp_ret
2216 if (!tmp_ret.moveTo(fname_))
2222 // failed to write/rename tmp_ret so try writing direct
2223 if (!buffer_.writeFile(fname_)) {
2224 // It is dangerous to do this in the child,
2225 // but safe in the parent, so...
2226 if (pid == -1) // emit message signal.
2227 buffer_.message(_("Autosave failed!"));
2231 if (pid == 0) // we are the child so...
2240 // Perfect target for a thread...
2241 void Buffer::autoSave() const
2243 if (isBakClean() || isReadonly()) {
2244 // We don't save now, but we'll try again later
2245 resetAutosaveTimers();
2249 // emit message signal.
2250 message(_("Autosaving current document..."));
2252 // create autosave filename
2253 string fname = filePath();
2255 fname += d->filename.onlyFileName();
2258 AutoSaveBuffer autosave(*this, FileName(fname));
2262 resetAutosaveTimers();
2266 string Buffer::bufferFormat() const
2276 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2277 string & result_file) const
2279 string backend_format;
2280 OutputParams runparams(¶ms().encoding());
2281 runparams.flavor = OutputParams::LATEX;
2282 runparams.linelen = lyxrc.plaintext_linelen;
2283 vector<string> backs = backends();
2284 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2285 // Get shortest path to format
2286 Graph::EdgePath path;
2287 for (vector<string>::const_iterator it = backs.begin();
2288 it != backs.end(); ++it) {
2289 Graph::EdgePath p = theConverters().getPath(*it, format);
2290 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2291 backend_format = *it;
2296 runparams.flavor = theConverters().getFlavor(path);
2298 Alert::error(_("Couldn't export file"),
2299 bformat(_("No information for exporting the format %1$s."),
2300 formats.prettyName(format)));
2304 backend_format = format;
2305 // FIXME: Don't hardcode format names here, but use a flag
2306 if (backend_format == "pdflatex")
2307 runparams.flavor = OutputParams::PDFLATEX;
2310 string filename = latexName(false);
2311 filename = addName(temppath(), filename);
2312 filename = changeExtension(filename,
2313 formats.extension(backend_format));
2316 updateMacroInstances();
2318 // Plain text backend
2319 if (backend_format == "text")
2320 writePlaintextFile(*this, FileName(filename), runparams);
2322 else if (backend_format == "lyx")
2323 writeFile(FileName(filename));
2325 else if (isDocBook()) {
2326 runparams.nice = !put_in_tempdir;
2327 makeDocBookFile(FileName(filename), runparams);
2330 else if (backend_format == format) {
2331 runparams.nice = true;
2332 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2334 } else if (!lyxrc.tex_allows_spaces
2335 && contains(filePath(), ' ')) {
2336 Alert::error(_("File name error"),
2337 _("The directory path to the document cannot contain spaces."));
2340 runparams.nice = false;
2341 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2345 string const error_type = (format == "program")
2346 ? "Build" : bufferFormat();
2347 string const ext = formats.extension(format);
2348 FileName const tmp_result_file(changeExtension(filename, ext));
2349 bool const success = theConverters().convert(this, FileName(filename),
2350 tmp_result_file, FileName(absFileName()), backend_format, format,
2351 errorList(error_type));
2352 // Emit the signal to show the error list.
2353 if (format != backend_format)
2358 if (put_in_tempdir) {
2359 result_file = tmp_result_file.absFilename();
2363 result_file = changeExtension(absFileName(), ext);
2364 // We need to copy referenced files (e. g. included graphics
2365 // if format == "dvi") to the result dir.
2366 vector<ExportedFile> const files =
2367 runparams.exportdata->externalFiles(format);
2368 string const dest = onlyPath(result_file);
2369 CopyStatus status = SUCCESS;
2370 for (vector<ExportedFile>::const_iterator it = files.begin();
2371 it != files.end() && status != CANCEL; ++it) {
2372 string const fmt = formats.getFormatFromFile(it->sourceName);
2373 status = copyFile(fmt, it->sourceName,
2374 makeAbsPath(it->exportName, dest),
2375 it->exportName, status == FORCE);
2377 if (status == CANCEL) {
2378 message(_("Document export cancelled."));
2379 } else if (tmp_result_file.exists()) {
2380 // Finally copy the main file
2381 status = copyFile(format, tmp_result_file,
2382 FileName(result_file), result_file,
2384 message(bformat(_("Document exported as %1$s "
2386 formats.prettyName(format),
2387 makeDisplayPath(result_file)));
2389 // This must be a dummy converter like fax (bug 1888)
2390 message(bformat(_("Document exported as %1$s"),
2391 formats.prettyName(format)));
2398 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2401 return doExport(format, put_in_tempdir, result_file);
2405 bool Buffer::preview(string const & format) const
2408 if (!doExport(format, true, result_file))
2410 return formats.view(*this, FileName(result_file), format);
2414 bool Buffer::isExportable(string const & format) const
2416 vector<string> backs = backends();
2417 for (vector<string>::const_iterator it = backs.begin();
2418 it != backs.end(); ++it)
2419 if (theConverters().isReachable(*it, format))
2425 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2427 vector<string> backs = backends();
2428 vector<Format const *> result =
2429 theConverters().getReachable(backs[0], only_viewable, true);
2430 for (vector<string>::const_iterator it = backs.begin() + 1;
2431 it != backs.end(); ++it) {
2432 vector<Format const *> r =
2433 theConverters().getReachable(*it, only_viewable, false);
2434 result.insert(result.end(), r.begin(), r.end());
2440 vector<string> Buffer::backends() const
2443 if (params().baseClass()->isTeXClassAvailable()) {
2444 v.push_back(bufferFormat());
2445 // FIXME: Don't hardcode format names here, but use a flag
2446 if (v.back() == "latex")
2447 v.push_back("pdflatex");
2449 v.push_back("text");
2455 bool Buffer::readFileHelper(FileName const & s)
2457 // File information about normal file
2459 docstring const file = makeDisplayPath(s.absFilename(), 50);
2460 docstring text = bformat(_("The specified document\n%1$s"
2461 "\ncould not be read."), file);
2462 Alert::error(_("Could not read document"), text);
2466 // Check if emergency save file exists and is newer.
2467 FileName const e(s.absFilename() + ".emergency");
2469 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2470 docstring const file = makeDisplayPath(s.absFilename(), 20);
2471 docstring const text =
2472 bformat(_("An emergency save of the document "
2474 "Recover emergency save?"), file);
2475 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2476 _("&Recover"), _("&Load Original"),
2480 // the file is not saved if we load the emergency file.
2490 // Now check if autosave file is newer.
2491 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2493 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2494 docstring const file = makeDisplayPath(s.absFilename(), 20);
2495 docstring const text =
2496 bformat(_("The backup of the document "
2497 "%1$s is newer.\n\nLoad the "
2498 "backup instead?"), file);
2499 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2500 _("&Load backup"), _("Load &original"),
2504 // the file is not saved if we load the autosave file.
2508 // Here we delete the autosave
2519 bool Buffer::loadLyXFile(FileName const & s)
2521 if (s.isReadableFile()) {
2522 if (readFileHelper(s)) {
2523 lyxvc().file_found_hook(s);
2524 if (!s.isWritable())
2529 docstring const file = makeDisplayPath(s.absFilename(), 20);
2530 // Here we probably should run
2531 if (LyXVC::file_not_found_hook(s)) {
2532 docstring const text =
2533 bformat(_("Do you want to retrieve the document"
2534 " %1$s from version control?"), file);
2535 int const ret = Alert::prompt(_("Retrieve from version control?"),
2536 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2539 // How can we know _how_ to do the checkout?
2540 // With the current VC support it has to be,
2541 // a RCS file since CVS do not have special ,v files.
2543 return loadLyXFile(s);
2551 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2553 TeXErrors::Errors::const_iterator cit = terr.begin();
2554 TeXErrors::Errors::const_iterator end = terr.end();
2556 for (; cit != end; ++cit) {
2559 int errorRow = cit->error_in_line;
2560 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2566 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2567 } while (found && id_start == id_end && pos_start == pos_end);
2569 errorList.push_back(ErrorItem(cit->error_desc,
2570 cit->error_text, id_start, pos_start, pos_end));