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/lassert.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 = 340; //jamatos: add plain layout
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);
142 mutable TexRow texrow;
143 Buffer const * parent_buffer;
145 /// need to regenerate .tex?
149 mutable bool lyx_clean;
151 /// is autosave needed?
152 mutable bool bak_clean;
154 /// is this a unnamed file (New...)?
160 /// name of the file the buffer is associated with.
163 /** Set to true only when the file is fully loaded.
164 * Used to prevent the premature generation of previews
165 * and by the citation inset.
167 bool file_fully_loaded;
170 mutable TocBackend toc_backend;
173 typedef pair<DocIterator, MacroData> ScopeMacro;
174 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
175 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
176 /// map from the macro name to the position map,
177 /// which maps the macro definition position to the scope and the MacroData.
178 NamePositionScopeMacroMap macros;
181 /// positions of child buffers in the buffer
182 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
183 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
184 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
185 /// position of children buffers in this buffer
186 BufferPositionMap children_positions;
187 /// map from children inclusion positions to their scope and their buffer
188 PositionScopeBufferMap position_to_children;
190 /// Container for all sort of Buffer dependant errors.
191 map<string, ErrorList> errorLists;
193 /// timestamp and checksum used to test if the file has been externally
194 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
196 unsigned long checksum_;
199 frontend::WorkAreaManager * wa_;
204 /// A cache for the bibfiles (including bibfiles of loaded child
205 /// documents), needed for appropriate update of natbib labels.
206 mutable support::FileNameList bibfilesCache_;
208 // FIXME The caching mechanism could be improved. At present, we have a
209 // cache for each Buffer, that caches all the bibliography info for that
210 // Buffer. A more efficient solution would be to have a global cache per
211 // file, and then to construct the Buffer's bibinfo from that.
212 /// A cache for bibliography info
213 mutable BiblioInfo bibinfo_;
214 /// whether the bibinfo cache is valid
215 bool bibinfoCacheValid_;
216 /// Cache of timestamps of .bib files
217 map<FileName, time_t> bibfileStatus_;
219 mutable RefCache ref_cache_;
221 /// our Text that should be wrapped in an InsetText
226 /// Creates the per buffer temporary directory
227 static FileName createBufferTmpDir()
230 // We are in our own directory. Why bother to mangle name?
231 // In fact I wrote this code to circumvent a problematic behaviour
232 // (bug?) of EMX mkstemp().
233 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
234 convert<string>(count++));
236 if (!tmpfl.createDirectory(0777)) {
237 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
238 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
239 from_utf8(tmpfl.absFilename())));
245 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
246 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
247 read_only(readonly_), filename(file), file_fully_loaded(false),
248 toc_backend(&parent), macro_lock(false), timestamp_(0),
249 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
251 temppath = createBufferTmpDir();
252 lyxvc.setBuffer(&parent);
254 wa_ = new frontend::WorkAreaManager;
258 Buffer::Buffer(string const & file, bool readonly)
259 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
261 LYXERR(Debug::INFO, "Buffer::Buffer()");
263 d->inset = new InsetText(*this);
264 d->inset->setAutoBreakRows(true);
265 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
271 LYXERR(Debug::INFO, "Buffer::~Buffer()");
272 // here the buffer should take care that it is
273 // saved properly, before it goes into the void.
275 // GuiView already destroyed
279 // loop over children
280 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
281 Impl::BufferPositionMap::iterator end = d->children_positions.end();
282 for (; it != end; ++it)
283 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
285 // clear references to children in macro tables
286 d->children_positions.clear();
287 d->position_to_children.clear();
289 if (!d->temppath.destroyDirectory()) {
290 Alert::warning(_("Could not remove temporary directory"),
291 bformat(_("Could not remove the temporary directory %1$s"),
292 from_utf8(d->temppath.absFilename())));
295 // Remove any previewed LaTeX snippets associated with this buffer.
296 thePreviews().removeLoader(*this);
302 void Buffer::changed() const
309 frontend::WorkAreaManager & Buffer::workAreaManager() const
311 LASSERT(d->wa_, /**/);
316 Text & Buffer::text() const
318 return d->inset->text();
322 Inset & Buffer::inset() const
328 BufferParams & Buffer::params()
334 BufferParams const & Buffer::params() const
340 ParagraphList & Buffer::paragraphs()
342 return text().paragraphs();
346 ParagraphList const & Buffer::paragraphs() const
348 return text().paragraphs();
352 LyXVC & Buffer::lyxvc()
358 LyXVC const & Buffer::lyxvc() const
364 string const Buffer::temppath() const
366 return d->temppath.absFilename();
370 TexRow const & Buffer::texrow() const
376 TocBackend & Buffer::tocBackend() const
378 return d->toc_backend;
382 Undo & Buffer::undo()
388 string Buffer::latexName(bool const no_path) const
390 FileName latex_name = makeLatexName(d->filename);
391 return no_path ? latex_name.onlyFileName()
392 : latex_name.absFilename();
396 string Buffer::logName(LogType * type) const
398 string const filename = latexName(false);
400 if (filename.empty()) {
406 string const path = temppath();
408 FileName const fname(addName(temppath(),
409 onlyFilename(changeExtension(filename,
411 FileName const bname(
412 addName(path, onlyFilename(
413 changeExtension(filename,
414 formats.extension("literate") + ".out"))));
416 // If no Latex log or Build log is newer, show Build log
418 if (bname.exists() &&
419 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
420 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
423 return bname.absFilename();
425 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
428 return fname.absFilename();
432 void Buffer::setReadonly(bool const flag)
434 if (d->read_only != flag) {
441 void Buffer::setFileName(string const & newfile)
443 d->filename = makeAbsPath(newfile);
444 setReadonly(d->filename.isReadOnly());
449 int Buffer::readHeader(Lexer & lex)
451 int unknown_tokens = 0;
453 int begin_header_line = -1;
455 // Initialize parameters that may be/go lacking in header:
456 params().branchlist().clear();
457 params().preamble.erase();
458 params().options.erase();
459 params().master.erase();
460 params().float_placement.erase();
461 params().paperwidth.erase();
462 params().paperheight.erase();
463 params().leftmargin.erase();
464 params().rightmargin.erase();
465 params().topmargin.erase();
466 params().bottommargin.erase();
467 params().headheight.erase();
468 params().headsep.erase();
469 params().footskip.erase();
470 params().columnsep.erase();
471 params().fontsCJK.erase();
472 params().listings_params.clear();
473 params().clearLayoutModules();
474 params().clearRemovedModules();
475 params().pdfoptions().clear();
477 for (int i = 0; i < 4; ++i) {
478 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
479 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
482 ErrorList & errorList = d->errorLists["Parse"];
491 if (token == "\\end_header")
495 if (token == "\\begin_header") {
496 begin_header_line = line;
500 LYXERR(Debug::PARSER, "Handling document header token: `"
503 string unknown = params().readToken(lex, token, d->filename.onlyPath());
504 if (!unknown.empty()) {
505 if (unknown[0] != '\\' && token == "\\textclass") {
506 Alert::warning(_("Unknown document class"),
507 bformat(_("Using the default document class, because the "
508 "class %1$s is unknown."), from_utf8(unknown)));
511 docstring const s = bformat(_("Unknown token: "
515 errorList.push_back(ErrorItem(_("Document header error"),
520 if (begin_header_line) {
521 docstring const s = _("\\begin_header is missing");
522 errorList.push_back(ErrorItem(_("Document header error"),
526 params().makeDocumentClass();
528 return unknown_tokens;
533 // changed to be public and have one parameter
534 // Returns false if "\end_document" is not read (Asger)
535 bool Buffer::readDocument(Lexer & lex)
537 ErrorList & errorList = d->errorLists["Parse"];
540 if (!lex.checkFor("\\begin_document")) {
541 docstring const s = _("\\begin_document is missing");
542 errorList.push_back(ErrorItem(_("Document header error"),
546 // we are reading in a brand new document
547 LASSERT(paragraphs().empty(), /**/);
551 if (params().outputChanges) {
552 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
553 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
554 LaTeXFeatures::isAvailable("xcolor");
556 if (!dvipost && !xcolorsoul) {
557 Alert::warning(_("Changes not shown in LaTeX output"),
558 _("Changes will not be highlighted in LaTeX output, "
559 "because neither dvipost nor xcolor/soul are installed.\n"
560 "Please install these packages or redefine "
561 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
562 } else if (!xcolorsoul) {
563 Alert::warning(_("Changes not shown in LaTeX output"),
564 _("Changes will not be highlighted in LaTeX output "
565 "when using pdflatex, because xcolor and soul are not installed.\n"
566 "Please install both packages or redefine "
567 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
571 if (!params().master.empty()) {
572 FileName const master_file = makeAbsPath(params().master,
573 onlyPath(absFileName()));
574 if (isLyXFilename(master_file.absFilename())) {
575 Buffer * master = checkAndLoadLyXFile(master_file);
576 d->parent_buffer = master;
581 bool const res = text().read(*this, lex, errorList, d->inset);
584 updateMacroInstances();
589 // needed to insert the selection
590 void Buffer::insertStringAsLines(ParagraphList & pars,
591 pit_type & pit, pos_type & pos,
592 Font const & fn, docstring const & str, bool autobreakrows)
596 // insert the string, don't insert doublespace
597 bool space_inserted = true;
598 for (docstring::const_iterator cit = str.begin();
599 cit != str.end(); ++cit) {
600 Paragraph & par = pars[pit];
602 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
603 breakParagraph(params(), pars, pit, pos,
604 par.layout().isEnvironment());
607 space_inserted = true;
611 // do not insert consecutive spaces if !free_spacing
612 } else if ((*cit == ' ' || *cit == '\t') &&
613 space_inserted && !par.isFreeSpacing()) {
615 } else if (*cit == '\t') {
616 if (!par.isFreeSpacing()) {
617 // tabs are like spaces here
618 par.insertChar(pos, ' ', font, params().trackChanges);
620 space_inserted = true;
622 const pos_type n = 8 - pos % 8;
623 for (pos_type i = 0; i < n; ++i) {
624 par.insertChar(pos, ' ', font, params().trackChanges);
627 space_inserted = true;
629 } else if (!isPrintable(*cit)) {
630 // Ignore unprintables
633 // just insert the character
634 par.insertChar(pos, *cit, font, params().trackChanges);
636 space_inserted = (*cit == ' ');
643 bool Buffer::readString(string const & s)
645 params().compressed = false;
647 // remove dummy empty par
648 paragraphs().clear();
652 FileName const name = FileName::tempName("Buffer_readString");
653 switch (readFile(lex, name, true)) {
657 // We need to call lyx2lyx, so write the input to a file
658 ofstream os(name.toFilesystemEncoding().c_str());
661 return readFile(name);
671 bool Buffer::readFile(FileName const & filename)
673 FileName fname(filename);
675 // remove dummy empty par
676 paragraphs().clear();
679 if (readFile(lex, fname) != success)
686 bool Buffer::isFullyLoaded() const
688 return d->file_fully_loaded;
692 void Buffer::setFullyLoaded(bool value)
694 d->file_fully_loaded = value;
698 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
701 LASSERT(!filename.empty(), /**/);
703 // the first (non-comment) token _must_ be...
704 if (!lex.checkFor("\\lyxformat")) {
705 Alert::error(_("Document format failure"),
706 bformat(_("%1$s is not a readable LyX document."),
707 from_utf8(filename.absFilename())));
713 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
714 // if present remove ".," from string.
715 size_t dot = tmp_format.find_first_of(".,");
716 //lyxerr << " dot found at " << dot << endl;
717 if (dot != string::npos)
718 tmp_format.erase(dot, 1);
719 int const file_format = convert<int>(tmp_format);
720 //lyxerr << "format: " << file_format << endl;
722 // save timestamp and checksum of the original disk file, making sure
723 // to not overwrite them with those of the file created in the tempdir
724 // when it has to be converted to the current format.
726 // Save the timestamp and checksum of disk file. If filename is an
727 // emergency file, save the timestamp and checksum of the original lyx file
728 // because isExternallyModified will check for this file. (BUG4193)
729 string diskfile = filename.absFilename();
730 if (suffixIs(diskfile, ".emergency"))
731 diskfile = diskfile.substr(0, diskfile.size() - 10);
732 saveCheckSum(FileName(diskfile));
735 if (file_format != LYX_FORMAT) {
738 // lyx2lyx would fail
741 FileName const tmpfile = FileName::tempName("Buffer_readFile");
742 if (tmpfile.empty()) {
743 Alert::error(_("Conversion failed"),
744 bformat(_("%1$s is from a different"
745 " version of LyX, but a temporary"
746 " file for converting it could"
748 from_utf8(filename.absFilename())));
751 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
752 if (lyx2lyx.empty()) {
753 Alert::error(_("Conversion script not found"),
754 bformat(_("%1$s is from a different"
755 " version of LyX, but the"
756 " conversion script lyx2lyx"
757 " could not be found."),
758 from_utf8(filename.absFilename())));
761 ostringstream command;
762 command << os::python()
763 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
764 << " -t " << convert<string>(LYX_FORMAT)
765 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
766 << ' ' << quoteName(filename.toFilesystemEncoding());
767 string const command_str = command.str();
769 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
771 cmd_ret const ret = runCommand(command_str);
772 if (ret.first != 0) {
773 Alert::error(_("Conversion script failed"),
774 bformat(_("%1$s is from a different version"
775 " of LyX, but the lyx2lyx script"
776 " failed to convert it."),
777 from_utf8(filename.absFilename())));
780 bool const ret = readFile(tmpfile);
781 // Do stuff with tmpfile name and buffer name here.
782 return ret ? success : failure;
787 if (readDocument(lex)) {
788 Alert::error(_("Document format failure"),
789 bformat(_("%1$s ended unexpectedly, which means"
790 " that it is probably corrupted."),
791 from_utf8(filename.absFilename())));
794 d->file_fully_loaded = true;
799 // Should probably be moved to somewhere else: BufferView? LyXView?
800 bool Buffer::save() const
802 // We don't need autosaves in the immediate future. (Asger)
803 resetAutosaveTimers();
805 string const encodedFilename = d->filename.toFilesystemEncoding();
808 bool madeBackup = false;
810 // make a backup if the file already exists
811 if (lyxrc.make_backup && fileName().exists()) {
812 backupName = FileName(absFileName() + '~');
813 if (!lyxrc.backupdir_path.empty()) {
814 string const mangledName =
815 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
816 backupName = FileName(addName(lyxrc.backupdir_path,
819 if (fileName().copyTo(backupName)) {
822 Alert::error(_("Backup failure"),
823 bformat(_("Cannot create backup file %1$s.\n"
824 "Please check whether the directory exists and is writeable."),
825 from_utf8(backupName.absFilename())));
826 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
830 // ask if the disk file has been externally modified (use checksum method)
831 if (fileName().exists() && isExternallyModified(checksum_method)) {
832 docstring const file = makeDisplayPath(absFileName(), 20);
833 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
834 "you want to overwrite this file?"), file);
835 int const ret = Alert::prompt(_("Overwrite modified file?"),
836 text, 1, 1, _("&Overwrite"), _("&Cancel"));
841 if (writeFile(d->filename)) {
845 // Saving failed, so backup is not backup
847 backupName.moveTo(d->filename);
853 bool Buffer::writeFile(FileName const & fname) const
855 if (d->read_only && fname == d->filename)
860 docstring const str = bformat(_("Saving document %1$s..."),
861 makeDisplayPath(fname.absFilename()));
864 if (params().compressed) {
865 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
866 retval = ofs && write(ofs);
868 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
869 retval = ofs && write(ofs);
873 message(str + _(" could not write file!"));
877 removeAutosaveFile(d->filename.absFilename());
879 saveCheckSum(d->filename);
880 message(str + _(" done."));
886 bool Buffer::write(ostream & ofs) const
889 // Use the standard "C" locale for file output.
890 ofs.imbue(locale::classic());
893 // The top of the file should not be written by params().
895 // write out a comment in the top of the file
896 ofs << "#LyX " << lyx_version
897 << " created this file. For more info see http://www.lyx.org/\n"
898 << "\\lyxformat " << LYX_FORMAT << "\n"
899 << "\\begin_document\n";
901 /// For each author, set 'used' to true if there is a change
902 /// by this author in the document; otherwise set it to 'false'.
903 AuthorList::Authors::const_iterator a_it = params().authors().begin();
904 AuthorList::Authors::const_iterator a_end = params().authors().end();
905 for (; a_it != a_end; ++a_it)
906 a_it->second.setUsed(false);
908 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
909 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
910 for ( ; it != end; ++it)
911 it->checkAuthors(params().authors());
913 // now write out the buffer parameters.
914 ofs << "\\begin_header\n";
915 params().writeFile(ofs);
916 ofs << "\\end_header\n";
919 ofs << "\n\\begin_body\n";
920 text().write(*this, ofs);
921 ofs << "\n\\end_body\n";
923 // Write marker that shows file is complete
924 ofs << "\\end_document" << endl;
926 // Shouldn't really be needed....
929 // how to check if close went ok?
930 // Following is an attempt... (BE 20001011)
932 // good() returns false if any error occured, including some
934 // bad() returns true if something bad happened in the buffer,
935 // which should include file system full errors.
940 lyxerr << "File was not closed properly." << endl;
947 bool Buffer::makeLaTeXFile(FileName const & fname,
948 string const & original_path,
949 OutputParams const & runparams,
950 bool output_preamble, bool output_body) const
952 string const encoding = runparams.encoding->iconvName();
953 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
956 try { ofs.reset(encoding); }
957 catch (iconv_codecvt_facet_exception & e) {
958 lyxerr << "Caught iconv exception: " << e.what() << endl;
959 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
960 "verify that the support software for your encoding (%1$s) is "
961 "properly installed"), from_ascii(encoding)));
964 if (!openFileWrite(ofs, fname))
967 //TexStream ts(ofs.rdbuf(), &texrow());
968 ErrorList & errorList = d->errorLists["Export"];
970 bool failed_export = false;
973 writeLaTeXSource(ofs, original_path,
974 runparams, output_preamble, output_body);
976 catch (EncodingException & e) {
977 odocstringstream ods;
978 ods.put(e.failed_char);
980 oss << "0x" << hex << e.failed_char << dec;
981 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
982 " (code point %2$s)"),
983 ods.str(), from_utf8(oss.str()));
984 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
985 "representable in the chosen encoding.\n"
986 "Changing the document encoding to utf8 could help."),
987 e.par_id, e.pos, e.pos + 1));
988 failed_export = true;
990 catch (iconv_codecvt_facet_exception & e) {
991 errorList.push_back(ErrorItem(_("iconv conversion failed"),
992 _(e.what()), -1, 0, 0));
993 failed_export = true;
995 catch (exception const & e) {
996 errorList.push_back(ErrorItem(_("conversion failed"),
997 _(e.what()), -1, 0, 0));
998 failed_export = true;
1001 lyxerr << "Caught some really weird exception..." << endl;
1007 failed_export = true;
1008 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1012 return !failed_export;
1016 void Buffer::writeLaTeXSource(odocstream & os,
1017 string const & original_path,
1018 OutputParams const & runparams_in,
1019 bool const output_preamble, bool const output_body) const
1021 // The child documents, if any, shall be already loaded at this point.
1023 OutputParams runparams = runparams_in;
1025 // validate the buffer.
1026 LYXERR(Debug::LATEX, " Validating buffer...");
1027 LaTeXFeatures features(*this, params(), runparams);
1029 LYXERR(Debug::LATEX, " Buffer validation done.");
1031 // The starting paragraph of the coming rows is the
1032 // first paragraph of the document. (Asger)
1033 if (output_preamble && runparams.nice) {
1034 os << "%% LyX " << lyx_version << " created this file. "
1035 "For more info, see http://www.lyx.org/.\n"
1036 "%% Do not edit unless you really know what "
1038 d->texrow.newline();
1039 d->texrow.newline();
1041 LYXERR(Debug::INFO, "lyx document header finished");
1043 // Don't move this behind the parent_buffer=0 code below,
1044 // because then the macros will not get the right "redefinition"
1045 // flag as they don't see the parent macros which are output before.
1048 // fold macros if possible, still with parent buffer as the
1049 // macros will be put in the prefix anyway.
1050 updateMacroInstances();
1052 // There are a few differences between nice LaTeX and usual files:
1053 // usual is \batchmode and has a
1054 // special input@path to allow the including of figures
1055 // with either \input or \includegraphics (what figinsets do).
1056 // input@path is set when the actual parameter
1057 // original_path is set. This is done for usual tex-file, but not
1058 // for nice-latex-file. (Matthias 250696)
1059 // Note that input@path is only needed for something the user does
1060 // in the preamble, included .tex files or ERT, files included by
1061 // LyX work without it.
1062 if (output_preamble) {
1063 if (!runparams.nice) {
1064 // code for usual, NOT nice-latex-file
1065 os << "\\batchmode\n"; // changed
1066 // from \nonstopmode
1067 d->texrow.newline();
1069 if (!original_path.empty()) {
1071 // We don't know the encoding of inputpath
1072 docstring const inputpath = from_utf8(latex_path(original_path));
1073 os << "\\makeatletter\n"
1074 << "\\def\\input@path{{"
1075 << inputpath << "/}}\n"
1076 << "\\makeatother\n";
1077 d->texrow.newline();
1078 d->texrow.newline();
1079 d->texrow.newline();
1082 // get parent macros (if this buffer has a parent) which will be
1083 // written at the document begin further down.
1084 MacroSet parentMacros;
1085 listParentMacros(parentMacros, features);
1087 // Write the preamble
1088 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1090 runparams.use_japanese = features.isRequired("japanese");
1096 os << "\\begin{document}\n";
1097 d->texrow.newline();
1099 // output the parent macros
1100 MacroSet::iterator it = parentMacros.begin();
1101 MacroSet::iterator end = parentMacros.end();
1102 for (; it != end; ++it)
1103 (*it)->write(os, true);
1104 } // output_preamble
1106 d->texrow.start(paragraphs().begin()->id(), 0);
1108 LYXERR(Debug::INFO, "preamble finished, now the body.");
1110 // if we are doing a real file with body, even if this is the
1111 // child of some other buffer, let's cut the link here.
1112 // This happens for example if only a child document is printed.
1113 Buffer const * save_parent = 0;
1114 if (output_preamble) {
1115 save_parent = d->parent_buffer;
1116 d->parent_buffer = 0;
1120 latexParagraphs(*this, text(), os, d->texrow, runparams);
1122 // Restore the parenthood if needed
1123 if (output_preamble)
1124 d->parent_buffer = save_parent;
1126 // add this just in case after all the paragraphs
1128 d->texrow.newline();
1130 if (output_preamble) {
1131 os << "\\end{document}\n";
1132 d->texrow.newline();
1133 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1135 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1137 runparams_in.encoding = runparams.encoding;
1139 // Just to be sure. (Asger)
1140 d->texrow.newline();
1142 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1143 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1147 bool Buffer::isLatex() const
1149 return params().documentClass().outputType() == LATEX;
1153 bool Buffer::isLiterate() const
1155 return params().documentClass().outputType() == LITERATE;
1159 bool Buffer::isDocBook() const
1161 return params().documentClass().outputType() == DOCBOOK;
1165 void Buffer::makeDocBookFile(FileName const & fname,
1166 OutputParams const & runparams,
1167 bool const body_only) const
1169 LYXERR(Debug::LATEX, "makeDocBookFile...");
1172 if (!openFileWrite(ofs, fname))
1175 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1179 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1183 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1184 OutputParams const & runparams,
1185 bool const only_body) const
1187 LaTeXFeatures features(*this, params(), runparams);
1192 DocumentClass const & tclass = params().documentClass();
1193 string const top_element = tclass.latexname();
1196 if (runparams.flavor == OutputParams::XML)
1197 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1200 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1203 if (! tclass.class_header().empty())
1204 os << from_ascii(tclass.class_header());
1205 else if (runparams.flavor == OutputParams::XML)
1206 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1207 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1209 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1211 docstring preamble = from_utf8(params().preamble);
1212 if (runparams.flavor != OutputParams::XML ) {
1213 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1214 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1215 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1216 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1219 string const name = runparams.nice
1220 ? changeExtension(absFileName(), ".sgml") : fname;
1221 preamble += features.getIncludedFiles(name);
1222 preamble += features.getLyXSGMLEntities();
1224 if (!preamble.empty()) {
1225 os << "\n [ " << preamble << " ]";
1230 string top = top_element;
1232 if (runparams.flavor == OutputParams::XML)
1233 top += params().language->code();
1235 top += params().language->code().substr(0,2);
1238 if (!params().options.empty()) {
1240 top += params().options;
1243 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1244 << " file was created by LyX " << lyx_version
1245 << "\n See http://www.lyx.org/ for more information -->\n";
1247 params().documentClass().counters().reset();
1251 sgml::openTag(os, top);
1253 docbookParagraphs(paragraphs(), *this, os, runparams);
1254 sgml::closeTag(os, top_element);
1258 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1259 // Other flags: -wall -v0 -x
1260 int Buffer::runChktex()
1264 // get LaTeX-Filename
1265 FileName const path(temppath());
1266 string const name = addName(path.absFilename(), latexName());
1267 string const org_path = filePath();
1269 PathChanger p(path); // path to LaTeX file
1270 message(_("Running chktex..."));
1272 // Generate the LaTeX file if neccessary
1273 OutputParams runparams(¶ms().encoding());
1274 runparams.flavor = OutputParams::LATEX;
1275 runparams.nice = false;
1276 makeLaTeXFile(FileName(name), org_path, runparams);
1279 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1280 int const res = chktex.run(terr); // run chktex
1283 Alert::error(_("chktex failure"),
1284 _("Could not run chktex successfully."));
1285 } else if (res > 0) {
1286 ErrorList & errlist = d->errorLists["ChkTeX"];
1288 bufferErrors(terr, errlist);
1299 void Buffer::validate(LaTeXFeatures & features) const
1301 params().validate(features);
1305 for_each(paragraphs().begin(), paragraphs().end(),
1306 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1308 if (lyxerr.debugging(Debug::LATEX)) {
1309 features.showStruct();
1314 void Buffer::getLabelList(vector<docstring> & list) const
1316 // If this is a child document, use the parent's list instead.
1317 if (d->parent_buffer) {
1318 d->parent_buffer->getLabelList(list);
1323 Toc & toc = d->toc_backend.toc("label");
1324 TocIterator toc_it = toc.begin();
1325 TocIterator end = toc.end();
1326 for (; toc_it != end; ++toc_it) {
1327 if (toc_it->depth() == 0)
1328 list.push_back(toc_it->str());
1333 void Buffer::updateBibfilesCache() const
1335 // If this is a child document, use the parent's cache instead.
1336 if (d->parent_buffer) {
1337 d->parent_buffer->updateBibfilesCache();
1341 d->bibfilesCache_.clear();
1342 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1343 if (it->lyxCode() == BIBTEX_CODE) {
1344 InsetBibtex const & inset =
1345 static_cast<InsetBibtex const &>(*it);
1346 support::FileNameList const bibfiles = inset.getBibFiles();
1347 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1350 } else if (it->lyxCode() == INCLUDE_CODE) {
1351 InsetInclude & inset =
1352 static_cast<InsetInclude &>(*it);
1353 inset.updateBibfilesCache();
1354 support::FileNameList const & bibfiles =
1355 inset.getBibfilesCache(*this);
1356 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1361 // the bibinfo cache is now invalid
1362 d->bibinfoCacheValid_ = false;
1366 void Buffer::invalidateBibinfoCache()
1368 d->bibinfoCacheValid_ = false;
1372 support::FileNameList const & Buffer::getBibfilesCache() const
1374 // If this is a child document, use the parent's cache instead.
1375 if (d->parent_buffer)
1376 return d->parent_buffer->getBibfilesCache();
1378 // We update the cache when first used instead of at loading time.
1379 if (d->bibfilesCache_.empty())
1380 const_cast<Buffer *>(this)->updateBibfilesCache();
1382 return d->bibfilesCache_;
1386 BiblioInfo const & Buffer::masterBibInfo() const
1388 // if this is a child document and the parent is already loaded
1389 // use the parent's list instead [ale990412]
1390 Buffer const * const tmp = masterBuffer();
1393 return tmp->masterBibInfo();
1394 return localBibInfo();
1398 BiblioInfo const & Buffer::localBibInfo() const
1400 if (d->bibinfoCacheValid_) {
1401 support::FileNameList const & bibfilesCache = getBibfilesCache();
1402 // compare the cached timestamps with the actual ones.
1403 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1404 support::FileNameList::const_iterator en = bibfilesCache.end();
1405 for (; ei != en; ++ ei) {
1406 time_t lastw = ei->lastModified();
1407 if (lastw != d->bibfileStatus_[*ei]) {
1408 d->bibinfoCacheValid_ = false;
1409 d->bibfileStatus_[*ei] = lastw;
1415 if (!d->bibinfoCacheValid_) {
1416 d->bibinfo_.clear();
1417 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1418 it->fillWithBibKeys(d->bibinfo_, it);
1419 d->bibinfoCacheValid_ = true;
1425 bool Buffer::isDepClean(string const & name) const
1427 DepClean::const_iterator const it = d->dep_clean.find(name);
1428 if (it == d->dep_clean.end())
1434 void Buffer::markDepClean(string const & name)
1436 d->dep_clean[name] = true;
1440 bool Buffer::dispatch(string const & command, bool * result)
1442 return dispatch(lyxaction.lookupFunc(command), result);
1446 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1448 bool dispatched = true;
1450 switch (func.action) {
1451 case LFUN_BUFFER_EXPORT: {
1452 bool const tmp = doExport(to_utf8(func.argument()), false);
1458 case LFUN_BRANCH_ACTIVATE:
1459 case LFUN_BRANCH_DEACTIVATE: {
1460 BranchList & branchList = params().branchlist();
1461 docstring const branchName = func.argument();
1462 Branch * branch = branchList.find(branchName);
1464 LYXERR0("Branch " << branchName << " does not exist.");
1466 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1478 void Buffer::changeLanguage(Language const * from, Language const * to)
1480 LASSERT(from, /**/);
1483 for_each(par_iterator_begin(),
1485 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1489 bool Buffer::isMultiLingual() const
1491 ParConstIterator end = par_iterator_end();
1492 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1493 if (it->isMultiLingual(params()))
1500 DocIterator Buffer::getParFromID(int const id) const
1503 // John says this is called with id == -1 from undo
1504 lyxerr << "getParFromID(), id: " << id << endl;
1505 return doc_iterator_end(inset());
1508 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1509 if (it.paragraph().id() == id)
1512 return doc_iterator_end(inset());
1516 bool Buffer::hasParWithID(int const id) const
1518 return !getParFromID(id).atEnd();
1522 ParIterator Buffer::par_iterator_begin()
1524 return ParIterator(doc_iterator_begin(inset()));
1528 ParIterator Buffer::par_iterator_end()
1530 return ParIterator(doc_iterator_end(inset()));
1534 ParConstIterator Buffer::par_iterator_begin() const
1536 return lyx::par_const_iterator_begin(inset());
1540 ParConstIterator Buffer::par_iterator_end() const
1542 return lyx::par_const_iterator_end(inset());
1546 Language const * Buffer::language() const
1548 return params().language;
1552 docstring const Buffer::B_(string const & l10n) const
1554 return params().B_(l10n);
1558 bool Buffer::isClean() const
1560 return d->lyx_clean;
1564 bool Buffer::isBakClean() const
1566 return d->bak_clean;
1570 bool Buffer::isExternallyModified(CheckMethod method) const
1572 LASSERT(d->filename.exists(), /**/);
1573 // if method == timestamp, check timestamp before checksum
1574 return (method == checksum_method
1575 || d->timestamp_ != d->filename.lastModified())
1576 && d->checksum_ != d->filename.checksum();
1580 void Buffer::saveCheckSum(FileName const & file) const
1582 if (file.exists()) {
1583 d->timestamp_ = file.lastModified();
1584 d->checksum_ = file.checksum();
1586 // in the case of save to a new file.
1593 void Buffer::markClean() const
1595 if (!d->lyx_clean) {
1596 d->lyx_clean = true;
1599 // if the .lyx file has been saved, we don't need an
1601 d->bak_clean = true;
1605 void Buffer::markBakClean() const
1607 d->bak_clean = true;
1611 void Buffer::setUnnamed(bool flag)
1617 bool Buffer::isUnnamed() const
1623 // FIXME: this function should be moved to buffer_pimpl.C
1624 void Buffer::markDirty()
1627 d->lyx_clean = false;
1630 d->bak_clean = false;
1632 DepClean::iterator it = d->dep_clean.begin();
1633 DepClean::const_iterator const end = d->dep_clean.end();
1635 for (; it != end; ++it)
1640 FileName Buffer::fileName() const
1646 string Buffer::absFileName() const
1648 return d->filename.absFilename();
1652 string Buffer::filePath() const
1654 return d->filename.onlyPath().absFilename() + "/";
1658 bool Buffer::isReadonly() const
1660 return d->read_only;
1664 void Buffer::setParent(Buffer const * buffer)
1666 // Avoids recursive include.
1667 d->parent_buffer = buffer == this ? 0 : buffer;
1672 Buffer const * Buffer::parent()
1674 return d->parent_buffer;
1678 Buffer const * Buffer::masterBuffer() const
1680 if (!d->parent_buffer)
1683 return d->parent_buffer->masterBuffer();
1687 bool Buffer::isChild(Buffer * child) const
1689 return d->children_positions.find(child) != d->children_positions.end();
1693 template<typename M>
1694 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1699 typename M::iterator it = m.lower_bound(x);
1700 if (it == m.begin())
1708 MacroData const * Buffer::getBufferMacro(docstring const & name,
1709 DocIterator const & pos) const
1711 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1713 // if paragraphs have no macro context set, pos will be empty
1717 // we haven't found anything yet
1718 DocIterator bestPos = par_iterator_begin();
1719 MacroData const * bestData = 0;
1721 // find macro definitions for name
1722 Impl::NamePositionScopeMacroMap::iterator nameIt
1723 = d->macros.find(name);
1724 if (nameIt != d->macros.end()) {
1725 // find last definition in front of pos or at pos itself
1726 Impl::PositionScopeMacroMap::const_iterator it
1727 = greatest_below(nameIt->second, pos);
1728 if (it != nameIt->second.end()) {
1730 // scope ends behind pos?
1731 if (pos < it->second.first) {
1732 // Looks good, remember this. If there
1733 // is no external macro behind this,
1734 // we found the right one already.
1735 bestPos = it->first;
1736 bestData = &it->second.second;
1740 // try previous macro if there is one
1741 if (it == nameIt->second.begin())
1748 // find macros in included files
1749 Impl::PositionScopeBufferMap::const_iterator it
1750 = greatest_below(d->position_to_children, pos);
1751 if (it == d->position_to_children.end())
1752 // no children before
1756 // do we know something better (i.e. later) already?
1757 if (it->first < bestPos )
1760 // scope ends behind pos?
1761 if (pos < it->second.first) {
1762 // look for macro in external file
1763 d->macro_lock = true;
1764 MacroData const * data
1765 = it->second.second->getMacro(name, false);
1766 d->macro_lock = false;
1768 bestPos = it->first;
1774 // try previous file if there is one
1775 if (it == d->position_to_children.begin())
1780 // return the best macro we have found
1785 MacroData const * Buffer::getMacro(docstring const & name,
1786 DocIterator const & pos, bool global) const
1791 // query buffer macros
1792 MacroData const * data = getBufferMacro(name, pos);
1796 // If there is a master buffer, query that
1797 if (d->parent_buffer) {
1798 d->macro_lock = true;
1799 MacroData const * macro = d->parent_buffer->getMacro(
1800 name, *this, false);
1801 d->macro_lock = false;
1807 data = MacroTable::globalMacros().get(name);
1816 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1818 // set scope end behind the last paragraph
1819 DocIterator scope = par_iterator_begin();
1820 scope.pit() = scope.lastpit() + 1;
1822 return getMacro(name, scope, global);
1826 MacroData const * Buffer::getMacro(docstring const & name,
1827 Buffer const & child, bool global) const
1829 // look where the child buffer is included first
1830 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1831 if (it == d->children_positions.end())
1834 // check for macros at the inclusion position
1835 return getMacro(name, it->second, global);
1839 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1841 pit_type lastpit = it.lastpit();
1843 // look for macros in each paragraph
1844 while (it.pit() <= lastpit) {
1845 Paragraph & par = it.paragraph();
1847 // iterate over the insets of the current paragraph
1848 InsetList const & insets = par.insetList();
1849 InsetList::const_iterator iit = insets.begin();
1850 InsetList::const_iterator end = insets.end();
1851 for (; iit != end; ++iit) {
1852 it.pos() = iit->pos;
1854 // is it a nested text inset?
1855 if (iit->inset->asInsetText()) {
1856 // Inset needs its own scope?
1857 InsetText const * itext
1858 = iit->inset->asInsetText();
1859 bool newScope = itext->isMacroScope();
1861 // scope which ends just behind the inset
1862 DocIterator insetScope = it;
1865 // collect macros in inset
1866 it.push_back(CursorSlice(*iit->inset));
1867 updateMacros(it, newScope ? insetScope : scope);
1872 // is it an external file?
1873 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1874 // get buffer of external file
1875 InsetCommand const & inset
1876 = static_cast<InsetCommand const &>(*iit->inset);
1877 InsetCommandParams const & ip = inset.params();
1878 d->macro_lock = true;
1879 Buffer * child = loadIfNeeded(*this, ip);
1880 d->macro_lock = false;
1884 // register its position, but only when it is
1885 // included first in the buffer
1886 if (d->children_positions.find(child)
1887 == d->children_positions.end())
1888 d->children_positions[child] = it;
1890 // register child with its scope
1891 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1895 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1899 MathMacroTemplate & macroTemplate
1900 = static_cast<MathMacroTemplate &>(*iit->inset);
1901 MacroContext mc(*this, it);
1902 macroTemplate.updateToContext(mc);
1905 bool valid = macroTemplate.validMacro();
1906 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1907 // then the BufferView's cursor will be invalid in
1908 // some cases which leads to crashes.
1913 d->macros[macroTemplate.name()][it] =
1914 Impl::ScopeMacro(scope, MacroData(*this, it));
1924 void Buffer::updateMacros() const
1929 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1931 // start with empty table
1933 d->children_positions.clear();
1934 d->position_to_children.clear();
1936 // Iterate over buffer, starting with first paragraph
1937 // The scope must be bigger than any lookup DocIterator
1938 // later. For the global lookup, lastpit+1 is used, hence
1939 // we use lastpit+2 here.
1940 DocIterator it = par_iterator_begin();
1941 DocIterator outerScope = it;
1942 outerScope.pit() = outerScope.lastpit() + 2;
1943 updateMacros(it, outerScope);
1947 void Buffer::updateMacroInstances() const
1949 LYXERR(Debug::MACROS, "updateMacroInstances for "
1950 << d->filename.onlyFileName());
1951 DocIterator it = doc_iterator_begin(inset());
1952 DocIterator end = doc_iterator_end(inset());
1953 for (; it != end; it.forwardPos()) {
1954 // look for MathData cells in InsetMathNest insets
1955 Inset * inset = it.nextInset();
1959 InsetMath * minset = inset->asInsetMath();
1963 // update macro in all cells of the InsetMathNest
1964 DocIterator::idx_type n = minset->nargs();
1965 MacroContext mc = MacroContext(*this, it);
1966 for (DocIterator::idx_type i = 0; i < n; ++i) {
1967 MathData & data = minset->cell(i);
1968 data.updateMacros(0, mc);
1974 void Buffer::listMacroNames(MacroNameSet & macros) const
1979 d->macro_lock = true;
1981 // loop over macro names
1982 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1983 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1984 for (; nameIt != nameEnd; ++nameIt)
1985 macros.insert(nameIt->first);
1987 // loop over children
1988 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1989 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1990 for (; it != end; ++it)
1991 it->first->listMacroNames(macros);
1994 if (d->parent_buffer)
1995 d->parent_buffer->listMacroNames(macros);
1997 d->macro_lock = false;
2001 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2003 if (!d->parent_buffer)
2007 d->parent_buffer->listMacroNames(names);
2010 MacroNameSet::iterator it = names.begin();
2011 MacroNameSet::iterator end = names.end();
2012 for (; it != end; ++it) {
2014 MacroData const * data =
2015 d->parent_buffer->getMacro(*it, *this, false);
2017 macros.insert(data);
2019 // we cannot access the original MathMacroTemplate anymore
2020 // here to calls validate method. So we do its work here manually.
2021 // FIXME: somehow make the template accessible here.
2022 if (data->optionals() > 0)
2023 features.require("xargs");
2029 Buffer::References & Buffer::references(docstring const & label)
2031 if (d->parent_buffer)
2032 return const_cast<Buffer *>(masterBuffer())->references(label);
2034 RefCache::iterator it = d->ref_cache_.find(label);
2035 if (it != d->ref_cache_.end())
2036 return it->second.second;
2038 static InsetLabel const * dummy_il = 0;
2039 static References const dummy_refs;
2040 it = d->ref_cache_.insert(
2041 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2042 return it->second.second;
2046 Buffer::References const & Buffer::references(docstring const & label) const
2048 return const_cast<Buffer *>(this)->references(label);
2052 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2054 masterBuffer()->d->ref_cache_[label].first = il;
2058 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2060 return masterBuffer()->d->ref_cache_[label].first;
2064 void Buffer::clearReferenceCache() const
2066 if (!d->parent_buffer)
2067 d->ref_cache_.clear();
2071 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2074 //FIXME: This does not work for child documents yet.
2075 LASSERT(code == CITE_CODE, /**/);
2076 // Check if the label 'from' appears more than once
2077 vector<docstring> labels;
2079 BiblioInfo const & keys = masterBibInfo();
2080 BiblioInfo::const_iterator bit = keys.begin();
2081 BiblioInfo::const_iterator bend = keys.end();
2083 for (; bit != bend; ++bit)
2085 labels.push_back(bit->first);
2088 if (count(labels.begin(), labels.end(), from) > 1)
2091 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2092 if (it->lyxCode() == code) {
2093 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2094 docstring const oldValue = inset.getParam(paramName);
2095 if (oldValue == from)
2096 inset.setParam(paramName, to);
2102 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2103 pit_type par_end, bool full_source)
2105 OutputParams runparams(¶ms().encoding());
2106 runparams.nice = true;
2107 runparams.flavor = OutputParams::LATEX;
2108 runparams.linelen = lyxrc.plaintext_linelen;
2109 // No side effect of file copying and image conversion
2110 runparams.dryrun = true;
2114 os << "% " << _("Preview source code") << "\n\n";
2115 d->texrow.newline();
2116 d->texrow.newline();
2118 writeLaTeXSource(os, filePath(), runparams, true, true);
2120 writeDocBookSource(os, absFileName(), runparams, false);
2122 runparams.par_begin = par_begin;
2123 runparams.par_end = par_end;
2124 if (par_begin + 1 == par_end) {
2126 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2130 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2131 convert<docstring>(par_begin),
2132 convert<docstring>(par_end - 1))
2135 d->texrow.newline();
2136 d->texrow.newline();
2137 // output paragraphs
2139 latexParagraphs(*this, text(), os, d->texrow, runparams);
2142 docbookParagraphs(paragraphs(), *this, os, runparams);
2147 ErrorList & Buffer::errorList(string const & type) const
2149 static ErrorList emptyErrorList;
2150 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2151 if (I == d->errorLists.end())
2152 return emptyErrorList;
2158 void Buffer::structureChanged() const
2161 gui_->structureChanged();
2165 void Buffer::errors(string const & err) const
2172 void Buffer::message(docstring const & msg) const
2179 void Buffer::setBusy(bool on) const
2186 void Buffer::setReadOnly(bool on) const
2189 d->wa_->setReadOnly(on);
2193 void Buffer::updateTitles() const
2196 d->wa_->updateTitles();
2200 void Buffer::resetAutosaveTimers() const
2203 gui_->resetAutosaveTimers();
2207 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2216 class AutoSaveBuffer : public ForkedProcess {
2219 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2220 : buffer_(buffer), fname_(fname) {}
2222 virtual boost::shared_ptr<ForkedProcess> clone() const
2224 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2229 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2230 from_utf8(fname_.absFilename())));
2231 return run(DontWait);
2235 virtual int generateChild();
2237 Buffer const & buffer_;
2242 int AutoSaveBuffer::generateChild()
2244 // tmp_ret will be located (usually) in /tmp
2245 // will that be a problem?
2246 // Note that this calls ForkedCalls::fork(), so it's
2247 // ok cross-platform.
2248 pid_t const pid = fork();
2249 // If you want to debug the autosave
2250 // you should set pid to -1, and comment out the fork.
2251 if (pid != 0 && pid != -1)
2254 // pid = -1 signifies that lyx was unable
2255 // to fork. But we will do the save
2257 bool failed = false;
2258 FileName const tmp_ret = FileName::tempName("lyxauto");
2259 if (!tmp_ret.empty()) {
2260 buffer_.writeFile(tmp_ret);
2261 // assume successful write of tmp_ret
2262 if (!tmp_ret.moveTo(fname_))
2268 // failed to write/rename tmp_ret so try writing direct
2269 if (!buffer_.writeFile(fname_)) {
2270 // It is dangerous to do this in the child,
2271 // but safe in the parent, so...
2272 if (pid == -1) // emit message signal.
2273 buffer_.message(_("Autosave failed!"));
2277 if (pid == 0) // we are the child so...
2286 // Perfect target for a thread...
2287 void Buffer::autoSave() const
2289 if (isBakClean() || isReadonly()) {
2290 // We don't save now, but we'll try again later
2291 resetAutosaveTimers();
2295 // emit message signal.
2296 message(_("Autosaving current document..."));
2298 // create autosave filename
2299 string fname = filePath();
2301 fname += d->filename.onlyFileName();
2304 AutoSaveBuffer autosave(*this, FileName(fname));
2308 resetAutosaveTimers();
2312 string Buffer::bufferFormat() const
2318 if (params().encoding().package() == Encoding::japanese)
2324 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2325 string & result_file) const
2327 string backend_format;
2328 OutputParams runparams(¶ms().encoding());
2329 runparams.flavor = OutputParams::LATEX;
2330 runparams.linelen = lyxrc.plaintext_linelen;
2331 vector<string> backs = backends();
2332 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2333 // Get shortest path to format
2334 Graph::EdgePath path;
2335 for (vector<string>::const_iterator it = backs.begin();
2336 it != backs.end(); ++it) {
2337 Graph::EdgePath p = theConverters().getPath(*it, format);
2338 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2339 backend_format = *it;
2344 runparams.flavor = theConverters().getFlavor(path);
2346 Alert::error(_("Couldn't export file"),
2347 bformat(_("No information for exporting the format %1$s."),
2348 formats.prettyName(format)));
2352 backend_format = format;
2353 // FIXME: Don't hardcode format names here, but use a flag
2354 if (backend_format == "pdflatex")
2355 runparams.flavor = OutputParams::PDFLATEX;
2358 string filename = latexName(false);
2359 filename = addName(temppath(), filename);
2360 filename = changeExtension(filename,
2361 formats.extension(backend_format));
2364 updateMacroInstances();
2366 // Plain text backend
2367 if (backend_format == "text")
2368 writePlaintextFile(*this, FileName(filename), runparams);
2370 else if (backend_format == "lyx")
2371 writeFile(FileName(filename));
2373 else if (isDocBook()) {
2374 runparams.nice = !put_in_tempdir;
2375 makeDocBookFile(FileName(filename), runparams);
2378 else if (backend_format == format) {
2379 runparams.nice = true;
2380 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2382 } else if (!lyxrc.tex_allows_spaces
2383 && contains(filePath(), ' ')) {
2384 Alert::error(_("File name error"),
2385 _("The directory path to the document cannot contain spaces."));
2388 runparams.nice = false;
2389 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2393 string const error_type = (format == "program")
2394 ? "Build" : bufferFormat();
2395 ErrorList & error_list = d->errorLists[error_type];
2396 string const ext = formats.extension(format);
2397 FileName const tmp_result_file(changeExtension(filename, ext));
2398 bool const success = theConverters().convert(this, FileName(filename),
2399 tmp_result_file, FileName(absFileName()), backend_format, format,
2401 // Emit the signal to show the error list.
2402 if (format != backend_format)
2407 if (put_in_tempdir) {
2408 result_file = tmp_result_file.absFilename();
2412 result_file = changeExtension(absFileName(), ext);
2413 // We need to copy referenced files (e. g. included graphics
2414 // if format == "dvi") to the result dir.
2415 vector<ExportedFile> const files =
2416 runparams.exportdata->externalFiles(format);
2417 string const dest = onlyPath(result_file);
2418 CopyStatus status = SUCCESS;
2419 for (vector<ExportedFile>::const_iterator it = files.begin();
2420 it != files.end() && status != CANCEL; ++it) {
2421 string const fmt = formats.getFormatFromFile(it->sourceName);
2422 status = copyFile(fmt, it->sourceName,
2423 makeAbsPath(it->exportName, dest),
2424 it->exportName, status == FORCE);
2426 if (status == CANCEL) {
2427 message(_("Document export cancelled."));
2428 } else if (tmp_result_file.exists()) {
2429 // Finally copy the main file
2430 status = copyFile(format, tmp_result_file,
2431 FileName(result_file), result_file,
2433 message(bformat(_("Document exported as %1$s "
2435 formats.prettyName(format),
2436 makeDisplayPath(result_file)));
2438 // This must be a dummy converter like fax (bug 1888)
2439 message(bformat(_("Document exported as %1$s"),
2440 formats.prettyName(format)));
2447 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2450 return doExport(format, put_in_tempdir, result_file);
2454 bool Buffer::preview(string const & format) const
2457 if (!doExport(format, true, result_file))
2459 return formats.view(*this, FileName(result_file), format);
2463 bool Buffer::isExportable(string const & format) const
2465 vector<string> backs = backends();
2466 for (vector<string>::const_iterator it = backs.begin();
2467 it != backs.end(); ++it)
2468 if (theConverters().isReachable(*it, format))
2474 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2476 vector<string> backs = backends();
2477 vector<Format const *> result =
2478 theConverters().getReachable(backs[0], only_viewable, true);
2479 for (vector<string>::const_iterator it = backs.begin() + 1;
2480 it != backs.end(); ++it) {
2481 vector<Format const *> r =
2482 theConverters().getReachable(*it, only_viewable, false);
2483 result.insert(result.end(), r.begin(), r.end());
2489 vector<string> Buffer::backends() const
2492 if (params().baseClass()->isTeXClassAvailable()) {
2493 v.push_back(bufferFormat());
2494 // FIXME: Don't hardcode format names here, but use a flag
2495 if (v.back() == "latex")
2496 v.push_back("pdflatex");
2498 v.push_back("text");
2504 bool Buffer::readFileHelper(FileName const & s)
2506 // File information about normal file
2508 docstring const file = makeDisplayPath(s.absFilename(), 50);
2509 docstring text = bformat(_("The specified document\n%1$s"
2510 "\ncould not be read."), file);
2511 Alert::error(_("Could not read document"), text);
2515 // Check if emergency save file exists and is newer.
2516 FileName const e(s.absFilename() + ".emergency");
2518 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2519 docstring const file = makeDisplayPath(s.absFilename(), 20);
2520 docstring const text =
2521 bformat(_("An emergency save of the document "
2523 "Recover emergency save?"), file);
2524 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2525 _("&Recover"), _("&Load Original"),
2529 // the file is not saved if we load the emergency file.
2539 // Now check if autosave file is newer.
2540 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2542 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2543 docstring const file = makeDisplayPath(s.absFilename(), 20);
2544 docstring const text =
2545 bformat(_("The backup of the document "
2546 "%1$s is newer.\n\nLoad the "
2547 "backup instead?"), file);
2548 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2549 _("&Load backup"), _("Load &original"),
2553 // the file is not saved if we load the autosave file.
2557 // Here we delete the autosave
2568 bool Buffer::loadLyXFile(FileName const & s)
2570 if (s.isReadableFile()) {
2571 if (readFileHelper(s)) {
2572 lyxvc().file_found_hook(s);
2573 if (!s.isWritable())
2578 docstring const file = makeDisplayPath(s.absFilename(), 20);
2579 // Here we probably should run
2580 if (LyXVC::file_not_found_hook(s)) {
2581 docstring const text =
2582 bformat(_("Do you want to retrieve the document"
2583 " %1$s from version control?"), file);
2584 int const ret = Alert::prompt(_("Retrieve from version control?"),
2585 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2588 // How can we know _how_ to do the checkout?
2589 // With the current VC support it has to be,
2590 // a RCS file since CVS do not have special ,v files.
2592 return loadLyXFile(s);
2600 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2602 TeXErrors::Errors::const_iterator cit = terr.begin();
2603 TeXErrors::Errors::const_iterator end = terr.end();
2605 for (; cit != end; ++cit) {
2608 int errorRow = cit->error_in_line;
2609 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2615 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2616 } while (found && id_start == id_end && pos_start == pos_end);
2618 errorList.push_back(ErrorItem(cit->error_desc,
2619 cit->error_text, id_start, pos_start, pos_end));